release-2.8.0 (#1456)

* Fix private AI custom endpoints (#1299)

* Fix Proxmox credential guest imports (#1300)

* Fix Fleet command results layout (#1301)

* Fix synced client tunnel endpoints (#1302)

* Fix Proxmox sync jump host persistence (#1303)

* Fix command palette keyboard navigation (#1304)

* Add accessible interface font choices (#1306)

* Add selectable host temperature sensors (#1307)

* Improve file manager navigation and compact layout (#1308)

* Add configurable global hotkeys (#1305)

* fix: restore split layout selection (#1310)

* fix: support macOS VNC connections (#1311)

* fix: use matching Undici fetch for private AI providers (#1309)

Co-authored-by: Angad Singh <angad@singhangad.in>

* feat: support additional TOTP authenticators (#1312)

* feat: add VNC display zoom controls (#1314)

* feat: add host context menu actions (#1315)

* fix: force classic auth for macOS VNC (#1313)

* fix: harden HTTP trust boundaries (#1316)

* fix: harden application trust boundaries (#1317)

* fix: verify OPKSSH binary integrity (#1318)

* Fix remote desktop connection timeout (#1319)

* chore(deps): bump node in /docker in the docker-major-updates group (#1321)

Bumps the docker-major-updates group in /docker with 1 update: node.


Updates `node` from 24-slim to 26-slim

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-slim
  dependency-type: direct:production
  dependency-group: docker-major-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-patch-updates group with 15 updates (#1322)

Bumps the dev-patch-updates group with 15 updates:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.7` | `6.43.9` |
| [@commitlint/cli](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/cli) | `21.2.1` | `21.2.2` |
| [@commitlint/config-conventional](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/config-conventional) | `21.2.0` | `21.2.2` |
| [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) | `7.0.0` | `7.0.1` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.1` | `14.6.5` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.10` | `4.1.11` |
| [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.10` | `4.1.11` |
| [concurrently](https://github.com/open-cli-tools/concurrently) | `10.0.4` | `10.0.5` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.0` | `3.34.1` |
| [eslint](https://github.com/eslint/eslint) | `10.8.0` | `10.8.1` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.3` | `0.5.4` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.0.11` | `17.0.12` |
| [sonner](https://github.com/emilkowalski/sonner) | `2.0.7` | `2.0.8` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.2.0` | `8.2.2` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.10` | `4.1.11` |


Updates `@codemirror/view` from 6.43.7 to 6.43.9
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@commitlint/cli` from 21.2.1 to 21.2.2
- [Release notes](https://github.com/conventional-changelog/commitlint/releases)
- [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/cli/CHANGELOG.md)
- [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/cli)

Updates `@commitlint/config-conventional` from 21.2.0 to 21.2.2
- [Release notes](https://github.com/conventional-changelog/commitlint/releases)
- [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/config-conventional/CHANGELOG.md)
- [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/config-conventional)

Updates `@testing-library/jest-dom` from 7.0.0 to 7.0.1
- [Release notes](https://github.com/testing-library/jest-dom/releases)
- [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/jest-dom/compare/v7.0.0...v7.0.1)

Updates `@testing-library/user-event` from 14.6.1 to 14.6.5
- [Release notes](https://github.com/testing-library/user-event/releases)
- [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/user-event/compare/v14.6.1...v14.6.5)

Updates `@vitest/coverage-v8` from 4.1.10 to 4.1.11
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/coverage-v8)

Updates `@vitest/ui` from 4.1.10 to 4.1.11
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/ui)

Updates `concurrently` from 10.0.4 to 10.0.5
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v10.0.4...v10.0.5)

Updates `cytoscape` from 3.34.0 to 3.34.1
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.0...v3.34.1)

Updates `eslint` from 10.8.0 to 10.8.1
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v10.8.0...v10.8.1)

Updates `eslint-plugin-react-refresh` from 0.5.3 to 0.5.4
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.3...v0.5.4)

Updates `react-i18next` from 17.0.11 to 17.0.12
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.0.11...v17.0.12)

Updates `sonner` from 2.0.7 to 2.0.8
- [Release notes](https://github.com/emilkowalski/sonner/releases)
- [Commits](https://github.com/emilkowalski/sonner/compare/v2.0.7...v2.0.8)

Updates `vite` from 8.2.0 to 8.2.2
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.2.2/packages/vite)

Updates `vitest` from 4.1.10 to 4.1.11
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/vitest)

---
updated-dependencies:
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@commitlint/cli"
  dependency-version: 21.2.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@commitlint/config-conventional"
  dependency-version: 21.2.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/jest-dom"
  dependency-version: 7.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/user-event"
  dependency-version: 14.6.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitest/ui"
  dependency-version: 4.1.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: concurrently
  dependency-version: 10.0.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: cytoscape
  dependency-version: 3.34.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint
  dependency-version: 10.8.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: react-i18next
  dependency-version: 17.0.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: sonner
  dependency-version: 2.0.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: vite
  dependency-version: 8.2.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: vitest
  dependency-version: 4.1.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump the prod-patch-updates group with 5 updates (#1324)

Bumps the prod-patch-updates group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.9` | `3.14.10` |
| [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | `13.0.2` | `13.0.3` |
| [jose](https://github.com/panva/jose) | `6.2.8` | `6.2.9` |
| [mysql2](https://github.com/sidorares/node-mysql2) | `3.23.2` | `3.23.4` |
| [ws](https://github.com/websockets/ws) | `8.21.1` | `8.21.3` |


Updates `@tanstack/react-virtual` from 3.14.9 to 3.14.10
- [Release notes](https://github.com/TanStack/virtual/releases)
- [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md)
- [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.10/packages/react-virtual)

Updates `better-sqlite3` from 13.0.2 to 13.0.3
- [Release notes](https://github.com/WiseLibs/better-sqlite3/releases)
- [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v13.0.2...v13.0.3)

Updates `jose` from 6.2.8 to 6.2.9
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.8...v6.2.9)

Updates `mysql2` from 3.23.2 to 3.23.4
- [Release notes](https://github.com/sidorares/node-mysql2/releases)
- [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md)
- [Commits](https://github.com/sidorares/node-mysql2/compare/v3.23.2...v3.23.4)

Updates `ws` from 8.21.1 to 8.21.3
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.21.1...8.21.3)

---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
  dependency-version: 3.14.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: better-sqlite3
  dependency-version: 13.0.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: jose
  dependency-version: 6.2.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: mysql2
  dependency-version: 3.23.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: ws
  dependency-version: 8.21.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump motion in the major-updates group (#1326)

Bumps the major-updates group with 1 update: [motion](https://github.com/motiondivision/motion).


Updates `motion` from 12.43.0 to 13.1.1
- [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md)
- [Commits](https://github.com/motiondivision/motion/compare/v12.43.0...v13.1.1)

---
updated-dependencies:
- dependency-name: motion
  dependency-version: 13.1.1
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: major-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* feat: add semantic motion system (#1320)

* feat: add semantic motion system

* feat: animate session workspace transitions

* feat: refine motion accessibility and transfer feedback

* feat: enforce RBAC and harden collaboration features (#1327)

* feat: enforce RBAC and harden collaboration features

- Mount requirePermission on hosts/snippets/credentials/automations/AI routes
- Seed and backfill system role permissions on every dialect at startup
- Support personal credential overrides for RDP/VNC/Telnet shared hosts
- Broadcast participant presence in shared terminal sessions
- Make audit log forwarding configurable from the admin panel
- Add role members endpoint and snippet folder sharing

* fix: enforce RBAC across split routes

* fix: reject malformed Guacamole tokens safely (#1329)

* fix: allow approved private notification hosts (#1330)

* feat: collaboration rooms with switchable presenter (#1328)

* feat: add collaboration rooms with switchable presenter

Rooms are a group of members watching one stage - the live SSH/RDP/VNC
session the current presenter shares. Any member can take over the
stage; the host can invite, force-stop and end the meeting. Stages
reuse session_shares (new room share type), so gating, recording,
expiry and the global sharing toggle all apply unchanged.

* feat: add stage control handoff to collaboration rooms

The presenter or host can grant any member write access to the live
stage and take it back; members can raise a hand to ask. SSH flips the
participant's permission on the live gate; RDP/VNC re-mint the viewer's
join token. Control clears on every stage switch.

* feat: guest links, role invites and invite awareness for collab rooms

- Anonymous guest link per room (host toggles/rotates), followed by
  polling the public resolve endpoint; SSH guests join over the terminal
  WS with roomGuestToken, guac guests get read-only join tokens
- Invite by role (expands to current members, snapshot semantics)
- Toast when a room you were invited to appears
- Stale stages are cleared lazily when the presenter is gone
- Telnet presenting, expired-tab fallback, documented single-instance
  and guac-kick limits
- Tests for the collab routes, room hub, share access and control flip

* fix: keep remote desktop collaboration read-only

* fix: restore RDP clipboard paste across browsers (#1331)

* fix: show the full command line in the process inspector (#1334)

The CMD column rendered ps's comm field, which the kernel caps at 15
characters, so anything longer looked truncated no matter how wide the
column was. The full args were already collected; show them.

* fix: harden collaboration room access (#1332)

* fix: harden collaboration room access

* fix: confirm guest link lifecycle changes

* fix: make RDP drive redirection writable on the stock deployment (#1333)

* fix: make RDP drive redirection writable on the stock deployment

The default drive-path was /drive on the guacd side, which the official
guacd image cannot create as its non-root user, so every upload was
refused with guacd's raw "FAIL (CANNOT OPEN)" ack. Default to
GUACD_DRIVE_PATH (set to the shared termix-data volume in compose) with
one folder per user, and explain guacd's refusal in the file browser.

* style: format RDP drive settings

* feat: quick connect for RDP and VNC (#1335)

The Quick Connect panel gets a protocol switch. RDP/VNC quick hosts are
built like SSH ones (never saved) and opened as regular remote desktop
tabs; GuacamoleApp mints their token from the typed fields through the
existing /guacamole/token endpoint instead of a host-row lookup.

* fix: authenticate unwatched hosts during the status probe (#1337)

With metrics enabled, the status probe left SSH authentication to the
metrics poll - which only runs while someone is viewing the host. An
unwatched host therefore never left "reachable", while a host with
metrics disabled (whose probe always authenticates) showed online. The
probe now authenticates whenever no metrics poll will.

* feat: compact snippet list option (#1339)

A "Show Commands" toggle in the snippets settings menu hides the command
text under each snippet name, for people who dock the panel on the
narrow right rail and only need the names. Local preference, on by
default.

* fix: guide users to Auto-Tmux when a persisted session expires (#1336)

* fix: guide users to Auto-Tmux when a persisted session expires

A timed-out terminal session silently reconnected to a fresh shell, so
people running long jobs lost them with no explanation and never learned
about Auto-Tmux. Explain the expiry with a one-click Enable Auto-Tmux
action, let admins default it for new hosts and tune the persistence
timeout from the UI, and move the setting up with copy that says what it
does. The global default stays off.

* style: format terminal expiry notice

* feat: improve collaboration rooms (#1338)

* feat: Step CA SSH certificates as a host authentication type (#1340)

* feat: Step CA SSH certificates as a host authentication type

Issue short-lived SSH user certificates from a smallstep CA through its
OIDC provisioner, over the CA's HTTP API rather than the step binary.
Everything after issuance reuses the OPKSSH plumbing: the same encrypted
per-user/host token store, WebSocket dialog and ssh2 certificate
injection, with the connect paths branching on a shared
usesIssuedCertificate() predicate. Instance-wide CA settings live in the
admin panel, with a private-host allowlist for the SSRF guard.

* fix: harden Step CA callback flow

* style: format Step CA changes

* feat: 1Password Connect secret sources for SSH credentials (#1341)

* feat: 1Password Connect secret sources for SSH credentials

Hosts and credentials can hold op://vault/item/field references instead
of secrets; they are resolved at connect time from the user's secret
source (1Password Connect) at the single point where every subsystem
receives plaintext credentials, so terminal, SFTP, Docker, metrics and
tunnels all work without per-subsystem changes. Sources are per user,
optionally shared, with the access token encrypted under the owner's
data key; resolved values are cached briefly in memory.

* style: format secret source changes

* feat: share credentials with users and roles, inherit data on account deletion (#1342)

* feat: share credentials with users and roles, inherit data on account deletion

Credentials can be shared at "use" or "manage" level. Recipients get
a copy re-encrypted under their own data key (shared_credential_secrets),
kept in step with the owner's row through the same lifecycle hooks as
shared host secrets. One gate, findUsableCredential(), replaces the
private-namespace lookups so a shared credential works wherever a
private one does. Deleting a user now hands their hosts and credentials
to a successor (the deleting admin by default) instead of revoking
everything they shared.

* fix: harden credential ownership transfer

* feat: folder shares apply to hosts added later (#1343)

* feat: folder shares apply to hosts added later

Sharing a folder only fanned grants out to the hosts in it at the time.
The share is now also kept as a standing rule on the folder, and a host
created in or moved into it (or a subfolder) inherits the same access
and secret snapshots. Rules follow folder renames and can be stopped
from the share dialog.

* fix: stabilize folder access migrations

* fix: package sharp for both macOS architectures (#1344)

* fix: prompt shared RDP users for credentials (#1345)

* feat: add terminal copy-on-select option (#1346)

* fix: retry protected file reads with sudo (#1349)

* fix: stop SSH-authenticating hosts during routine status polling (#1347)

* fix: preserve omitted host protocol settings (#1350)

* fix: surface remote sync reauthentication failures (#1351)

* fix: harden file reads and timer cleanup (#1352)

* fix: harden file reads and timer cleanup

* fix: preserve literal file path escapes

* fix: enforce SSH pool connection limits (#1353)

* fix: enforce SSH pool connection limits

* fix: discard stale pooled connections

* fix: harden connection, payload, and persisted state handling (#1354)

* fix: clean up Cloudflare tunnel timeouts

* fix: couple tunnel socket lifecycle

* fix: validate Docker console messages

* fix: bound homepage proxy responses

* fix: bound reconnect and response failures

* fix: harden persisted and socket state

* fix: support local connections to shared hosts

* fix: recover expired dashboard metrics sessions (#1355)

* fix: upload files to redirected RDP drives (#1356)

* fix: unify connection toolbar visibility (#1357)

* fix: reset host virtualizer after editing (#1358)

* test: update Guacamole toolbar display mock (#1360)

* fix: reflect live SSH sessions in host status (#1359)

* fix: support Vault auth in file manager (#1361)

* fix: allow exec on shared hosts (#1362)

* fix(file-manager): align chunked upload contract (#1371)

* fix(file-manager): make bulk uploads resilient (#1373)

* fix(terminal): disable local echo on alternate screen (#1372)

* fix(homepage): validate clock widget timezones (#1374)

An invalid timezone in a clock widget's config reached toLocaleTimeString
unchecked, throwing RangeError during render and taking the homepage canvas
down with it. The edit dialog accepted any string, so "America/New York" - a
space where IANA wants an underscore - was easy to save, and the homepage
stayed broken on every later load because the value is reloaded from the
database.

The edit dialog now flags an unusable zone the way FolderMetadataDialog flags
a duplicate folder name: inline message, aria-invalid, and a disabled Save.
Whitespace is normalized to underscores on save, so the space spelling is
stored as America/New_York rather than rejected. ClockWidget falls back to
local time for any config already holding an invalid zone.

Related to Termix-SSH/Support#1238

* fix(hosts): preserve connection origin in editor (#1376)

* fix(remote-sync): expose local login notification (#1375)

* fix(auth): allow passkeys in desktop login (#1378)

* fix(proxmox): elevate guest discovery commands (#1379)

* Fix permanent file-transfer completion toasts (#1383)

* fix(file-manager): expire completed progress toasts

* test(file-manager): use valid transfer status

* fix(hosts): allow clearing SSH key type (#1384)

* fix(terminal): suppress local echo for contextual password prompts (#1387)

* fix(desktop): surface a failed embedded backend start (#1382)

* fix(desktop): surface a failed embedded backend start

When the embedded backend's HTTP port was already taken, the desktop app
sat on the "Loading..." spinner forever with nothing in the UI to say
why. The backend logged the conflict and exited 1, and startBackendServer
resolved false, but that verdict never reached the renderer: the
get-embedded-server-status channel was not exposed in preload and nothing
called it.

The renderer, by design, treats every connection failure as "the embedded
backend is still booting" and retries indefinitely -- in main.tsx's
verifying phase, in Auth's desktop auto-session, and in
FullScreenAppWrapper. That holds while the backend is merely slow to boot,
but not once the process has exited, and nothing distinguished the two.

Classify why the child died from its exit code and a bounded tail of its
stderr, report it through get-embedded-server-status, and have each retry
loop keep waiting only while no failure is reported. A port conflict names
the port, since that is what the user has to act on -- most often a Termix
container on the same ports, or a backend orphaned by a hard-kill that
reapOrphanedBackendProcess could not claim.

A deliberate shutdown is not reported as a crash, and a backend that is
only slow to start still gets retried as before.

Fixes Termix-SSH/Support#1254

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(desktop): treat every unrequested backend exit as a failure

The classifier exempted a clean exit and SIGTERM/SIGINT, calling those a
deliberate shutdown. It has no evidence for that: its only caller already
sits behind backendStopRequested, so it is reached only for exits
stopBackendServer() did not ask for. A backend that exited 0 on its own,
or was terminated by the OS or an external signal, therefore reported no
failure at all -- leaving all three renderer loops waiting forever for a
process that is gone, which is the exact hang this change set exists to
remove.

Every exit reaching the classifier is now a failure, port-in-use when
stderr carries EADDRINUSE and crashed otherwise, with backendStopRequested
left as the sole deliberate-shutdown guard. That makes the exit code and
signal irrelevant to the verdict, so the classifier now takes only the
stderr tail rather than carrying two parameters it no longer reads.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* Add white label branding settings (#1386)

* feat(admin): add white label branding settings

Admins can configure a custom app name, logo and tagline from the
Admin Settings panel. The values apply to the login screen and the
browser tab title/favicon at runtime.

* fix(admin): restore default icons on logo reset, validate upload MIME type

Resetting the logo now restores the bundled favicon/apple-touch-icon
instead of leaving the previous custom one until a reload. The admin
upload also validates file.type up front instead of only failing
later on save.

* fix(admin): restore default favicons and reject invalid logo types

Capture bundled icon hrefs before the first custom logo is applied so a
reset does not leave the previous upload in the tab, and reject
non-image uploads before they are read into branding state.

* test(admin): cover branding routes and logo validation

Add backend tests for the public GET, admin-only PATCH, unknown-field
rejection, and parseBrandingLogoDataUrl so invalid images cannot land
in settings without a failing test.

* fix(backend): report port conflicts on the service ports (#1388)

Express's app.listen(port, host, callback) registers that callback as the
server's error handler as well as its listening handler:

    if (typeof args[args.length - 1] === 'function') {
      var done = args[args.length - 1] = once(args[args.length - 1])
      server.once('error', done)
    }

so a bind failure invoked the service's "started" callback with an
EADDRINUSE error as its only argument and emitted nothing. None of the
services read that argument, which made a failed bind indistinguishable
from a successful one: the service logged that it had started, ran its
initialisation, and served nothing. With one of 30003-30012 occupied the
backend still reported backend_init_complete, the app loaded, and the
affected feature was dead for the session with no error anywhere in the
logs -- searching the backend log, the Electron main log and stdout for
EADDRINUSE returned nothing, as did uncaughtException and
unhandledRejection probes.

This is also why only the main port behaved sensibly: database.ts does
not use app.listen(), it builds the server and attaches a real error
handler, so 30001 was the one port whose conflict was ever detected.

listenOnServicePort() builds the server so that listening and error stay
separate, and treats a conflict the way database.ts already does -- name
the port, then exit -- rather than running on with one feature missing.
Exiting also hands the desktop app the classified failure it already
surfaces, so the user is told which port to free. Services that must own
their server, such as the tunnel service with its WebSocket upgrade
handler, get the same handler via attachServicePortConflictHandler().

Note that adding .on("error") to the services would not have worked:
express consumes the event through once('error', done) before any later
handler runs. The callback has to stop being passed to listen() at all.

Fixes Termix-SSH/Support#1260

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* feat(desktop): allow RDP/VNC/Telnet to originate from this device (#1389)

The desktop pinned rdp/vnc/telnet to the remote server, so a host the
user's own machine could reach but the Termix server could not was
impossible to open: the app answered "Remote server required" even when
no remote server was wanted. The embedded backend already runs the
Guacamole websocket server and guacd's address is already configurable
globally and per host, so what was missing was the choice.

resolveConnectionOrigin now honours an explicit per-host origin for
these protocols. Left on Default they still resolve to remote: they need
a guacd, which the desktop does not ship, so originating locally only
works once the user has pointed Termix at one of their own. Keeping that
opt-in means an upgrade never moves a working connection onto a guacd
that is not there. Serial and non-Electron behaviour are unchanged.

Three call paths had the same assumption baked in and would have quietly
ignored the setting:

- The Guacamole call sites resolved the origin without passing the
  host's own override, so it could never take effect.
- guacamole-api sent every token, connect-host and status call to the
  remote server whenever running under Electron, and remapped the host
  id onto the remote server's id -- which would address the wrong row,
  or fail outright with no server configured.
- GuacamoleDisplay minted its token before resolving the origin, so the
  token could come from a different backend than the socket dialled.

The origin is a required parameter on those API functions rather than a
defaulted one. A default silently sent a missed call site to the remote
server: the guacd status check in fetchToken was one, and it failed with
a bare "Network Error" on a desktop with no server configured. Making it
required means the compiler names every caller instead. That also
covers CollabRoomTab, which now resolves from the host it already holds,
so a locally-originated host stays local when presented into a room.

Finally, the Connection Origin control was gated on SSH alone, so a host
enabling only these protocols could never reach the setting. That gate
is now a named predicate covering every protocol the control applies to.

Verified end to end on Linux against a local guacd: with a host set to
"This device", guacd accepted the connection and reached the target,
which answered for itself. With guacd stopped, the guacd status check
that has run before every connection since v2.3.0 -- now asking the
backend the session will actually use -- reports it clearly before a
socket is opened.

Refs Termix-SSH/Support#1240

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* feat(local-terminal): add copy/paste support (#1391)

* feat(local-terminal): add copy/paste support

Local terminal had no clipboard wiring, so selected text couldn't be
copied. Extracted the SSH terminal's copy/paste shortcut and
right-click handling into a shared terminal-clipboard module and wired
it into both terminals, removing duplicated logic in the process.

* fix(local-terminal): stop language changes from restarting the shell session

The session effect that starts the local PTY depended on `t`, whose
identity changes on every language switch (react-i18next). That tore
down the running shell and spawned a new one just from changing the UI
language. Read translations through a ref instead so localization
stays decoupled from the PTY lifecycle.

Also adds regression coverage for the extracted terminal-clipboard.ts
helpers: copy with/without selection, explicit vs native paste,
right-click preference, and Ctrl+right-click passthrough.

* fix(file-manager): keep name column visible on narrow viewports in list view (#1402)

Rebased onto dev-2.8.0 (the density refactor kept the same 3
list-view grid patterns). Use minmax(140px, 1fr) for the name track
so it cannot collapse to 0px on narrow viewports; the table scrolls
horizontally instead of hiding names and icons.

Co-authored-by: inontz <inontz@users.noreply.github.com>

* feat(desktop): local filesystem and transfer bridge for the file manager (#1392)

* feat(desktop): local filesystem and transfer bridge for the file manager

Adds the Electron main-process side of the upcoming Local | Remote dual-pane
file manager, with no UI yet:

- electron/local-files.cjs: IPC handlers to browse the local disk (home,
  list, mkdir, createFile, rename, trash, ensureDir, walk, reveal, open) and
  to stream files between the local disk and the file-manager backend
  (uploadLocalFile / downloadToLocal with progress events and cancellation).
  Streams go through Electron's `net` so the session cookie / remembered JWT
  is attached the same way as the renderer's own requests.
- electron/preload.js: exposes them as `window.electronAPI.localFs` and
  `window.electronAPI.localTransfer`; the existing `invoke` allowlist is
  untouched.
- src/types/electron.d.ts: typings for the new surface.
- electron/main.cjs: registers the handlers.

Follow-up PRs add the renderer side (local pane, drag-and-drop transfers,
context menu).

* fix(desktop): harden the local transfer bridge (origin allowlist, collision policy)

Addresses the review on the transfer boundary:

- The renderer no longer supplies a URL or headers. It sends
  `{ origin: "local" | "remote", route, deviceId }` and the main process
  resolves the target itself: fixed route allowlist (`uploadFileStream`,
  `downloadFileStream`), local = the embedded backend base, remote = the
  remote-sync config's URL (http/https only) with the stored JWT. Anything
  else is rejected before a request is made. `deviceId` is validated.
- Downloads never rename or replace silently. The destination is checked
  first and `EEXIST` is returned unless the caller passes `overwrite: true`.
  Each transfer writes to its own `<dest>.<transferId>.termix-part` opened
  with `wx`, and publishes with `fs.link` / `COPYFILE_EXCL` (rename only when
  overwriting), so concurrent transfers to the same path cannot share or
  clobber a partial (`EBUSY` for the second). Partials are removed on
  failure or cancel.
- New `local-fs:exists` handler so the renderer can ask before starting.
- `createLocalFileHandlers` / `createTargetResolver` take their
  dependencies (net, shell, remote-sync getters) as parameters so the
  boundary is unit-testable without Electron.
- src/backend/tests/electron/local-files.test.ts: target resolution and
  off-origin refusal, EEXIST / EBUSY / overwrite paths, unique partials and
  cleanup, upload multipart integrity (parsed with Busboy).

* fix(desktop): Windows-safe replace for overwrite downloads

`publishDownload()` used `rename(partial, dest)` for the explicit overwrite
path. POSIX replaces the destination, but on Windows rename() onto an
existing name commonly fails (EEXIST / EPERM, always while the file is
open), so "Replace" did not actually work there.

The overwrite path no longer renames onto an occupied name:

1. the current file is moved aside to a transfer-unique sibling
   (`<dest>.<transferId>.termix-replaced`) - renaming to a fresh name is
   safe on every platform;
2. the partial is published exclusively under the now-free name (the same
   `link` / `COPYFILE_EXCL` primitive the non-overwrite path uses);
3. the aside copy is deleted (retried once; if another process still holds
   it open on Windows it is left in place and logged rather than failing
   the transfer).

Failure handling preserves the original: if step 1 fails (file in use)
nothing has changed and the caller gets `EBUSY`; if step 2 fails the aside
copy is moved back under its name and the error propagates. Replacing a
folder with a file is refused with `EISDIR`; a destination that vanished
mid-transfer falls back to the exclusive publish.

The publish primitives take their filesystem operations as an injectable
`publishFs` (default: real fs), and the tests drive them with a
Windows-like fs whose rename() refuses to overwrite - so the strategy is
verified without relying on POSIX rename-over-existing semantics:
successful swap with no rename ever targeting an occupied name, original
restored byte-for-byte when publishing fails, EBUSY with nothing touched
when the file cannot be moved aside, EISDIR for folders, vanished
destination, and the end-to-end overwrite through the download handler.

---------

Co-authored-by: Max <maxim@cogitate.ai>

* chore: update package lock

* feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop)

Renderer side of the dual-pane file manager, built on the local filesystem
bridge added in the previous PR. Desktop app only; the web build is
unchanged (the toggle is hidden when `window.electronAPI.localFs` is absent).

- New Local pane (LocalFilePane) next to the remote grid, toggled from the
  toolbar (Laptop icon); path, visibility and width are remembered in
  localStorage (`termix:file-manager:local-pane:*`). Grid and list views,
  hidden files toggle, breadcrumb navigation, New Folder.
- Drag files/folders from the Local pane onto the remote grid to upload,
  and from the remote grid onto the Local pane to download. Both directions
  stream through the main process (`useLocalTransfers`) with a single
  progress toast per batch (speed, ETA, cancel). Finder drops onto the
  remote grid keep working as before.
- Collision policy for downloads: destinations are checked first; if any
  exist the user is asked Replace / Skip for the batch. Skip, dismiss and
  timeout all mean skip - nothing is ever replaced without an explicit
  click, and the main process enforces the same rule (`EEXIST` unless
  `overwrite` is set).
- Drag MIME contract: `application/x-termix-local-files` for local drags,
  `application/x-termix-remote-files` marker on the remote grid's internal
  drags, so each pane can tell the two apart from Finder drops.
- Transfer targets are described as `{ origin, route, deviceId }`
  (`getSessionOrigin` in main-axios) - the renderer never hands the main
  process a URL.
- i18n: new `fileManager.local*` keys in en.json only (other locales via
  Crowdin).
- Tests: LocalFilePane rendering/navigation, local-transfer-utils
  (relative-path planning, size formatting).
- Modified column uses the same `Mon DD HH:MM` / `Mon DD  YYYY` (ls -l style)
  format as the remote grid, so both panes read alike.

* docs: point security note to the docs root (old /security page is gone) (#1400)

* chore: sync Crowdin translations

* chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325)

Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg).


Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0)

Updates `js-yaml` from 5.2.3 to 5.3.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0)

Updates `pg` from 8.22.0 to 8.23.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg)

---
updated-dependencies:
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.120.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: js-yaml
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: pg
  dependency-version: 8.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323)

Bumps the dev-minor-updates group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` |
| [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` |
| [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` |
| [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` |
| [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` |



Updates `@codemirror/commands` from 6.10.4 to 6.11.0
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@types/node` from 26.1.2 to 26.2.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

Updates `electron` from 43.2.0 to 43.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1)

Updates `globals` from 17.9.0 to 17.11.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0)

Updates `i18next` from 26.3.6 to 26.4.0
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0)

Updates `lucide-react` from 1.28.0 to 1.33.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react)

Updates `react-hook-form` from 7.84.0 to 7.85.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0)

Updates `react-pdf` from 10.4.1 to 10.5.0
- [Release notes](https://github.com/wojtekmaj/react-pdf/releases)
- [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf)

Updates `typescript-eslint` from 8.66.0 to 8.67.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@types/node"
  dependency-version: 26.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 43.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: globals
  dependency-version: 17.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: i18next
  dependency-version: 26.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.33.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.85.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-pdf
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.67.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: sync Crowdin translations

* Update redirect-issues workflow configuration

Updated the workflow to change the runner and modify the issue response message.

* chore: sync Crowdin translations

* Add Hetzner logo and referral link to README

Added Hetzner logo with a referral link to README.

* Fix Hetzner logo URL in README.md

* docs: point security note to the feature security page

The old /security page is gone and the docs root redirects to /install/,
which loses the encryption context the sentence promises. Point the
per-user secret and database encryption note at the canonical
docs.termix.site/features/authentication/security/ page instead.
Applied across all README locales.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>
Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>

* fix: use i18n for host status tooltip labels (#1403)

* chore: sync Crowdin translations

* chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325)

Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg).


Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0)

Updates `js-yaml` from 5.2.3 to 5.3.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0)

Updates `pg` from 8.22.0 to 8.23.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg)

---
updated-dependencies:
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.120.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: js-yaml
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: pg
  dependency-version: 8.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323)

Bumps the dev-minor-updates group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` |
| [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` |
| [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` |
| [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` |
| [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` |



Updates `@codemirror/commands` from 6.10.4 to 6.11.0
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@types/node` from 26.1.2 to 26.2.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

Updates `electron` from 43.2.0 to 43.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1)

Updates `globals` from 17.9.0 to 17.11.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0)

Updates `i18next` from 26.3.6 to 26.4.0
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0)

Updates `lucide-react` from 1.28.0 to 1.33.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react)

Updates `react-hook-form` from 7.84.0 to 7.85.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0)

Updates `react-pdf` from 10.4.1 to 10.5.0
- [Release notes](https://github.com/wojtekmaj/react-pdf/releases)
- [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf)

Updates `typescript-eslint` from 8.66.0 to 8.67.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@types/node"
  dependency-version: 26.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 43.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: globals
  dependency-version: 17.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: i18next
  dependency-version: 26.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.33.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.85.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-pdf
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.67.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: sync Crowdin translations

* Update redirect-issues workflow configuration

Updated the workflow to change the runner and modify the issue response message.

* chore: sync Crowdin translations

* fix: use i18n for host status tooltip labels (#1265)

* fix: add missing hosts.status.* locale keys (fixes #1265)

* fix: add hosts.status.* translation keys for i18n tooltip

The buildStatusTooltip function calls t("hosts.status.available"), t("hosts.status.reachable"), t("hosts.status.offline"), and t("hosts.status.monitoringDisabled"), but the locale file only had "status": "Status" as a flat string.

Replaced with a status object containing all four keys plus a "label" key preserving the original "Status" string.

* fix: restore final newline in en.json

Requested by ZacharyZcR in review feedback.

* test: assert translated labels in buildStatusTooltip

Per review feedback from ZacharyZcR: add focused tests that exercise
buildStatusTooltip with a translator and assert the rendered labels
rather than key paths. Covers all three status values, monitoring
disabled, protocol list, and the no-key-path regression guard.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>

* fix(workspaces): fall back when randomUUID is unavailable (#1397)

* fix(terminal): preserve macOS Alt digit characters (#1398)

* fix(ssh): verify resolved server host identity (#1419)

* fix: add principals to Termix ID certificates (#1421)

* chore: sync Crowdin translations

* chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325)

Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg).


Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0)

Updates `js-yaml` from 5.2.3 to 5.3.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0)

Updates `pg` from 8.22.0 to 8.23.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg)

---
updated-dependencies:
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.120.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: js-yaml
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: pg
  dependency-version: 8.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323)

Bumps the dev-minor-updates group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` |
| [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` |
| [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` |
| [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` |
| [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` |



Updates `@codemirror/commands` from 6.10.4 to 6.11.0
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@types/node` from 26.1.2 to 26.2.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

Updates `electron` from 43.2.0 to 43.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1)

Updates `globals` from 17.9.0 to 17.11.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0)

Updates `i18next` from 26.3.6 to 26.4.0
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0)

Updates `lucide-react` from 1.28.0 to 1.33.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react)

Updates `react-hook-form` from 7.84.0 to 7.85.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0)

Updates `react-pdf` from 10.4.1 to 10.5.0
- [Release notes](https://github.com/wojtekmaj/react-pdf/releases)
- [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf)

Updates `typescript-eslint` from 8.66.0 to 8.67.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@types/node"
  dependency-version: 26.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 43.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: globals
  dependency-version: 17.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: i18next
  dependency-version: 26.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.33.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.85.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-pdf
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.67.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: sync Crowdin translations

* Update redirect-issues workflow configuration

Updated the workflow to change the runner and modify the issue response message.

* chore: sync Crowdin translations

* Add Hetzner logo and referral link to README

Added Hetzner logo with a referral link to README.

* Fix Hetzner logo URL in README.md

* chore: pull sponsor logos from the docs site

* fix: add principals to Termix ID certificates

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>

* fix(deps): resolve transitive security advisories (#1412)

* chore: sync Crowdin translations

* chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325)

Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg).


Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0)

Updates `js-yaml` from 5.2.3 to 5.3.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0)

Updates `pg` from 8.22.0 to 8.23.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg)

---
updated-dependencies:
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.120.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: js-yaml
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: pg
  dependency-version: 8.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323)

Bumps the dev-minor-updates group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` |
| [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` |
| [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` |
| [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` |
| [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` |



Updates `@codemirror/commands` from 6.10.4 to 6.11.0
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@types/node` from 26.1.2 to 26.2.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

Updates `electron` from 43.2.0 to 43.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1)

Updates `globals` from 17.9.0 to 17.11.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0)

Updates `i18next` from 26.3.6 to 26.4.0
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0)

Updates `lucide-react` from 1.28.0 to 1.33.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react)

Updates `react-hook-form` from 7.84.0 to 7.85.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0)

Updates `react-pdf` from 10.4.1 to 10.5.0
- [Release notes](https://github.com/wojtekmaj/react-pdf/releases)
- [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf)

Updates `typescript-eslint` from 8.66.0 to 8.67.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@types/node"
  dependency-version: 26.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 43.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: globals
  dependency-version: 17.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: i18next
  dependency-version: 26.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.33.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.85.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-pdf
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.67.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: sync Crowdin translations

* Update redirect-issues workflow configuration

Updated the workflow to change the runner and modify the issue response message.

* chore: sync Crowdin translations

* Add Hetzner logo and referral link to README

Added Hetzner logo with a referral link to README.

* Fix Hetzner logo URL in README.md

* chore: pull sponsor logos from the docs site

* fix(deps): resolve transitive security advisories

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>

* fix(sync): map nested host parent references (#1418)

* fix(metrics): surface SSH host key changes (#1404)

* fix(guacamole): coalesce VNC wheel floods and label meta keys by device (#1385)

High-latency proxies like Cloudflare queue guacamole-common-js scroll
clicks so the desktop keeps crawling after the user stops. Cap in-flight
wheel buttons, and show Super/Cmd in the VNC toolbar on non-Windows clients.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>

* fix(file-manager): keep downloaded files inside the selected local folder

Remote file names were turned into local destinations by splitting the
relative remote path on "/" and concatenating each name with the platform
separator. A POSIX file name may contain "\", ":" or end in a dot, so on
Windows a remote "..\outside.txt" downloaded into C:\Downloads\selected was
normalised to C:\Downloads\outside.txt - outside the folder the user picked,
even with overwrite disabled. The main process only normalised destPath and
never checked it against the selected root.

Two independent layers now enforce containment:

Renderer (local-transfer-utils.ts)
- `assertSafeLocalComponent(name, separator)` validates each remote path
  component for the destination platform: never empty, "." or "..", never
  "/" or NUL; on Windows (separator "\") additionally no "\ : * ? " < > |",
  no control characters, no trailing dot/space, no reserved device names
  (CON, NUL, COM1...). Backslashes stay legal on macOS/Linux, where they are
  ordinary file-name characters and the result remains inside the folder.
- `buildLocalDestination(localDir, relativePath, separator)` joins the
  validated components and asserts the result is strictly under localDir
  (case-insensitive on Windows).
- useLocalTransfers builds every file and directory destination through it.
  Items that fail are skipped before any filesystem call and reported
  ("Skipped N item(s) whose names cannot be used on this computer").

Main process (electron/local-files.cjs)
- `assertWithinRoot(rootPath, candidate, pathImpl)` resolves + normalises
  both paths and refuses anything that is the root itself, escapes it
  (".." after normalisation), is absolute relative to it (another drive,
  UNC) or contains empty/".." segments. `pathImpl` is injectable so the
  Windows rules run in tests on any OS.
- downloadToLocal requires `rootPath` (the selected folder) and checks the
  destination before the request is made or any file is created; the
  ensure-dir handler applies the same check when a root is passed (used for
  the directory skeleton of downloaded trees).
- LocalDownloadRequest / downloadSessionFileToLocal / ensureLocalDirectory
  carry the root.

Tests
- Renderer: ordinary nested folders on Windows; backslash traversal in a
  POSIX name; absolute, drive-qualified and UNC names; reserved names,
  trailing dots/spaces, control chars; POSIX traversal rejected while a
  POSIX-legal backslash name is kept inside the folder.
- Main process (path.win32): nested destinations accepted incl. case
  differences; "selected\..\outside.txt" refused; other drive / UNC /
  sibling folder refused; missing root refused; end-to-end handler test that
  a POSIX "../outside.txt" download and an escaping ensure-dir are refused
  before any network traffic or disk write.

* feat(file-manager): right-click context menu for the local pane

Mirrors the remote grid's menu for the user's own disk. On an entry (or
the current multi-selection): Open / Open folder, Upload to server,
Reveal in Finder/Explorer, Rename (inline, F2), Copy Path, Move to Trash
(confirmation toast, Del). On the background: New Folder, New File,
Reveal, Show/Hide hidden files, Refresh (F5). Enter opens, Cmd/Ctrl+A
selects all, Escape clears the selection.

Deletion goes through shell.trashItem so it lands in the OS Trash and is
recoverable; rename and create refuse names containing path separators
and never overwrite an existing entry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* feat(file-manager): resizable list-view columns in both panes

Drag the boundary at the left edge of a column header (Modified, Owner,
Size, Permissions on the remote grid; Modified, Size, Kind in the local
pane) to change its width; the Name column takes whatever is left.
Double-click a handle to reset that column. Widths are remembered per
pane in localStorage. Finishing a drag over a sortable header no longer
toggles the sort.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* feat(file-manager): pinned ".." parent entry in both panes

Both the remote grid (list, grid and empty-folder states) and the local
pane show a Termius-style ".." row pinned above the entries whenever the
current folder has a parent. Double-clicking it goes up one level. It is
also a drop target: local files dropped on it upload into the parent
folder, remote rows dragged onto it move there, and remote items dropped
on the local pane's ".." download into the parent folder.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* feat(file-manager): show/hide list-view columns from the header

Right-click a list-view header (remote grid or local pane) to open a
Columns menu and tick/untick Modified, Owner, Size, Permissions (remote)
or Modified, Size, Kind (local). Hidden columns leave the grid template
entirely so the Name column gets the space back; at least one optional
column always stays on. The choice is remembered per pane alongside the
column widths.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* feat(file-manager): sidebar toggle works on desktop too

The toolbar's sidebar button now shows/hides the directories panel on
desktop (persisted), while below md it still opens the mobile overlay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* feat(file-manager): resizable directories sidebar

The Trash/Directories sidebar can now be resized by dragging its right
edge (160px minimum, up to 40% of the row); double-click the handle to
restore the default 224px. The width is remembered. The same handle and
persisted-width hook now also drive the local pane divider, replacing the
inline implementation.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W

* fix(metrics): support macOS/WIN hosts in stats collection (#1430)

* fix(metrics): support macOS hosts in stats collection

Host metrics collectors only ever ran Linux commands (/proc/*, ip,
GNU df flags), so any macOS host always reported 0%/null for
cpu, memory, uptime, network and disk. Detect the host platform
once per poll and use vm_stat, sysctl, top, ifconfig and netstat
on Darwin hosts instead.

* fix(metrics): support Windows hosts in stats collection

RDP/VNC hosts running Windows hit the same problem as macOS did:
no /proc, no BSD tools, not even uname. Route CPU, memory, uptime,
network and disk through PowerShell (WMI/CIM) when the host is
detected as Windows, using -EncodedCommand so there's no cmd.exe
quoting to fight with.

* fix(metrics): use real macOS df/mount for disk collection

BSD df's -T flag filters by filesystem type instead of printing one
like GNU df does, so the previous macOS disk path was still running
a GNU-only command and coming back empty. Now uses df -Pk plus mount
output to build the filesystem type/percent list, filtering out the
noisy APFS system volumes and devfs/autofs mounts. Verified on an
M4 MacBook running the latest macOS - disk usage now reports correctly.

* feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop) (#1413)

Integrate the reviewed change and its maintainer fixes into dev-2.8.0.

Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs.

* fix(terminal): persist Ctrl+/- font zoom so it survives option refreshes (#1399)

Integrate the reviewed change and its maintainer fixes into dev-2.8.0.

Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs.

* Fix macOS terminal packaging and keyboard shortcuts. (#1417)

Integrate the reviewed change and its maintainer fixes into dev-2.8.0.

Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs.

* fix(auth): skip TOTP only after verified WebAuthn user verification (#1420)

Integrate the reviewed change and its maintainer fixes into dev-2.8.0.

Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs.

* feat(hosts): add per-host Web Endpoints (direct or SSH-tunnelled web UIs) (#1416)

* test: provide an in-memory localStorage for the vitest environment

jsdom in this project ships without a localStorage global, so every suite
that touched storage threw "Cannot read properties of undefined" during
setup and failed wholesale -- 119 tests across 15 files, none of them
actual product defects.

Node only supplies localStorage with --localstorage-file, which persists to
disk and is shared across test files. A per-process in-memory Storage is
what tests want, so define one (plus sessionStorage) when the global is
absent, alongside the existing matchMedia shim.

Full suite goes from 15 failed files / 119 failed tests to 400 files and
2888 tests passing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fdjjsdaz6aFMyJr4h3Y6qj

* feat(web-endpoints): add endpoint types and URL resolution

First step of per-host Web Endpoints: a host declares web UIs it serves and
opens them either directly at the host's address or through an SSH forward
Termix establishes on demand.

This commit is pure logic with no I/O, so it needs no mocks to test.

resolveWebEndpointUrl expects an already-normalized path -- normalization is
the storage boundary's job (a later commit), and duplicating it here would
invite the two copies to drift.

separatedTunnelHost is the one part that is a security control rather than a
convenience. Cookies are keyed by host and ignore the port, and SameSite
computes "site" as scheme + registrable domain -- also ignoring the port. A
forward reached at the host string serving Termix is therefore same-site with
Termix, which leaks the session both ways: the framed service receives the jwt
cookie, and a Set-Cookie it returns lands in the jar Termix's own API calls
read from. So a tunnel URL resolves to a different loopback spelling than the
page's, and refuses outright when no alias exists. Only loopback literals
qualify -- a same-registrable-domain alias could still answer Set-Cookie with
a Domain attribute that reaches Termix.

The cookie-separation tests were verified to fail against a resolver that
returns the page host (4 failures), so they cannot pass vacuously.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(web-endpoints): validate and normalize endpoint config

normalizeWebEndpoints is the enforcement point for values that reach an href
and an iframe src, so the editor's constraints are UX rather than security.
It drops any row it refuses instead of rejecting the whole host -- one bad
endpoint must not make a host unsaveable or unlistable.

Paths are checked for C0 controls and DEL by codepoint rather than by regex
character class: "\t//evil.example" defeats a startsWith("//") guard, because
the browser strips the control character and then follows the authority.

bindHost lands both in a TCP listener and in a URL authority, so it is
restricted to a bare host literal -- nothing carrying a scheme, port, path or
credentials survives. bindHost and localPort are ignored on a direct endpoint,
which never creates a forward.

parseWebUiConfig never throws. A malformed stored value yields an empty
endpoint list, so a half-written config cannot take out the whole host
listing -- which is what dockerConfig's bare JSON.parse does today.

The editor validator is a second implementation in a layer that cannot import
backend route modules. Its accompanying test runs BOTH implementations over
the same path and port samples, because drift here is invisible in the worst
way: the editor accepts a row, the normalizer silently drops it, and the
endpoint disappears on reload with no error. That agreement test was verified
to fail (4 cases) when the editor's control-character check is removed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(db): migrate the shared_credential_secrets foreign key rename

Running `npm run schema:migrations` on an UNCHANGED schema emits these, so
they are pre-existing drift between schema.ts and drizzle/, not something this
branch introduced. Landing them alone, before the web-endpoint columns, so the
feature's own migration is reviewable without an unrelated table rebuild
sitting in the middle of it.

Both forms are a foreign-key constraint rename only. Postgres drops and
re-adds the constraint under a shorter name. SQLite has no ALTER for that, so
drizzle emits the standard table rebuild -- verified data-preserving: CREATE
lists 14 columns, INSERT...SELECT copies the same 14 in the same order, and
both indexes are recreated.

The SQLite file is in practice dead code: runRemoteMigrations throws for
sqlite, which builds its schema from db/index.ts instead. It is kept rather
than hand-trimmed because drizzle derives the meta snapshot from schema.ts
regardless, so trimming the .sql while the snapshot advances would make the
drift permanently invisible -- no future `generate` would re-emit it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(db): add enable_web_ui and web_ui_config columns

Two columns on ssh_data mirroring the Docker pair. No show_web_ui_in_sidebar:
every existing showXInSidebar column is vestigial -- they appear only in
defaults, the export payload and tests, and gate no rendering -- so a fourth
dead column plus a migration buys nothing.

web_ui_config stores an object rather than a bare array so host-level web
settings can be added later without a second migration.

The column has to be declared in FOUR places, not one. SQLite never runs the
drizzle migrations at all (runRemoteMigrations throws for sqlite), so the live
default-dialect schema comes from hand-written DDL:

  1. db/schema.ts, then the two generated dialect schemas and the migrations
  2. db/index.ts CREATE TABLE -- fresh databases
  3. db/index.ts addColumnIfNotExists -- existing databases
  4. database.ts CREATE TABLE and its positional INSERT -- encrypted export

Missing 2 or 3 breaks every host write on the default dialect while the
migration file sits there looking correct.

Two guards, both watched failing first. bootstrap-matches-schema-columns boots
a real database and compares PRAGMA table_info against the drizzle definition
for every table -- it reported ssh_data.enable_web_ui and ssh_data.web_ui_config
missing before item 2/3 landed. A grep-based guard could not: db/index.ts
names columns as snake_case strings, never the camelCase the schema uses.

export-ddl-matches-schema-columns covers database.ts, which no booted database
reaches. It caught a real defect while being written: the two new columns went
into the INSERT list but the VALUES list still held 53 placeholders for 55
columns. Being positional, that shifts every later value by one. The
placeholder-count assertion is now permanent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(hosts): thread web endpoint config through host read and write paths

A host field has to be enumerated by hand in nine places here, and "added a
column, missed one update path" is this codebase's most repeated bug -- during
the first attempt at this feature a field was missed at one of these points
six separate times, each surfacing as a different mystery: endpoints that
saved but never appeared, config that vanished on reload.

Backend: host-normalizers (input type, CONNECT_LEVEL_FIELDS, boolean
normalization, parse block), host.ts (create, update, both read paths,
quick-connect defaults), host-bulk-routes (bulk update, import, reset).
Renderer: host-export-payload, HostManagerData's sshHostToHost, tabUtils'
hostToSSHHost, HostEditorData's form seed and payload builder. The three
renderer mappers copy field by field, so an unlisted field is silently
dropped -- which is how endpoints saved correctly and never appeared.

webUiConfig is parsed with parseWebUiConfig rather than a bare JSON.parse.
dockerConfig on the adjacent line uses a bare one, so a single malformed value
takes out the whole host listing; that is a bug to avoid copying, not a
convention to follow.

All three write paths now clear webUiConfig when the feature is disabled. They
disagreed before, and the export payload ships the config unconditionally -- so
a host disabled without clearing still exported its endpoint list (internal
hostnames, ports, paths) while the UI read as off, and re-enabling resurrected
stale endpoints.

webUiConfig is shared with connect-level recipients, unlike dockerConfig. A
connect-level recipient is already authorized to open these tunnels, so
withholding the config only breaks discovery while the flag advertises the
feature. Docker's precedent does not transfer: its tab works without its
config, whereas a web endpoint IS its config.

The enumeration guard asserts every one of the nine files mentions the web
endpoint field beside its Docker counterpart, and checks the Docker anchor is
present too so it cannot pass vacuously if a file is restructured.

The clear-on-disable assertion was rewritten after the first version passed
with the guard deleted -- a loose regex matched unrelated sites. Both halves
are now anchored on exact text and were watched failing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(tunnel): report the real bound port, support idle close, reserve web:

Three changes the web endpoint open route depends on, plus the name
reservation that makes the scheme safe.

Real bound port. Under sourcePort 0 the kernel assigns the port, but the
runtime recorded the requested value -- so it advertised 0 and any caller
reusing it failed. It now records tcpServer.address().port.

Idle close, behind the new tunnelConfig.idleTimeoutMs. Web endpoint tunnels
are opened on demand and must not outlive their use. The timer lives inside
establishDirectTunnel because the socket set is only visible from that
closure, polls at min(30s, timeout) so "empty for N" means roughly that rather
than "empty at the instant of one N-spaced tick", and unrefs so it cannot hold
the process open. It calls cleanupTunnelResources rather than close(): close()
stops the listener but leaves the entry in activeTunnelRuntimes, so the open
route would keep handing out a port nothing is listening on.

Reserved names skip retry. handleDisconnect returns early for a "web:" name
after a forced cleanup. maxRetries: 0 would NOT achieve this -- the retry path
reads `maxRetries || 3`, so 0 falls through to 3. The cleanup is forced
because cleanupTunnelResources no-ops while tunnelConnecting holds the name,
and a web tunnel has no retry pass to self-heal a leaked runtime.

That early return carries an identity guard, which is the subtle one.
sourceClient.end() only STARTS an async teardown, so the SSH "close" event
lands after a reopen may already have registered a NEW runtime under the same
name. Acting by name alone would tear down the successor rather than the stale
tunnel -- surfacing as a 200 with a good port followed by a silent connection
reset and no error anywhere. handleDisconnect now takes the closing Client and
returns early when the registered runtime belongs to someone else. The idle
timer carries the same guard for the same reason.

/ssh/tunnel/connect now rejects a user-supplied "web:" name with 400.
validateTunnelConfig is no defence here: it returns true unconditionally for
any name that is not the legacy 6-part format, so an authenticated user could
otherwise create a real retry-configured tunnel that collides with a live web
endpoint forward and silently loses its own reconnect behaviour.

The manager tests run against a real TCP listener and real timers -- mixing
fake timers with real socket I/O is a known route to a hanging test. Both were
watched failing: reverting the bound port fails the port test, and swapping
cleanupTunnelResources for close() fails the idle test, which asserts the
ENTRY is gone rather than merely that the listener stopped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(tunnel): add the web endpoint open route

POST /ssh/tunnel/web-endpoint/open { hostId, endpointId } -> { port }.

The host is resolved through the user-scoped resolveHostById, so an
authenticated user cannot obtain a forward to a host id they do not own. The
endpoint is re-normalized out of storage rather than trusted: the stored value
predates any later tightening of the rules, and this is what a forward gets
built from. An enabled flag is required as well as a present endpoint -- a
bulk update that sends only { webUiConfig } can leave a configured endpoint on
a host whose UI reads as off everywhere.

Not gated to the desktop. The forward binds wherever this backend runs, as the
server tunnels feature does, and the endpoint's own bindHost decides whether
that is reachable from a browser.

endpointHost: "127.0.0.1" is load-bearing, not cosmetic. connectSSHTunnel
picks its strategy via shouldEstablishDirectTunnel -> isSingleHostTunnel, which
keys on endpointHost -- setting only targetHost selects a different path and
the forward never binds locally.

connectSSHTunnel never rejects, and its promise resolves right after
conn.connect() -- long before the SSH "ready" event populates
activeTunnelRuntimes. Awaited is not connected, so waitForTunnelSettled polls
the maps the manager already exports. Polling rather than adding a
promise-returning variant: every existing caller is fire-and-forget by design,
and changing that contract for one new caller is the larger blast radius.

A probe forwardOut runs before returning 200. Without it the route succeeds the
moment listen() does, and forwardOut is only attempted per inbound socket where
failure is swallowed -- so the likeliest real error, nothing listening on the
endpoint's port, reached the user as a blank frame and no message.

Staleness is validated at open, never on save: host save lives in the database
service and the runtimes live in the tunnel service, with no push between them.
On reuse the route compares a fingerprint covering the endpoint's target AND
the host's SSH identity, and reopens when it differs. An absent fingerprint
means reuse, not staleness -- a reserved-prefixed runtime can only have been
created here. Deletion, disabling and host removal then need no handling:
nothing reopens the tunnel, so it idles out.

Also closes an authorization gap this feature would otherwise have created.
/ssh/tunnel/disconnect and /ssh/tunnel/cancel checked ownership only inside
`if (config && config.sourceHostId)`, and web tunnels are deliberately absent
from tunnelConfigs -- so the check never ran for them. Host ids are small
sequential integers and endpoint ids are client-supplied, so the name is
guessable and any authenticated user could force-close another user's tunnel.
authorizeTunnelAction recovers the host id from the name and fails closed when
it cannot; the tests were watched failing against the old behaviour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(hosts): add the web endpoint client and per-origin certificate allowance

The client posts a path relative to tunnelApi's base, which already includes
/ssh -- a leading "/ssh" here resolves to /ssh/ssh/... and 404s on every call.
The test asserts that on the captured runtime argument rather than by scanning
source, so quoting style and indirection cannot fool it.

Backend error messages are preserved rather than collapsed. 502 is this
route's likeliest real failure and carries the actionable cause -- SSH auth
rejected, host unreachable, nothing listening on the target port -- and
handleApiError would replace all three with "Server error occurred". It stays
as the fallback for bodies that carry no string reason, so a body shaped
{ error: <object> } cannot reach the user as "[object Object]".

openWebEndpointExternally applies the same refusal gate as the embedded tab.
Opening in the real browser is not the safer path: the cookie jar is the
browser's either way, so a tunnel URL on the page's own host string leaks the
session exactly as a frame would. The refusal happens before the forward is
opened -- binding the port and then declining to navigate would be no
protection.

Certificate allowance covers the one case Electron's existing handling misses:
direct access to a HOSTNAME over https. isPrivateNetworkHost matches IP
literals only and sshData.ip has no IP validation, so https://nas.local:8006
fails the check and renders blank inside an iframe with no click-through --
Chromium offers no proceed option for subframes.

Three properties of that allowance are deliberate and now pinned by tests,
because each would otherwise be undone by a reasonable-looking simplification:

  - it is NOT wired into isInvalidCertificateAllowedForUrl, which also governs
    this process's own outbound TLS via getTlsVerificationOptions;
  - it is https-only, in both the check and the IPC handler, since a non-TLS
    origin in a TLS-error allowlist is meaningless and file:/ftp: must never
    be storable; and
  - entries carry a five-minute TTL refreshed on each registration. Main has
    no host-database access and cannot verify the renderer's claim that an
    origin is a configured endpoint, so the residual risk has to be a
    momentary window rather than one lasting until the app restarts.

The handler stores the parsed origin, never the caller's string, so a path or
wildcard cannot widen the allowance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(hosts): add the Web UI editor tab

Mounted as a Web UI sub-tab inside the SSH group, beside Docker, Tunnels,
Files and Host Metrics, and laid out as two SectionCards following the tunnels
editor: settings first, then the list it governs.

There is a deliberate asymmetry with the sidebar here. The sidebar entry will
appear on enableWebUi alone, because a direct endpoint needs no SSH -- but Web
UI is an SSH sub-tab, so a host with SSH disabled cannot configure endpoints at
all. That is the accepted behaviour and both halves are pinned by tests, so
neither gets "fixed" into agreement later.

tunnelAvailable is enableSsh && originIsLocal, resolved inside HostWebUiTab
rather than in HostEditor.tsx, which is already ~2600 lines. It is NOT gated on
isElectron(): the forward binds wherever the backend runs, exactly as the
server tunnels feature does. resolveConnectionOrigin is called with
connectionType "ssh" deliberately -- a tunnel endpoint always rides SSH, and
"ssh" avoids the guacamole special case that forces "remote" for
RDP/VNC/Telnet.

Three input details that each prevent a silent data loss:

  - the id generator falls back off crypto.randomUUID, which is undefined
    outside a secure context -- a plain-http web deployment is a first-class
    target for direct+external and would otherwise throw on "Add endpoint";
  - a new row gets a de-duplicated label, since labels are what identify an
    endpoint in the sidebar picker; and
  - the port field commits only a value the normalizer would keep. Number("")
    is 0, which the normalizer rejects, so clearing the field would otherwise
    write an endpoint that vanishes on save with no error.

The tunnel fields carry three warnings: a non-loopback bind exposes the
target's web UI unauthenticated to anyone who can reach the port; a loopback
bind on a remote backend cannot be reached from a browser at all; and a tunnel
reached at Termix's own hostname would hand the tunnelled service this
session. All three are shown while configuring rather than only when the tab
fails to load.

The unavailable-tunnel reason is shown whenever tunnelling is unavailable, not
only once a row asks for it -- a disabled dropdown option with no stated reason
reads as the control being broken.

Copy is reused verbatim from the previous iteration's reviewed strings rather
than reworded.

One test was written and then removed rather than kept: its name promised that
switching to tunnel access clears ignoreCert, but Radix Select needs pointer
APIs jsdom lacks, so the body only asserted the control existed. The clearing
is covered where it is enforced, in the normalizer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(hosts): open web endpoints from the sidebar and in a tab

One sidebar entry per host, never one per endpoint: a host may declare up to
16, and a row of 16 identical globes is unusable. With a single endpoint the
entry wears its label and acts directly; with several it carries no endpointId
and the click opens a picker -- a DropdownMenu in the tray, a DropdownMenuSub
in the Connect submenu.

The entry is gated on enableWebUi ALONE, unlike every neighbouring action,
which requires enableSsh. A direct endpoint needs no SSH; SSH matters only
per-endpoint, for tunnel access, which the open route enforces.

openTab gains a fourth optional parameter rather than overloading `restore`,
which means something else. What was actually broken for two endpoints on one
host was the LABEL -- tab ids are already `${name}-${type}-${Date.now()}`, so
they never collided. All existing call sites keep working.

The tab is passed the endpoint ID, not the endpoint object, so one deleted
while its tab is open renders a plain message instead of throwing.

Reload re-resolves and REMOUNTS. A direct endpoint's URL never changes and a
live tunnel returns the same port on every open, so setUrl(resolved) would be
a same-value setState that React bails out of, leaving the frame untouched --
Reload would silently do nothing in the two most common cases. A generation
counter folded into the iframe key fixes that and doubles as the staleness
guard for two resolutions landing out of order. The test captures the DOM node
before and after, and was watched failing against a url-only key.

PERSISTENT_TAB_TYPES is hoisted to module scope and exported so it can be
asserted on -- it was a local const inside the component and therefore
untestable. web-endpoint is deliberately excluded: an idle tunnel re-binds a
fresh kernel-assigned port, so a restored tab could never hold a valid URL.

Two notes on verification. `tsc -p tsconfig.json` passes vacuously in this
repo -- tsconfig.json is a solution file with project references and does
nothing without -b -- so `npm run type-check` (tsc -b --force) is the real
check; it caught two insertions that had landed in the wrong function. And the
one full-suite failure seen along the way was vault-signer-core, which passes
in isolation and on re-run, is untouched by this branch, and is a flake under
parallel load.

Lint: 0 errors, 102 warnings, identical to the baseline on a clean tree.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(tunnel): register the web endpoint route under its /ssh path

Every route in routes.ts registers the full "/ssh/tunnel/..." path -- nginx
proxies /ssh through with the path intact -- and the client resolves
"/tunnel/web-endpoint/open" against a baseURL that already ends in /ssh. The
unprefixed registration therefore 404'd every call.

No handler unit test could catch this: they call handleWebEndpointOpen
directly and never touch registration. It surfaced only on opening a real
tunnel against a deployed build, which is why that step exists.

Added a registration test that captures the paths passed to app.post, so the
invariant is checked without needing a server.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(hosts): apply session-cookie isolation to direct web endpoints

The cookie guard only covered tunnel access. `unreachableTunnelReason`
returned null for every `access: direct` endpoint, so WebEndpointTab framed
the host's own address unconditionally. With Termix served at
https://termix.example/ and a direct endpoint at https://termix.example:8443/,
the browser attaches Termix's `jwt` to the framed request -- cookies are keyed
by host and ignore the port -- and a `Set-Cookie` from that service lands in
the jar both auth middlewares read before the Authorization header.

Renames the helper to `webEndpointRefusalReason` so its scope is no longer
tunnel-only, and gives it the endpoint's target host. A direct endpoint is now
refused in a browser when that host shares Termix's cookie site, checked
BEFORE any navigation in both open paths (embedded tab and external window) --
refusing after framing would leak on the first request.

`sharesCookieSiteWithPage` treats an equal host as same-site (the jwt is set
host-only, so the port is irrelevant) and also a parent/sub domain, which a
`Set-Cookie: Domain=` from the target crosses. The suffix test is anchored on a
dot boundary so `eviltermix.example` does not pass as `termix.example`. A
precise eTLD+1 test would also catch sibling subdomains, but needs a public
suffix list this app does not bundle.

The desktop stays exempt: its session is Bearer-only with no `jwt` in the jar.

Also drops "or change this endpoint to Direct" from the tunnel refusal copy,
which pointed at the path that had this same leak.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>

* fix(tunnel): preserve local status when remote names collide (#1431)

* fix(desktop): honor remote sync certificate setting (#1432)

* fix(file-manager): interpolate preview download filename (#1433)

* fix(automations): dispatch SSH login events to triggers (#1434)

* fix(hosts): preserve imported settings and remap jump hosts (#1435)

* fix(hosts): preserve terminal switches across JSON transfer

* fix(hosts): remap imported jump-host dependencies

* fix(ssh): preserve agent framing after unsupported extensions (#1436)

* fix(guacamole): return tokens before awaiting the client handshake (#1437)

* fix(sidebar): unmount the host tree while its panel is hidden (#1438)

* fix(terminal): leave macOS Option characters enabled by default (#1439)

* fix(dashboard): open the enabled remote desktop protocol (#1440)

* fix(version): preserve local version when update checks fail (#1441)

* fix(sftp): create uploaded directories without shell access (#1442)

* fix(desktop): honor explicit GPU acceleration opt-out (#1443)

* fix(desktop): exclude remote-only host IDs from local tab persistence (#1444)

* Enhance SFTP and terminal flows, stabilize desktop sync (#1377)

* feat: add electron sftp c2s and terminal ai flows

* fix: stabilize desktop sync and c2s tunnels

* Improve remote tunnels and SFTP transfer feedback

* chore: sync Crowdin translations

* chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325)

Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg).


Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0)

Updates `js-yaml` from 5.2.3 to 5.3.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0)

Updates `pg` from 8.22.0 to 8.23.0
- [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md)
- [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg)

---
updated-dependencies:
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.120.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: js-yaml
  dependency-version: 5.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
- dependency-name: pg
  dependency-version: 8.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: prod-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323)

Bumps the dev-minor-updates group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` |
| [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` |
| [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` |
| [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` |
| [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` |
| [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` |



Updates `@codemirror/commands` from 6.10.4 to 6.11.0
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@types/node` from 26.1.2 to 26.2.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react)

Updates `electron` from 43.2.0 to 43.4.1
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1)

Updates `globals` from 17.9.0 to 17.11.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0)

Updates `i18next` from 26.3.6 to 26.4.0
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0)

Updates `lucide-react` from 1.28.0 to 1.33.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react)

Updates `react-hook-form` from 7.84.0 to 7.85.0
- [Release notes](https://github.com/react-hook-form/react-hook-form/releases)
- [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md)
- [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0)

Updates `react-pdf` from 10.4.1 to 10.5.0
- [Release notes](https://github.com/wojtekmaj/react-pdf/releases)
- [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf)

Updates `typescript-eslint` from 8.66.0 to 8.67.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@types/node"
  dependency-version: 26.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: electron
  dependency-version: 43.4.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: globals
  dependency-version: 17.11.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: i18next
  dependency-version: 26.4.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: lucide-react
  dependency-version: 1.33.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-hook-form
  dependency-version: 7.85.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: react-pdf
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
- dependency-name: typescript-eslint
  dependency-version: 8.67.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore: sync Crowdin translations

* Update redirect-issues workflow configuration

Updated the workflow to change the runner and modify the issue response message.

* test(sftp): verify local collection limit boundaries

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: LukeGus <bugattiguy527@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>

* chore: increment ver

* fix: allow any origin by default when CORS_ALLOWED_ORIGINS is unset

* feat(file-manager): parallel local transfers (#1446)

Uploads from the Local pane (and downloads to it) ran strictly one file
after another. Batches of many small files were bound by per-file latency
rather than bandwidth.

- `runWithConcurrency(items, limit, worker, shouldStop)`: a bounded worker
  pool that dispatches in order, keeps at most `limit` transfers in flight,
  and stops dispatching once cancelled while letting in-flight items
  finish. Worker errors are handled by the worker (one failure never aborts
  the batch).
- useLocalTransfers: both directions go through the pool. Remote / local
  directory skeletons are still created up front, so file order does not
  matter. The batch runner now tracks a set of in-flight transfer ids
  (Cancel cancels all of them), sums bytes across in-flight transfers plus
  settled ones for the progress bar / speed, and shows how many files are
  moving at once.
- New preference "Simultaneous File Transfers" (1-8, default 4) in the
  profile settings, stored in localStorage
  (`termix:file-manager:transfer-concurrency`) and part of the storage
  snapshot. 1 restores the previous sequential behaviour; the hint suggests
  lowering it for servers that limit SFTP channels.
- Remote directories are created with the now-idempotent mkdir (#1442)
  without swallowing its errors, so a real failure stops the batch up
  front instead of surfacing as N per-file failures. When files do fail,
  the summary toast carries the first underlying reason (e.g. the
  backend's 401 message) instead of a bare "Upload failed".
- Tests: pool never exceeds the limit and drains everything, stops on
  cancel, tolerates a failing item, handles empty input; preference
  clamping and persistence; bridge-level concurrent uploads/downloads
  with a mid-flight cancel leave every other file intact and no partials.

Co-authored-by: Max <maxim@cogitate.ai>

* fix(sftp): complete streamed uploads and stop pre-parsing chunk bodies

* fix(desktop): stop setting Content-Length on local download requests

* fix(file-manager): keep drop overlays in view when the list is scrolled

* fix(file-manager): let remote rows be dropped on the local pane

* fix(desktop): authenticate local transfers with the renderer's token

* chore: update release notes

* chore: remove unused gitlab ci and argocd deploy configs

* chore: remove unused files

* feat: improve loading animation

* fix(shell): stop tab reorder from resetting terminals and tab indicator

Keep the tab-content portal order stable so reordering tabs doesn't
retrigger React's offscreen pass and dispose live terminals. Also stop
the active tab indicator from teleporting during a drag, and fix the
drag ghost's size/border mismatch.

* fix(shell): hand-roll the tab indicator instead of a shared layoutId

Framer's layoutId could measure the wrong tab's rect during a reorder
and land on an inactive tab, or leave a stray line visible mid-drag.
Now it reads the active tab's own DOM rect directly and hides while
dragging.

* fix(hosts): fix right-click menu position and unwanted tray expand

* chore: update release notes

* fix(terminal): stop autosuggestion ghost text overlapping typed input

Position was computed from cursorX before server echo landed, causing
a stale read that overlapped just-typed characters on fast local input.

* chore: update release notes for v2.8.0

* fix(sftp): rebuild transfer tab for web, fix menu offset bug

Drop the electron-only local mode and dead code, i18n all strings,
fix double progress toasts and a wrong pane refresh on move.
Fix context menus rendering offset due to a lingering CSS transform
from the tab-switch animation. Move SFTP next to SSH Tools in the rail.

* fix(file-manager): shrink oversized .. entry, navigate on single click

* fix: make select2 component use rounded corners

* fix: rebuild terminal AI assistant on the real backend

Removes the Electron-only Agent Mode/AI Command Helper that bypassed
admin/user gating and ran commands with no approval step. Replaces it
with a terminal-docked panel on the same gated backend as the AI tab,
adds a per-host toggle (off by default), moves it into the toolbar,
and fixes proposal ordering and run-in-terminal execution.

* fix(file-manager): remove duplicate borders in toolbar view toggle

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: separate registration toggle from step ca settings

* fix: collab room bugs and add room deletion

Accent-colored new room button, fix fullscreen guest view layout and
duplicate view-only badges, self-heal stale presenter state, add
delete room for persistent rooms.

* refactor: move host-identity helpers to hosts core

Used by docker, file-manager, and terminal alike, so it belongs
at the hosts root instead of under terminal/.

* refactor: move host-session-status singleton to hosts core

metrics subscribed to terminal's private online/offline pub-sub
module. Moved to hosts core so both sides depend on a shared
module instead of metrics reaching into terminal. Marked the
subscribe call with PLUGIN-EVENT for the future event bus.

* refactor: split generic automation event notify out of metrics

notifyAutomationInternalEvent was in hosts/metrics/automation-bridge.ts
but is used by tunnel, host routes, user routes, and automations
engine itself, not just metrics. Moved it to hosts/automation-events.ts
so those callers depend on a shared module instead of metrics
internals. Left the metrics-specific notifiers in place.

* feat: add plugin system schema and repositories

Adds plugins, plugin_permission_grants, plugin_registries, and
plugin_install_counts tables plus their repositories. No routes or UI yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat: add runtime rail item and tab component registries for plugins

* feat: support runtime-registered permission groups

Adds register/unregister for plugin permission groups so the RBAC
catalog and validation can grow beyond the static list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat: add plugin-api nginx route and dispatcher stub

* feat: add plugin manifest schema and validator

* chore: update release notes

* chore: update i18n for local/remote file manager

* feat: add toggle to show/hide app rail pin button

* feat(host-metrics): add NVIDIA GPU metrics card (#1452)

* feat(host-metrics): add NVIDIA GPU metrics card

Collect per-GPU utilization, VRAM, temperature, power, fan speed and
the processes using each GPU over SSH with nvidia-smi. The collector
exits immediately when nvidia-smi is missing, so hosts without a GPU
pay almost nothing per poll.

The GPU card is opt-in: it is available from the Add card tray but is
not part of new-host defaults or any UI preset. It shows live
sparklines for utilization and VRAM per GPU.

Adaptive polling now also watches GPU readings and the GPU process
count, so it no longer backs off on hosts where only the GPU is busy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8

* fix(host-metrics): draw sparklines from the first metrics sample

The first sample fetched when the tab connects was shown but never
added to the sparkline history, so every sparkline (CPU, memory, disk,
GPU) stayed empty until the second poll, a full metrics interval later
(about 35 s with the default 30 s interval). Record the first sample
like every later one, so the lines appear as soon as the tab loads.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8

* Fix logical condition for memory percentage calculation

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix: annotate local transfer plan type to fix CI type-check

* fix: move connection toolbar settings to bottom of host editor general tab

* chore: add debug logging for macOS sharp packaging failure

Temporary diagnostic to find which phase drops @img/sharp-darwin-x64
from the packaged app. Revert once root cause is found.

* fix: correct macOS sharp verify script for universal build layout

electron-builder uses mergeASARs: false, so universal builds ship
app-x64.asar.unpacked and app-arm64.asar.unpacked side by side instead
of a single app.asar.unpacked. The verify script only checked the
single-asar path, so it always failed on universal/mas artifacts even
when packaging was correct.

* fix: update sharp verify test fixtures for universal build layout

The test built fake apps using the single app.asar.unpacked layout,
which doesn't match how universal builds are actually packaged now
(app-x64.asar.unpacked / app-arm64.asar.unpacked side by side).

* chore: update readme

* fix: guard against missing rooms array in collab list response

* fix: distinct guac connection log stages, RDP black screen before failure

* fix: proxy /collab routes in nginx configs

* fix: stop tab-switch flash and host metrics/proxmox reconnect

Tab DOM visibility now syncs before paint instead of after, and
switching tabs no longer tears down live metrics connections.

* fix: tab bar flashing, growing, and merged separators

Terminal tabs no longer flash when switching, the enter animation no
longer nudges layout size, and a stray transform on resting tabs no
longer causes the border between tabs to vanish at some zoom levels.

* fix: match select trigger height to inputs in web UI editor

* chore: lint, format, and bump version to 2.8.0

* chore: sync Crowdin translations for 2.8.0

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
Co-authored-by: Angad Singh <7099405+singhangadin@users.noreply.github.com>
Co-authored-by: Angad Singh <angad@singhangad.in>
Co-authored-by: Neo <54811660+neooriginal@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Wali Lambert <98448225+YatoVoid@users.noreply.github.com>
Co-authored-by: Nasif Rahman <44437976+nasif-naseef@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: vietanhtwdk <vietanhtruongwdk@gmail.com>
Co-authored-by: inontz <inontz@icloud.com>
Co-authored-by: inontz <inontz@users.noreply.github.com>
Co-authored-by: Max Serov <133950708+maxser0v@users.noreply.github.com>
Co-authored-by: Max <maxim@cogitate.ai>
Co-authored-by: ssmurfgg04-gif <ssmurfgg04@gmail.com>
Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com>
Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com>
Co-authored-by: slsgzs-cloud <slsgzs@gmail.com>
Co-authored-by: anshtsolanki-sketch <anshtsolanki@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: tcezarl <tomescu.cezar.laurentiu@gmail.com>
Co-authored-by: Anton Priestley <anton@priestley.me>
Co-authored-by: Hakim M <hakimmarsudi@outlook.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Adel Alzubeir <14052842+Adelzu@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
692 files changed
+334737 -5210

No files matched your search

+342 -39
View File
@@ -19,6 +19,7 @@ import {
useRef,
useCallback,
useEffect,
useLayoutEffect,
createRef,
lazy,
Suspense,
@@ -40,6 +41,13 @@ import { useUiPreferencesContext } from "@/contexts/UiPreferencesContext";
import { defaultSizes, SplitView, type RowColSizes } from "@/shell/SplitView";
import { renderTabContent } from "@/shell/tabUtils";
import { TabBar } from "@/shell/TabBar";
import { dispatchCtrlW, isShiftKey } from "@/lib/app-keyboard-shortcuts";
import { parseCustomKeybindings } from "@/api/open-tabs-api";
import { findMatchingKeybinding } from "@/lib/keybinding-match";
import type {
CustomKeybinding,
KeybindingActionType,
} from "@/types/keybindings";
// Shell surfaces that are not needed for first paint.
const CommandPalette = lazy(() =>
@@ -73,6 +81,9 @@ const AlertManager = lazy(() =>
const SshToolsPanel = lazy(() =>
import("@/sidebar/SshToolsPanel").then((m) => ({ default: m.SshToolsPanel })),
);
const CollabPanel = lazy(() =>
import("@/sidebar/CollabPanel").then((m) => ({ default: m.CollabPanel })),
);
const SnippetsPanel = lazy(() =>
import("@/sidebar/SnippetsPanel").then((m) => ({ default: m.SnippetsPanel })),
);
@@ -123,6 +134,11 @@ const CredentialsPanel = lazy(() =>
default: m.CredentialsPanel,
})),
);
const PortForwardingPanel = lazy(() =>
import("@/sidebar/PortForwardingPanel").then((m) => ({
default: m.PortForwardingPanel,
})),
);
const TermixIdPanel = lazy(() =>
import("@/sidebar/TermixIdPanel").then((m) => ({ default: m.TermixIdPanel })),
);
@@ -153,6 +169,7 @@ import type {
} from "@/types/ui-types";
import { applyAccentColor, applyFontSize, PANE_COUNTS } from "@/lib/theme";
import { globalShortcutHandler } from "@/lib/global-shortcut-handler";
import { getTabJumpDigit } from "@/lib/tab-jump-hotkey";
import { useTheme } from "@/components/theme-provider";
import {
getSSHHosts,
@@ -206,12 +223,35 @@ export { tabIcon, renderTabContent } from "@/shell/tabUtils";
// ─── AppShell ────────────────────────────────────────────────────────────────
/**
* Tab types whose open/close is mirrored to the backend's open-tabs record, so
* they survive a reload or reopen on another device.
*
* "web-endpoint" is deliberately ABSENT. The backend closes an idle tunnel
* after ten minutes and re-binds a fresh kernel-assigned port on the next
* open, so a restored web-endpoint tab could never hold a valid URL -- and the
* endpoint may have been edited or deleted meanwhile besides. Restoring one
* would mean re-opening the tunnel on restore, which is a feature, not
* symmetry. A web-endpoint tab is session-only and simply closes on reload,
* the same as "local-terminal" already does.
*/
export const PERSISTENT_TAB_TYPES: TabType[] = [
"terminal",
"rdp",
"vnc",
"telnet",
"files",
"docker",
"host-metrics",
"tunnel",
];
export function AppShell({
username,
onLogout,
}: {
username: string;
onLogout: () => void;
onLogout: (options?: { manual?: boolean }) => void;
}) {
const { t, i18n } = useTranslation();
const { setTheme } = useTheme();
@@ -323,6 +363,8 @@ export function AppShell({
const [remoteSyncInitialServerUrl, setRemoteSyncInitialServerUrl] = useState<
string | undefined
>(undefined);
const [remoteSyncReconnectRequested, setRemoteSyncReconnectRequested] =
useState(false);
const [sidebarWidth, setSidebarWidth] = useState(() => {
const saved = localStorage.getItem("termix_sidebarWidth");
return saved ? parseInt(saved, 10) : 291;
@@ -453,6 +495,7 @@ export function AppShell({
const tabsRef = useRef(tabs);
const activeTabIdRef = useRef(activeTabId);
const closeActiveTabRef = useRef<() => void>(() => {});
const globalKeybindingsRef = useRef<CustomKeybinding[]>([]);
const splitModeRef = useRef(splitMode);
const focusedPaneIndexRef = useRef<number | null>(null);
const paneContentElsRef = useRef<(HTMLDivElement | null)[]>(
@@ -462,17 +505,89 @@ export function AppShell({
useEffect(() => {
tabsRef.current = tabs;
}, [tabs]);
useEffect(() => {
let cancelled = false;
const load = () => {
getUserPreferences()
.then((prefs) => {
if (cancelled) return;
globalKeybindingsRef.current = parseCustomKeybindings(
prefs.customKeybindings,
).filter(
(binding) =>
binding.enabled &&
["nextTab", "previousTab", "openCommandPalette"].includes(
binding.action.type,
),
);
})
.catch(() => {});
};
load();
window.addEventListener("customKeybindingsChanged", load);
return () => {
cancelled = true;
window.removeEventListener("customKeybindingsChanged", load);
};
}, []);
useEffect(() => {
const runAction = (type: KeybindingActionType) => {
if (type === "openCommandPalette") {
setCommandPaletteOpen(true);
return;
}
const currentTabs = tabsRef.current;
if (currentTabs.length < 2) return;
const index = currentTabs.findIndex(
(tab) => tab.id === activeTabIdRef.current,
);
const offset = type === "nextTab" ? 1 : -1;
const next = (index + offset + currentTabs.length) % currentTabs.length;
setActiveTabId(currentTabs[next].id);
};
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.target instanceof Element &&
event.target.closest("[data-keybinding-recorder]")
)
return;
const binding = findMatchingKeybinding(
event,
globalKeybindingsRef.current,
);
if (!binding) return;
event.preventDefault();
event.stopPropagation();
runAction(binding.action.type);
};
const handleAction = (event: Event) =>
runAction(
(event as CustomEvent<{ type: KeybindingActionType }>).detail.type,
);
window.addEventListener("keydown", handleKeyDown, true);
window.addEventListener("termix:global-keybinding", handleAction);
return () => {
window.removeEventListener("keydown", handleKeyDown, true);
window.removeEventListener("termix:global-keybinding", handleAction);
};
}, []);
useEffect(() => {
activeTabIdRef.current = activeTabId;
}, [activeTabId]);
useEffect(() => {
return window.electronAPI?.onCloseActiveTab?.(() =>
closeActiveTabRef.current(),
);
return window.electronAPI?.onCloseActiveTab?.(() => {
if (dispatchCtrlW(document.activeElement)) return;
closeActiveTabRef.current();
});
}, []);
const skipSplitSyncRef = useRef(false);
const activeTabAvailable = tabs.some((tab) => tab.id === activeTabId);
useEffect(() => {
const active = tabsRef.current.find((tab) => tab.id === activeTabId);
const active = tabs.find((tab) => tab.id === activeTabId);
const config = active?.type === "split-screen" ? active.splitConfig : null;
skipSplitSyncRef.current = true;
if (!config) {
@@ -486,7 +601,7 @@ export function AppShell({
setRowSizes(config.rowSizes);
setRowColSizes(config.rowColSizes);
setFocusedPaneIndex(0);
}, [activeTabId]);
}, [activeTabId, activeTabAvailable]);
useEffect(() => {
if (skipSplitSyncRef.current) {
@@ -542,6 +657,10 @@ export function AppShell({
// target never changes (changing the target causes a remount).
const tabNodesRef = useRef<Map<string, HTMLDivElement>>(new Map());
const normalViewRef = useRef<HTMLDivElement>(null);
// Tab id the enter animation has already played for, so a re-render while
// the tab stays active (there can be several right after a switch) doesn't
// replay it — only a genuine switch to a different tab should.
const lastAnimatedTabIdRef = useRef<string | null>(null);
const getTabNode = useCallback((tabId: string, isTerminal: boolean) => {
if (!tabNodesRef.current.has(tabId)) {
@@ -555,6 +674,30 @@ export function AppShell({
return tabNodesRef.current.get(tabId)!;
}, []);
// Portal render order for tab content, kept independent of the tab bar's
// visual order. Reordering tabs in the bar reorders `tabs`, and mapping
// that array directly to portals reshuffles the Suspense-wrapped portal
// children's sibling order in the fiber tree — React then runs its
// Offscreen disconnect/reconnect pass on the ones that moved, which tears
// down and rebuilds every passive effect underneath (including
// react-xtermjs's terminal-creation effect), dropping the live terminal
// and its WebSocket. Portal position doesn't need to track tab order at
// all, so we only ever append new ids and drop closed ones here.
const portalOrderRef = useRef<string[]>([]);
{
const liveIds = new Set(tabs.map((t) => t.id));
portalOrderRef.current = portalOrderRef.current.filter((id) =>
liveIds.has(id),
);
const known = new Set(portalOrderRef.current);
for (const tab of tabs) {
if (!known.has(tab.id)) portalOrderRef.current.push(tab.id);
}
}
const tabsByPortalOrder = portalOrderRef.current
.map((id) => tabs.find((t) => t.id === id))
.filter((t): t is Tab => t !== undefined);
const onPaneContentRef = useCallback(
(paneIndex: number, el: HTMLDivElement | null) => {
setPaneContentEls((prev) => {
@@ -575,7 +718,7 @@ export function AppShell({
// hard to discover.
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.code === "ShiftLeft" && !e.repeat) {
if (isShiftKey(e) && !e.repeat) {
const now = Date.now();
if (now - lastShiftTime.current < 300 && commandPaletteShortcutEnabled)
setCommandPaletteOpen((prev) => !prev);
@@ -735,18 +878,18 @@ export function AppShell({
}
return;
}
}
// Alt+1..9 — jump directly to the tab at that position
const digitMatch = /^Digit([1-9])$/.exec(e.code);
if (digitMatch) {
const currentTabs = tabsRef.current;
const index = Number(digitMatch[1]) - 1;
if (index < currentTabs.length) {
e.preventDefault();
setActiveTabId(currentTabs[index].id);
}
return;
// Cmd+1..9 on macOS, Alt+1..9 elsewhere — jump directly to the tab at that position
const tabDigit = getTabJumpDigit(e);
if (tabDigit !== null) {
const currentTabs = tabsRef.current;
const index = tabDigit - 1;
if (index < currentTabs.length) {
e.preventDefault();
setActiveTabId(currentTabs[index].id);
}
return;
}
// Ctrl+Shift+] / Ctrl+Shift+[ — cycle through open tabs (] = next, [ = previous)
@@ -789,7 +932,12 @@ export function AppShell({
}, []);
useEffect(() => {
const handle = () => onLogout();
const handle = (event: Event) => {
const manual =
event instanceof CustomEvent &&
(event.detail as { manual?: boolean } | undefined)?.manual === true;
onLogout(manual ? { manual: true } : undefined);
};
window.addEventListener("termix:logout", handle);
return () => window.removeEventListener("termix:logout", handle);
}, [onLogout]);
@@ -859,6 +1007,7 @@ export function AppShell({
const SNAPSHOT_KEYS = [
"termix-accent",
"termix-font-size",
"termix-ui-font",
"i18nextLng",
"commandAutocomplete",
"commandPaletteShortcutEnabled",
@@ -1079,17 +1228,6 @@ export function AppShell({
return () => window.removeEventListener("termix:open-tab", handle);
}, [allHosts]);
const PERSISTENT_TAB_TYPES: TabType[] = [
"terminal",
"rdp",
"vnc",
"telnet",
"files",
"docker",
"host-metrics",
"tunnel",
];
function buildWorkspacePayload(): WorkspacePayload {
return buildWorkspacePayloadUtil({
tabs,
@@ -1491,7 +1629,9 @@ export function AppShell({
serialConfig?: SerialConfig;
joinSharedSessionId?: string | null;
joinShareId?: string | null;
collabRoomId?: string;
},
options?: { endpointId?: string; label?: string },
) {
const tabId = `${host.name}-${type}-${Date.now()}`;
const instanceId =
@@ -1536,6 +1676,7 @@ export function AppShell({
initialFilePath,
initialPath,
serialConfig,
collabRoomId: restore?.collabRoomId,
},
];
}
@@ -1544,8 +1685,11 @@ export function AppShell({
(t) =>
t.type === type && t.label.replace(/ \(\d+\)$/, "") === host.name,
);
finalLabel =
same.length === 0 ? host.name : `${host.name} (${same.length + 1})`;
finalLabel = options?.label
? options.label
: same.length === 0
? host.name
: `${host.name} (${same.length + 1})`;
// Retrofit the first duplicate's label to "(1)" if needed
const next =
@@ -1571,6 +1715,8 @@ export function AppShell({
initialFilePath,
initialPath,
serialConfig,
collabRoomId: restore?.collabRoomId,
endpointId: options?.endpointId,
},
];
});
@@ -1589,14 +1735,18 @@ export function AppShell({
return tabId;
}, []);
function connectHost(host: Host, preferredType?: TabType) {
function connectHost(
host: Host,
preferredType?: TabType,
options?: { endpointId?: string; label?: string },
) {
const type = resolveHostTabType(host, preferredType);
// --- tmux-monitor --- singleton tab, not a per-host tab
if (type === "tmux_monitor") {
openSingletonTab(type, undefined, host);
return;
}
openTab(host, type);
openTab(host, type, undefined, options);
}
const saveQuickConnectHost = useCallback(
@@ -1638,6 +1788,7 @@ export function AppShell({
enableProxmoxStats: false,
enableTmuxMonitor: false,
enableTerminalToolbar: false,
enableAiAssistant: false,
enableSsh: false,
enableRdp: false,
enableVnc: false,
@@ -1688,6 +1839,52 @@ export function AppShell({
return id;
}
// Invite awareness: rooms are discovered by polling, so a room that has
// never been shown to this browser gets one toast with an Open action.
useEffect(() => {
const SEEN_KEY = "termix:collab-rooms-seen";
let cancelled = false;
const check = async () => {
try {
const { listCollabRooms } = await import("@/api/collab-api");
const { rooms = [] } = await listCollabRooms();
if (cancelled) return;
let seen: string[] = [];
try {
seen = JSON.parse(localStorage.getItem(SEEN_KEY) ?? "[]");
} catch {
seen = [];
}
const seenSet = new Set(seen);
const fresh = rooms.filter((room) => !seenSet.has(room.id));
if (fresh.length === 0) return;
localStorage.setItem(
SEEN_KEY,
JSON.stringify([...seenSet, ...fresh.map((room) => room.id)]),
);
// The first poll after login only records what already exists.
if (seen.length === 0) return;
for (const room of fresh) {
if (room.ownerUserId === userId) continue;
toast(t("collab.invitedTo", { name: room.name }), {
action: {
label: t("collab.openRoom"),
onClick: () => setRailView("collab"),
},
});
}
} catch {
/* next poll */
}
};
void check();
const timer = setInterval(() => void check(), 60_000);
return () => {
cancelled = true;
clearInterval(timer);
};
}, []);
const openSingletonTab = useCallback(
// --- tmux-monitor --- (added optional `host` so tmux_monitor can open
// with a preselected host; existing callers are unaffected)
@@ -1741,6 +1938,7 @@ export function AppShell({
"host-manager": t("nav.hostManager"),
docker: t("nav.docker"),
tunnel: t("nav.tunnels"),
sftp: t("nav.sftp"),
network_graph: t("nav.networkGraph"),
tmux_monitor: t("nav.tmuxMonitor"), // --- tmux-monitor ---
homepage: t("nav.homepage"),
@@ -2085,6 +2283,12 @@ export function AppShell({
}
function handleRailClick(view: RailView) {
if (view === "sftp") {
openSingletonTab("sftp");
if (isMobile) setSidebarOpen(false);
return;
}
if (railView === view && sidebarOpen) {
setSidebarOpen(false);
} else {
@@ -2177,7 +2381,10 @@ export function AppShell({
// Move each tab's stable DOM node to the right container (pane or normal-view).
// This is vanilla DOM so React's portal target never changes — changing the portal
// target causes a remount which is exactly what we're trying to avoid.
useEffect(() => {
// useLayoutEffect (not useEffect) so visibility/display are corrected before
// the browser paints — otherwise the previous tab's node can flash on screen
// for a frame while still visible.
useLayoutEffect(() => {
const normalView = normalViewRef.current;
if (!normalView) return;
@@ -2206,6 +2413,7 @@ export function AppShell({
node.style.pointerEvents = "auto";
node.style.display = "";
node.style.zIndex = "";
node.style.contentVisibility = "";
} else {
if (node.parentElement !== normalView) normalView.appendChild(node);
if (isTerminal) {
@@ -2213,7 +2421,37 @@ export function AppShell({
node.style.visibility = activeInline ? "visible" : "hidden";
node.style.pointerEvents = activeInline ? "auto" : "none";
node.style.zIndex = activeInline ? "1" : "0";
// xterm renders to a <canvas>; visibility:hidden alone can still let
// a stale composited frame flash through for a tick when switching
// to/from a non-terminal tab. content-visibility:hidden fully skips
// painting the subtree while keeping its layout box intact, so
// fitAddon.fit() still sees correct dimensions once it's shown again.
node.style.contentVisibility = activeInline ? "" : "hidden";
} else {
// Plays a quick opacity fade-in on the tab that just became active.
// Only play it on an actual switch into this tab -- gating on the
// class alone replayed the animation on every unrelated re-render
// that happened while the tab was still active (any render after
// animationend had stripped the class), which looked like the
// panel kept growing for up to a second after switching.
if (activeInline && lastAnimatedTabIdRef.current !== tab.id) {
lastAnimatedTabIdRef.current = tab.id;
node.classList.remove("motion-workspace-enter");
// Force a reflow so re-adding the class restarts the animation
// instead of no-oping because it was already removed this tick.
void node.offsetWidth;
node.classList.add("motion-workspace-enter");
node.addEventListener(
"animationend",
() => node.classList.remove("motion-workspace-enter"),
{ once: true },
);
} else if (!activeInline) {
node.classList.remove("motion-workspace-enter");
if (lastAnimatedTabIdRef.current === tab.id) {
lastAnimatedTabIdRef.current = null;
}
}
node.style.visibility = "";
node.style.pointerEvents = "";
node.style.zIndex = activeInline ? "2" : "";
@@ -2261,8 +2499,8 @@ export function AppShell({
className={`flex flex-col flex-1 min-h-0 ${railView === "hosts" ? "" : "hidden"}`}
>
<HostsPanel
onOpenTab={(host, type) => {
connectHost(host, type);
onOpenTab={(host, type, options) => {
connectHost(host, type, options);
if (isMobile) setSidebarOpen(false);
}}
onEditHost={editHostInManager}
@@ -2284,6 +2522,12 @@ export function AppShell({
</>
)}
{railView === "port-forwarding" && (
<div className="flex flex-col flex-1 min-h-0">
<PortForwardingPanel />
</div>
)}
{railView === "termix-id" && (
<div className="flex flex-col flex-1 min-h-0">
<TermixIdPanel />
@@ -2483,6 +2727,7 @@ export function AppShell({
enableProxmoxStats: false,
enableTmuxMonitor: false,
enableTerminalToolbar: false,
enableAiAssistant: false,
enableSsh: false,
enableRdp: false,
enableVnc: false,
@@ -2513,6 +2758,58 @@ export function AppShell({
</div>
)}
{railView === "collab" && (
<div className="flex-1 min-h-0 overflow-y-auto">
<CollabPanel
onOpenRoom={(room) => {
const roomHost: Host = {
id: `collab-${room.id}`,
name: room.name,
username: "",
ip: "",
port: 0,
folder: "",
online: false,
cpu: null,
ram: null,
lastAccess: new Date().toISOString(),
authType: "none",
enableTerminal: false,
enableCommandHistory: false,
enableTunnel: false,
enableFileManager: false,
enableDocker: false,
enableProxmox: false,
enableProxmoxStats: false,
enableTmuxMonitor: false,
enableTerminalToolbar: false,
enableAiAssistant: false,
enableSsh: false,
enableRdp: false,
enableVnc: false,
enableTelnet: false,
sshPort: 22,
rdpPort: 3389,
vncPort: 5900,
telnetPort: 23,
serverTunnels: [],
quickActions: [],
};
openTab(roomHost, "collab", {
instanceId:
typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,
restoredSessionId: null,
savedLabel: room.name,
collabRoomId: room.id,
});
if (isMobile) setSidebarOpen(false);
}}
/>
</div>
)}
{railView === "session-logs" && (
<div className="relative flex-1 min-h-0 flex flex-col">
<SessionLogsPanel />
@@ -2529,6 +2826,10 @@ export function AppShell({
setUserPrefs((current) => ({ ...current, ...updates }))
}
remoteSyncInitialServerUrl={remoteSyncInitialServerUrl}
remoteSyncReconnectRequested={remoteSyncReconnectRequested}
onRemoteSyncReconnectHandled={() =>
setRemoteSyncReconnectRequested(false)
}
/>
</div>
)}
@@ -2638,6 +2939,7 @@ export function AppShell({
variant="ghost"
size="icon"
className="h-full w-12.5 rounded-none text-muted-foreground hover:text-foreground"
title="Collapse sidebar"
onClick={() => {
setSettingsFullscreen(false);
setSidebarOpen(false);
@@ -2669,6 +2971,7 @@ export function AppShell({
onReconnect={() => {
setRailView("user-profile");
if (!sidebarOpen) setSidebarOpen(true);
setRemoteSyncReconnectRequested(true);
}}
/>
<MigrationNoticeDialog
@@ -2743,7 +3046,7 @@ export function AppShell({
<div
inert={settingsFullscreen ? true : undefined}
aria-hidden={settingsFullscreen || undefined}
className={`relative flex flex-col flex-1 min-w-0 overflow-hidden transition-all duration-200 ${!isMobile && !sidebarOpen ? "pl-6" : ""}`}
className={`relative flex flex-col flex-1 min-w-0 overflow-hidden transition-[padding] duration-200 ${!isMobile && !sidebarOpen ? "pl-6" : ""}`}
>
{!isMobile && !sidebarOpen && (
<button
@@ -2783,7 +3086,7 @@ export function AppShell({
{/* Split view — always mounted when not mobile, hidden via CSS when inactive */}
{!isMobile && (
<div
className="absolute inset-0"
className="motion-workspace-layout absolute inset-0"
style={{
display: isSplit ? "flex" : "none",
flexDirection: "column",
@@ -2818,7 +3121,7 @@ export function AppShell({
display: isSplit && !isMobile ? "none" : undefined,
}}
>
{tabs.map((tab) => {
{tabsByPortalOrder.map((tab) => {
const tabNode = getTabNode(
tab.id,
tab.type === "terminal" || tab.type === "local-terminal",
+87 -1
View File
@@ -114,7 +114,11 @@ export async function probeAiModels(input: {
baseUrl?: string | null;
apiKey?: string | null;
providerId?: number | null;
}): Promise<{ models: string[]; source: "live" | "fallback" | "none" }> {
}): Promise<{
models: string[];
source: "live" | "fallback" | "none";
warning?: string;
}> {
try {
return (await authApi.post("/ai/probe-models", input)).data;
} catch (error) {
@@ -176,6 +180,27 @@ export async function rejectAiProposal(id: number): Promise<void> {
}
}
/**
* For the terminal-docked assistant: records that a run_command proposal was
* typed into the user's open terminal instead of run over a pooled connection.
*/
export async function markAiProposalRunInTerminal(
id: number,
hostId: number,
summary?: string,
): Promise<{ success: boolean; summary: string }> {
try {
return (
await authApi.post(`/ai/proposals/${id}/mark-run-in-terminal`, {
hostId,
summary,
})
).data;
} catch (error) {
throw handleApiError(error, "mark AI proposal run in terminal");
}
}
// --- admin ---
export async function getAiGloballyEnabled(): Promise<boolean> {
@@ -212,3 +237,64 @@ export async function setAiPrivateEndpoints(
throw handleApiError(error, "update AI endpoint allowlist");
}
}
export async function getNotificationPrivateEndpoints(): Promise<string[]> {
try {
return (await authApi.get("/users/notification-private-endpoints")).data
.hosts;
} catch (error) {
throw handleApiError(error, "get notification endpoint allowlist");
}
}
export async function getStepCaPrivateEndpoints(): Promise<string[]> {
try {
return (await authApi.get("/users/step-ca-private-endpoints")).data.hosts;
} catch (error) {
throw handleApiError(error, "get Step CA endpoint allowlist");
}
}
export async function setStepCaPrivateEndpoints(
hosts: string[],
): Promise<string[]> {
try {
return (await authApi.patch("/users/step-ca-private-endpoints", { hosts }))
.data.hosts;
} catch (error) {
throw handleApiError(error, "update Step CA endpoint allowlist");
}
}
export async function getSecretSourcePrivateEndpoints(): Promise<string[]> {
try {
return (await authApi.get("/users/secret-source-private-endpoints")).data
.hosts;
} catch (error) {
throw handleApiError(error, "get secret source endpoint allowlist");
}
}
export async function setSecretSourcePrivateEndpoints(
hosts: string[],
): Promise<string[]> {
try {
return (
await authApi.patch("/users/secret-source-private-endpoints", { hosts })
).data.hosts;
} catch (error) {
throw handleApiError(error, "update secret source endpoint allowlist");
}
}
export async function setNotificationPrivateEndpoints(
hosts: string[],
): Promise<string[]> {
try {
return (
await authApi.patch("/users/notification-private-endpoints", { hosts })
).data.hosts;
} catch (error) {
throw handleApiError(error, "update notification endpoint allowlist");
}
}
+30
View File
@@ -105,3 +105,33 @@ export async function getAuditLogActions(): Promise<{ actions: string[] }> {
handleApiError(error, "fetch audit log actions");
}
}
export interface AuditForwardingSettings {
url: string;
hasToken: boolean;
envConfigured: boolean;
}
export async function getAuditForwarding(): Promise<AuditForwardingSettings> {
try {
const response = await authApi.get("/users/audit-forwarding");
return response.data;
} catch (error) {
throw handleApiError(error, "get audit forwarding settings");
}
}
export async function updateAuditForwarding(
url: string,
token?: string,
): Promise<{ url: string; hasToken: boolean }> {
try {
const response = await authApi.patch("/users/audit-forwarding", {
url,
token,
});
return response.data;
} catch (error) {
throw handleApiError(error, "update audit forwarding settings");
}
}
+238
View File
@@ -0,0 +1,238 @@
import axios from "axios";
import { authApi, handleApiError } from "@/main-axios";
import { resolveApiBaseUrl } from "@/api/session-sharing-api";
export interface CollabRoom {
id: string;
name: string;
ownerUserId: string;
persistent: boolean;
presenterUserId: string | null;
stageProtocol: string | null;
stageHostId: number | null;
stageShareId: string | null;
guestLinkEnabled: boolean;
createdAt: string;
endedAt: string | null;
}
export interface CollabRoomMember {
userId: string;
username: string;
roomRole: string;
createdAt: string;
}
export interface CollabOnlineUser {
userId: string;
username: string;
}
export interface CollabStage {
presenterUserId: string | null;
protocol: "ssh" | "rdp" | "vnc" | "telnet" | null;
hostId: number | null;
shareId: string | null;
sessionId?: string;
controllerUserId?: string | null;
connectParams?: { token: string };
}
export interface CollabRoomDetail {
room: CollabRoom;
me: string;
isHost: boolean;
members: CollabRoomMember[];
online: CollabOnlineUser[];
stage: CollabStage;
controllerUserId: string | null;
controlRequests: CollabControlRequest[];
}
export interface CollabControlRequest {
userId: string;
username: string;
requestedAt: string;
}
export async function listCollabRooms(): Promise<{ rooms: CollabRoom[] }> {
try {
const response = await authApi.get("/collab/rooms");
return response.data;
} catch (error) {
throw handleApiError(error, "list collab rooms");
}
}
export async function createCollabRoom(
name: string,
persistent: boolean,
): Promise<{ room: CollabRoom }> {
try {
const response = await authApi.post("/collab/rooms", { name, persistent });
return response.data;
} catch (error) {
throw handleApiError(error, "create collab room");
}
}
export async function getCollabRoom(roomId: string): Promise<CollabRoomDetail> {
try {
const response = await authApi.get(`/collab/rooms/${roomId}`);
return response.data;
} catch (error) {
throw handleApiError(error, "get collab room");
}
}
export async function inviteCollabMembers(
roomId: string,
targets: { userIds?: string[]; roleIds?: number[] },
): Promise<void> {
try {
await authApi.post(`/collab/rooms/${roomId}/members`, targets);
} catch (error) {
throw handleApiError(error, "invite collab members");
}
}
export async function removeCollabMember(
roomId: string,
userId: string,
): Promise<void> {
try {
await authApi.delete(`/collab/rooms/${roomId}/members/${userId}`);
} catch (error) {
throw handleApiError(error, "remove collab member");
}
}
export async function presentCollabStage(
roomId: string,
input: { protocol: string; sessionId: string; hostId: number },
): Promise<{ stage: CollabStage }> {
try {
const response = await authApi.post(
`/collab/rooms/${roomId}/present`,
input,
);
return response.data;
} catch (error) {
throw handleApiError(error, "start presenting");
}
}
export async function stopCollabStage(roomId: string): Promise<void> {
try {
await authApi.post(`/collab/rooms/${roomId}/stop`);
} catch (error) {
throw handleApiError(error, "stop presenting");
}
}
export async function getCollabStage(
roomId: string,
): Promise<{ stage: CollabStage | null }> {
try {
const response = await authApi.get(`/collab/rooms/${roomId}/stage`);
return response.data;
} catch (error) {
throw handleApiError(error, "resolve collab stage");
}
}
export async function setCollabStageControl(
roomId: string,
userId: string | null,
): Promise<void> {
try {
await authApi.post(`/collab/rooms/${roomId}/control`, { userId });
} catch (error) {
throw handleApiError(error, "change stage control");
}
}
export async function requestCollabStageControl(
roomId: string,
): Promise<{ request: CollabControlRequest }> {
try {
const response = await authApi.post(
`/collab/rooms/${roomId}/control/request`,
);
return response.data;
} catch (error) {
throw handleApiError(error, "request stage control");
}
}
export async function listCollabControlRequests(
roomId: string,
): Promise<{ requests: CollabControlRequest[] }> {
try {
const response = await authApi.get(
`/collab/rooms/${roomId}/control/requests`,
);
return response.data;
} catch (error) {
throw handleApiError(error, "list control requests");
}
}
export async function dismissCollabControlRequest(
roomId: string,
userId: string,
): Promise<void> {
try {
await authApi.delete(`/collab/rooms/${roomId}/control/requests/${userId}`);
} catch (error) {
throw handleApiError(error, "dismiss control request");
}
}
export async function endCollabRoom(roomId: string): Promise<void> {
try {
await authApi.post(`/collab/rooms/${roomId}/end`);
} catch (error) {
throw handleApiError(error, "end collab room");
}
}
export async function deleteCollabRoom(roomId: string): Promise<void> {
try {
await authApi.delete(`/collab/rooms/${roomId}`);
} catch (error) {
throw handleApiError(error, "delete collab room");
}
}
export async function setCollabGuestLink(
roomId: string,
enabled: boolean,
): Promise<{ guestLinkToken: string | null }> {
try {
const response = await authApi.post(`/collab/rooms/${roomId}/guest-link`, {
enabled,
});
return response.data;
} catch (error) {
throw handleApiError(error, "update guest link");
}
}
export interface CollabGuestStage {
protocol: "ssh" | "rdp" | "vnc" | "telnet";
shareId: string;
wsPath?: string;
connectParams?: { token: string };
}
/** Anonymous: guests poll this to follow the presenter. Throws on 404/429. */
export async function resolveCollabGuestStage(
token: string,
): Promise<{ roomName: string; stage: CollabGuestStage | null }> {
const baseUrl = await resolveApiBaseUrl();
const response = await axios.get(
`${baseUrl}/collab/guest/${encodeURIComponent(token)}`,
);
return response.data;
}
+43 -14
View File
@@ -7,15 +7,26 @@ import {
import type { AxiosInstance } from "axios";
import type { GuacamoleConfig } from "@/types/guacamole-config";
import { resolveRemoteHostId } from "@/lib/remote-server-api";
import type { ConnectionOrigin } from "@/lib/connection-origin";
/**
* The embedded desktop backend does not bundle guacd, which is why
* resolveConnectionOrigin() pins RDP/VNC/Telnet to "remote". These calls have to
* follow: asking the embedded backend reports the guacd *it* cannot reach,
* rather than the one on the connected server that serves the session.
* Picks the backend that will actually serve this session, so the token and
* status come from the same place as the connection.
*
* Outside Electron there is only one backend. Inside it, a host left on
* Default still resolves to the connected server -- asking the embedded
* backend would report the guacd *it* can reach rather than the one serving
* the session. A host explicitly set to "This Device" (Support#1240) is
* served by the embedded backend against the user's own guacd, so its calls
* have to go there instead.
*
* Callers pass the origin explicitly rather than defaulting it: a default
* silently sent a missed call site to the remote server, which fails with a
* bare network error on a desktop that has none configured.
*/
function guacamoleApi(): AxiosInstance {
return isElectron() ? getRemoteGuacamoleApi() : authApi;
function guacamoleApi(origin: ConnectionOrigin): AxiosInstance {
if (!isElectron()) return authApi;
return origin === "local" ? authApi : getRemoteGuacamoleApi();
}
export interface GuacamoleTokenRequest {
@@ -33,6 +44,7 @@ export interface GuacamoleTokenRequest {
export interface GuacamoleTokenResponse {
token: string;
guacamoleConnectionId?: string | null;
termixConnectId?: string;
}
type GuacamoleConfigSource = {
@@ -157,11 +169,12 @@ function toGuacamoleParams(
export async function getGuacamoleToken(
request: GuacamoleTokenRequest,
origin: ConnectionOrigin,
): Promise<GuacamoleTokenResponse> {
try {
const guacParams = toGuacamoleParams(request.guacamoleConfig);
const response = await guacamoleApi().post("/guacamole/token", {
const response = await guacamoleApi(origin).post("/guacamole/token", {
type: request.protocol,
hostname: request.hostname,
port: request.port,
@@ -180,6 +193,7 @@ export async function getGuacamoleToken(
export async function getGuacamoleTokenFromHost(
hostId: number,
origin: ConnectionOrigin,
protocol?: "rdp" | "vnc" | "telnet",
promptedCredentials?: {
username?: string;
@@ -189,14 +203,17 @@ export async function getGuacamoleTokenFromHost(
syncId?: string | null,
): Promise<GuacamoleTokenResponse> {
try {
const remoteHostId = isElectron()
? await resolveRemoteHostId(syncId)
: null;
if (isElectron() && syncId && remoteHostId === null) {
// A locally-originated session is served by the embedded backend, which
// knows the host by its local id -- remapping it onto the remote
// server's id would address the wrong row, or fail outright when no
// server is configured at all.
const useRemote = isElectron() && origin === "remote";
const remoteHostId = useRemote ? await resolveRemoteHostId(syncId) : null;
if (useRemote && syncId && remoteHostId === null) {
throw new Error("The synced host does not exist on the remote server");
}
const targetHostId = remoteHostId ?? hostId;
const response = await guacamoleApi().post(
const response = await guacamoleApi(origin).post(
`/guacamole/connect-host/${targetHostId}`,
{
...(protocol ? { protocol } : {}),
@@ -217,9 +234,21 @@ export async function getGuacamoleTokenFromHost(
}
}
export async function getGuacdStatus(): Promise<{
export async function getGuacdStatus(origin: ConnectionOrigin): Promise<{
guacd: { status: string };
}> {
const response = await guacamoleApi().get("/guacamole/status");
const response = await guacamoleApi(origin).get("/guacamole/status");
return response.data;
}
export async function getGuacamoleConnectionId(
connectId: string,
origin: ConnectionOrigin,
signal?: AbortSignal,
): Promise<string | null> {
const response = await guacamoleApi(origin).get(
`/guacamole/connection/${encodeURIComponent(connectId)}`,
{ signal },
);
return response.data.guacamoleConnectionId ?? null;
}
+10 -2
View File
@@ -256,10 +256,18 @@ export async function stopMetricsPolling(
export async function sendMetricsHeartbeat(
viewerSessionId: string,
): Promise<void> {
): Promise<boolean> {
try {
await statsApi.post("/metrics/heartbeat", { viewerSessionId });
const response = await statsApi.post(
"/metrics/heartbeat",
{ viewerSessionId },
{ validateStatus: (status) => status === 200 || status === 404 },
);
return response.status !== 404;
} catch (error) {
if (axios.isAxiosError(error) && error.response?.status === 404) {
return false;
}
handleApiError(error, "send metrics heartbeat");
throw error;
}
+15
View File
@@ -0,0 +1,15 @@
import { authApi, handleApiError } from "@/main-axios";
/** Flips Auto-Tmux for one host without round-tripping the whole editor form. */
export async function setHostAutoTmux(
hostId: number,
autoTmux: boolean,
): Promise<void> {
try {
await authApi.patch(`/host/db/host/${hostId}/terminal-config`, {
autoTmux,
});
} catch (error) {
throw handleApiError(error, "update host auto-tmux");
}
}
+184
View File
@@ -0,0 +1,184 @@
// Local disk <-> remote SFTP transfers for the desktop app's dual-pane file
// manager. The bytes never pass through the renderer: the Electron main
// process streams them between disk and the backend's existing
// `uploadFileStream` / `downloadFileStream` routes (see
// electron/local-files.cjs), and we only orchestrate + relay progress here.
//
// The renderer deliberately does not choose the URL or the auth headers. It
// names the origin that owns the SSH session ("local" embedded backend or the
// configured Remote Sync server) and the main process resolves the rest, so a
// compromised renderer cannot turn the transfer bridge into an HTTP client.
import type {
LocalTransferOrigin,
LocalTransferProgress,
} from "@/types/electron";
import { getSessionOrigin } from "@/main-axios";
import { getDeviceId } from "@/lib/device-id";
export interface LocalTransferProgressEvent {
transferred: number;
total?: number;
}
type ProgressListener = (event: LocalTransferProgressEvent) => void;
/** Error from the main process; `code` is e.g. "EEXIST" or "EBUSY". */
export class LocalTransferError extends Error {
code?: string;
constructor(message: string, code?: string) {
super(message);
this.name = "LocalTransferError";
this.code = code;
}
}
const progressListeners = new Map<string, ProgressListener>();
let unsubscribeProgress: (() => void) | null = null;
function ensureProgressSubscription() {
if (unsubscribeProgress) return;
const api = window.electronAPI?.localTransfer;
if (!api) return;
unsubscribeProgress = api.onProgress((payload: LocalTransferProgress) => {
const listener = progressListeners.get(payload.transferId);
listener?.({ transferred: payload.transferred, total: payload.total });
});
}
function requireTransferApi() {
const api = window.electronAPI?.localTransfer;
if (!api) {
throw new Error("Local transfers are only available in the desktop app");
}
return api;
}
function transferOriginFor(sessionId: string): LocalTransferOrigin {
return getSessionOrigin(sessionId);
}
/**
* The token the desktop renderer uses for the embedded backend. The `jwt`
* cookie the main process would otherwise rely on lasts only a day after an
* interactive login, while this token (and every request the app makes with
* it) keeps working, so transfers must carry it too. Remote-origin transfers
* are authenticated by the main process from its own Remote Sync state.
*/
function localAuthTokenFor(origin: LocalTransferOrigin): string | undefined {
if (origin !== "local") return undefined;
try {
return localStorage.getItem("jwt") || undefined;
} catch {
return undefined;
}
}
export function createLocalTransferId(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
/**
* Streams a file from the local disk into `remoteDir` on the SSH session,
* using the same multipart route the in-browser upload uses.
*/
export async function uploadLocalFileToSession(options: {
sessionId: string;
remoteDir: string;
localPath: string;
fileName: string;
hostId?: number;
transferId?: string;
onProgress?: ProgressListener;
}): Promise<void> {
const api = requireTransferApi();
ensureProgressSubscription();
const transferId =
options.transferId ?? createLocalTransferId("local-upload");
const fields: Record<string, string> = {
sessionId: options.sessionId,
path: options.remoteDir,
};
if (options.hostId !== undefined) fields.hostId = String(options.hostId);
if (options.onProgress) {
progressListeners.set(transferId, options.onProgress);
}
const origin = transferOriginFor(options.sessionId);
try {
const result = await api.upload({
transferId,
origin,
deviceId: getDeviceId() ?? undefined,
authToken: localAuthTokenFor(origin),
fields,
localPath: options.localPath,
fileName: options.fileName,
});
if (result.success !== true) {
throw new LocalTransferError(
result.error || "Upload failed",
result.code,
);
}
} finally {
progressListeners.delete(transferId);
}
}
/**
* Streams a remote file from the SSH session straight to `destPath` on the
* local disk. Refuses to replace an existing file (code "EEXIST") unless
* `overwrite` is set.
*/
export async function downloadSessionFileToLocal(options: {
sessionId: string;
remotePath: string;
destPath: string;
/** The folder the user picked; the main process refuses any destination outside it. */
rootPath: string;
expectedSize?: number;
overwrite?: boolean;
transferId?: string;
onProgress?: ProgressListener;
}): Promise<void> {
const api = requireTransferApi();
ensureProgressSubscription();
const transferId =
options.transferId ?? createLocalTransferId("local-download");
if (options.onProgress) {
progressListeners.set(transferId, options.onProgress);
}
const origin = transferOriginFor(options.sessionId);
try {
const result = await api.download({
transferId,
origin,
deviceId: getDeviceId() ?? undefined,
authToken: localAuthTokenFor(origin),
body: { sessionId: options.sessionId, path: options.remotePath },
destPath: options.destPath,
rootPath: options.rootPath,
expectedSize: options.expectedSize,
overwrite: options.overwrite === true,
});
if (result.success !== true) {
throw new LocalTransferError(
result.error || "Download failed",
result.code,
);
}
} finally {
progressListeners.delete(transferId);
}
}
export async function cancelLocalTransfer(transferId: string): Promise<void> {
const api = window.electronAPI?.localTransfer;
if (!api) return;
await api.cancel(transferId);
}
+9 -1
View File
@@ -49,6 +49,11 @@ export interface ActiveSessionInfo {
shareId: string | null;
}
// Negative IDs identify remote-only shared hosts, absent from the local DB.
function hasPersistableHostId(tab: { hostId?: number | null }): boolean {
return tab.hostId == null || (Number.isInteger(tab.hostId) && tab.hostId > 0);
}
const activeSessionsCache = createTtlRequestCache<ActiveSessionInfo[]>(2_000);
export async function getOpenTabs(): Promise<OpenTabRecord[]> {
@@ -57,7 +62,7 @@ export async function getOpenTabs(): Promise<OpenTabRecord[]> {
}
export async function syncOpenTabs(tabs: OpenTabSyncPayload[]): Promise<void> {
await authApi.put("/open-tabs", { tabs });
await authApi.put("/open-tabs", { tabs: tabs.filter(hasPersistableHostId) });
}
export async function deleteOpenTab(instanceId: string): Promise<void> {
@@ -70,10 +75,12 @@ export async function patchOpenTab(
Pick<OpenTabRecord, "hostId" | "label" | "tabOrder" | "backendSessionId">
>,
): Promise<void> {
if (!hasPersistableHostId(updates)) return;
await authApi.patch(`/open-tabs/${instanceId}`, updates);
}
export async function addOpenTab(tab: OpenTabUpsertPayload): Promise<void> {
if (!hasPersistableHostId(tab)) return;
await authApi.post("/open-tabs", tab);
}
@@ -107,6 +114,7 @@ export interface UserPreferences {
hostTrayOnClick?: boolean | null;
pinAppRail?: boolean | null;
expandAppRailOnHover?: boolean | null;
showPinAppRailButton?: boolean | null;
foldersCollapsed?: boolean | null;
confirmSnippetExecution?: boolean | null;
disableUpdateCheck?: boolean | null;
+126 -4
View File
@@ -110,6 +110,24 @@ export async function removeRoleFromUser(
}
}
export interface RoleMember {
userId: string;
username: string;
grantedAt: string;
grantedBy: string | null;
}
export async function getRoleMembers(
roleId: number,
): Promise<{ members: RoleMember[] }> {
try {
const response = await rbacApi.get(`/rbac/roles/${roleId}/members`);
return response.data;
} catch (error) {
throw handleApiError(error, "get role members");
}
}
export type SharePermissionLevel = "connect" | "view" | "edit" | "manage";
export interface ShareTarget {
@@ -173,6 +191,42 @@ export async function shareFolder(
}
}
export interface FolderAccessRule {
id: number;
folder: string;
targetType: "user" | "role";
userId: string | null;
roleId: number | null;
username: string | null;
roleName: string | null;
roleDisplayName: string | null;
permissionLevel: SharePermissionLevel;
expiresAt: string | null;
createdAt: string;
}
/** Standing shares on a folder - what hosts added to it later inherit. */
export async function getFolderAccess(
folder: string,
): Promise<{ rules: FolderAccessRule[] }> {
try {
const response = await rbacApi.get("/rbac/folder/access", {
params: { folder },
});
return response.data;
} catch (error) {
throw handleApiError(error, "get folder access");
}
}
export async function revokeFolderAccess(ruleId: number): Promise<void> {
try {
await rbacApi.delete(`/rbac/folder/access/${ruleId}`);
} catch (error) {
throw handleApiError(error, "revoke folder access");
}
}
export async function updateHostAccess(
hostId: number,
accessId: number,
@@ -266,10 +320,14 @@ export async function revokeHostAccess(
export async function getHostAuthOverride(
hostId: number,
protocol: AuthOverrideProtocol,
remoteShared = false,
): Promise<{ protocol: AuthOverrideProtocol; credentialId: number | null }> {
try {
const response = await rbacApi.get(
`/rbac/host-access/${hostId}/auth/${protocol}`,
const api = remoteShared ? await getConnectedRemoteApi() : rbacApi;
if (!api) throw new Error("Remote server is not connected");
const targetHostId = remoteShared ? Math.abs(hostId) : hostId;
const response = await api.get(
`/rbac/host-access/${targetHostId}/auth/${protocol}`,
);
return response.data;
} catch (error) {
@@ -281,14 +339,18 @@ export async function setHostAuthOverride(
hostId: number,
protocol: AuthOverrideProtocol,
credentialId: number | null,
remoteShared = false,
): Promise<{
success: boolean;
protocol: AuthOverrideProtocol;
credentialId: number | null;
}> {
try {
const response = await rbacApi.put(
`/rbac/host-access/${hostId}/auth/${protocol}`,
const api = remoteShared ? await getConnectedRemoteApi() : rbacApi;
if (!api) throw new Error("Remote server is not connected");
const targetHostId = remoteShared ? Math.abs(hostId) : hostId;
const response = await api.put(
`/rbac/host-access/${targetHostId}/auth/${protocol}`,
{ credentialId },
);
return response.data;
@@ -321,6 +383,66 @@ export async function shareSnippet(
}
}
export async function shareSnippetFolder(
folder: string,
targets: ShareTarget[],
durationHours?: number,
): Promise<{ success: boolean; snippetsShared: number }> {
try {
const response = await rbacApi.post("/rbac/snippet-folder/share", {
folder,
targets,
durationHours,
});
return response.data;
} catch (error) {
throw handleApiError(error, "share snippet folder");
}
}
export type CredentialPermissionLevel = "use" | "manage";
export async function shareCredential(
credentialId: number,
targets: ShareTarget[],
permissionLevel: CredentialPermissionLevel,
durationHours?: number,
): Promise<{ success: boolean; expiresAt: string | null }> {
try {
const response = await rbacApi.post(
`/rbac/credential/${credentialId}/share`,
{ targets, permissionLevel, durationHours },
);
return response.data;
} catch (error) {
throw handleApiError(error, "share credential");
}
}
export async function getCredentialAccess(
credentialId: number,
): Promise<{ access: AccessRecord[] }> {
try {
const response = await rbacApi.get(
`/rbac/credential/${credentialId}/access`,
);
return response.data;
} catch (error) {
throw handleApiError(error, "get credential access");
}
}
export async function revokeCredentialAccess(
credentialId: number,
accessId: number,
): Promise<void> {
try {
await rbacApi.delete(`/rbac/credential/${credentialId}/access/${accessId}`);
} catch (error) {
throw handleApiError(error, "revoke credential access");
}
}
export async function getSnippetAccess(
snippetId: number,
): Promise<{ accessList: AccessRecord[] }> {
+69
View File
@@ -0,0 +1,69 @@
import { authApi, handleApiError } from "@/main-axios";
export interface SecretSource {
id: string;
userId: string;
name: string;
kind: "onepassword-connect";
baseUrl: string;
shared: boolean;
hasToken: boolean;
owned: boolean;
createdAt: string;
updatedAt: string;
}
export interface SecretSourcePayload {
name: string;
kind?: "onepassword-connect";
baseUrl: string;
token?: string;
shared?: boolean;
}
export async function listSecretSources(): Promise<SecretSource[]> {
try {
return (await authApi.get("/secret-sources")).data.sources;
} catch (error) {
throw handleApiError(error, "list secret sources");
}
}
export async function createSecretSource(
payload: SecretSourcePayload,
): Promise<SecretSource> {
try {
return (await authApi.post("/secret-sources", payload)).data.source;
} catch (error) {
throw handleApiError(error, "create secret source");
}
}
export async function updateSecretSource(
id: string,
payload: Partial<SecretSourcePayload>,
): Promise<void> {
try {
await authApi.put(`/secret-sources/${id}`, payload);
} catch (error) {
throw handleApiError(error, "update secret source");
}
}
export async function deleteSecretSource(id: string): Promise<void> {
try {
await authApi.delete(`/secret-sources/${id}`);
} catch (error) {
throw handleApiError(error, "delete secret source");
}
}
export async function testSecretSource(
id: string,
): Promise<{ ok: boolean; vaults?: number; error?: string }> {
try {
return (await authApi.post(`/secret-sources/${id}/test`)).data;
} catch (error) {
throw handleApiError(error, "test secret source");
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ const isDev = (): boolean =>
// truth, so a share link opened there always resolves against it --
// joining a session hosted on someone else's remote server isn't
// supported from the desktop app today.
async function resolveApiBaseUrl(): Promise<string> {
export async function resolveApiBaseUrl(): Promise<string> {
if (isDev()) {
const protocol = window.location.protocol === "https:" ? "https" : "http";
return `${protocol}://localhost:30001`;
+96
View File
@@ -61,6 +61,63 @@ export async function getSessionTimeout(): Promise<{ timeoutHours: number }> {
}
}
// How long a detached terminal session is kept alive server-side.
export async function getTerminalSessionSettings(): Promise<{
timeoutMinutes: number;
enabled: boolean;
}> {
try {
const response = await authApi.get("/terminal/session_settings");
return response.data;
} catch (error) {
handleApiError(error, "fetch terminal session settings");
}
}
export async function updateTerminalSessionSettings(input: {
timeoutMinutes?: number;
enabled?: boolean;
}): Promise<void> {
try {
await authApi.patch("/terminal/session_settings", input);
} catch (error) {
handleApiError(error, "update terminal session settings");
}
}
export interface StepCaSettings {
configured: boolean;
caUrl: string;
fingerprint: string;
provisioner: string;
}
export async function getStepCaSettings(): Promise<StepCaSettings> {
try {
const response = await authApi.get("/users/step-ca-settings");
return {
configured: !!response.data.configured,
caUrl: response.data.caUrl ?? "",
fingerprint: response.data.fingerprint ?? "",
provisioner: response.data.provisioner ?? "",
};
} catch (error) {
handleApiError(error, "fetch Step CA settings");
}
}
export async function updateStepCaSettings(input: {
caUrl: string;
fingerprint: string;
provisioner: string;
}): Promise<void> {
try {
await authApi.patch("/users/step-ca-settings", input);
} catch (error) {
handleApiError(error, "update Step CA settings");
}
}
export async function updateSessionTimeout(
timeoutHours: number,
): Promise<void> {
@@ -268,6 +325,44 @@ export async function testTerminalImageStorage(
}
}
// ============================================================================
// WHITE LABEL BRANDING
// ============================================================================
export interface BrandingSettings {
appName: string;
tagline: string;
/** PNG data URL, or null when no custom logo is configured. */
logo: string | null;
}
export interface BrandingSettingsUpdate {
appName?: string;
tagline?: string;
logo?: string | null;
}
/** Public endpoint -- no auth required, so the login screen can read it. */
export async function getBranding(): Promise<BrandingSettings> {
try {
const response = await authApi.get("/users/branding");
return response.data;
} catch (error) {
handleApiError(error, "fetch branding settings");
}
}
export async function updateBranding(
update: BrandingSettingsUpdate,
): Promise<BrandingSettings> {
try {
const response = await authApi.patch("/users/branding", update);
return response.data;
} catch (error) {
handleApiError(error, "update branding settings");
}
}
// ============================================================================
// HOST DEFAULTS SETTINGS
// ============================================================================
@@ -288,6 +383,7 @@ export type HostDefaults = {
cursorBlink?: boolean;
enableSessionLogging?: boolean;
enableCommandHistory?: boolean;
autoTmux?: boolean;
};
export async function getHostDefaults(): Promise<HostDefaults> {
+27 -17
View File
@@ -461,19 +461,20 @@ export async function uploadSSHFile(
const end = Math.min(start + CHUNK_SIZE_BYTES, file.size);
const chunkBlob = file.slice(start, end);
const form = new FormData();
form.append("sessionId", sessionId);
form.append("path", path);
form.append("fileName", fileName);
form.append("chunkIndex", String(i));
form.append("totalChunks", String(totalChunks));
form.append("totalSize", String(file.size));
form.append("chunk", chunkBlob, fileName);
const response = await getFileManagerApiForSession(sessionId).postForm(
const response = await getFileManagerApiForSession(sessionId).post(
"/ssh/uploadFileChunk",
form,
{ timeout: 0 },
chunkBlob,
{
params: {
sessionId,
path,
fileName,
offset: start,
totalSize: file.size,
},
headers: { "Content-Type": "application/octet-stream" },
timeout: 0,
},
);
bytesSent = end;
@@ -509,6 +510,18 @@ export async function uploadSSHFile(
form,
{
timeout: 0,
onUploadProgress: (event) => {
const totalBytes =
typeof event.total === "number" && event.total > 0
? event.total
: file.size;
onChunkProgress?.({
chunkIndex: 0,
totalChunks: 1,
bytesSent: Math.min(event.loaded, totalBytes),
totalBytes,
});
},
},
);
return response.data;
@@ -1030,7 +1043,7 @@ export async function ensureSSHSessionForHost(
export interface BrowseSSHDirectoryResult {
status: "ok" | "not_found" | "error";
path: string;
files: Array<{ name: string; type: "file" | "directory" | "link" }>;
files: FileItem[];
}
export async function browseSSHDirectory(
@@ -1042,10 +1055,7 @@ export async function browseSSHDirectory(
return {
status: "ok",
path: result.path,
files: result.files as Array<{
name: string;
type: "file" | "directory" | "link";
}>,
files: result.files,
};
} catch (err) {
const status =
+4 -3
View File
@@ -10,12 +10,13 @@ import {
// ALERTS
// ============================================================================
export async function setupTOTP(): Promise<{
export async function setupTOTP(credential?: string): Promise<{
secret: string;
qr_code: string;
additional?: boolean;
}> {
try {
const response = await authApi.post("/users/totp/setup");
const response = await authApi.post("/users/totp/setup", { credential });
return response.data;
} catch (error) {
handleApiError(error as AxiosError, "setup TOTP");
@@ -155,7 +156,7 @@ export async function getReleasesRSS(
}
export interface VersionInfo {
status?: "up_to_date" | "requires_update" | "beta";
status?: "up_to_date" | "requires_update" | "beta" | "unknown";
/** Same value as remoteVersion; the endpoint sends both. */
version?: string;
localVersion?: string;
+3 -2
View File
@@ -53,7 +53,7 @@ export async function getTunnelStatuses(): Promise<
try {
const remoteResult = await getRemoteTunnelApi().get("/tunnel/status");
return { ...localStatuses, ...(remoteResult.data || {}) };
return { ...(remoteResult.data || {}), ...localStatuses };
} catch {
return localStatuses;
}
@@ -74,7 +74,8 @@ export function subscribeTunnelStatuses(
let stopRemotePolling: (() => void) | null = null;
const emitMerged = () => {
onStatuses({ ...latestLocal, ...latestRemote });
// Controls target the local backend, so its state wins name collisions.
onStatuses({ ...latestRemote, ...latestLocal });
};
const waitToReconnect = () =>
+2 -1
View File
@@ -154,10 +154,11 @@ export async function removeAdminStatus(
export async function deleteUser(
username: string,
successorUserId?: string | "none",
): Promise<Record<string, unknown>> {
try {
const response = await authApi.delete("/users/delete-user", {
data: { username },
data: { username, successorUserId },
});
return response.data;
} catch (error) {
+139
View File
@@ -0,0 +1,139 @@
import {
currentTunnelHost,
resolveWebEndpointUrl,
} from "@/lib/web-endpoint-url";
import axios from "axios";
import { handleApiError, tunnelApi } from "@/main-axios";
import { isElectron } from "@/lib/electron";
import type { WebEndpoint } from "@/types/index";
/**
* Thrown when the backend rejects a web endpoint tunnel open with a specific,
* actionable reason -- most commonly a 502 carrying the real cause: SSH auth
* rejected, host unreachable, or nothing listening on the target port.
* Preserves that reason instead of letting handleApiError collapse three
* actionable errors into "Server error occurred. Please try again later."
*/
export class WebEndpointTunnelError extends Error {
constructor(
message: string,
public readonly status?: number,
) {
super(message);
this.name = "WebEndpointTunnelError";
}
}
/**
* Opens (or reuses) the SSH forward for a tunnel-access web endpoint and
* returns the port it is listening on. The port is NOT stable across opens:
* the backend closes an idle tunnel and re-binds a fresh kernel-assigned port,
* so callers must re-resolve rather than cache it.
*/
export async function openWebEndpointTunnel(
hostId: number,
endpointId: string,
): Promise<number> {
try {
// Relative to the tunnel API base, which already includes /ssh
// (getApiUrl("/ssh", 30003)). A path beginning "/ssh" here would resolve
// to /ssh/ssh/... and 404 on every call.
const response = await tunnelApi.post("/tunnel/web-endpoint/open", {
hostId,
endpointId,
});
const port = (response?.data as { port?: number } | undefined)?.port;
if (!port) {
throw new Error("The endpoint tunnel returned no port");
}
return port;
} catch (error) {
if (axios.isAxiosError(error)) {
// Typed unknown, not string: the guard below is only meaningful if the
// type does not already promise what it checks.
const data = error.response?.data as
{ error?: unknown; message?: unknown } | undefined;
const backendMessage = data?.error ?? data?.message;
// A body shaped { error: <object> } would otherwise render as
// "[object Object]". Every response on this route sends a string today,
// but a proxy or a future handler need not.
if (typeof backendMessage === "string" && backendMessage) {
throw new WebEndpointTunnelError(
backendMessage,
error.response?.status,
);
}
}
return handleApiError(error, "open web endpoint tunnel");
}
}
/**
* Registers one exact origin as allowed to present an invalid TLS certificate.
* Only meaningful on the desktop, and only for direct endpoints -- a tunnel
* endpoint's host component is loopback, which the main process already
* exempts.
*/
export async function allowInvalidCertificateForOrigin(
origin: string,
): Promise<void> {
if (!isElectron()) return;
try {
await window.electronAPI?.invoke?.(
"allow-invalid-certificate-for-origin",
origin,
);
} catch {
// The user's build may predate the handler; the load then simply fails the
// certificate check as it would have before.
}
}
/**
* A web endpoint tunnel opens through the backend's numeric host id.
* Quick-connect hosts (ids like "quick-connect-<n>") have no row on the
* server, so there is nothing to open a tunnel through -- unlike a direct
* endpoint, which never touches the backend and works regardless.
*/
export function requireNumericHostId(id: string): number {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error(
"This endpoint needs an SSH tunnel, which requires a saved host",
);
}
return numericId;
}
/** Desktop windows use a dedicated ephemeral session, including login popups. */
export async function openWebEndpointExternally(
host: { id: string; ip: string },
endpoint: WebEndpoint,
): Promise<void> {
if (!isElectron() || !window.electronAPI?.invoke) {
throw new Error(
"Isolated windows require the desktop app. Choose Embedded in the endpoint settings.",
);
}
const localPort =
endpoint.access === "tunnel"
? await openWebEndpointTunnel(requireNumericHostId(host.id), endpoint.id)
: undefined;
const url = resolveWebEndpointUrl({
hostAddress: host.ip,
endpoint,
localPort,
tunnelHost: currentTunnelHost(true) ?? undefined,
});
const result = await window.electronAPI.invoke("open-isolated-web-endpoint", {
url,
ignoreCert: endpoint.ignoreCert === true,
});
if (
!result ||
typeof result !== "object" ||
!("success" in result) ||
result.success !== true
)
throw new Error("Failed to open isolated web endpoint");
}
+247 -50
View File
@@ -36,10 +36,15 @@ import {
requestDesktopAutoSession,
requestTrustedProxyLogin,
} from "@/main-axios";
import {
getEmbeddedServerFailure,
type EmbeddedServerFailure,
} from "@/lib/embedded-server-status";
import { getSSOProviders, ldapLogin } from "@/api/sso-provider-api";
import { isPasskeySupported, loginWithPasskey } from "@/api/webauthn-api";
import type { SSOProviderPublic } from "@/types/index";
import { Checkbox } from "@/components/checkbox";
import { useBranding } from "@/contexts/BrandingContext";
import {
changeAppLanguage,
normalizeLanguageCode,
@@ -49,6 +54,7 @@ import {
removeSilentSigninFromSearch,
shouldTriggerSilentSignin,
} from "./silent-signin";
import { Select2 } from "@/components/select2";
const LANGUAGES = [
{ code: "en", label: "English" },
@@ -89,6 +95,7 @@ const LANGUAGES = [
];
const STORAGE_KEY = "termix_auth";
const DESKTOP_MANUAL_LOGOUT_KEY = "termix_desktop_manual_logout";
export function getStoredAuth(): {
loggedIn: boolean;
@@ -107,6 +114,18 @@ export function clearStoredAuth() {
localStorage.removeItem(STORAGE_KEY);
}
export function markDesktopManualLogout() {
localStorage.setItem(DESKTOP_MANUAL_LOGOUT_KEY, "true");
}
export function clearDesktopManualLogout() {
localStorage.removeItem(DESKTOP_MANUAL_LOGOUT_KEY);
}
function hasDesktopManualLogout() {
return localStorage.getItem(DESKTOP_MANUAL_LOGOUT_KEY) === "true";
}
function storeAuth(username: string) {
localStorage.setItem(
STORAGE_KEY,
@@ -214,6 +233,8 @@ function Field({
export function Auth({ onLogin }: AuthProps) {
const { t } = useTranslation();
const branding = useBranding();
const localDesktopAuth = isElectron() && !isInElectronWebView();
const [view, setView] = useState<AuthView>("login");
const [loading, setLoading] = useState(false);
const [providerLoading, setProviderLoading] = useState<
@@ -274,23 +295,28 @@ export function Auth({ onLogin }: AuthProps) {
useState(false);
const [firstUser, setFirstUser] = useState(false);
const [dbConnectionFailed, setDbConnectionFailed] = useState(false);
const [dbHealthChecking, setDbHealthChecking] = useState(true);
const [dbHealthChecking, setDbHealthChecking] = useState(
() => !localDesktopAuth || !hasDesktopManualLogout(),
);
const [webviewAuthSuccess, setWebviewAuthSuccess] = useState(false);
const [desktopManualLogoutActive, setDesktopManualLogoutActive] = useState(
() => localDesktopAuth && hasDesktopManualLogout(),
);
// Electron, non-iframed only: the desktop app never shows a login form
// when running standalone -- the embedded backend auto-provisions a
// single local user on first boot, and this component silently exchanges
// that for a session instead of rendering login/register.
// null = probe still in flight (Electron only, blocks rendering below).
// true = probe settled with no auto-login (not applicable outside
// Electron, multiple users exist, or setup is genuinely required) --
// safe to fall through to the normal form/health-check flow.
// Auto-login success never sets this; it calls onLogin directly and this
// component unmounts.
// Electron, non-iframed only: the desktop app owns an embedded local
// backend with an auto-provisioned local user, so it should never show
// username/password registration for that local surface. null means the
// auto-session probe is still in flight; true means the probe settled
// without a session and the local recovery panel can render.
const [desktopAutoSessionDone, setDesktopAutoSessionDone] = useState<
boolean | null
>(!isElectron() || isInElectronWebView() ? true : null);
>(!localDesktopAuth || hasDesktopManualLogout() ? true : null);
const [desktopAutoSessionRetries, setDesktopAutoSessionRetries] = useState(0);
// Set only when the Electron main process reports that the embedded
// backend died for good, which is the one case where retrying the
// auto-session forever is wrong.
const [embeddedServerFailure, setEmbeddedServerFailure] =
useState<EmbeddedServerFailure | null>(null);
useEffect(() => {
if (proxySigninHandledRef.current || isElectron()) return;
@@ -341,6 +367,11 @@ export function Auth({ onLogin }: AuthProps) {
}, [t]);
useEffect(() => {
if (localDesktopAuth) {
setSsoProvidersLoaded(true);
setOidcSilentLoginDefaultLoaded(true);
return;
}
getRegistrationAllowed()
.then((res) => setRegistrationAllowed(res.allowed))
.catch(() => {});
@@ -358,7 +389,7 @@ export function Auth({ onLogin }: AuthProps) {
.then((res) => setOidcSilentLoginDefault(res.enabled))
.catch(() => {})
.finally(() => setOidcSilentLoginDefaultLoaded(true));
}, []);
}, [localDesktopAuth]);
useEffect(() => {
// Runs once the auto-session probe has settled (immediately outside
@@ -366,6 +397,10 @@ export function Auth({ onLogin }: AuthProps) {
// Electron). Waiting avoids flashing a login screen the user is about
// to skip past via auto-login.
if (desktopAutoSessionDone !== true) return;
if (localDesktopAuth) {
setDbHealthChecking(false);
return;
}
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
@@ -408,7 +443,7 @@ export function Auth({ onLogin }: AuthProps) {
cancelled = true;
if (retryTimer) clearTimeout(retryTimer);
};
}, [desktopAutoSessionDone]);
}, [desktopAutoSessionDone, localDesktopAuth]);
// A cold first launch spawns the embedded backend as a separate process
// that can take anywhere from a couple seconds to much longer to finish
@@ -419,20 +454,37 @@ export function Auth({ onLogin }: AuthProps) {
// "retry" outcome (connection error, not a real verdict) is retried
// forever with capped backoff rather than ever giving up and falling
// through to the login form: that form is not a valid destination for a
// standalone install with no remote sync configured, since the only
// local account has no password to log in with. Only a definitive
// "declined" (backend reachable and says no -- multiple users, or the
// sole local user has a real credential) stops retrying and shows the
// real form.
// standalone install with no remote sync configured. Only a definitive
// "declined" stops retrying and shows a local recovery panel.
useEffect(() => {
if (desktopAutoSessionDone !== null) return;
if (embeddedServerFailure) return;
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
// "Retry forever" holds only while the backend could still be booting.
// If the main process reports that it exited -- a port conflict being
// by far the most common cause -- there is nothing left to wait for, so
// the reason is shown instead of an unending spinner.
const retryUnlessBackendIsGone = async () => {
const failure = await getEmbeddedServerFailure();
if (cancelled) return;
if (failure) {
setEmbeddedServerFailure(failure);
return;
}
const delay = Math.min(1000 * 2 ** desktopAutoSessionRetries, 10000);
retryTimer = setTimeout(() => {
if (!cancelled) setDesktopAutoSessionRetries((c) => c + 1);
}, delay);
};
requestDesktopAutoSession()
.then((outcome) => {
if (cancelled) return;
if (outcome.kind === "success") {
storeAuth(outcome.data.username || "");
clearDesktopManualLogout();
onLogin(
outcome.data.username || "",
outcome.data.userId || undefined,
@@ -441,26 +493,25 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
if (outcome.kind === "retry") {
const delay = Math.min(1000 * 2 ** desktopAutoSessionRetries, 10000);
retryTimer = setTimeout(() => {
if (!cancelled) setDesktopAutoSessionRetries((c) => c + 1);
}, delay);
void retryUnlessBackendIsGone();
return;
}
setDesktopAutoSessionDone(true);
})
.catch(() => {
if (cancelled) return;
const delay = Math.min(1000 * 2 ** desktopAutoSessionRetries, 10000);
retryTimer = setTimeout(() => {
if (!cancelled) setDesktopAutoSessionRetries((c) => c + 1);
}, delay);
void retryUnlessBackendIsGone();
});
return () => {
cancelled = true;
if (retryTimer) clearTimeout(retryTimer);
};
}, [desktopAutoSessionDone, desktopAutoSessionRetries, onLogin]);
}, [
desktopAutoSessionDone,
desktopAutoSessionRetries,
embeddedServerFailure,
onLogin,
]);
useEffect(() => {
if (view === "totp" && totpInputRef.current) totpInputRef.current.focus();
@@ -519,26 +570,41 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
if (isInElectronWebView()) {
window.parent.postMessage(
{
type: "AUTH_SUCCESS",
source: "oidc_callback",
platform: "desktop",
timestamp: Date.now(),
},
"*",
);
setWebviewAuthSuccess(true);
window.history.replaceState(
{},
document.title,
window.location.pathname,
);
// Electron Remote Sync embeds the remote server in an iframe. The
// OIDC callback authenticates by setting the remote origin's
// HttpOnly cookie, so read the JWT back before notifying the parent.
const postToken = (token: string | null) => {
window.parent.postMessage(
{
type: "AUTH_SUCCESS",
source: "oidc_callback",
platform: "desktop",
token,
timestamp: Date.now(),
},
"*",
);
setWebviewAuthSuccess(true);
window.history.replaceState(
{},
document.title,
window.location.pathname,
);
};
const urlToken = urlParams.get("token");
if (urlToken) {
postToken(urlToken);
} else {
getCurrentToken()
.then((token) => postToken(token ?? null))
.catch(() => postToken(null));
}
return;
}
getUserInfo()
.then((meRes) => {
storeAuth(meRes.username || "");
clearDesktopManualLogout();
onLogin(
meRes.username || "",
meRes.userId || undefined,
@@ -576,6 +642,13 @@ export function Auth({ onLogin }: AuthProps) {
setView(v);
}
function continueLocalDesktopSession() {
clearDesktopManualLogout();
setDesktopManualLogoutActive(false);
setDesktopAutoSessionRetries(0);
setDesktopAutoSessionDone(null);
}
async function handleLogin(e: React.FormEvent) {
e.preventDefault();
if (!username.trim()) {
@@ -623,6 +696,7 @@ export function Auth({ onLogin }: AuthProps) {
}
const meRes = await getUserInfo();
storeAuth(meRes.username || username.trim());
clearDesktopManualLogout();
toast.success(t("messages.loginSuccess"));
onLogin(
meRes.username || username.trim(),
@@ -764,6 +838,7 @@ export function Auth({ onLogin }: AuthProps) {
}
const meRes = await getUserInfo();
storeAuth(meRes.username || username.trim());
clearDesktopManualLogout();
toast.success(t("messages.registrationSuccess"));
onLogin(
meRes.username || username.trim(),
@@ -823,6 +898,7 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
storeAuth(res.username || username);
clearDesktopManualLogout();
toast.success(t("messages.loginSuccess"));
onLogin(
res.username || username,
@@ -1034,6 +1110,7 @@ export function Auth({ onLogin }: AuthProps) {
);
const meRes = await getUserInfo();
storeAuth(meRes.username || "");
clearDesktopManualLogout();
toast.success(t("messages.loginSuccess"));
onLogin(
meRes.username || "",
@@ -1098,6 +1175,46 @@ export function Auth({ onLogin }: AuthProps) {
// Electron, non-iframed: wait for the auto-session probe before rendering
// anything, so a standalone desktop install never flashes a login form
// it's about to skip past.
if (embeddedServerFailure) {
const detail =
embeddedServerFailure.reason === "port-in-use"
? embeddedServerFailure.port !== null
? t("messages.embeddedServerPortInUse", {
port: embeddedServerFailure.port,
})
: t("messages.embeddedServerPortInUseUnknownPort")
: t("messages.embeddedServerCrashed");
return (
<div className="fixed inset-0 flex items-center justify-center bg-background p-6">
<div className="flex flex-col gap-5 p-6 border border-border bg-card max-w-sm w-full">
<div className="flex flex-col gap-1">
<p className="font-bold text-destructive">
{t("errors.embeddedServerFailed")}
</p>
<p className="text-sm text-muted-foreground">{detail}</p>
</div>
<div className="flex items-center justify-between pt-2 border-t border-border">
<span className="text-xs text-muted-foreground">
{t("common.language")}
</span>
<select
value={language}
onChange={(e) => handleLanguageChange(e.target.value)}
className="px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
>
{LANGUAGES.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.label}
</option>
))}
</select>
</div>
</div>
</div>
);
}
if (
isElectron() &&
!isInElectronWebView() &&
@@ -1139,7 +1256,7 @@ export function Auth({ onLogin }: AuthProps) {
<span className="text-xs text-muted-foreground">
{t("common.language")}
</span>
<select
<Select2
value={language}
onChange={(e) => handleLanguageChange(e.target.value)}
className="px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
@@ -1149,7 +1266,7 @@ export function Auth({ onLogin }: AuthProps) {
{lang.label}
</option>
))}
</select>
</Select2>
</div>
</div>
</div>
@@ -1162,6 +1279,79 @@ export function Auth({ onLogin }: AuthProps) {
</div>
);
if (localDesktopAuth)
return (
<div className="fixed inset-0 flex flex-col bg-background overflow-hidden">
<div className="flex flex-1 overflow-hidden">
<div className="hidden lg:flex flex-col w-[420px] shrink-0 bg-sidebar border-r border-border relative overflow-hidden select-none">
<div
className="absolute inset-0"
style={{
backgroundImage:
"radial-gradient(circle, color-mix(in oklch, var(--border) 80%, transparent) 1px, transparent 1px)",
backgroundSize: "24px 24px",
}}
/>
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 z-10 px-12">
<span className="text-4xl font-bold tracking-[0.3em] font-mono">
TERMIX
</span>
<div className="w-8 h-px bg-accent-brand" />
<span className="text-[11px] font-mono text-muted-foreground uppercase tracking-[0.25em]">
{t("auth.tagline")}
</span>
</div>
</div>
<div className="flex flex-1 items-center justify-center p-6 overflow-y-auto relative">
<div className="w-full max-w-sm flex flex-col gap-6">
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<h1 className="text-xl font-bold">
{desktopManualLogoutActive
? "Local desktop signed out"
: "Local desktop session unavailable"}
</h1>
<p className="text-xs text-muted-foreground leading-relaxed">
{desktopManualLogoutActive
? "You signed out of the local desktop session. Continue locally to use this device's embedded Termix server again."
: "Termix could not create a local desktop session. Retry the embedded local session instead of registering a new account."}
</p>
</div>
<Button
type="button"
variant={desktopManualLogoutActive ? "outline" : "default"}
className="w-full"
onClick={continueLocalDesktopSession}
>
{desktopManualLogoutActive
? "Continue with local desktop"
: "Retry local desktop session"}
</Button>
<Separator />
<div className="flex items-center justify-between pt-1">
<span className="text-xs text-muted-foreground">
{t("common.language")}
</span>
<Select2
value={language}
onChange={(e) => handleLanguageChange(e.target.value)}
className="px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
>
{LANGUAGES.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.label}
</option>
))}
</Select2>
</div>
</div>
</div>
</div>
</div>
</div>
);
const TAB_ITEMS: { id: AuthView; label: string; show: boolean }[] = [
{
id: "login",
@@ -1194,12 +1384,19 @@ export function Auth({ onLogin }: AuthProps) {
}}
/>
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 z-10 px-12">
<span className="text-4xl font-bold tracking-[0.3em] font-mono">
TERMIX
{branding.logo && (
<img
src={branding.logo}
alt=""
className="w-16 h-16 object-contain mb-1"
/>
)}
<span className="text-4xl font-bold tracking-[0.3em] font-mono uppercase">
{branding.appName}
</span>
<div className="w-8 h-px bg-accent-brand" />
<span className="text-[11px] font-mono text-muted-foreground uppercase tracking-[0.25em]">
{t("auth.tagline")}
{branding.tagline || t("auth.tagline")}
</span>
</div>
</div>
@@ -1731,7 +1928,7 @@ export function Auth({ onLogin }: AuthProps) {
<span className="text-xs text-muted-foreground">
{t("common.language")}
</span>
<select
<Select2
value={language}
onChange={(e) => handleLanguageChange(e.target.value)}
className="px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
@@ -1741,7 +1938,7 @@ export function Auth({ onLogin }: AuthProps) {
{lang.label}
</option>
))}
</select>
</Select2>
</div>
</div>
)}
+31 -21
View File
@@ -20,6 +20,10 @@ interface SaveRemoteSyncJwtResult {
success: boolean;
reason?: string;
error?: string;
status?: {
needsReauth?: boolean;
lastError?: string | null;
} | null;
}
const AUTH_MESSAGE_SOURCES = new Set([
@@ -56,27 +60,33 @@ export function ElectronLoginForm({
setIsAuthenticating(true);
try {
if (token) {
if (targetPurpose === "remoteSync") {
// The main process refuses to persist the JWT when it has no OS
// keyring to encrypt it with, and reports that by resolving with
// success: false. Dropping the result signs the user in against a
// store that kept nothing, so the next sync tick calls a session
// that was never saved expired.
const result = (await window.electronAPI?.invoke?.(
"save-remote-sync-jwt",
token,
)) as SaveRemoteSyncJwtResult | undefined;
if (!result?.success) {
throw new Error(
result?.reason === "encryption_unavailable"
? t("errors.keyringUnavailable")
: result?.error || t("errors.authTokenSaveFailed"),
);
}
} else {
localStorage.setItem("jwt", token);
if (targetPurpose === "remoteSync") {
if (!token) {
throw new Error(t("errors.authTokenMissing"));
}
// The main process refuses to persist the JWT when it has no OS
// keyring to encrypt it with, and reports that by resolving with
// success: false. Dropping the result signs the user in against a
// store that kept nothing, so the next sync tick calls a session
// that was never saved expired.
const result = (await window.electronAPI?.invoke?.(
"save-remote-sync-jwt",
token,
)) as SaveRemoteSyncJwtResult | undefined;
if (!result?.success) {
throw new Error(
result?.reason === "encryption_unavailable"
? t("errors.keyringUnavailable")
: result?.error || t("errors.authTokenSaveFailed"),
);
}
if (result.status?.needsReauth || result.status?.lastError) {
throw new Error(
result.status.lastError || t("errors.authTokenRejected"),
);
}
} else if (token) {
localStorage.setItem("jwt", token);
}
await onAuthSuccessRef.current(token);
} catch (err) {
@@ -307,7 +317,7 @@ export function ElectronLoginForm({
className="w-full h-full border-0"
title="Server Authentication"
sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-storage-access-by-user-activation allow-top-navigation allow-top-navigation-by-user-activation allow-modals allow-downloads"
allow="clipboard-read; clipboard-write"
allow="clipboard-read; clipboard-write; publickey-credentials-get; publickey-credentials-create"
/>
</div>
</div>
+1 -1
View File
@@ -6,7 +6,7 @@ import { Slot } from "radix-ui";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group/button inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,opacity,box-shadow,transform] outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
@@ -2,7 +2,7 @@ import React from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils.ts";
import { Button } from "@/components/button.tsx";
import { RefreshCw } from "lucide-react";
import { Loader2, RefreshCw } from "lucide-react";
import { ConnectionLogPanel } from "@/components/connection/ConnectionLogPanel.tsx";
import type { ConnectionStatus } from "@/components/connection/connection-status.ts";
@@ -49,7 +49,13 @@ export function ConnectionScreen({
return (
<div
className={cn("absolute inset-0 z-[100] flex flex-col", className)}
role="status"
aria-live="polite"
data-status={status}
className={cn(
"motion-context-enter absolute inset-0 z-[100] flex flex-col",
className,
)}
style={{ backgroundColor: backgroundColor || "var(--bg-base)" }}
>
<div className="flex-1 min-h-0 flex items-center justify-center">
@@ -57,7 +63,12 @@ export function ConnectionScreen({
emptyState
) : (
<div className="flex flex-col items-center gap-4 px-6 text-center">
{showSpinner && <div className="simple-spinner" />}
{showSpinner && (
<Loader2
className="size-8 animate-spin text-accent-brand"
aria-hidden="true"
/>
)}
{message && (
<p className="text-sm text-foreground-secondary font-medium">
{message}
@@ -105,23 +116,6 @@ export function ConnectionScreen({
position={logPosition}
/>
)}
<style>
{`
@keyframes connection-screen-spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.simple-spinner {
width: 40px;
height: 40px;
border: 4px solid var(--border-base);
border-top-color: var(--foreground);
border-radius: 50%;
animation: connection-screen-spin 0.8s linear infinite;
}
`}
</style>
</div>
);
}
-167
View File
@@ -1,167 +0,0 @@
/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import {
Controller,
FormProvider,
useFormContext,
useFormState,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form";
import { cn } from "@/lib/utils";
import { Label } from "@/components/label";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue,
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState } = useFormContext();
const formState = useFormState({ name: fieldContext.name });
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue,
);
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div
data-slot="form-item"
className={cn("grid gap-2", className)}
{...props}
/>
</FormItemContext.Provider>
);
}
function FormLabel({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
const { error, formItemId } = useFormField();
return (
<Label
data-slot="form-label"
data-error={!!error}
className={cn("data-[error=true]:text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
}
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
data-slot="form-control"
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
}
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
const { formDescriptionId } = useFormField();
return (
<p
data-slot="form-description"
id={formDescriptionId}
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : props.children;
if (!body) {
return null;
}
return (
<p
data-slot="form-message"
id={formMessageId}
className={cn("text-destructive text-sm", className)}
{...props}
>
{body}
</p>
);
}
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};
@@ -11,13 +11,7 @@ import {
DialogTitle,
DialogFooter,
} from "@/components/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/select";
import { Select2 } from "@/components/select2";
import {
discoverProxmoxGuestsStream,
bulkImportSSHHosts,
@@ -270,26 +264,19 @@ export function ProxmoxDiscoverDialog({
{/* Host selector — hidden when launched from a specific host */}
{!preselectedHostId && (
<div className="flex gap-2">
<Select
<Select2
value={selectedHostId}
onValueChange={setSelectedHostId}
onChange={(event) => setSelectedHostId(event.target.value)}
disabled={discovering}
placeholder={t("hosts.proxmoxSelectHost")}
className="flex-1 text-xs h-8"
>
<SelectTrigger className="flex-1 text-xs h-8">
<SelectValue placeholder={t("hosts.proxmoxSelectHost")} />
</SelectTrigger>
<SelectContent>
{sshHosts.map((h) => (
<SelectItem
key={h.id}
value={String(h.id)}
className="text-xs"
>
{h.name || h.ip}
</SelectItem>
))}
</SelectContent>
</Select>
{sshHosts.map((h) => (
<option key={h.id} value={String(h.id)}>
{h.name || h.ip}
</option>
))}
</Select2>
<Button
size="sm"
variant="outline"
@@ -3,6 +3,7 @@ const SECRETLESS_AUTH_TYPES = new Set([
"none",
"agent",
"opkssh",
"stepca",
"tailscale",
"vault",
]);
+3
View File
@@ -65,10 +65,12 @@ export function SettingRow({
export function FakeSwitch({
defaultChecked = false,
disabled = false,
checked,
onChange,
}: {
defaultChecked?: boolean;
disabled?: boolean;
checked?: boolean;
onChange?: (v: boolean) => void;
}) {
@@ -76,6 +78,7 @@ export function FakeSwitch({
const on = checked !== undefined ? checked : internalOn;
return (
<button
disabled={disabled}
onClick={() => {
const next = !on;
if (checked === undefined) setInternalOn(next);
+236
View File
@@ -0,0 +1,236 @@
import * as React from "react";
import { Check, ChevronDown, Search } from "lucide-react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/popover";
import { cn } from "@/lib/utils";
type Select2Option = {
value: string;
label: string;
disabled: boolean;
hidden: boolean;
group?: string;
};
type Select2Props = Omit<
React.ButtonHTMLAttributes<HTMLButtonElement>,
"value" | "defaultValue" | "onChange"
> &
Pick<
React.SelectHTMLAttributes<HTMLSelectElement>,
"value" | "defaultValue" | "onChange" | "required"
> & {
placeholder?: string;
};
function getText(children: React.ReactNode): string {
return React.Children.toArray(children)
.map((child) => {
if (typeof child === "string" || typeof child === "number") {
return String(child);
}
if (React.isValidElement<{ children?: React.ReactNode }>(child)) {
return getText(child.props.children);
}
return "";
})
.join("")
.trim();
}
function getOptions(
children: React.ReactNode,
group?: string,
): Select2Option[] {
return React.Children.toArray(children).flatMap((child) => {
if (!React.isValidElement(child)) return [];
if (child.type === "optgroup") {
const props =
child.props as React.OptgroupHTMLAttributes<HTMLOptGroupElement>;
return getOptions(props.children, props.label);
}
if (child.type !== "option") return [];
const props = child.props as React.OptionHTMLAttributes<HTMLOptionElement>;
const label = props.label ?? getText(props.children);
return [
{
value: String(props.value ?? label),
label,
disabled: Boolean(props.disabled),
hidden: Boolean(props.hidden),
group,
},
];
});
}
function createSelectChangeEvent(
value: string,
name: string | undefined,
): React.ChangeEvent<HTMLSelectElement> {
return {
target: { value, name },
currentTarget: { value, name },
} as React.ChangeEvent<HTMLSelectElement>;
}
function Select2({
className,
children,
value,
defaultValue,
onChange,
disabled,
placeholder,
name,
id,
required,
"aria-label": ariaLabel,
...props
}: Select2Props) {
const options = React.useMemo(() => getOptions(children), [children]);
const [open, setOpen] = React.useState(false);
const [query, setQuery] = React.useState("");
const [uncontrolledValue, setUncontrolledValue] = React.useState(
String(defaultValue ?? ""),
);
const currentValue =
value === undefined ? uncontrolledValue : String(value ?? "");
const selected = options.find((option) => option.value === currentValue);
const visibleOptions = options.filter((option) => !option.hidden);
const normalizedQuery = query.trim().toLowerCase();
const filteredOptions = visibleOptions.filter((option) => {
if (!normalizedQuery) return true;
return (
option.label.toLowerCase().includes(normalizedQuery) ||
option.value.toLowerCase().includes(normalizedQuery) ||
option.group?.toLowerCase().includes(normalizedQuery)
);
});
const selectValue = (nextValue: string) => {
if (value === undefined) setUncontrolledValue(nextValue);
onChange?.(createSelectChangeEvent(nextValue, name));
setOpen(false);
setQuery("");
};
React.useEffect(() => {
if (!open) setQuery("");
}, [open]);
return (
<Popover open={open} onOpenChange={setOpen}>
<select
name={name}
value={currentValue}
disabled={disabled}
required={required}
aria-label={ariaLabel}
className="sr-only"
tabIndex={-1}
onChange={(event) => selectValue(event.target.value)}
>
{children}
</select>
<PopoverTrigger asChild>
<button
type="button"
id={id}
name={name}
disabled={disabled}
aria-label={ariaLabel}
aria-haspopup="listbox"
aria-expanded={open}
aria-required={required}
className={cn(
"border-input bg-background text-foreground flex h-9 w-full items-center justify-between gap-2 rounded-none border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "Enter") {
event.preventDefault();
setOpen(true);
}
}}
{...props}
>
<span
className={cn(
"min-w-0 flex-1 truncate text-left",
!selected && "text-muted-foreground",
)}
>
{selected?.label || placeholder || "Select an option"}
</span>
<ChevronDown className="size-4 shrink-0 text-muted-foreground opacity-70" />
</button>
</PopoverTrigger>
<PopoverContent
align="start"
className="z-[99999] w-[var(--radix-popover-trigger-width)] min-w-52 p-0"
>
<div className="flex items-center border-b border-border px-2">
<Search className="mr-2 size-4 shrink-0 text-muted-foreground" />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search..."
className="h-9 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
autoFocus
/>
</div>
<div
role="listbox"
className="max-h-64 overflow-y-auto p-1 thin-scrollbar"
>
{filteredOptions.length === 0 ? (
<div className="px-2 py-6 text-center text-sm text-muted-foreground">
No results found
</div>
) : (
filteredOptions.map((option, index) => {
const showGroup =
option.group &&
filteredOptions
.slice(0, index)
.every((previous) => previous.group !== option.group);
const isSelected = option.value === currentValue;
return (
<React.Fragment key={`${option.group ?? ""}:${option.value}`}>
{showGroup && (
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
{option.group}
</div>
)}
<button
type="button"
role="option"
aria-selected={isSelected}
disabled={option.disabled}
className={cn(
"flex w-full items-center gap-2 rounded-none px-2 py-1.5 text-left text-sm outline-none transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50",
isSelected && "bg-muted text-accent-foreground",
)}
onClick={() => selectValue(option.value)}
>
<span className="min-w-0 flex-1 truncate">
{option.label}
</span>
{isSelected && <Check className="size-4 shrink-0" />}
</button>
</React.Fragment>
);
})
)}
</div>
</PopoverContent>
</Popover>
);
}
export { Select2 };
+1 -1
View File
@@ -11,7 +11,7 @@ function Switch({
<SwitchPrimitive.Root
data-slot="switch"
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-[background-color,border-color,box-shadow,opacity] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
{...props}
-114
View File
@@ -1,114 +0,0 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto thin-scrollbar"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};
+2 -1
View File
@@ -1,7 +1,7 @@
import { useTranslation } from "react-i18next";
interface VersionBadgeProps {
status: "up_to_date" | "requires_update" | "beta";
status: "up_to_date" | "requires_update" | "beta" | "unknown";
releaseUrl?: string;
className?: string;
}
@@ -12,6 +12,7 @@ export function VersionBadge({
className = "",
}: VersionBadgeProps) {
const { t } = useTranslation();
if (status === "unknown") return null;
const badgeClassName = `text-[10px] px-1.5 py-0.5 font-semibold leading-none ${
status === "beta"
+106
View File
@@ -0,0 +1,106 @@
/* eslint-disable react-refresh/only-export-components */
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { getBranding, type BrandingSettings } from "@/api/settings-api";
import {
BRANDING_ICON_SELECTORS,
captureDefaultIconHrefs,
nextIconHref,
} from "./branding-document.ts";
const DEFAULT_APP_NAME = "Termix";
const DEFAULT_ICON_HREFS: Record<string, string> = {};
interface BrandingContextValue {
ready: boolean;
appName: string;
tagline: string;
logo: string | null;
/** Re-applies a freshly saved BrandingSettings without a page reload. */
applyBranding: (settings: BrandingSettings) => void;
}
const BrandingContext = createContext<BrandingContextValue>({
ready: false,
appName: DEFAULT_APP_NAME,
tagline: "",
logo: null,
applyBranding: () => {},
});
function applyDocumentBranding(settings: BrandingSettings): void {
document.title = settings.appName;
if (settings.logo) {
captureDefaultIconHrefs(DEFAULT_ICON_HREFS, (selector) =>
document.querySelector<HTMLLinkElement>(selector),
);
}
for (const selector of BRANDING_ICON_SELECTORS) {
const link = document.querySelector<HTMLLinkElement>(selector);
if (!link) continue;
link.href = nextIconHref(
settings.logo,
DEFAULT_ICON_HREFS[selector],
link.href,
);
}
}
export function BrandingProvider({ children }: { children: ReactNode }) {
const [ready, setReady] = useState(false);
const [branding, setBranding] = useState<BrandingSettings>({
appName: DEFAULT_APP_NAME,
tagline: "",
logo: null,
});
useEffect(() => {
let cancelled = false;
getBranding()
.then((settings) => {
if (cancelled) return;
setBranding(settings);
applyDocumentBranding(settings);
})
.catch(() => {})
.finally(() => {
if (!cancelled) setReady(true);
});
return () => {
cancelled = true;
};
}, []);
const applyBranding = useCallback((settings: BrandingSettings) => {
setBranding(settings);
applyDocumentBranding(settings);
}, []);
const value = useMemo(
() => ({
ready,
appName: branding.appName,
tagline: branding.tagline,
logo: branding.logo,
applyBranding,
}),
[ready, branding, applyBranding],
);
return (
<BrandingContext.Provider value={value}>
{children}
</BrandingContext.Provider>
);
}
export function useBranding(): BrandingContextValue {
return useContext(BrandingContext);
}
+29
View File
@@ -0,0 +1,29 @@
export const BRANDING_ICON_SELECTORS = [
'link[rel="icon"]',
'link[rel="apple-touch-icon"]',
] as const;
/**
* Snapshot bundled favicon hrefs before the first custom logo is written.
* Reset then restores those snapshots instead of leaving the previous upload
* in the tab until a full reload.
*/
export function captureDefaultIconHrefs(
stored: Record<string, string>,
query: (selector: string) => { href: string } | null,
): void {
for (const selector of BRANDING_ICON_SELECTORS) {
if (stored[selector]) continue;
const link = query(selector);
if (link?.href) stored[selector] = link.href;
}
}
export function nextIconHref(
customLogo: string | null,
defaultHref: string | undefined,
currentHref: string,
): string {
if (customLogo) return customLogo;
return defaultHref ?? currentHref;
}
+37 -10
View File
@@ -139,7 +139,7 @@ function StatsBarCard({
hosts: Host[];
uptimeFormatted: string;
versionText: string;
versionStatus: "up_to_date" | "requires_update" | "beta";
versionStatus: "up_to_date" | "requires_update" | "beta" | "unknown";
releaseUrl: string;
dbHealth: "healthy" | "error";
}) {
@@ -473,7 +473,20 @@ export function HostStatusCard({
return (
<div
key={i}
onClick={() => onOpenTab(host, "host-metrics")}
onClick={() =>
onOpenTab(
host,
host.enableSsh
? "host-metrics"
: host.enableRdp
? "rdp"
: host.enableVnc
? "vnc"
: host.enableTelnet
? "telnet"
: "host-metrics",
)
}
className="flex min-w-0 items-center justify-between px-4 py-2.5 border-b border-border last:border-0 hover:bg-muted/50 cursor-pointer group/row"
>
<div className="flex min-w-0 flex-1 items-center gap-2.5">
@@ -838,7 +851,7 @@ function CardItem({
>;
uptimeFormatted: string;
versionText: string;
versionStatus: "up_to_date" | "requires_update" | "beta";
versionStatus: "up_to_date" | "requires_update" | "beta" | "unknown";
releaseUrl: string;
dbHealth: "healthy" | "error";
credentialCount: number;
@@ -1066,7 +1079,7 @@ type PanelColumnProps = {
>;
uptimeFormatted: string;
versionText: string;
versionStatus: "up_to_date" | "requires_update" | "beta";
versionStatus: "up_to_date" | "requires_update" | "beta" | "unknown";
releaseUrl: string;
dbHealth: "healthy" | "error";
credentialCount: number;
@@ -1327,7 +1340,7 @@ export function DashboardTab({
const [uptimeFormatted, setUptimeFormatted] = useState("");
const [versionText, setVersionText] = useState("");
const [versionStatus, setVersionStatus] = useState<
"up_to_date" | "requires_update" | "beta"
"up_to_date" | "requires_update" | "beta" | "unknown"
>("up_to_date");
const [releaseUrl, setReleaseUrl] = useState("");
const [dbHealth, setDbHealth] = useState<"healthy" | "error">("healthy");
@@ -1357,11 +1370,19 @@ export function DashboardTab({
const hostId = Number(host.id);
const knownStatus = statuses?.[hostId]?.status;
if (knownStatus === "offline") return null;
if (host.authType === "none" || host.authType === "opkssh") return null;
if (
host.authType === "none" ||
host.authType === "opkssh" ||
host.authType === "stepca"
)
return null;
try {
const existing = newSessions.get(hostId);
if (!existing) {
if (existing && !(await sendMetricsHeartbeat(existing))) {
newSessions.delete(hostId);
}
if (!newSessions.has(hostId)) {
const reg = await registerMetricsViewer(hostId);
if (reg.skipped) return null;
if (reg.success && reg.viewerSessionId) {
@@ -1421,7 +1442,7 @@ export function DashboardTab({
getVersionInfo()
.then((info) => {
setVersionText(info.localVersion ?? "");
setVersionStatus(info.status ?? "up_to_date");
setVersionStatus(info.status ?? "unknown");
setReleaseUrl(releaseUrlFrom(info));
})
.catch(() => {});
@@ -1484,8 +1505,14 @@ export function DashboardTab({
if (!isVisible || viewerSessionsRef.current.size === 0) return;
const heartbeat = setInterval(async () => {
if (document.visibilityState === "hidden") return;
for (const [, sessionId] of viewerSessionsRef.current) {
sendMetricsHeartbeat(sessionId).catch(() => {});
for (const [hostId, sessionId] of viewerSessionsRef.current) {
sendMetricsHeartbeat(sessionId)
.then((alive) => {
if (!alive && viewerSessionsRef.current.get(hostId) === sessionId) {
viewerSessionsRef.current.delete(hostId);
}
})
.catch(() => {});
}
}, 30000);
return () => clearInterval(heartbeat);
+11 -10
View File
@@ -63,6 +63,7 @@ import { useTranslation } from "react-i18next";
import { useTabsSafe } from "@/shell/TabContext";
import { cn } from "@/lib/utils";
import { readStatusColorScheme } from "@/hooks/use-status-color-scheme";
import { Select2 } from "@/components/select2";
const AVAILABLE_COLORS = [
{ value: "#ef4444", label: "Red" },
@@ -961,7 +962,7 @@ export function NetworkGraphCard({
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>{t("networkGraph.selectHost")}</Label>
<select
<Select2
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={selectedHostForAddNode}
onChange={(e) => setSelectedHostForAddNode(e.target.value)}
@@ -972,11 +973,11 @@ export function NetworkGraphCard({
{h.name || h.ip}
</option>
))}
</select>
</Select2>
</div>
<div className="grid gap-2">
<Label>{t("networkGraph.parentGroup")}</Label>
<select
<Select2
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={selectedGroupForAddNode}
onChange={(e) => setSelectedGroupForAddNode(e.target.value)}
@@ -987,7 +988,7 @@ export function NetworkGraphCard({
{g.label}
</option>
))}
</select>
</Select2>
</div>
</div>
<DialogFooter>
@@ -1084,7 +1085,7 @@ export function NetworkGraphCard({
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>{t("networkGraph.selectGroup")}</Label>
<select
<Select2
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={selectedGroupForMove}
onChange={(e) => setSelectedGroupForMove(e.target.value)}
@@ -1097,7 +1098,7 @@ export function NetworkGraphCard({
{g.label}
</option>
))}
</select>
</Select2>
</div>
</div>
<DialogFooter>
@@ -1123,7 +1124,7 @@ export function NetworkGraphCard({
<div className="grid gap-4 py-4">
<div className="grid gap-2">
<Label>{t("networkGraph.source")}</Label>
<select
<Select2
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={selectedHostForEdge}
onChange={(e) => setSelectedHostForEdge(e.target.value)}
@@ -1136,11 +1137,11 @@ export function NetworkGraphCard({
{el.label}
</option>
))}
</select>
</Select2>
</div>
<div className="grid gap-2">
<Label>{t("networkGraph.target")}</Label>
<select
<Select2
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
value={targetHostForEdge}
onChange={(e) => setTargetHostForEdge(e.target.value)}
@@ -1153,7 +1154,7 @@ export function NetworkGraphCard({
{el.label}
</option>
))}
</select>
</Select2>
</div>
</div>
<DialogFooter>
+13 -1
View File
@@ -12,6 +12,7 @@ import type { SSHHost } from "@/types";
import { Auth } from "@/auth/Auth.tsx";
import { Toaster } from "@/components/sonner.tsx";
import { dbHealthMonitor } from "@/lib/db-health-monitor.ts";
import { getEmbeddedServerFailure } from "@/lib/embedded-server-status.ts";
import { useTranslation } from "react-i18next";
import { ConnectionScreen } from "@/components/connection/ConnectionScreen.tsx";
@@ -89,7 +90,18 @@ export const FullScreenAppWrapper: React.FC<FullScreenAppWrapperProps> = ({
setAuthLoading(false);
return;
}
// "retry": keep retrying indefinitely with capped backoff.
// "retry": keep retrying indefinitely with capped backoff -- but
// only while the embedded backend could still be booting. Once the
// main process reports it exited for good (a port conflict, most
// often), fall through to the unauthenticated render, where Auth
// shows the actual reason rather than spinning forever.
if (await getEmbeddedServerFailure()) {
if (cancelled) return;
setIsAuthenticated(false);
setAuthLoading(false);
return;
}
if (cancelled) return;
const delay = Math.min(1000 * 2 ** attempt, 10000);
retryTimer = setTimeout(() => {
if (!cancelled) checkAuth(attempt + 1);
+12 -4
View File
@@ -85,21 +85,24 @@ function AiProviderEditForm({
const [models, setModels] = useState<string[]>([]);
const [customModel, setCustomModel] = useState(false);
const [detecting, setDetecting] = useState(false);
const [detectWarning, setDetectWarning] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const detectModels = useCallback(async () => {
setDetecting(true);
setDetectWarning(null);
try {
const detected = await getAiProviderModels(provider.id);
setModels(detected);
setCustomModel(!!defaultModel && !detected.includes(defaultModel));
} catch {
} catch (error) {
setModels([]);
setCustomModel(true);
setDetectWarning(getErrorMessage(error, t("ai.modelDetectFailed")));
} finally {
setDetecting(false);
}
}, [provider.id, defaultModel]);
}, [provider.id, defaultModel, t]);
useEffect(() => {
void detectModels();
@@ -203,6 +206,11 @@ function AiProviderEditForm({
placeholder={t("ai.defaultModelPlaceholder")}
/>
)}
{detectWarning && (
<p className="text-[11px] leading-snug text-destructive">
{detectWarning}
</p>
)}
</div>
<div className="flex gap-2">
@@ -269,8 +277,8 @@ export function AiProviderSettings({
apiKey: apiKey.trim() || null,
});
setModels(result.models);
if (result.source === "fallback") {
setDetectWarning(t("ai.modelDetectFailed"));
if (result.source !== "live") {
setDetectWarning(result.warning || t("ai.modelDetectFailed"));
}
// Pick the first suggestion so the field is never left empty.
setDefaultModel((current) => current || result.models[0] || "");
+125
View File
@@ -0,0 +1,125 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { AlertCircle, Eye, Presentation, Users } from "lucide-react";
import { GuacamoleDisplay } from "@/features/guacamole/GuacamoleDisplay.tsx";
import {
GuestTerminalView,
type SessionParticipantInfo,
} from "@/features/session-sharing/SharedSessionView";
import {
resolveCollabGuestStage,
type CollabGuestStage,
} from "@/api/collab-api";
const POLL_MS = 5000;
/**
* Anonymous guest page for a collab room (?view=collab-guest&token=...).
* Guests have no account and no event channel, so they poll the public
* resolve endpoint and remount the viewer whenever the stage share changes.
*/
export default function CollabGuestView() {
const { t } = useTranslation();
const token = new URLSearchParams(window.location.search).get("token");
const [roomName, setRoomName] = useState<string | null>(null);
const [stage, setStage] = useState<CollabGuestStage | null>(null);
const [error, setError] = useState<string | null>(null);
const [participantCount, setParticipantCount] = useState(0);
const stageShareIdRef = useRef<string | null>(null);
useEffect(() => {
if (!token) {
setError(t("collab.guest.linkInvalid"));
return;
}
let cancelled = false;
const poll = async () => {
try {
const result = await resolveCollabGuestStage(token);
if (cancelled) return;
setRoomName(result.roomName);
setError(null);
const nextShareId = result.stage?.shareId ?? null;
// Tokens are minted per resolve; only swap the viewer on a real change.
if (nextShareId !== stageShareIdRef.current) {
stageShareIdRef.current = nextShareId;
setStage(result.stage);
setParticipantCount(0);
}
} catch {
if (!cancelled) setError(t("collab.guest.linkInvalid"));
}
};
void poll();
const timer = setInterval(() => void poll(), POLL_MS);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [token, t]);
return (
<div
className="fixed inset-0 flex flex-col"
style={{ backgroundColor: "var(--bg-base)", color: "var(--foreground)" }}
>
<div className="flex items-center gap-2 px-3 py-2 border-b border-border text-sm shrink-0">
<Presentation className="size-4 text-muted-foreground shrink-0" />
<span className="font-semibold truncate min-w-0">
{roomName ?? t("collab.guest.title")}
</span>
<div className="flex items-center gap-3 shrink-0 ml-auto text-xs text-muted-foreground">
{participantCount >= 2 && (
<span className="flex items-center gap-1">
<Users className="size-3.5" />
{participantCount}
</span>
)}
<span className="flex items-center gap-1">
<Eye className="size-3.5" />
{t("sessionSharing.guestView.readOnlyBadge")}
</span>
</div>
</div>
<div className="relative flex-1 min-h-0">
{error ? (
<Note icon={<AlertCircle className="size-8" />} text={error} />
) : !stage ? (
<Note
icon={<Presentation className="size-8" />}
text={t("collab.guest.waiting")}
/>
) : stage.protocol === "ssh" ? (
<GuestTerminalView
key={stage.shareId}
share={{ permissionLevel: "read-only" }}
wsQuery={`roomGuestToken=${encodeURIComponent(token ?? "")}`}
hideBadges
onParticipantsChange={(participants: SessionParticipantInfo[]) =>
setParticipantCount(participants.length)
}
/>
) : stage.connectParams?.token ? (
<GuacamoleDisplay
key={stage.shareId}
connectionConfig={{
token: stage.connectParams.token,
protocol: stage.protocol,
type: stage.protocol,
}}
isVisible
/>
) : null}
</div>
</div>
);
}
function Note({ icon, text }: { icon: React.ReactNode; text: string }) {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 text-muted-foreground">
{icon}
<p className="text-sm">{text}</p>
</div>
);
}
@@ -0,0 +1,287 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
Check,
Crown,
Hand,
MonitorUp,
MousePointerClick,
UserMinus,
Users,
X,
} from "lucide-react";
import { Badge } from "@/components/badge";
import { Button } from "@/components/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/alert-dialog";
import type { CollabControlRequest, CollabRoomDetail } from "@/api/collab-api";
interface CollabMembersSidebarProps {
detail: CollabRoomDetail;
onClose: () => void;
onInvite: () => void;
onControl: (userId: string | null) => Promise<void>;
onDismissRequest: (userId: string) => Promise<void>;
onRemoveMember: (userId: string) => Promise<void>;
}
export function CollabMembersSidebar({
detail,
onClose,
onInvite,
onControl,
onDismissRequest,
onRemoveMember,
}: CollabMembersSidebarProps) {
const { t } = useTranslation();
const [removing, setRemoving] = useState<{
userId: string;
username: string;
} | null>(null);
const [busyUserId, setBusyUserId] = useState<string | null>(null);
const onlineIds = new Set(detail.online.map((user) => user.userId));
const presenterUserId = detail.stage.presenterUserId;
const canManageControl = detail.isHost || presenterUserId === detail.me;
const canControl =
canManageControl &&
detail.stage.protocol === "ssh" &&
!!detail.stage.shareId;
async function run(userId: string, action: () => Promise<void>) {
setBusyUserId(userId);
try {
await action();
} finally {
setBusyUserId(null);
}
}
async function grant(request: CollabControlRequest) {
await run(request.userId, async () => {
await onControl(request.userId);
});
}
return (
<aside
id="collab-members-sidebar"
aria-label={t("collab.membersPanel")}
className="absolute inset-y-0 right-0 z-30 flex h-full w-[min(20rem,100%)] shrink-0 flex-col border-l border-border bg-background shadow-xl lg:static lg:z-auto lg:shadow-none"
>
<header className="flex h-11 items-center gap-2 border-b border-border px-3">
<Users className="size-4 text-muted-foreground" />
<h2 className="flex-1 text-sm font-semibold">
{t("collab.membersWithCount", { count: detail.members.length })}
</h2>
{detail.isHost && (
<Button size="sm" variant="outline" onClick={onInvite}>
{t("collab.invite")}
</Button>
)}
<Button
size="icon-sm"
variant="ghost"
aria-label={t("common.close")}
onClick={onClose}
>
<X className="size-4" />
</Button>
</header>
{canManageControl && (
<section className="border-b border-border p-3" aria-live="polite">
<div className="mb-2 flex items-center gap-2">
<Hand className="size-3.5 text-muted-foreground" />
<h3 className="text-xs font-semibold uppercase tracking-wide">
{t("collab.controlQueue")}
</h3>
{detail.controlRequests.length > 0 && (
<Badge variant="default" className="ml-auto text-xs">
{detail.controlRequests.length}
</Badge>
)}
</div>
{detail.controlRequests.length === 0 ? (
<p className="text-xs text-muted-foreground">
{t("collab.noControlRequests")}
</p>
) : (
<div className="flex flex-col gap-2">
{detail.controlRequests.map((request) => (
<div
key={request.userId}
className="flex items-center gap-2 border border-border p-2"
>
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-medium">
{request.username}
</p>
<p className="text-xs text-muted-foreground">
{new Date(request.requestedAt).toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
})}
</p>
</div>
<Button
size="icon-sm"
aria-label={t("collab.grantControlTo", {
name: request.username,
})}
disabled={busyUserId === request.userId}
onClick={() => void grant(request)}
>
<Check className="size-3.5" />
</Button>
<Button
size="icon-sm"
variant="outline"
aria-label={t("collab.dismissControlRequest", {
name: request.username,
})}
disabled={busyUserId === request.userId}
onClick={() =>
void run(request.userId, () =>
onDismissRequest(request.userId),
)
}
>
<X className="size-3.5" />
</Button>
</div>
))}
</div>
)}
</section>
)}
<section className="min-h-0 flex-1 overflow-y-auto p-2">
<h3 className="sr-only">{t("collab.members")}</h3>
<div className="flex flex-col gap-1">
{detail.members.map((member) => {
const isOnline = onlineIds.has(member.userId);
const isPresenter = member.userId === presenterUserId;
const hasControl = member.userId === detail.controllerUserId;
return (
<div
key={member.userId}
className="group flex min-h-11 items-center gap-2 border border-transparent px-2 py-1.5 hover:border-border hover:bg-muted/40"
>
<span
className={`size-2 shrink-0 rounded-full ${
isOnline ? "bg-green-500" : "bg-muted-foreground/30"
}`}
aria-label={t(isOnline ? "collab.online" : "collab.offline")}
role="img"
/>
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-medium">
{member.username}
{member.userId === detail.me && (
<span className="ml-1 text-muted-foreground">
{t("collab.you")}
</span>
)}
</p>
<div className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">
{member.roomRole === "host" && (
<span className="flex items-center gap-1">
<Crown className="size-3" /> {t("collab.hostBadge")}
</span>
)}
{isPresenter && (
<span className="flex items-center gap-1">
<MonitorUp className="size-3" />
{t("collab.presenterBadge")}
</span>
)}
{hasControl && (
<span className="flex items-center gap-1">
<MousePointerClick className="size-3" />
{t("collab.controlBadge")}
</span>
)}
</div>
</div>
{canControl && !isPresenter && (
<Button
size="icon-sm"
variant={hasControl ? "default" : "ghost"}
aria-label={t(
hasControl
? "collab.revokeControl"
: "collab.grantControlTo",
{ name: member.username },
)}
disabled={busyUserId === member.userId}
onClick={() =>
void run(member.userId, () =>
onControl(hasControl ? null : member.userId),
)
}
>
<MousePointerClick className="size-3.5" />
</Button>
)}
{detail.isHost && member.userId !== detail.room.ownerUserId && (
<Button
size="icon-sm"
variant="ghost"
aria-label={t("collab.removeMember", {
name: member.username,
})}
onClick={() =>
setRemoving({
userId: member.userId,
username: member.username,
})
}
>
<UserMinus className="size-3.5" />
</Button>
)}
</div>
);
})}
</div>
</section>
<AlertDialog
open={Boolean(removing)}
onOpenChange={(open) => {
if (!open) setRemoving(null);
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{t("collab.removeMemberTitle")}</AlertDialogTitle>
<AlertDialogDescription>
{t("collab.removeMemberDescription", {
name: removing?.username,
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => {
if (removing) void onRemoveMember(removing.userId);
}}
>
{t("collab.deleteMember")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</aside>
);
}
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -41,6 +41,7 @@ import { ConnectionScreen } from "@/components/connection/ConnectionScreen.tsx";
import { useConnectionRetry } from "@/lib/useConnectionRetry.ts";
import { useAdaptivePolling } from "@/hooks/use-adaptive-polling.ts";
import type { LogEntry } from "@/types/connection-log.ts";
import { Select2 } from "@/components/select2";
interface DockerManagerProps {
hostConfig?: SSHHost;
@@ -709,7 +710,7 @@ function DockerManagerInner({
className="pl-8 h-8"
/>
</div>
<select
<Select2
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="h-8 px-2 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
@@ -721,7 +722,7 @@ function DockerManagerInner({
<option value="restarting">
{t("docker.stateRestarting")}
</option>
</select>
</Select2>
<Separator orientation="vertical" className="h-8 mx-1" />
<Button
variant="ghost"
@@ -7,13 +7,7 @@ import { RobustClipboardProvider } from "@/lib/clipboard-provider";
import { copyToClipboard, readFromClipboard } from "@/lib/clipboard";
import { WebLinksAddon } from "@xterm/addon-web-links";
import { Button } from "@/components/button.tsx";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/select.tsx";
import { Select2 } from "@/components/select2";
import { Card, CardContent } from "@/components/card.tsx";
import { getBasePath } from "@/lib/base-path";
import {
@@ -313,6 +307,7 @@ function ConsoleTerminalInner({
window.location.port === "");
let baseWsUrl: string;
let wsProtocols: string[] = [];
if (isDev) {
baseWsUrl = `${window.location.protocol === "https:" ? "wss" : "ws"}://localhost:30009`;
} else if (isElectronApp) {
@@ -331,12 +326,13 @@ function ConsoleTerminalInner({
toast.error(t("errors.remoteServerRequired"));
return;
}
baseWsUrl = resolvedUrl;
baseWsUrl = resolvedUrl.url;
wsProtocols = resolvedUrl.protocols;
} else {
baseWsUrl = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}${getBasePath()}/docker/console/`;
}
const ws = new WebSocket(baseWsUrl);
const ws = new WebSocket(baseWsUrl, wsProtocols);
ws.onopen = () => {
const cols = terminal.cols || 80;
@@ -543,20 +539,17 @@ function ConsoleTerminalInner({
{t("docker.console")}
</span>
</div>
<Select
<Select2
value={selectedShell}
onValueChange={setSelectedShell}
onChange={(event) => setSelectedShell(event.target.value)}
disabled={isConnected}
placeholder={t("docker.selectShell")}
className="w-[120px]"
>
<SelectTrigger className="w-[120px]">
<SelectValue placeholder={t("docker.selectShell")} />
</SelectTrigger>
<SelectContent>
<SelectItem value="bash">{t("docker.bash")}</SelectItem>
<SelectItem value="sh">{t("docker.sh")}</SelectItem>
<SelectItem value="ash">{t("docker.ash")}</SelectItem>
</SelectContent>
</Select>
<option value="bash">{t("docker.bash")}</option>
<option value="sh">{t("docker.sh")}</option>
<option value="ash">{t("docker.ash")}</option>
</Select2>
<div className="flex gap-2 sm:gap-2">
{!isConnected ? (
<Button
@@ -9,6 +9,7 @@ import { useTranslation } from "react-i18next";
import type { DockerLogOptions } from "@/types";
import { getContainerLogs, downloadContainerLogs } from "@/main-axios.ts";
import { useAdaptivePolling } from "@/hooks/use-adaptive-polling.ts";
import { Select2 } from "@/components/select2";
interface LogViewerProps {
sessionId: string;
@@ -158,7 +159,7 @@ export function LogViewer({
label={t("docker.timestamps")}
/>
<Separator orientation="vertical" className="h-4" />
<select
<Select2
value={tailLines}
onChange={(e) => setTailLines(e.target.value)}
className="h-7 px-2 text-[10px] bg-background border border-border text-foreground outline-none uppercase font-bold"
@@ -168,7 +169,7 @@ export function LogViewer({
<option value="500">{t("docker.last500")}</option>
<option value="1000">{t("docker.last1000")}</option>
<option value="all">{t("docker.allLogs")}</option>
</select>
</Select2>
<Separator orientation="vertical" className="h-4" />
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-widest">
{filteredLogs.length}/{rawLogs.length} {t("docker.lines")}
+216 -22
View File
@@ -29,6 +29,11 @@ import { useTranslation } from "react-i18next";
import { FileManagerDialogs } from "./FileManagerDialogs.tsx";
import { PassphraseDialog } from "@/ssh/dialogs/PassphraseDialog.tsx";
import { FileManagerToolbar } from "./FileManagerToolbar.tsx";
import { LocalFilePane } from "./LocalFilePane.tsx";
import { useLocalTransfers } from "./hooks/useLocalTransfers.ts";
import { usePaneWidth } from "./hooks/usePaneWidth.ts";
import { PaneResizeHandle } from "./components/PaneResizeHandle.tsx";
import { isLocalFileBrowserAvailable } from "@/lib/local-files.ts";
import { TransferToHostDialog } from "./components/TransferToHostDialog.tsx";
import { FileManagerTrashDialog } from "./FileManagerTrashDialog.tsx";
import { TerminalWindow } from "./components/TerminalWindow.tsx";
@@ -93,7 +98,7 @@ import type {
PendingSudoOperation,
SSHConnectionError,
} from "./file-manager-types.ts";
import { formatFileSize } from "./file-manager-utils.ts";
import { formatFileSize, runWithConcurrency } from "./file-manager-utils.ts";
import {
invalidateCachedFileList,
peekCachedFileList,
@@ -107,6 +112,15 @@ import {
restoreItems,
} from "./optimistic-file-list";
const LOCAL_PANE_OPEN_STORAGE_KEY = "termix:file-manager:local-pane:open";
const SIDEBAR_OPEN_STORAGE_KEY = "termix:file-manager:sidebar:open";
const LOCAL_PANE_WIDTH_STORAGE_KEY = "termix:file-manager:local-pane:width";
const LOCAL_PANE_MIN_WIDTH = 300;
const LOCAL_PANE_DEFAULT_WIDTH = 440;
const SIDEBAR_WIDTH_STORAGE_KEY = "termix:file-manager:sidebar:width";
const SIDEBAR_MIN_WIDTH = 160;
const SIDEBAR_DEFAULT_WIDTH = 224; // matches the previous fixed w-56
const LARGE_FILE_WARNING_SIZE = 50 * 1024 * 1024;
function FileManagerContent({
@@ -154,6 +168,11 @@ function FileManagerContent({
const saved = localStorage.getItem("fileManagerViewMode");
return saved === "grid" || saved === "list" ? saved : "grid";
});
const [density, setDensity] = useState<"comfortable" | "compact">(() =>
localStorage.getItem("fileManagerDensity") === "compact"
? "compact"
: "comfortable",
);
// Picking an interface preset seeds this key from another part of the app.
useEffect(() => {
const handler = () => {
@@ -190,6 +209,61 @@ function FileManagerContent({
const [showPassphraseDialog, setShowPassphraseDialog] = useState(false);
const [pinnedFiles, setPinnedFiles] = useState<Set<string>>(new Set());
const [sidebarRefreshTrigger, setSidebarRefreshTrigger] = useState(0);
// Desktop-only Local | Remote split view (Termius-style dual pane).
const localPaneAvailable = isLocalFileBrowserAvailable();
const [localPaneOpen, setLocalPaneOpen] = useState<boolean>(() => {
try {
return localStorage.getItem(LOCAL_PANE_OPEN_STORAGE_KEY) === "true";
} catch {
return false;
}
});
const [localPaneRefreshToken, setLocalPaneRefreshToken] = useState(0);
// Desktop directories sidebar visibility (mobile uses the overlay state).
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
try {
return localStorage.getItem(SIDEBAR_OPEN_STORAGE_KEY) !== "false";
} catch {
return true;
}
});
const toggleSidebar = useCallback(() => {
setSidebarOpen((prev) => {
const next = !prev;
try {
localStorage.setItem(SIDEBAR_OPEN_STORAGE_KEY, String(next));
} catch {
// storage unavailable
}
return next;
});
}, []);
const panesRowRef = useRef<HTMLDivElement>(null);
const localPaneSize = usePaneWidth({
storageKey: LOCAL_PANE_WIDTH_STORAGE_KEY,
defaultWidth: LOCAL_PANE_DEFAULT_WIDTH,
minWidth: LOCAL_PANE_MIN_WIDTH,
maxFraction: 0.65,
containerRef: panesRowRef,
});
const sidebarSize = usePaneWidth({
storageKey: SIDEBAR_WIDTH_STORAGE_KEY,
defaultWidth: SIDEBAR_DEFAULT_WIDTH,
minWidth: SIDEBAR_MIN_WIDTH,
maxFraction: 0.4,
containerRef: panesRowRef,
});
const toggleLocalPane = useCallback(() => {
setLocalPaneOpen((prev) => {
const next = !prev;
try {
localStorage.setItem(LOCAL_PANE_OPEN_STORAGE_KEY, String(next));
} catch {
// storage unavailable
}
return next;
});
}, []);
const [trashOpen, setTrashOpen] = useState(false);
const [hasConnectionError, setHasConnectionError] = useState<boolean>(false);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
@@ -884,6 +958,25 @@ function FileManagerContent({
}
}, [navIndex, navHistory, sshSessionId]);
useEffect(() => {
const handleMouseNavigation = (event: MouseEvent) => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
if (event.button === 3) goBack();
else goForward();
};
const preventBrowserMouseNavigation = (event: MouseEvent) => {
if (event.button === 3 || event.button === 4) event.preventDefault();
};
window.addEventListener("mouseup", handleMouseNavigation);
window.addEventListener("auxclick", preventBrowserMouseNavigation);
return () => {
window.removeEventListener("mouseup", handleMouseNavigation);
window.removeEventListener("auxclick", preventBrowserMouseNavigation);
};
}, [goBack, goForward]);
const goUp = useCallback(() => {
if (currentPath === "/") return;
const parent =
@@ -938,6 +1031,46 @@ function FileManagerContent({
return () => window.removeEventListener("file-manager:refresh", handler);
}, [currentHost?.id, handleRefreshDirectory]);
const localTransfers = useLocalTransfers({
sshSessionId,
hostId: currentHost?.id,
ensureSSHConnection,
onRemoteChanged: (remoteDir) => {
if (sshSessionId) invalidateCachedFileList(sshSessionId, remoteDir);
handleRefreshDirectory();
setSidebarRefreshTrigger((prev) => prev + 1);
},
onLocalChanged: () => setLocalPaneRefreshToken((prev) => prev + 1),
});
// Entries dragged from the local pane onto the remote grid (or onto one of
// its folders) upload into that folder, preserving directory structure.
const handleLocalFilesDrop = useCallback(
(localPaths: string[], targetDir?: FileItem) => {
const remoteDir = targetDir?.path ?? currentPathRef.current;
void localTransfers.uploadLocalPaths(localPaths, remoteDir);
},
[localTransfers],
);
// Remote rows dragged onto the local pane download into the folder shown
// there (or the folder row they were dropped on).
const handleRemoteItemsDroppedToLocal = useCallback(
(remotePaths: string[], localDir: string) => {
const known = new Map(files.map((f) => [f.path, f]));
const items: FileItem[] = remotePaths.map(
(p) =>
known.get(p) ?? {
name: p.split("/").filter(Boolean).pop() || p,
path: p,
type: "file",
},
);
void localTransfers.downloadRemoteItems(items, localDir);
},
[files, localTransfers],
);
useEffect(() => {
const handler = (event: Event) => {
const detail = (
@@ -1066,16 +1199,12 @@ function FileManagerContent({
const parentDir = dir.split("/").slice(0, -1).join("/");
const targetPath = parentDir ? `${base}${parentDir}/` : base;
const folderName = dir.split("/").pop()!;
try {
await createSSHFolder(
sshSessionId,
targetPath,
folderName,
currentHost?.id,
);
} catch {
// directory may already exist
}
await createSSHFolder(
sshSessionId,
targetPath,
folderName,
currentHost?.id,
);
}
for (const { file, relativePath } of files) {
@@ -1121,15 +1250,13 @@ function FileManagerContent({
}
}
function handleFilesDropped(fileList: FileList) {
async function handleFilesDropped(fileList: FileList) {
if (!sshSessionId) {
toast.error(t("fileManager.noSSHConnection"));
return;
}
Array.from(fileList).forEach((file) => {
handleUploadFile(file);
});
await runWithConcurrency(Array.from(fileList), 3, handleUploadFile);
}
async function handleUploadFile(file: File) {
@@ -1246,7 +1373,7 @@ function FileManagerContent({
toast.success(
t("fileManager.fileDownloadedSuccessfully", { name: file.name }),
{ id: toastId },
{ id: toastId, duration: undefined },
);
} catch (error: unknown) {
const err = error instanceof Error ? error : null;
@@ -1260,10 +1387,13 @@ function FileManagerContent({
ip: currentHost?.ip,
port: currentHost?.port,
}),
{ id: toastId },
{ id: toastId, duration: undefined },
);
} else {
toast.error(t("fileManager.failedToDownloadFile"), { id: toastId });
toast.error(t("fileManager.failedToDownloadFile"), {
id: toastId,
duration: undefined,
});
}
console.error("Download failed:", error);
}
@@ -3145,6 +3275,10 @@ function FileManagerContent({
localStorage.setItem("fileManagerViewMode", viewMode);
}, [viewMode]);
useEffect(() => {
localStorage.setItem("fileManagerDensity", density);
}, [density]);
useEffect(() => {
localStorage.setItem("fileManagerSortBy", sortBy);
localStorage.setItem("fileManagerSortOrder", sortOrder);
@@ -3223,6 +3357,8 @@ function FileManagerContent({
setSearchQuery={setSearchQuery}
viewMode={viewMode}
setViewMode={setViewMode}
density={density}
setDensity={setDensity}
sortBy={sortBy}
setSortBy={setSortBy}
sortOrder={sortOrder}
@@ -3238,9 +3374,15 @@ function FileManagerContent({
handleFilesDropped={handleFilesDropped}
handleCreateNewFolder={handleCreateNewFolder}
handleCreateNewFile={handleCreateNewFile}
showLocalPaneToggle={localPaneAvailable}
localPaneOpen={localPaneAvailable && localPaneOpen}
onToggleLocalPane={toggleLocalPane}
sidebarOpen={sidebarOpen}
onToggleSidebar={toggleSidebar}
/>
<div
ref={panesRowRef}
className="flex-1 flex px-3 pb-3 pt-2 gap-3 min-h-0 relative"
{...dragHandlers}
>
@@ -3255,12 +3397,18 @@ function FileManagerContent({
{/* Sidebar — fixed overlay on mobile, static on desktop */}
<div
className={cn(
"w-56 flex-shrink-0 h-full flex flex-col",
"md:flex",
"flex-shrink-0 h-full flex flex-col",
mobileSidebarOpen
? "fixed left-0 top-0 bottom-0 w-64 z-30 flex"
: "hidden md:flex",
: sidebarOpen
? "hidden md:flex"
: "hidden",
)}
style={
mobileSidebarOpen
? undefined
: { width: sidebarSize.width, minWidth: SIDEBAR_MIN_WIDTH }
}
>
<div className="flex-1 flex flex-col overflow-hidden min-h-0 border border-border bg-card">
<FileManagerSidebar
@@ -3276,8 +3424,42 @@ function FileManagerContent({
/>
</div>
</div>
{sidebarOpen && !mobileSidebarOpen && (
<PaneResizeHandle
label={t("fileManager.resizeSidebar")}
onMouseDown={sidebarSize.startResize}
onDoubleClick={sidebarSize.resetWidth}
active={sidebarSize.isResizing}
/>
)}
<div className="flex-1 relative overflow-hidden min-h-0 flex flex-col border border-border bg-card">
{localPaneAvailable && localPaneOpen && (
<>
<div
className="hidden md:flex flex-shrink-0 relative overflow-hidden min-h-0 flex-col border border-border bg-card"
style={{
width: localPaneSize.width,
minWidth: LOCAL_PANE_MIN_WIDTH,
maxWidth: "65%",
}}
>
<LocalFilePane
refreshToken={localPaneRefreshToken}
onClose={toggleLocalPane}
onRemoteItemsDropped={handleRemoteItemsDroppedToLocal}
onUploadToRemote={handleLocalFilesDrop}
/>
</div>
<PaneResizeHandle
label={t("fileManager.resizeLocalPane")}
onMouseDown={localPaneSize.startResize}
onDoubleClick={localPaneSize.resetWidth}
active={localPaneSize.isResizing}
/>
</>
)}
<div className="flex-1 basis-0 relative overflow-hidden min-h-0 flex flex-col border border-border bg-card">
<div className="flex-1 relative min-h-0 h-full">
<FileManagerGrid
files={filteredFiles}
@@ -3287,6 +3469,17 @@ function FileManagerContent({
onSelectionChange={setSelection}
onRefresh={handleRefreshDirectory}
onUpload={handleFilesDropped}
onUploadItems={handleItemsDropped}
onLocalFilesDrop={
localPaneAvailable ? handleLocalFilesDrop : undefined
}
parentPath={
currentPath === "/"
? null
: currentPath.substring(0, currentPath.lastIndexOf("/")) ||
"/"
}
onNavigateUp={goUp}
sortBy={sortBy}
sortOrder={sortOrder}
onSortChange={(field) => {
@@ -3304,6 +3497,7 @@ function FileManagerContent({
}
onContextMenu={handleContextMenu}
viewMode={viewMode}
density={density}
onRename={handleRenameConfirm}
editingFile={editingFile}
onStartEdit={handleStartEdit}
+425 -100
View File
@@ -23,6 +23,7 @@ import {
Download,
Upload,
ArrowUp,
CornerLeftUp,
ArrowDown,
FileSymlink,
Move,
@@ -32,9 +33,49 @@ import { useTranslation } from "react-i18next";
import type { FileItem } from "@/types/index";
import type { CreateIntent } from "./file-manager-types.ts";
import { formatFileSize } from "./file-manager-utils.ts";
import {
beginRemoteFilesDrag,
isLocalFilesDrag,
parseLocalFilesDragPayload,
} from "./local-transfer-utils.ts";
import {
useResizableColumns,
type ResizableColumnSpec,
} from "./hooks/useResizableColumns.ts";
import { ColumnResizeHandle } from "./components/ColumnResizeHandle.tsx";
import { ColumnVisibilityMenu } from "./components/ColumnVisibilityMenu.tsx";
// Fixed list-view columns after the flexible name column; user-resizable.
const LIST_COLUMNS: ResizableColumnSpec[] = [
{
key: "modified",
labelKey: "fileManager.modified",
defaultWidth: 120,
minWidth: 70,
},
{
key: "owner",
labelKey: "fileManager.owner",
defaultWidth: 150,
minWidth: 60,
},
{ key: "size", labelKey: "fileManager.size", defaultWidth: 80, minWidth: 56 },
{
key: "permissions",
labelKey: "fileManager.permissions",
defaultWidth: 90,
minWidth: 70,
},
];
const LIST_COLUMNS_STORAGE_KEY = "termix:file-manager:columns:remote";
interface DragState {
type: "none" | "internal" | "external";
/**
* internal: rows of this grid being moved around
* external: files dragged in from the OS
* local: entries dragged from the desktop app's local pane
*/
type: "none" | "internal" | "external" | "local";
files: FileItem[];
draggedFiles?: FileItem[];
target?: FileItem;
@@ -50,9 +91,14 @@ interface FileManagerGridProps {
onSelectionChange: (files: FileItem[]) => void;
onRefresh: () => void;
onUpload?: (files: FileList) => void;
/** OS drop that contains at least one directory (needs a recursive walk). */
onUploadItems?: (entries: FileSystemEntry[]) => void;
/** Entries dragged from the local pane; `targetDir` when dropped on a folder. */
onLocalFilesDrop?: (localPaths: string[], targetDir?: FileItem) => void;
onDownload?: (files: FileItem[]) => void;
onContextMenu?: (event: React.MouseEvent, file?: FileItem) => void;
viewMode?: "grid" | "list";
density?: "comfortable" | "compact";
onRename?: (file: FileItem, newName: string) => void;
editingFile?: FileItem | null;
onStartEdit?: (file: FileItem) => void;
@@ -75,6 +121,13 @@ interface FileManagerGridProps {
sortBy?: "name" | "modified" | "size";
sortOrder?: "asc" | "desc";
onSortChange?: (field: "name" | "modified" | "size") => void;
/**
* Parent of the listed directory. When set (together with onNavigateUp) a
* pinned ".." entry is shown first; double-click goes up and drops on it
* target the parent folder.
*/
parentPath?: string | null;
onNavigateUp?: () => void;
}
const getFileTypeColor = (file: FileItem): string => {
@@ -89,8 +142,18 @@ const getFileTypeColor = (file: FileItem): string => {
return "text-blue-400";
};
const getFileIcon = (file: FileItem, viewMode: "grid" | "list" = "grid") => {
const iconClass = viewMode === "grid" ? "w-8 h-8" : "w-6 h-6";
const getFileIcon = (
file: FileItem,
viewMode: "grid" | "list" = "grid",
compact = false,
) => {
const iconClass = compact
? viewMode === "grid"
? "size-6"
: "size-4"
: viewMode === "grid"
? "size-8"
: "size-6";
const colorClass = getFileTypeColor(file);
if (file.type === "directory") {
@@ -167,9 +230,12 @@ export function FileManagerGrid({
onSelectionChange,
onRefresh,
onUpload,
onUploadItems,
onLocalFilesDrop,
onDownload,
onContextMenu,
viewMode = "grid",
density = "comfortable",
onRename,
editingFile,
onStartEdit,
@@ -191,16 +257,21 @@ export function FileManagerGrid({
sortBy,
sortOrder,
onSortChange,
parentPath,
onNavigateUp,
}: FileManagerGridProps) {
const { t } = useTranslation();
const gridRef = useRef<HTMLDivElement>(null);
const [editingName, setEditingName] = useState("");
const [gridCols, setGridCols] = useState(4);
const LIST_ROW_H = 41;
const GRID_ROW_H = 112;
const LIST_HEADER_H = 33;
const CONTENT_PAD = 16;
const compact = density === "compact";
const LIST_ROW_H = compact ? 29 : 41;
const GRID_ROW_H = compact ? 76 : 112;
const LIST_HEADER_H = compact ? 25 : 33;
const CONTENT_PAD = compact ? 8 : 16;
const GRID_GAP = compact ? 8 : 16;
const GRID_CELL = compact ? 76 : 112;
const [dragState, setDragState] = useState<DragState>({
type: "none",
@@ -216,15 +287,17 @@ export function FileManagerGrid({
const updateCols = () => {
const w = el.clientWidth - CONTENT_PAD * 2;
// gap-4 (16px) + ~min cell 96px
const n = Math.max(2, Math.min(8, Math.floor((w + 16) / 112)));
const n = Math.max(
2,
Math.min(10, Math.floor((w + GRID_GAP) / GRID_CELL)),
);
setGridCols(n);
};
updateCols();
const ro = new ResizeObserver(updateCols);
ro.observe(el);
return () => ro.disconnect();
}, [viewMode]);
}, [viewMode, CONTENT_PAD, GRID_GAP, GRID_CELL]);
const gridRowCount = useMemo(
() => (viewMode === "grid" ? Math.ceil(files.length / gridCols) : 0),
@@ -240,6 +313,20 @@ export function FileManagerGrid({
enabled: viewMode === "list" && files.length > 0,
});
const listColumns = useResizableColumns({
storageKey: LIST_COLUMNS_STORAGE_KEY,
columns: LIST_COLUMNS,
});
const [columnMenu, setColumnMenu] = useState<{
x: number;
y: number;
visible: boolean;
}>({ x: 0, y: 0, visible: false });
const closeColumnMenu = useCallback(
() => setColumnMenu((prev) => ({ ...prev, visible: false })),
[],
);
const gridVirtualizer = useVirtualizer({
count: gridRowCount,
getScrollElement: () => gridRef.current,
@@ -252,7 +339,14 @@ export function FileManagerGrid({
useLayoutEffect(() => {
if (viewMode === "list") listVirtualizer.measure();
else gridVirtualizer.measure();
}, [viewMode, files.length, editingFile?.path, createIntent, gridCols]);
}, [
viewMode,
density,
files.length,
editingFile?.path,
createIntent,
gridCols,
]);
useEffect(() => {
const handleGlobalMouseMove = (e: MouseEvent) => {
@@ -321,12 +415,10 @@ export function FileManagerGrid({
mousePosition: { x: e.clientX, y: e.clientY },
});
const dragData = {
type: "internal_files",
files: filesToDrag.map((f) => f.path),
};
e.dataTransfer.setData("text/plain", JSON.stringify(dragData));
e.dataTransfer.effectAllowed = "move";
beginRemoteFilesDrag(
e.dataTransfer,
filesToDrag.map((f) => f.path),
);
};
const handleFileDragOver = (e: React.DragEvent, targetFile: FileItem) => {
@@ -339,6 +431,20 @@ export function FileManagerGrid({
) {
setDragState((prev) => ({ ...prev, target: targetFile }));
e.dataTransfer.dropEffect = "move";
} else if (isLocalFilesDrag(e.dataTransfer)) {
e.dataTransfer.dropEffect = "copy";
const nextTarget =
targetFile.type === "directory" ? targetFile : undefined;
if (
dragState.type !== "local" ||
dragState.target?.path !== nextTarget?.path
) {
setDragState((prev) => ({
...prev,
type: "local",
target: nextTarget,
}));
}
}
};
@@ -355,6 +461,20 @@ export function FileManagerGrid({
e.preventDefault();
e.stopPropagation();
if (isLocalFilesDrag(e.dataTransfer)) {
const localPaths = parseLocalFilesDragPayload(
e.dataTransfer.getData("text/plain"),
);
setDragState({ type: "none", files: [], counter: 0 });
if (localPaths) {
onLocalFilesDrop?.(
localPaths,
targetFile.type === "directory" ? targetFile : undefined,
);
}
return;
}
if (dragState.type !== "internal" || dragState.files.length === 0) {
setDragState((prev) => ({ ...prev, target: undefined }));
return;
@@ -409,9 +529,12 @@ export function FileManagerGrid({
const isInternalDrag = dragState.type === "internal";
if (!isInternalDrag) {
const nextType = isLocalFilesDrag(e.dataTransfer)
? "local"
: "external";
setDragState((prev) => ({
...prev,
type: "external",
type: nextType,
counter: prev.counter + 1,
}));
}
@@ -426,13 +549,17 @@ export function FileManagerGrid({
const isInternalDrag = dragState.type === "internal";
if (!isInternalDrag && dragState.type === "external") {
if (
!isInternalDrag &&
(dragState.type === "external" || dragState.type === "local")
) {
setDragState((prev) => {
const newCounter = prev.counter - 1;
return {
...prev,
counter: newCounter,
type: newCounter <= 0 ? "none" : "external",
type: newCounter <= 0 ? "none" : prev.type,
target: newCounter <= 0 ? undefined : prev.target,
};
});
}
@@ -558,7 +685,8 @@ export function FileManagerGrid({
const contentLeft = selectionBox.left - CONTENT_PAD;
const contentRight = selectionBox.right - CONTENT_PAD;
const cellW =
(gridRef.current.clientWidth - CONTENT_PAD * 2 + 16) / gridCols;
(gridRef.current.clientWidth - CONTENT_PAD * 2 + GRID_GAP) /
gridCols;
const startCol = Math.max(0, Math.floor(contentLeft / cellW));
const endCol = Math.min(
gridCols - 1,
@@ -618,6 +746,7 @@ export function FileManagerGrid({
files,
onSelectionChange,
viewMode,
GRID_GAP,
createIntent,
gridCols,
gridRowCount,
@@ -703,15 +832,39 @@ export function FileManagerGrid({
if (dragState.type === "internal") {
setDragState({ type: "none", files: [], counter: 0 });
} else if (dragState.type === "external") {
if (onUpload && e.dataTransfer.files.length > 0) {
onUpload(e.dataTransfer.files);
return;
}
// Read everything off dataTransfer before any setState: the browser
// clears it once the handler unwinds and a state flush can get there
// first.
const localPaths = isLocalFilesDrag(e.dataTransfer)
? parseLocalFilesDragPayload(e.dataTransfer.getData("text/plain"))
: null;
const files = e.dataTransfer.files;
const entries: FileSystemEntry[] = [];
if (onUploadItems && e.dataTransfer.items?.length > 0) {
for (const item of Array.from(e.dataTransfer.items)) {
const entry = item.webkitGetAsEntry?.();
if (entry) entries.push(entry);
}
}
setDragState({ type: "none", files: [], counter: 0 });
if (localPaths) {
onLocalFilesDrop?.(localPaths);
return;
}
if (onUploadItems && entries.some((entry) => entry.isDirectory)) {
onUploadItems(entries);
return;
}
if (onUpload && files.length > 0) {
onUpload(files);
}
},
[onUpload, dragState],
[onUpload, onUploadItems, onLocalFilesDrop, dragState],
);
const handleFileClick = (file: FileItem, event: React.MouseEvent) => {
@@ -915,14 +1068,89 @@ export function FileManagerGrid({
onUndo,
]);
// Pinned ".." entry (Termius-style). Behaves as a directory drop target
// for internal moves and local-pane uploads, and navigates up on open.
const parentEntry: FileItem | null =
parentPath && onNavigateUp
? { name: "..", path: parentPath, type: "directory" }
: null;
const isParentTarget =
!!parentEntry && dragState.target?.path === parentEntry.path;
const parentEntryHandlers = parentEntry
? {
onClick: (e: React.MouseEvent) => {
e.stopPropagation();
onNavigateUp?.();
},
onDoubleClick: (e: React.MouseEvent) => e.stopPropagation(),
onContextMenu: (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
},
onDragOver: (e: React.DragEvent) => handleFileDragOver(e, parentEntry),
onDragLeave: (e: React.DragEvent) =>
handleFileDragLeave(e, parentEntry),
onDrop: (e: React.DragEvent) => handleFileDrop(e, parentEntry),
}
: null;
const parentListRow =
parentEntry && parentEntryHandlers ? (
<div
data-parent-entry
title={t("fileManager.goToParentFolder")}
style={{ gridTemplateColumns: listColumns.gridTemplateColumns }}
className={cn(
"grid gap-2 items-center cursor-pointer border-b border-border hover:bg-muted/50 rounded-none select-none transition-colors",
compact ? "px-2 py-1 text-[11px]" : "px-4 py-2 text-xs",
isParentTarget &&
"bg-accent-brand/20 border-accent-brand border-dashed",
)}
{...parentEntryHandlers}
>
<div className="flex items-center gap-3 overflow-hidden pointer-events-none">
<div className="shrink-0">
<CornerLeftUp className="size-4 text-muted-foreground" />
</div>
<span className="font-bold tracking-tight text-muted-foreground">
..
</span>
</div>
</div>
) : null;
const parentGridStrip =
parentEntry && parentEntryHandlers ? (
<div
data-parent-entry
title={t("fileManager.goToParentFolder")}
className={cn(
"flex items-center gap-2 rounded-none border border-transparent transition-colors cursor-pointer hover:bg-muted/50 select-none",
compact
? "-mx-2 -mt-2 px-2 py-1 text-[11px]"
: "-mx-4 -mt-4 px-4 py-1.5 text-xs",
isParentTarget &&
"bg-accent-brand/20 border-accent-brand border-dashed",
)}
{...parentEntryHandlers}
>
<CornerLeftUp className="size-3.5 text-muted-foreground pointer-events-none" />
<span className="font-bold tracking-tight text-muted-foreground pointer-events-none">
..
</span>
</div>
) : null;
return (
<div className="h-full flex flex-col bg-card overflow-hidden relative">
<div className="flex-1 relative overflow-hidden">
<div
ref={gridRef}
className={cn(
"absolute inset-0 p-4 overflow-y-auto thin-scrollbar",
dragState.type === "external" &&
"absolute inset-0 overflow-y-auto thin-scrollbar",
compact ? "p-2" : "p-4",
(dragState.type === "external" || dragState.type === "local") &&
"bg-muted/20 border-2 border-dashed border-primary",
)}
onClick={handleGridClick}
@@ -937,29 +1165,22 @@ export function FileManagerGrid({
onContextMenu={(e) => onContextMenu?.(e)}
tabIndex={0}
>
{dragState.type === "external" && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50 z-10 pointer-events-none">
<div className="text-center p-8 bg-card/95 border border-accent-brand/40 flex flex-col items-center gap-4">
<Upload className="size-12 text-accent-brand" />
<p className="text-[10px] font-bold uppercase tracking-widest text-accent-brand">
{t("fileManager.dragFilesToUpload")}
</p>
{files.length === 0 && !createIntent ? (
<div className="h-full flex flex-col">
{viewMode === "grid" ? parentGridStrip : parentListRow}
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground opacity-10 gap-4 select-none pointer-events-none">
<Folder className="size-32" strokeWidth={1} />
<span className="text-2xl font-black uppercase tracking-[0.2em]">
{t("fileManager.emptyFolder")}
</span>
</div>
</div>
)}
{files.length === 0 && !createIntent ? (
<div className="h-full flex flex-col items-center justify-center text-muted-foreground opacity-10 gap-4 select-none pointer-events-none">
<Folder className="size-32" strokeWidth={1} />
<span className="text-2xl font-black uppercase tracking-[0.2em]">
{t("fileManager.emptyFolder")}
</span>
</div>
) : viewMode === "grid" ? (
<div className="flex flex-col gap-4">
<div className={cn("flex flex-col", compact ? "gap-2" : "gap-4")}>
{parentGridStrip}
{createIntent && (
<div
className="grid gap-4"
className={cn("grid", compact ? "gap-2" : "gap-4")}
style={{
gridTemplateColumns: `repeat(${gridCols}, minmax(0, 1fr))`,
}}
@@ -989,7 +1210,10 @@ export function FileManagerGrid({
}}
>
<div
className="grid gap-4 pb-4"
className={cn(
"grid",
compact ? "gap-2 pb-2" : "gap-4 pb-4",
)}
style={{
gridTemplateColumns: `repeat(${gridCols}, minmax(0, 1fr))`,
}}
@@ -1004,7 +1228,8 @@ export function FileManagerGrid({
data-file-path={file.path}
draggable={true}
className={cn(
"group flex flex-col items-center p-3 rounded-none border-2 border-transparent transition-all cursor-pointer hover:bg-muted/50 select-none",
"group flex flex-col items-center rounded-none border-2 border-transparent transition-all cursor-pointer hover:bg-muted/50 select-none",
compact ? "p-1.5" : "p-3",
isSelected &&
"bg-accent-brand/10 border-accent-brand/40",
dragState.target?.path === file.path &&
@@ -1026,8 +1251,13 @@ export function FileManagerGrid({
onDrop={(e) => handleFileDrop(e, file)}
onDragEnd={handleFileDragEnd}
>
<div className="relative mb-2 pointer-events-none">
{getFileIcon(file, viewMode)}
<div
className={cn(
"relative pointer-events-none",
compact ? "mb-1" : "mb-2",
)}
>
{getFileIcon(file, viewMode, compact)}
</div>
<div className="w-full flex flex-col items-center pointer-events-none">
{editingFile?.path === file.path ? (
@@ -1046,7 +1276,10 @@ export function FileManagerGrid({
/>
) : (
<p
className="text-[11px] font-bold tracking-tight text-center truncate w-full px-1"
className={cn(
"font-bold tracking-tight text-center truncate w-full px-1",
compact ? "text-[10px]" : "text-[11px]",
)}
title={file.name}
>
{file.name}
@@ -1079,9 +1312,21 @@ export function FileManagerGrid({
</div>
) : (
<div className="flex flex-col">
<div className="grid grid-cols-[1fr_120px_150px_80px_90px] gap-2 px-4 py-2 text-[10px] font-bold uppercase tracking-widest text-muted-foreground border-b border-border sticky top-0 bg-card z-10">
<div
className={cn(
"grid gap-2 text-[10px] font-bold uppercase tracking-widest text-muted-foreground border-b border-border bg-card",
compact ? "px-2 py-1" : "px-4 py-2",
)}
style={{ gridTemplateColumns: listColumns.gridTemplateColumns }}
title={t("fileManager.columnsHint")}
onContextMenu={(e) => {
e.preventDefault();
e.stopPropagation();
setColumnMenu({ x: e.clientX, y: e.clientY, visible: true });
}}
>
<div
className="flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors"
className="flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors min-w-0"
onClick={() => onSortChange?.("name")}
>
{t("fileManager.name")}
@@ -1092,38 +1337,75 @@ export function FileManagerGrid({
<ArrowDown className="size-3" />
))}
</div>
<div
className="flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors"
onClick={() => onSortChange?.("modified")}
>
{t("fileManager.modified")}
{sortBy === "modified" &&
(sortOrder === "asc" ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
))}
</div>
<div className="hidden md:block" />
<div
className="flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors justify-end"
onClick={() => onSortChange?.("size")}
>
{t("fileManager.size")}
{sortBy === "size" &&
(sortOrder === "asc" ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
))}
</div>
<div className="text-right">{t("fileManager.permissions")}</div>
{listColumns.isVisible("modified") && (
<div
className="relative flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors min-w-0"
onClick={() => onSortChange?.("modified")}
>
<ColumnResizeHandle
{...listColumns.getHandleProps("modified")}
/>
<span className="truncate">
{t("fileManager.modified")}
</span>
{sortBy === "modified" &&
(sortOrder === "asc" ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
))}
</div>
)}
{listColumns.isVisible("owner") && (
<div className="relative hidden md:flex items-center min-w-0">
<ColumnResizeHandle
{...listColumns.getHandleProps("owner")}
/>
<span className="truncate">{t("fileManager.owner")}</span>
</div>
)}
{listColumns.isVisible("size") && (
<div
className="relative flex items-center gap-1 cursor-pointer hover:text-accent-brand transition-colors justify-end min-w-0"
onClick={() => onSortChange?.("size")}
>
<ColumnResizeHandle
{...listColumns.getHandleProps("size")}
/>
<span className="truncate">{t("fileManager.size")}</span>
{sortBy === "size" &&
(sortOrder === "asc" ? (
<ArrowUp className="size-3" />
) : (
<ArrowDown className="size-3" />
))}
</div>
)}
{listColumns.isVisible("permissions") && (
<div className="relative flex items-center justify-end min-w-0">
<ColumnResizeHandle
{...listColumns.getHandleProps("permissions")}
/>
<span className="truncate">
{t("fileManager.permissions")}
</span>
</div>
)}
</div>
<ColumnVisibilityMenu
x={columnMenu.x}
y={columnMenu.y}
isVisible={columnMenu.visible}
columns={listColumns}
onClose={closeColumnMenu}
/>
{parentListRow}
{createIntent && (
<CreateIntentListItem
intent={createIntent}
onConfirm={onConfirmCreate}
onCancel={onCancelCreate}
gridTemplateColumns={listColumns.gridTemplateColumns}
/>
)}
<div
@@ -1149,8 +1431,14 @@ export function FileManagerGrid({
<div
data-file-path={file.path}
draggable={true}
style={{
gridTemplateColumns: listColumns.gridTemplateColumns,
}}
className={cn(
"grid grid-cols-[1fr_120px_150px_80px_90px] gap-2 px-4 py-2 items-center text-xs cursor-pointer border-b border-border hover:bg-muted/50 rounded-none select-none transition-colors",
"grid gap-2 items-center cursor-pointer border-b border-border hover:bg-muted/50 rounded-none select-none transition-colors",
compact
? "px-2 py-1 text-[11px]"
: "px-4 py-2 text-xs",
isSelected && "bg-accent-brand/10",
dragState.target?.path === file.path &&
"bg-accent-brand/20 border-accent-brand border-dashed",
@@ -1169,9 +1457,14 @@ export function FileManagerGrid({
onDrop={(e) => handleFileDrop(e, file)}
onDragEnd={handleFileDragEnd}
>
<div className="flex items-center gap-3 overflow-hidden pointer-events-none">
<div
className={cn(
"flex items-center overflow-hidden pointer-events-none",
compact ? "gap-2" : "gap-3",
)}
>
<div className="shrink-0">
{getFileIcon(file, viewMode)}
{getFileIcon(file, viewMode, compact)}
</div>
{editingFile?.path === file.path ? (
<input
@@ -1200,27 +1493,35 @@ export function FileManagerGrid({
)}
</div>
<span className="text-[10px] text-muted-foreground pointer-events-none">
{file.modified || "—"}
</span>
{listColumns.isVisible("modified") && (
<span className="text-[10px] text-muted-foreground pointer-events-none truncate">
{file.modified || "—"}
</span>
)}
<span className="text-[10px] text-muted-foreground truncate hidden md:block pointer-events-none">
{file.owner
? `${file.owner}${file.group ? `:${file.group}` : ""}`
: "—"}
</span>
{listColumns.isVisible("owner") && (
<span className="text-[10px] text-muted-foreground truncate hidden md:block pointer-events-none">
{file.owner
? `${file.owner}${file.group ? `:${file.group}` : ""}`
: "—"}
</span>
)}
<span className="text-[10px] text-right text-muted-foreground tabular-nums pointer-events-none">
{file.type === "file" &&
file.size !== undefined &&
file.size !== null
? formatFileSize(file.size)
: "—"}
</span>
{listColumns.isVisible("size") && (
<span className="text-[10px] text-right text-muted-foreground tabular-nums pointer-events-none">
{file.type === "file" &&
file.size !== undefined &&
file.size !== null
? formatFileSize(file.size)
: "—"}
</span>
)}
<span className="text-[10px] text-right font-mono text-muted-foreground/60 pointer-events-none">
{file.permissions || "—"}
</span>
{listColumns.isVisible("permissions") && (
<span className="text-[10px] text-right font-mono text-muted-foreground/60 pointer-events-none truncate">
{file.permissions || "—"}
</span>
)}
</div>
</div>
);
@@ -1241,6 +1542,24 @@ export function FileManagerGrid({
/>
)}
</div>
{/* Sibling of the scroll container, not a child: an absolutely
positioned child of a scroll container scrolls away with the
content, so the hint would land above the viewport whenever the
list is scrolled down. */}
{(dragState.type === "external" ||
(dragState.type === "local" && !dragState.target)) && (
<div className="absolute inset-0 flex items-center justify-center bg-background/50 z-10 pointer-events-none">
<div className="text-center p-8 bg-card/95 border border-accent-brand/40 flex flex-col items-center gap-4">
<Upload className="size-12 text-accent-brand" />
<p className="text-[10px] font-bold uppercase tracking-widest text-accent-brand">
{dragState.type === "local"
? t("fileManager.dropToUploadHere")
: t("fileManager.dragFilesToUpload")}
</p>
</div>
</div>
)}
</div>
<div className="px-4 py-1.5 bg-muted/30 border-t border-border flex items-center justify-between text-[10px] font-bold uppercase tracking-widest text-muted-foreground shrink-0">
@@ -1404,10 +1723,12 @@ function CreateIntentListItem({
intent,
onConfirm,
onCancel,
gridTemplateColumns,
}: {
intent: CreateIntent;
onConfirm?: (name: string) => void;
onCancel?: () => void;
gridTemplateColumns?: string;
}) {
const { t } = useTranslation();
const [inputName, setInputName] = useState(intent.currentName);
@@ -1451,7 +1772,11 @@ function CreateIntentListItem({
return (
<div
className="grid grid-cols-[1fr_120px_150px_80px_90px] gap-2 px-4 py-2 items-center border-b border-accent-brand/30 bg-accent-brand/5 rounded-none"
className="grid gap-2 px-4 py-2 items-center border-b border-accent-brand/30 bg-accent-brand/5 rounded-none"
style={{
gridTemplateColumns:
gridTemplateColumns ?? "minmax(140px, 1fr) 120px 150px 80px 90px",
}}
onClick={(e) => e.stopPropagation()}
onMouseDown={(e) => e.stopPropagation()}
>
@@ -8,10 +8,12 @@ import {
Folder,
FolderPlus,
Grid3X3,
Laptop,
Layout,
List,
Plus,
RefreshCw,
Rows3,
Search,
Trash2,
Upload,
@@ -33,6 +35,7 @@ import type { FileItem } from "@/types/index";
type SortBy = "name" | "modified" | "size";
type SortOrder = "asc" | "desc";
type ViewMode = "grid" | "list";
type Density = "comfortable" | "compact";
type FileManagerToolbarProps = {
t: (key: string) => string;
@@ -46,6 +49,8 @@ type FileManagerToolbarProps = {
setSearchQuery: (query: string) => void;
viewMode: ViewMode;
setViewMode: (mode: ViewMode) => void;
density: Density;
setDensity: (density: Density) => void;
sortBy: SortBy;
setSortBy: (sortBy: SortBy) => void;
sortOrder: SortOrder;
@@ -61,6 +66,13 @@ type FileManagerToolbarProps = {
handleFilesDropped: (fileList: FileList) => void;
handleCreateNewFolder: () => void;
handleCreateNewFile: () => void;
/** Desktop app only: show the Local | Remote split-view toggle. */
showLocalPaneToggle?: boolean;
localPaneOpen?: boolean;
onToggleLocalPane?: () => void;
/** Desktop directories sidebar (mobile uses the overlay instead). */
sidebarOpen?: boolean;
onToggleSidebar?: () => void;
};
function Breadcrumb({
@@ -197,6 +209,8 @@ export function FileManagerToolbar({
setSearchQuery,
viewMode,
setViewMode,
density,
setDensity,
sortBy,
setSortBy,
sortOrder,
@@ -212,6 +226,11 @@ export function FileManagerToolbar({
handleFilesDropped,
handleCreateNewFolder,
handleCreateNewFile,
showLocalPaneToggle = false,
localPaneOpen = false,
onToggleLocalPane,
sidebarOpen = true,
onToggleSidebar,
}: FileManagerToolbarProps) {
return (
<div className="flex flex-col shrink-0 mx-3 mt-3 border border-border bg-card">
@@ -220,9 +239,18 @@ export function FileManagerToolbar({
<Button
variant="ghost"
size="icon"
onClick={() => setMobileSidebarOpen((open) => !open)}
className="md:hidden size-8 rounded-none"
onClick={() => {
// Below md the sidebar is an overlay; above it, a persisted
// show/hide of the directories panel.
const isDesktop =
typeof window !== "undefined" &&
window.matchMedia("(min-width: 768px)").matches;
if (isDesktop && onToggleSidebar) onToggleSidebar();
else setMobileSidebarOpen((open) => !open);
}}
className={`size-8 rounded-none ${sidebarOpen ? "" : "md:bg-accent-brand/10 md:text-accent-brand"}`}
title={t("fileManager.toggleSidebar")}
aria-pressed={!sidebarOpen}
>
<Layout className="size-4" />
</Button>
@@ -304,12 +332,29 @@ export function FileManagerToolbar({
/>
</div>
{showLocalPaneToggle && (
<Button
variant={localPaneOpen ? "secondary" : "ghost"}
size="icon"
onClick={onToggleLocalPane}
title={
localPaneOpen
? t("fileManager.hideLocalFiles")
: t("fileManager.showLocalFiles")
}
aria-pressed={localPaneOpen}
className={`hidden md:inline-flex size-8 rounded-none border border-border ${localPaneOpen ? "bg-accent-brand/10 text-accent-brand border-accent-brand/40" : ""}`}
>
<Laptop className="size-4" />
</Button>
)}
<div className="flex items-center border border-border rounded-none overflow-hidden">
<Button
variant={viewMode === "grid" ? "secondary" : "ghost"}
size="icon"
onClick={() => setViewMode("grid")}
className={`size-8 rounded-none border-y-0 border-l-0 border-r border-border ${viewMode === "grid" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
className={`size-8 rounded-none ${viewMode === "grid" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
>
<Grid3X3 className="size-4" />
</Button>
@@ -317,10 +362,25 @@ export function FileManagerToolbar({
variant={viewMode === "list" ? "secondary" : "ghost"}
size="icon"
onClick={() => setViewMode("list")}
className={`size-8 rounded-none border-y-0 border-r-0 border-border ${viewMode === "list" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
className={`size-8 rounded-none border-l border-border ${viewMode === "list" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
>
<List className="size-4" />
</Button>
<Button
variant={density === "compact" ? "secondary" : "ghost"}
size="icon"
onClick={() =>
setDensity(density === "compact" ? "comfortable" : "compact")
}
className={`size-8 rounded-none border-l border-border ${density === "compact" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
title={t(
density === "compact"
? "fileManager.comfortableLayout"
: "fileManager.compactLayout",
)}
>
<Rows3 className="size-4" />
</Button>
</div>
<label
@@ -0,0 +1,322 @@
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils.ts";
import {
Clipboard,
Edit3,
Eye,
EyeOff,
ExternalLink,
FilePlus,
FolderOpen,
FolderPlus,
RefreshCw,
Trash2,
Upload,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { Kbd, KbdKey, KbdSeparator } from "@/components/kbd.tsx";
import type { LocalFileEntry } from "@/types/electron";
const VIEWPORT_PADDING = 16;
export interface LocalFileContextMenuProps {
x: number;
y: number;
/** Entries the menu acts on; empty means the pane background was clicked. */
entries: LocalFileEntry[];
isVisible: boolean;
showHidden: boolean;
canUpload: boolean;
onClose: () => void;
onOpen: (entry: LocalFileEntry) => void;
onUploadToRemote: (entries: LocalFileEntry[]) => void;
onReveal: (entry?: LocalFileEntry) => void;
onRename: (entry: LocalFileEntry) => void;
onCopyPath: (entries: LocalFileEntry[]) => void;
onNewFolder: () => void;
onNewFile: () => void;
onRefresh: () => void;
onToggleHidden: () => void;
onDelete: (entries: LocalFileEntry[]) => void;
}
interface MenuItem {
icon?: React.ReactNode;
label?: string;
action?: () => void;
shortcut?: string;
separator?: boolean;
disabled?: boolean;
danger?: boolean;
}
/**
* Right-click menu for the local pane. Same chrome and dismissal rules as
* FileManagerContextMenu, with the subset of actions that make sense for the
* user's own disk.
*/
export function LocalFileContextMenu({
x,
y,
entries,
isVisible,
showHidden,
canUpload,
onClose,
onOpen,
onUploadToRemote,
onReveal,
onRename,
onCopyPath,
onNewFolder,
onNewFile,
onRefresh,
onToggleHidden,
onDelete,
}: LocalFileContextMenuProps) {
const { t } = useTranslation();
const menuRef = useRef<HTMLDivElement>(null);
const [menuPosition, setMenuPosition] = useState({ x, y });
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
if (!isVisible) {
setIsMounted(false);
return;
}
setIsMounted(true);
let cleanupFn: (() => void) | null = null;
const timeoutId = setTimeout(() => {
const handleClickOutside = (event: MouseEvent) => {
if (!menuRef.current?.contains(event.target as Node)) onClose();
};
const handleRightClick = (event: MouseEvent) => {
event.preventDefault();
onClose();
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
onClose();
}
};
const handleBlur = () => onClose();
const handleScroll = () => onClose();
document.addEventListener("mousedown", handleClickOutside, true);
document.addEventListener("contextmenu", handleRightClick);
document.addEventListener("keydown", handleKeyDown);
window.addEventListener("blur", handleBlur);
window.addEventListener("scroll", handleScroll, true);
cleanupFn = () => {
document.removeEventListener("mousedown", handleClickOutside, true);
document.removeEventListener("contextmenu", handleRightClick);
document.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("blur", handleBlur);
window.removeEventListener("scroll", handleScroll, true);
};
}, 50);
return () => {
clearTimeout(timeoutId);
cleanupFn?.();
};
}, [isVisible, x, y, onClose]);
useLayoutEffect(() => {
if (!isVisible || !menuRef.current) return;
const menuWidth = menuRef.current.offsetWidth;
const menuHeight = menuRef.current.offsetHeight;
let adjustedX = x;
let adjustedY = y;
if (x + menuWidth > window.innerWidth) {
adjustedX = window.innerWidth - menuWidth - 10;
}
if (y + menuHeight > window.innerHeight) {
adjustedY = Math.max(10, window.innerHeight - menuHeight - 10);
}
setMenuPosition({ x: Math.max(8, adjustedX), y: Math.max(8, adjustedY) });
}, [isVisible, x, y, entries.length]);
const isEntryContext = entries.length > 0;
const isSingle = entries.length === 1;
const single = isSingle ? entries[0] : null;
const menuItems: MenuItem[] = [];
if (isEntryContext) {
if (single) {
menuItems.push({
icon: <ExternalLink className="size-3.5" />,
label:
single.type === "directory"
? t("fileManager.localOpenFolder")
: t("fileManager.localOpen"),
action: () => onOpen(single),
shortcut: "Enter",
});
}
menuItems.push({
icon: <Upload className="size-3.5" />,
label: isSingle
? t("fileManager.localUploadToRemote")
: t("fileManager.localUploadToRemoteMany", { count: entries.length }),
action: () => onUploadToRemote(entries),
disabled: !canUpload,
});
menuItems.push({
icon: <FolderOpen className="size-3.5" />,
label: t("fileManager.localRevealInFileManager"),
action: () => onReveal(entries[0]),
});
menuItems.push({ separator: true });
if (single) {
menuItems.push({
icon: <Edit3 className="size-3.5" />,
label: t("fileManager.rename"),
action: () => onRename(single),
shortcut: "F2",
});
}
menuItems.push({
icon: <Clipboard className="size-3.5" />,
label: isSingle ? t("fileManager.copyPath") : t("fileManager.copyPaths"),
action: () => onCopyPath(entries),
});
menuItems.push({ separator: true });
menuItems.push({
icon: <Trash2 className="size-3.5" />,
label: isSingle
? t("fileManager.localMoveToTrash")
: t("fileManager.localMoveToTrashMany", { count: entries.length }),
action: () => onDelete(entries),
shortcut: "Del",
danger: true,
});
} else {
menuItems.push({
icon: <FolderPlus className="size-3.5" />,
label: t("fileManager.newFolder"),
action: onNewFolder,
});
menuItems.push({
icon: <FilePlus className="size-3.5" />,
label: t("fileManager.newFile"),
action: onNewFile,
});
menuItems.push({ separator: true });
menuItems.push({
icon: <FolderOpen className="size-3.5" />,
label: t("fileManager.localRevealInFileManager"),
action: () => onReveal(),
});
menuItems.push({
icon: showHidden ? (
<EyeOff className="size-3.5" />
) : (
<Eye className="size-3.5" />
),
label: showHidden
? t("fileManager.localHideHidden")
: t("fileManager.localShowHidden"),
action: onToggleHidden,
});
menuItems.push({
icon: <RefreshCw className="size-3.5" />,
label: t("fileManager.refresh"),
action: onRefresh,
shortcut: "F5",
});
}
const renderShortcut = (shortcut: string) => {
const keys = shortcut.split("+");
if (keys.length === 1) return <Kbd>{keys[0]}</Kbd>;
return (
<Kbd>
{keys.map((key, index) => (
<React.Fragment key={`${key}-${index}`}>
<KbdKey>{key}</KbdKey>
{index < keys.length - 1 && <KbdSeparator />}
</React.Fragment>
))}
</Kbd>
);
};
if (!isVisible && !isMounted) return null;
return (
<>
<div
className={cn(
"fixed inset-0 z-[99990] transition-opacity duration-150",
!isMounted && "opacity-0",
)}
/>
<div
ref={menuRef}
data-context-menu
data-testid="local-file-context-menu"
className="fixed bg-card border border-border rounded-none shadow-md min-w-[220px] max-w-[300px] z-[99995] overflow-x-hidden overflow-y-auto py-1"
style={{
left: menuPosition.x,
top: menuPosition.y,
maxHeight: `calc(100vh - ${VIEWPORT_PADDING * 2}px)`,
}}
>
{menuItems.map((item, index) => {
if (item.separator) {
return (
<div
key={`separator-${index}`}
className="my-1 border-t border-border"
/>
);
}
return (
<button
key={`${item.label}-${index}`}
type="button"
className={cn(
"w-full px-3 min-h-8 py-1.5 text-left text-xs font-semibold flex items-center justify-between gap-3 rounded-none transition-colors cursor-pointer",
"hover:bg-accent-brand/10 hover:text-accent-brand",
item.disabled &&
"opacity-40 cursor-not-allowed hover:bg-transparent hover:text-current",
item.danger &&
"text-destructive hover:bg-destructive/10 hover:text-destructive",
)}
onClick={() => {
if (item.disabled) return;
item.action?.();
onClose();
}}
disabled={item.disabled}
>
<div className="flex items-center gap-2 flex-1 min-w-0">
<div className="flex-shrink-0 text-muted-foreground">
{item.icon}
</div>
<span className="flex-1 leading-tight">{item.label}</span>
</div>
{item.shortcut && (
<div className="ml-auto flex-shrink-0 opacity-50">
{renderShortcut(item.shortcut)}
</div>
)}
</button>
);
})}
</div>
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,43 @@
import type React from "react";
import { cn } from "@/lib/utils.ts";
interface ColumnResizeHandleProps {
onMouseDown: (event: React.MouseEvent) => void;
onDoubleClick: (event: React.MouseEvent) => void;
onClick: (event: React.MouseEvent) => void;
"data-resizing"?: string;
title?: string;
}
/**
* Thin grab area on the left edge of a list-view header cell. The parent cell
* must be `relative`. Shows a hairline on hover and while dragging.
*/
export function ColumnResizeHandle({
title,
"data-resizing": resizing,
...handlers
}: ColumnResizeHandleProps) {
return (
<div
role="separator"
aria-orientation="vertical"
title={title}
data-column-resize-handle
data-resizing={resizing}
className={cn(
"absolute -left-2 top-0 bottom-0 w-3 cursor-col-resize group/handle z-10",
)}
{...handlers}
>
<div
className={cn(
"absolute left-1/2 top-0.5 bottom-0.5 w-px -translate-x-1/2 transition-colors",
resizing
? "bg-accent-brand"
: "bg-transparent group-hover/handle:bg-accent-brand/60",
)}
/>
</div>
);
}
@@ -0,0 +1,105 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { Check } from "lucide-react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils.ts";
import type { ResizableColumns } from "../hooks/useResizableColumns.ts";
interface ColumnVisibilityMenuProps {
x: number;
y: number;
isVisible: boolean;
columns: ResizableColumns;
onClose: () => void;
}
/**
* Right-click menu for a list-view header: tick/untick which optional
* columns are shown. The name column is always on and not listed.
*/
export function ColumnVisibilityMenu({
x,
y,
isVisible,
columns,
onClose,
}: ColumnVisibilityMenuProps) {
const { t } = useTranslation();
const menuRef = useRef<HTMLDivElement>(null);
const [position, setPosition] = useState({ x, y });
useEffect(() => {
if (!isVisible) return;
const handleMouseDown = (event: MouseEvent) => {
if (!menuRef.current?.contains(event.target as Node)) onClose();
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") onClose();
};
const timeout = setTimeout(() => {
document.addEventListener("mousedown", handleMouseDown, true);
document.addEventListener("keydown", handleKeyDown);
window.addEventListener("blur", onClose);
}, 50);
return () => {
clearTimeout(timeout);
document.removeEventListener("mousedown", handleMouseDown, true);
document.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("blur", onClose);
};
}, [isVisible, onClose]);
useLayoutEffect(() => {
if (!isVisible || !menuRef.current) return;
const { offsetWidth, offsetHeight } = menuRef.current;
setPosition({
x: Math.max(8, Math.min(x, window.innerWidth - offsetWidth - 10)),
y: Math.max(8, Math.min(y, window.innerHeight - offsetHeight - 10)),
});
}, [isVisible, x, y]);
if (!isVisible) return null;
const onlyOneVisible = columns.visibleColumns.length <= 1;
return (
<div
ref={menuRef}
data-context-menu
data-testid="column-visibility-menu"
className="fixed bg-card border border-border rounded-none shadow-md min-w-[200px] z-[99995] py-1"
style={{ left: position.x, top: position.y }}
>
<div className="px-3 pt-1.5 pb-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("fileManager.columns")}
</div>
{columns.columns.map((column) => {
const visible = columns.isVisible(column.key);
// Keep at least one optional column so the header stays meaningful.
const disabled = visible && onlyOneVisible;
return (
<button
key={column.key}
type="button"
role="menuitemcheckbox"
aria-checked={visible}
disabled={disabled}
className={cn(
"w-full px-3 min-h-8 py-1.5 text-left text-xs font-semibold flex items-center gap-2 rounded-none transition-colors cursor-pointer",
"hover:bg-accent-brand/10 hover:text-accent-brand",
disabled &&
"opacity-40 cursor-not-allowed hover:bg-transparent hover:text-current",
)}
onClick={() => {
if (!disabled) columns.toggleColumn(column.key);
}}
>
<span className="size-3.5 flex items-center justify-center text-accent-brand">
{visible && <Check className="size-3.5" />}
</span>
<span className="flex-1 leading-tight">{t(column.labelKey)}</span>
</button>
);
})}
</div>
);
}
@@ -1,5 +1,7 @@
import { formatTransferMbPerSec } from "@/main-axios.ts";
import { useTranslation } from "react-i18next";
import { ArrowDownToLine } from "lucide-react";
import { TransferProgressBar } from "./TransferProgressBar";
interface DownloadProgressToastProps {
fileName: string;
@@ -22,26 +24,6 @@ function formatBytes(bytes: number): string {
return `${formattedSize} ${units[unitIndex]}`;
}
function IndeterminateProgressBar() {
return (
<div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
<div className="bg-primary/60 absolute inset-y-0 left-0 w-1/3 animate-pulse rounded-full" />
</div>
);
}
function DeterminateProgressBar({ value }: { value: number }) {
const clamped = Math.min(100, Math.max(0, value));
return (
<div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
<div
className="bg-primary h-full rounded-full transition-[width]"
style={{ width: `${clamped}%` }}
/>
</div>
);
}
export function DownloadProgressToast({
fileName,
loaded,
@@ -58,14 +40,16 @@ export function DownloadProgressToast({
return (
<div className="flex w-[min(calc(100vw-5rem),288px)] max-w-full flex-col gap-2 pr-2">
<p className="text-sm font-medium leading-tight truncate">
{t("fileManager.downloadingFile", { name: fileName })}
<p className="flex items-center gap-2 text-sm font-medium leading-tight">
<ArrowDownToLine className="size-3.5 shrink-0 text-accent-brand" />
<span className="truncate">
{t("fileManager.downloadingFile", { name: fileName })}
</span>
</p>
{percent === undefined ? (
<IndeterminateProgressBar />
) : (
<DeterminateProgressBar value={percent} />
)}
<TransferProgressBar
value={percent}
label={t("fileManager.downloadingFile", { name: fileName })}
/>
<div className="flex items-center justify-between gap-3 pr-1 text-xs text-muted-foreground">
<span className="min-w-0 truncate">
{total !== undefined
@@ -477,7 +477,11 @@ export function FileWindow({
document.body.removeChild(link);
URL.revokeObjectURL(url);
toast.success(t("fileManager.fileDownloadedSuccessfully"));
toast.success(
t("fileManager.fileDownloadedSuccessfully", {
name: response.fileName || file.name,
}),
);
}
} catch (error: unknown) {
console.error("Failed to download file:", error);
@@ -0,0 +1,110 @@
import { Button } from "@/components/button.tsx";
import { useTranslation } from "react-i18next";
import { formatFileSize } from "../file-manager-utils.ts";
export interface LocalTransferBatchStatus {
direction: "upload" | "download";
totalFiles: number;
completedFiles: number;
currentFileName?: string;
/** Files being transferred right now (parallel transfers). */
activeFiles?: number;
bytesDone: number;
totalBytes: number;
mbPerSec?: number;
cancelling?: boolean;
}
interface LocalTransferProgressToastProps {
status: LocalTransferBatchStatus;
onCancel?: () => void;
}
export function LocalTransferProgressToast({
status,
onCancel,
}: LocalTransferProgressToastProps) {
const { t } = useTranslation();
const percent =
status.totalBytes > 0
? Math.min(100, Math.round((status.bytesDone / status.totalBytes) * 100))
: undefined;
const title =
status.direction === "upload"
? t("fileManager.localUploadingProgress", {
current: Math.min(
status.completedFiles + Math.max(1, status.activeFiles ?? 1),
status.totalFiles,
),
total: status.totalFiles,
})
: t("fileManager.localDownloadingProgress", {
current: Math.min(
status.completedFiles + Math.max(1, status.activeFiles ?? 1),
status.totalFiles,
),
total: status.totalFiles,
});
return (
<div className="flex w-[min(calc(100vw-5rem),288px)] max-w-full flex-col gap-2 pr-2">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<p className="text-sm font-medium leading-tight">{title}</p>
{status.currentFileName && (
<p
className="text-xs text-muted-foreground truncate"
title={status.currentFileName}
>
{(status.activeFiles ?? 0) > 1 && (
<span className="mr-1 text-foreground/70">
{t("fileManager.localTransferInFlight", {
count: status.activeFiles,
})}
{" · "}
</span>
)}
{status.currentFileName}
</p>
)}
</div>
{onCancel && (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 shrink-0 px-2 text-xs"
disabled={status.cancelling}
onClick={onCancel}
>
{status.cancelling
? t("transfer.progressCancelling")
: t("transfer.progressCancel")}
</Button>
)}
</div>
<div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
{percent === undefined ? (
<div className="bg-primary/60 absolute inset-y-0 left-0 w-1/3 animate-pulse rounded-full" />
) : (
<div
className="bg-primary h-full rounded-full transition-[width]"
style={{ width: `${percent}%` }}
/>
)}
</div>
<div className="flex items-center justify-between gap-3 pr-1 text-xs text-muted-foreground">
<span className="min-w-0 truncate">
{formatFileSize(status.bytesDone)} /{" "}
{formatFileSize(status.totalBytes)}
</span>
<span className="shrink-0 tabular-nums font-medium text-foreground">
{status.mbPerSec !== undefined
? `${status.mbPerSec.toFixed(status.mbPerSec >= 10 ? 0 : 1)} MB/s`
: ""}
</span>
</div>
</div>
);
}
@@ -0,0 +1,43 @@
import type React from "react";
import { cn } from "@/lib/utils.ts";
interface PaneResizeHandleProps {
label: string;
onMouseDown: (event: React.MouseEvent) => void;
onDoubleClick?: () => void;
active?: boolean;
}
/**
* Vertical drag handle placed between two panes in a `gap-3` flex row. It
* overlaps the gap (negative margins) so the panes' spacing is unchanged, and
* shows a hairline on hover / while dragging. Double-click resets the width.
*/
export function PaneResizeHandle({
label,
onMouseDown,
onDoubleClick,
active = false,
}: PaneResizeHandleProps) {
return (
<div
role="separator"
aria-orientation="vertical"
aria-label={label}
title={label}
data-pane-resize-handle
onMouseDown={onMouseDown}
onDoubleClick={onDoubleClick}
className="hidden md:block -mx-3 w-3 shrink-0 cursor-col-resize group relative z-10"
>
<div
className={cn(
"absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors",
active
? "bg-accent-brand"
: "bg-transparent group-hover:bg-accent-brand/60",
)}
/>
</div>
);
}
@@ -0,0 +1,42 @@
import type { CSSProperties } from "react";
import { cn } from "@/lib/utils";
export function TransferProgressBar({
value,
label,
stalled = false,
}: {
value?: number;
label: string;
stalled?: boolean;
}) {
const clamped = Math.min(100, Math.max(0, value ?? 0));
const indeterminate = value === undefined;
return (
<div
role="progressbar"
aria-label={label}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={indeterminate ? undefined : clamped}
aria-busy={indeterminate}
data-stalled={stalled || undefined}
className="transfer-progress-track"
>
<div
className={cn(
"transfer-progress-fill",
indeterminate && "transfer-progress-indeterminate",
stalled && "transfer-progress-stalled",
)}
style={
indeterminate
? undefined
: ({ "--transfer-progress": clamped / 100 } as CSSProperties)
}
/>
</div>
);
}
@@ -5,6 +5,15 @@ import {
type TransferProgressResponse,
} from "@/main-axios.ts";
import { useTranslation } from "react-i18next";
import {
Archive,
ArchiveRestore,
ArrowRight,
Gauge,
RefreshCw,
ShieldCheck,
} from "lucide-react";
import { TransferProgressBar } from "./TransferProgressBar";
interface TransferProgressToastProps {
status: TransferProgressResponse;
@@ -15,26 +24,6 @@ interface TransferProgressToastProps {
cancelling?: boolean;
}
function IndeterminateProgressBar() {
return (
<div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
<div className="bg-primary/60 absolute inset-y-0 left-0 w-1/3 animate-pulse rounded-full" />
</div>
);
}
function DeterminateProgressBar({ value }: { value: number }) {
const clamped = Math.min(100, Math.max(0, value));
return (
<div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
<div
className="bg-primary h-full rounded-full transition-[width]"
style={{ width: `${clamped}%` }}
/>
</div>
);
}
export function TransferProgressToast({
status,
liveMbPerSec,
@@ -103,11 +92,29 @@ export function TransferProgressToast({
const showIndeterminate =
status.phase === "reconnecting" || percent === undefined;
const PhaseIcon =
status.phase === "compressing"
? Archive
: status.phase === "benchmarking"
? Gauge
: status.phase === "verifying"
? ShieldCheck
: status.phase === "extracting"
? ArchiveRestore
: status.phase === "reconnecting"
? RefreshCw
: ArrowRight;
return (
<div className="flex w-[min(calc(100vw-5rem),288px)] max-w-full flex-col gap-2 pr-2">
<div className="flex items-start justify-between gap-2">
<p className="text-sm font-medium leading-tight">{title}</p>
<p
key={status.phase}
className="motion-transfer-phase flex min-w-0 items-center gap-2 text-sm font-medium leading-tight"
>
<PhaseIcon className="size-3.5 shrink-0 text-accent-brand" />
<span className="truncate">{title}</span>
</p>
{onCancel && status.status === "running" && status.transferId && (
<Button
type="button"
@@ -123,11 +130,11 @@ export function TransferProgressToast({
</Button>
)}
</div>
{showIndeterminate ? (
<IndeterminateProgressBar />
) : (
<DeterminateProgressBar value={percent} />
)}
<TransferProgressBar
value={showIndeterminate ? undefined : percent}
label={title}
stalled={stalled}
/>
<div className="flex items-center justify-between gap-3 pr-1 text-xs text-muted-foreground">
<span className="min-w-0 truncate">{detailLeft ?? ""}</span>
<span
@@ -44,6 +44,7 @@ import {
type TransferMethodPreview,
} from "@/main-axios.ts";
import type { SSHHost } from "@/types";
import { Select2 } from "@/components/select2";
interface FileItem {
name: string;
@@ -715,7 +716,7 @@ export function TransferToHostDialog({
{t("transfer.selectDestinationHost")}
</Label>
<div className="relative">
<select
<Select2
value={selectedHostId}
onChange={(e) => handleHostChange(e.target.value)}
className="w-full appearance-none px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring pr-7"
@@ -728,7 +729,7 @@ export function TransferToHostDialog({
{host.name || host.ip}
</option>
))}
</select>
</Select2>
<ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
</div>
{selectedHost && (
@@ -945,7 +946,7 @@ export function TransferToHostDialog({
{t("transfer.methodLabel")}
</Label>
<div className="relative">
<select
<Select2
value={methodPreference}
onChange={(e) =>
setMethodPreference(
@@ -959,7 +960,7 @@ export function TransferToHostDialog({
<option value="item_sftp">
{t("transfer.methodItemSftp")}
</option>
</select>
</Select2>
<ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
</div>
<p className="text-[10px] text-muted-foreground">
@@ -976,7 +977,7 @@ export function TransferToHostDialog({
{t("transfer.parallelSegmentsLabel")}
</Label>
<div className="relative">
<select
<Select2
value={parallelSegmentCount}
onChange={(e) =>
setParallelSegmentCount(e.target.value)
@@ -989,7 +990,7 @@ export function TransferToHostDialog({
{t("transfer.parallelSegmentsOption", { count: n })}
</option>
))}
</select>
</Select2>
<ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
</div>
<p className="text-[10px] text-muted-foreground">
@@ -15,3 +15,21 @@ export function formatFileSize(bytes?: number): string {
size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
return `${formattedSize} ${units[unitIndex]}`;
}
export async function runWithConcurrency<T>(
items: T[],
limit: number,
task: (item: T) => Promise<void>,
): Promise<void> {
let nextIndex = 0;
const workerCount = Math.min(Math.max(1, limit), items.length);
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (nextIndex < items.length) {
const item = items[nextIndex++];
await task(item);
}
}),
);
}
@@ -0,0 +1,566 @@
import { useCallback, useRef } from "react";
import { createElement } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import type { FileItem } from "@/types/index";
import type { LocalWalkResult } from "@/types/electron";
import {
cancelLocalTransfer,
createLocalTransferId,
createSSHFolder,
downloadSessionFileToLocal,
listSSHFiles,
uploadLocalFileToSession,
} from "@/main-axios.ts";
import {
ensureLocalDirectory,
getLocalHome,
localPathsExist,
walkLocalPaths,
} from "@/lib/local-files.ts";
import {
UnsafeLocalNameError,
buildLocalDestination,
getTransferConcurrency,
runWithConcurrency,
joinRemotePath,
planRemoteDirectories,
remoteBaseName,
remoteDirForRelativePath,
} from "../local-transfer-utils.ts";
import {
LocalTransferProgressToast,
type LocalTransferBatchStatus,
} from "../components/LocalTransferProgressToast.tsx";
interface UseLocalTransfersOptions {
sshSessionId: string | null;
hostId?: number;
ensureSSHConnection: () => Promise<unknown>;
/** Called after uploads so the remote listing can refresh. */
onRemoteChanged: (remoteDir: string) => void;
/** Called after downloads so the local pane can refresh. */
onLocalChanged: (localDir: string) => void;
}
interface RemoteDownloadPlanEntry {
remotePath: string;
/** "/"-separated, includes the dragged root's own name. */
relativePath: string;
size?: number;
}
/**
* Asks whether existing local files may be replaced. Resolves `true` only on
* an explicit "Replace"; dismissing, auto-close and "Skip" all mean skip, so
* the batch can never overwrite silently.
*/
function askReplaceExisting(
t: ReturnType<typeof useTranslation>["t"],
count: number,
): Promise<boolean> {
return new Promise((resolve) => {
let settled = false;
const settle = (value: boolean) => {
if (settled) return;
settled = true;
resolve(value);
};
toast.warning(t("fileManager.localReplaceExistingPrompt", { count }), {
duration: 15000,
action: {
label: t("fileManager.localReplace"),
onClick: () => settle(true),
},
cancel: {
label: t("fileManager.localSkipExisting"),
onClick: () => settle(false),
},
onDismiss: () => settle(false),
onAutoClose: () => settle(false),
});
});
}
/** One line a user can act on, taken from whatever the bridge or backend said. */
function describeTransferError(error: unknown): string | undefined {
const message =
error instanceof Error ? error.message : String(error ?? "").trim();
return message ? message.slice(0, 200) : undefined;
}
class TransferCancelledError extends Error {
constructor() {
super("Transfer cancelled");
this.name = "TransferCancelledError";
}
}
function createSpeedometer() {
let lastBytes = 0;
let lastTime = Date.now();
let mbPerSec: number | undefined;
return (bytesDone: number) => {
const now = Date.now();
const deltaMs = now - lastTime;
if (deltaMs >= 300) {
const deltaBytes = bytesDone - lastBytes;
if (deltaBytes >= 0) {
mbPerSec = (deltaBytes / deltaMs / 1024 / 1024) * 1000;
}
lastBytes = bytesDone;
lastTime = now;
}
return mbPerSec;
};
}
/**
* Orchestrates batched local<->remote transfers for the dual-pane file
* manager: expands folders, creates directory skeletons, streams files one by
* one through the Electron main process, and reports aggregate progress in a
* single toast with a cancel button.
*/
export function useLocalTransfers({
sshSessionId,
hostId,
ensureSSHConnection,
onRemoteChanged,
onLocalChanged,
}: UseLocalTransfersOptions) {
const { t } = useTranslation();
const batchCounter = useRef(0);
const runBatch = useCallback(
async (
direction: "upload" | "download",
totalFiles: number,
totalBytes: number,
work: (ctx: {
isCancelled: () => boolean;
/** Marks a transfer as in flight so Cancel can reach it. */
trackTransfer: (id: string, fileName: string) => void;
/** Progress of one in-flight transfer; bytes are summed across all. */
progress: (id: string, transferred: number) => void;
/** Transfer finished (success or failure); its size is now settled. */
settleTransfer: (id: string, size: number) => void;
}) => Promise<{ failed: string[]; reason?: string }>,
) => {
batchCounter.current += 1;
const toastId = `local-transfer-${batchCounter.current}`;
let cancelled = false;
let cancelling = false;
const inFlight = new Map<
string,
{ fileName: string; transferred: number }
>();
let settledBytes = 0;
let completedFiles = 0;
let lastFileName: string | undefined;
const speed = createSpeedometer();
const status: LocalTransferBatchStatus = {
direction,
totalFiles,
completedFiles: 0,
bytesDone: 0,
totalBytes,
};
const render = () => {
toast.loading(
createElement(LocalTransferProgressToast, {
status: { ...status, cancelling },
onCancel: () => {
cancelled = true;
cancelling = true;
render();
for (const id of inFlight.keys()) void cancelLocalTransfer(id);
},
}),
{ id: toastId, duration: Infinity },
);
};
render();
try {
const refresh = () => {
let bytesDone = settledBytes;
for (const entry of inFlight.values()) bytesDone += entry.transferred;
status.completedFiles = completedFiles;
status.bytesDone = bytesDone;
status.activeFiles = inFlight.size;
status.currentFileName =
lastFileName ?? inFlight.values().next().value?.fileName;
status.mbPerSec = speed(bytesDone);
render();
};
const { failed, reason } = await work({
isCancelled: () => cancelled,
trackTransfer: (id, fileName) => {
inFlight.set(id, { fileName, transferred: 0 });
lastFileName = fileName;
refresh();
},
progress: (id, transferred) => {
const entry = inFlight.get(id);
if (!entry) return;
entry.transferred = transferred;
lastFileName = entry.fileName;
refresh();
},
settleTransfer: (id, size) => {
inFlight.delete(id);
settledBytes += size;
completedFiles += 1;
refresh();
},
});
toast.dismiss(toastId);
if (cancelled) {
toast.info(t("fileManager.localTransferCancelled"));
return;
}
const key = direction === "upload" ? "Upload" : "Download";
if (failed.length === 0) {
toast.success(
t(`fileManager.local${key}Complete`, { count: totalFiles }),
);
} else if (failed.length === totalFiles) {
// Every file failed the same way more often than not (auth,
// permissions, a dead session); say why instead of just "failed".
toast.error(
t(`fileManager.local${key}Failed`),
reason ? { description: reason } : undefined,
);
} else {
toast.warning(
t(`fileManager.local${key}Partial`, {
done: totalFiles - failed.length,
failed: failed.length,
}),
reason ? { description: reason } : undefined,
);
}
} catch (error) {
toast.dismiss(toastId);
if (error instanceof TransferCancelledError || cancelled) {
toast.info(t("fileManager.localTransferCancelled"));
return;
}
const message =
error instanceof Error ? error.message : String(error ?? "");
toast.error(
direction === "upload"
? t("fileManager.localUploadFailed")
: t("fileManager.localDownloadFailed"),
message ? { description: message } : undefined,
);
console.error(`Local ${direction} batch failed:`, error);
}
},
[t],
);
/** Uploads local files/folders (by absolute path) into a remote directory. */
const uploadLocalPaths = useCallback(
async (localPaths: string[], remoteDir: string) => {
if (!sshSessionId) {
toast.error(t("fileManager.noSSHConnection"));
return;
}
if (localPaths.length === 0) return;
let plan: LocalWalkResult;
try {
plan = await walkLocalPaths(localPaths);
} catch (error) {
toast.error(
t("fileManager.localUploadFailed"),
error instanceof Error ? { description: error.message } : undefined,
);
return;
}
if (plan.files.length === 0 && plan.emptyDirs.length === 0) {
toast.info(t("fileManager.localNothingToTransfer"));
return;
}
const sessionId = sshSessionId;
await runBatch(
"upload",
plan.files.length,
plan.totalBytes,
async ({ isCancelled, trackTransfer, progress, settleTransfer }) => {
await ensureSSHConnection();
const dirs = planRemoteDirectories(
plan.files.map((f) => f.relativePath),
plan.emptyDirs,
);
for (const dir of dirs) {
if (isCancelled()) throw new TransferCancelledError();
const parent = dir.includes("/")
? joinRemotePath(remoteDir, dir.slice(0, dir.lastIndexOf("/")))
: remoteDir;
const name = dir.split("/").pop()!;
// The backend tolerates existing directories (#1442), so a
// failure here is real and should stop the batch up front.
await createSSHFolder(sessionId, parent, name, hostId);
}
// Files go up several at a time (see "Simultaneous File Transfers"
// in the profile settings); directories were created above, so
// order between files no longer matters.
const failed: string[] = [];
let reason: string | undefined;
await runWithConcurrency(
plan.files,
getTransferConcurrency(),
async (file) => {
const fileName = file.relativePath.split("/").pop()!;
const targetDir = remoteDirForRelativePath(
remoteDir,
file.relativePath,
);
const transferId = createLocalTransferId("local-upload");
trackTransfer(transferId, fileName);
try {
await uploadLocalFileToSession({
sessionId,
remoteDir: targetDir,
localPath: file.localPath,
fileName,
hostId,
transferId,
onProgress: ({ transferred }) =>
progress(transferId, transferred),
});
} catch (error) {
if (!isCancelled()) {
failed.push(file.relativePath);
reason ??= describeTransferError(error);
console.error(`Failed to upload ${file.localPath}:`, error);
}
} finally {
settleTransfer(transferId, file.size);
}
},
isCancelled,
);
return { failed, reason };
},
);
onRemoteChanged(remoteDir);
},
[sshSessionId, hostId, ensureSSHConnection, onRemoteChanged, runBatch, t],
);
/** Downloads remote files/folders into a local directory. */
const downloadRemoteItems = useCallback(
async (items: FileItem[], localDir: string) => {
if (!sshSessionId) {
toast.error(t("fileManager.noSSHConnection"));
return;
}
if (items.length === 0) return;
const sessionId = sshSessionId;
const { separator } = await getLocalHome();
// Every remote name is validated for the local platform and the result
// must stay inside `localDir`; anything else is reported and skipped.
const toLocalPath = (relativePath: string) =>
buildLocalDestination(localDir, relativePath, separator);
// Expand directories into a flat file plan first so the toast can show
// a real total. Listing is the only part that goes through the
// renderer's normal API path.
const plan: RemoteDownloadPlanEntry[] = [];
const emptyDirs: string[] = [];
const expandTaskId = `local-download-expand-${Date.now()}`;
toast.loading(t("fileManager.localPreparingDownload"), {
id: expandTaskId,
duration: Infinity,
});
try {
await ensureSSHConnection();
const walkRemote = async (remotePath: string, relDir: string) => {
const { files } = await listSSHFiles(sessionId, remotePath, {
force: true,
});
if (files.length === 0) {
emptyDirs.push(relDir);
return;
}
for (const child of files) {
const rel = `${relDir}/${child.name}`;
if (child.type === "directory") {
await walkRemote(child.path, rel);
} else if (child.type === "file" || child.type === "link") {
plan.push({
remotePath: child.path,
relativePath: rel,
size: child.size,
});
}
}
};
for (const item of items) {
const name = item.name || remoteBaseName(item.path);
if (item.type === "directory") {
await walkRemote(item.path, name);
} else {
plan.push({
remotePath: item.path,
relativePath: name,
size: item.size,
});
}
}
} catch (error) {
toast.dismiss(expandTaskId);
toast.error(
t("fileManager.localDownloadFailed"),
error instanceof Error ? { description: error.message } : undefined,
);
return;
}
toast.dismiss(expandTaskId);
if (plan.length === 0 && emptyDirs.length === 0) {
toast.info(t("fileManager.localNothingToTransfer"));
return;
}
// Drop anything whose remote name cannot become a safe local path
// (separators, traversal, Windows-invalid characters). These never
// reach the filesystem; the user is told how many were skipped.
const unsafe: string[] = [];
const safeDest = (relativePath: string): string | null => {
try {
return toLocalPath(relativePath);
} catch (error) {
if (error instanceof UnsafeLocalNameError) {
unsafe.push(relativePath);
return null;
}
throw error;
}
};
const plannedDirs = emptyDirs
.map((dir) => ({ dir, dest: safeDest(dir) }))
.filter((d): d is { dir: string; dest: string } => d.dest !== null);
const plannedFiles = plan
.map((entry) => ({ entry, dest: safeDest(entry.relativePath) }))
.filter(
(p): p is { entry: RemoteDownloadPlanEntry; dest: string } =>
p.dest !== null,
);
if (unsafe.length > 0) {
toast.error(
t("fileManager.localUnsafeNamesSkipped", { count: unsafe.length }),
{ description: unsafe.slice(0, 3).join(", ") },
);
console.warn("Skipped remote items with unsafe local names:", unsafe);
}
if (plannedFiles.length === 0 && plannedDirs.length === 0) {
return;
}
// Collision policy: never replace silently. Find destinations that
// already exist and let the user choose Replace or Skip for the batch.
const destinations = plannedFiles.map((p) => p.dest);
let existing: Set<string>;
try {
existing = new Set(await localPathsExist(destinations));
} catch (error) {
toast.error(
t("fileManager.localDownloadFailed"),
error instanceof Error ? { description: error.message } : undefined,
);
return;
}
let overwriteExisting = false;
if (existing.size > 0) {
overwriteExisting = await askReplaceExisting(t, existing.size);
}
const skipped = overwriteExisting
? []
: plannedFiles.filter(({ dest }) => existing.has(dest));
const work = overwriteExisting
? plannedFiles
: plannedFiles.filter(({ dest }) => !existing.has(dest));
if (skipped.length > 0) {
toast.info(
t("fileManager.localSkippedExisting", { count: skipped.length }),
);
}
if (work.length === 0 && plannedDirs.length === 0) {
onLocalChanged(localDir);
return;
}
const workBytes = work.reduce((sum, w) => sum + (w.entry.size ?? 0), 0);
await runBatch(
"download",
work.length,
workBytes,
async ({ isCancelled, trackTransfer, progress, settleTransfer }) => {
for (const { dest } of plannedDirs) {
if (isCancelled()) throw new TransferCancelledError();
await ensureLocalDirectory(dest, localDir);
}
const failed: string[] = [];
let reason: string | undefined;
await runWithConcurrency(
work,
getTransferConcurrency(),
async ({ entry, dest }) => {
const fileName = entry.relativePath.split("/").pop()!;
const transferId = createLocalTransferId("local-download");
trackTransfer(transferId, fileName);
try {
await downloadSessionFileToLocal({
sessionId,
remotePath: entry.remotePath,
destPath: dest,
rootPath: localDir,
expectedSize: entry.size,
overwrite: overwriteExisting && existing.has(dest),
transferId,
onProgress: ({ transferred }) =>
progress(transferId, transferred),
});
} catch (error) {
if (!isCancelled()) {
failed.push(entry.relativePath);
reason ??= describeTransferError(error);
console.error(
`Failed to download ${entry.remotePath}:`,
error,
);
}
} finally {
settleTransfer(transferId, entry.size ?? 0);
}
},
isCancelled,
);
return { failed, reason };
},
);
onLocalChanged(localDir);
},
[sshSessionId, ensureSSHConnection, onLocalChanged, runBatch, t],
);
return { uploadLocalPaths, downloadRemoteItems };
}
@@ -0,0 +1,106 @@
import { useCallback, useRef, useState } from "react";
import type React from "react";
interface UsePaneWidthOptions {
/** localStorage key the width is remembered under. */
storageKey: string;
defaultWidth: number;
minWidth: number;
/**
* Upper bound as a fraction of the containing row's width (measured at
* drag start from `containerRef`), so a pane can never swallow the layout.
*/
maxFraction?: number;
containerRef?: React.RefObject<HTMLElement | null>;
}
function readStoredWidth(
storageKey: string,
defaultWidth: number,
minWidth: number,
): number {
try {
const saved = Number(localStorage.getItem(storageKey));
return Number.isFinite(saved) && saved >= minWidth ? saved : defaultWidth;
} catch {
return defaultWidth;
}
}
/**
* A persisted, drag-resizable pane width. `startResize` goes on the
* mousedown of a vertical drag handle sitting on the pane's right edge;
* `resetWidth` (e.g. on double-click) restores the default.
*/
export function usePaneWidth({
storageKey,
defaultWidth,
minWidth,
maxFraction = 0.65,
containerRef,
}: UsePaneWidthOptions) {
const [width, setWidth] = useState<number>(() =>
readStoredWidth(storageKey, defaultWidth, minWidth),
);
const [isResizing, setIsResizing] = useState(false);
const widthRef = useRef(width);
widthRef.current = width;
const persist = useCallback(
(value: number) => {
try {
localStorage.setItem(storageKey, String(value));
} catch {
// storage unavailable
}
},
[storageKey],
);
const startResize = useCallback(
(event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
const startWidth = widthRef.current;
const rowWidth =
containerRef?.current?.getBoundingClientRect().width ?? 0;
const maxWidth = Math.max(
minWidth,
rowWidth ? rowWidth * maxFraction : Number.POSITIVE_INFINITY,
);
let latest = startWidth;
setIsResizing(true);
const onMove = (e: MouseEvent) => {
latest = Math.round(
Math.min(
maxWidth,
Math.max(minWidth, startWidth + (e.clientX - startX)),
),
);
if (latest !== widthRef.current) setWidth(latest);
};
const onUp = () => {
document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
setIsResizing(false);
persist(latest);
};
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
document.addEventListener("mousemove", onMove);
document.addEventListener("mouseup", onUp);
},
[containerRef, maxFraction, minWidth, persist],
);
const resetWidth = useCallback(() => {
setWidth(defaultWidth);
persist(defaultWidth);
}, [defaultWidth, persist]);
return { width, isResizing, startResize, resetWidth };
}
@@ -0,0 +1,239 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type React from "react";
export interface ResizableColumnSpec {
/** Stable key, also used for persistence. */
key: string;
/** i18n key for the column's label (used by the show/hide menu). */
labelKey: string;
defaultWidth: number;
minWidth?: number;
maxWidth?: number;
}
interface UseResizableColumnsOptions {
/** localStorage key; widths are remembered per pane. */
storageKey: string;
/**
* Fixed-width columns, in visual order, that follow a leading flexible
* column (the file name). The flexible column absorbs whatever is left.
*/
columns: ResizableColumnSpec[];
}
const DEFAULT_MIN = 48;
const DEFAULT_MAX = 600;
function readStoredWidths(
storageKey: string,
columns: ResizableColumnSpec[],
): Record<string, number> {
const widths: Record<string, number> = {};
for (const column of columns) widths[column.key] = column.defaultWidth;
try {
const raw = localStorage.getItem(storageKey);
if (!raw) return widths;
const parsed = JSON.parse(raw) as Record<string, unknown>;
for (const column of columns) {
const value = parsed?.[column.key];
if (typeof value === "number" && Number.isFinite(value)) {
widths[column.key] = clamp(value, column);
}
}
} catch {
// storage unavailable or corrupt: fall back to defaults
}
return widths;
}
function readHiddenKeys(
storageKey: string,
columns: ResizableColumnSpec[],
): Set<string> {
try {
const raw = localStorage.getItem(`${storageKey}:hidden`);
if (!raw) return new Set();
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return new Set();
const known = new Set(columns.map((c) => c.key));
return new Set(
parsed.filter((k): k is string => typeof k === "string" && known.has(k)),
);
} catch {
return new Set();
}
}
function clamp(value: number, column: ResizableColumnSpec): number {
const min = column.minWidth ?? DEFAULT_MIN;
const max = column.maxWidth ?? DEFAULT_MAX;
return Math.round(Math.min(max, Math.max(min, value)));
}
/**
* Column widths for a list view whose first column is flexible and whose
* remaining columns are fixed and user-resizable by dragging the boundary at
* the left edge of each header cell. Double-clicking a handle resets that
* column to its default. Widths persist in localStorage.
*/
export function useResizableColumns({
storageKey,
columns,
}: UseResizableColumnsOptions) {
const [widths, setWidths] = useState<Record<string, number>>(() =>
readStoredWidths(storageKey, columns),
);
const [hiddenKeys, setHiddenKeys] = useState<Set<string>>(() =>
readHiddenKeys(storageKey, columns),
);
const [resizingKey, setResizingKey] = useState<string | null>(null);
const widthsRef = useRef(widths);
widthsRef.current = widths;
// Re-read if the pane is re-keyed (e.g. a different storage key).
useEffect(() => {
setWidths(readStoredWidths(storageKey, columns));
setHiddenKeys(readHiddenKeys(storageKey, columns));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [storageKey]);
const isVisible = useCallback(
(key: string) => !hiddenKeys.has(key),
[hiddenKeys],
);
const visibleColumns = useMemo(
() => columns.filter((c) => !hiddenKeys.has(c.key)),
[columns, hiddenKeys],
);
const toggleColumn = useCallback(
(key: string) => {
setHiddenKeys((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
try {
localStorage.setItem(
`${storageKey}:hidden`,
JSON.stringify(Array.from(next)),
);
} catch {
// storage unavailable
}
return next;
});
},
[storageKey],
);
const persist = useCallback(
(next: Record<string, number>) => {
try {
localStorage.setItem(storageKey, JSON.stringify(next));
} catch {
// storage unavailable
}
},
[storageKey],
);
const gridTemplateColumns = useMemo(
() =>
[
"minmax(140px, 1fr)",
...visibleColumns.map((c) => `${widths[c.key]}px`),
].join(" "),
[visibleColumns, widths],
);
const startResize = useCallback(
(key: string, event: React.MouseEvent) => {
const column = columns.find((c) => c.key === key);
if (!column) return;
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
const startWidth = widthsRef.current[key];
setResizingKey(key);
const onMove = (e: MouseEvent) => {
// The handle sits on the column's left edge, so dragging right
// narrows the column and dragging left widens it.
const next = clamp(startWidth - (e.clientX - startX), column);
if (next !== widthsRef.current[key]) {
setWidths((prev) => ({ ...prev, [key]: next }));
}
};
const onUp = () => {
document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
setResizingKey(null);
persist(widthsRef.current);
// The browser dispatches a click to the common ancestor of the
// mousedown/mouseup targets, which here is the sortable header cell.
// Swallow that one click so finishing a drag never toggles the sort.
const swallow = (e: MouseEvent) => {
e.stopPropagation();
e.preventDefault();
};
document.addEventListener("click", swallow, { capture: true });
setTimeout(
() =>
document.removeEventListener("click", swallow, { capture: true }),
0,
);
};
document.body.style.cursor = "col-resize";
document.body.style.userSelect = "none";
document.addEventListener("mousemove", onMove);
document.addEventListener("mouseup", onUp);
},
[columns, persist],
);
const resetColumn = useCallback(
(key: string) => {
const column = columns.find((c) => c.key === key);
if (!column) return;
setWidths((prev) => {
const next = { ...prev, [key]: column.defaultWidth };
persist(next);
return next;
});
},
[columns, persist],
);
const getHandleProps = useCallback(
(key: string) => ({
onMouseDown: (event: React.MouseEvent) => startResize(key, event),
onDoubleClick: (event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
resetColumn(key);
},
onClick: (event: React.MouseEvent) => event.stopPropagation(),
"data-resizing": resizingKey === key ? "true" : undefined,
}),
[startResize, resetColumn, resizingKey],
);
return {
widths,
gridTemplateColumns,
getHandleProps,
resizingKey,
columns,
visibleColumns,
isVisible,
toggleColumn,
};
}
export type ResizableColumns = ReturnType<typeof useResizableColumns>;
@@ -0,0 +1,413 @@
// Pure helpers shared by the dual-pane (local <-> remote) file manager code.
// Kept free of React/DOM so they can be unit tested directly.
import type { LocalFileEntry } from "@/types/electron";
/** Custom MIME type carried by drags that originate in the local pane. */
export const LOCAL_FILES_DRAG_MIME = "application/x-termix-local-files";
/**
* Custom MIME type the remote grid adds to its internal drags so other panes
* can recognise them during dragenter/dragover (when payloads are unreadable).
*/
export const REMOTE_FILES_DRAG_MIME = "application/x-termix-remote-files";
export interface LocalFilesDragPayload {
type: "local_files";
paths: string[];
}
export interface InternalFilesDragPayload {
type: "internal_files";
files: string[];
}
export function serializeLocalFilesDragPayload(paths: string[]): string {
const payload: LocalFilesDragPayload = { type: "local_files", paths };
return JSON.stringify(payload);
}
export function parseLocalFilesDragPayload(
raw: string | null | undefined,
): string[] | null {
if (!raw) return null;
try {
const parsed = JSON.parse(raw) as Partial<LocalFilesDragPayload>;
if (parsed?.type !== "local_files" || !Array.isArray(parsed.paths)) {
return null;
}
const paths = parsed.paths.filter(
(p): p is string => typeof p === "string" && p.length > 0,
);
return paths.length > 0 ? paths : null;
} catch {
return null;
}
}
/** Parses the payload the remote grid puts on `text/plain` for internal drags. */
export function parseInternalFilesDragPayload(
raw: string | null | undefined,
): string[] | null {
if (!raw) return null;
try {
const parsed = JSON.parse(raw) as Partial<InternalFilesDragPayload>;
if (parsed?.type !== "internal_files" || !Array.isArray(parsed.files)) {
return null;
}
const files = parsed.files.filter(
(p): p is string => typeof p === "string" && p.length > 0,
);
return files.length > 0 ? files : null;
} catch {
return null;
}
}
/** True while a drag that started in the local pane is over the element. */
export function isLocalFilesDrag(
dataTransfer: Pick<DataTransfer, "types"> | null | undefined,
): boolean {
if (!dataTransfer) return false;
return Array.from(dataTransfer.types ?? []).includes(LOCAL_FILES_DRAG_MIME);
}
/**
* Marks a drag that starts on remote rows. Within the remote grid a drop is a
* move; onto the local pane it is a copy (a download). The source has to
* allow both, because Chromium refuses a drop whose dropEffect is not in
* effectAllowed without firing any event at all -- the drop just silently
* does nothing.
*/
export function beginRemoteFilesDrag(
dataTransfer: Pick<DataTransfer, "setData" | "effectAllowed">,
remotePaths: string[],
): void {
const payload: InternalFilesDragPayload = {
type: "internal_files",
files: remotePaths,
};
dataTransfer.setData("text/plain", JSON.stringify(payload));
// Lets sibling panes recognise this drag before the payload is readable.
dataTransfer.setData(REMOTE_FILES_DRAG_MIME, "1");
dataTransfer.effectAllowed = "copyMove";
}
/** True while a drag that started in the remote grid is over the element. */
export function isRemoteFilesDrag(
dataTransfer: Pick<DataTransfer, "types"> | null | undefined,
): boolean {
if (!dataTransfer) return false;
return Array.from(dataTransfer.types ?? []).includes(REMOTE_FILES_DRAG_MIME);
}
/** Joins a POSIX remote directory with one or more path segments. */
export function joinRemotePath(base: string, ...segments: string[]): string {
let out = base || "/";
for (const segment of segments) {
const clean = segment.replace(/^\/+|\/+$/g, "");
if (!clean) continue;
out = out.endsWith("/") ? `${out}${clean}` : `${out}/${clean}`;
}
return out;
}
/** Joins a local directory and a file name using the platform separator. */
export function joinLocalPath(
base: string,
name: string,
separator: string,
): string {
const sep = separator || "/";
const trimmedBase = base.endsWith(sep) ? base.slice(0, -sep.length) : base;
// Root on POSIX is "/" which trims to ""; keep the separator in that case.
return `${trimmedBase}${sep}${name}`;
}
/** Thrown when a remote name cannot be used as a local path component. */
export class UnsafeLocalNameError extends Error {
readonly code = "EINVAL";
constructor(
readonly name: string,
readonly reason: string,
) {
super(`Unsafe file name "${name}": ${reason}`);
}
}
// Windows refuses these device names in any directory, with any extension.
const WINDOWS_RESERVED_NAMES =
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.[^.]*)?$/i;
/**
* Validates one remote path component for use as a single local path
* segment on the destination platform (`separator` "\\" means Windows).
*
* A POSIX file name may legally contain "\\", ":" or end in a dot, all of
* which Windows treats as separators, drive prefixes or strips — so a remote
* name like "..\\outside.txt" would otherwise be normalised out of the
* selected download folder. Anything that is not a plain name is rejected;
* traversal ("..") and separators are rejected on every platform.
*/
export function assertSafeLocalComponent(
name: string,
separator: string,
): string {
if (name === "" || name === "." || name === "..") {
throw new UnsafeLocalNameError(name, "empty or traversal component");
}
if (name.includes("/") || name.includes("\0")) {
throw new UnsafeLocalNameError(name, "contains a path separator or NUL");
}
if (separator === "\\") {
if (/[\\:*?"<>|]/.test(name)) {
throw new UnsafeLocalNameError(
name,
"contains a character Windows does not allow in file names",
);
}
if (/[\u0001-\u001f]/.test(name)) {
throw new UnsafeLocalNameError(name, "contains control characters");
}
if (/[. ]$/.test(name)) {
throw new UnsafeLocalNameError(
name,
"Windows strips trailing dots and spaces",
);
}
if (WINDOWS_RESERVED_NAMES.test(name)) {
throw new UnsafeLocalNameError(name, "reserved device name on Windows");
}
}
return name;
}
function samePathPrefix(a: string, b: string, separator: string): boolean {
return separator === "\\" ? a.toLowerCase() === b.toLowerCase() : a === b;
}
/**
* Builds the local destination for a "/"-separated relative remote path
* under `localDir`, validating every component for the destination platform
* and asserting the result stays strictly inside `localDir`.
*/
export function buildLocalDestination(
localDir: string,
relativePath: string,
separator: string,
): string {
const sep = separator || "/";
const parts = relativePath.split("/").filter((p) => p !== "");
if (parts.length === 0) {
throw new UnsafeLocalNameError(relativePath, "empty path");
}
const dest = parts.reduce(
(acc, part) => joinLocalPath(acc, assertSafeLocalComponent(part, sep), sep),
localDir,
);
const root = localDir.endsWith(sep) ? localDir : `${localDir}${sep}`;
if (
!samePathPrefix(dest.slice(0, root.length), root, sep) ||
dest.length <= root.length
) {
throw new UnsafeLocalNameError(
relativePath,
"destination escapes the selected folder",
);
}
return dest;
}
export function remoteBaseName(remotePath: string): string {
const trimmed = remotePath.replace(/\/+$/, "");
return trimmed.split("/").pop() || trimmed || "/";
}
/**
* Given the "/"-separated relative paths of files being uploaded (each
* including its top-level root name) plus any empty directories, returns the
* set of directories that must exist on the remote, shallowest first, so each
* parent is created before its children.
*/
export function planRemoteDirectories(
fileRelativePaths: string[],
emptyDirs: string[] = [],
): string[] {
const dirs = new Set<string>();
for (const relativePath of fileRelativePaths) {
const parts = relativePath.split("/").filter(Boolean);
for (let i = 1; i < parts.length; i++) {
dirs.add(parts.slice(0, i).join("/"));
}
}
for (const dir of emptyDirs) {
const parts = dir.split("/").filter(Boolean);
for (let i = 1; i <= parts.length; i++) {
dirs.add(parts.slice(0, i).join("/"));
}
}
return Array.from(dirs).sort(
(a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b),
);
}
/** Remote directory a file with the given relative path should land in. */
export function remoteDirForRelativePath(
base: string,
relativePath: string,
): string {
const idx = relativePath.lastIndexOf("/");
if (idx <= 0) return base;
return joinRemotePath(base, relativePath.slice(0, idx));
}
/** Short "Kind" column label, in the spirit of Finder / Termius. */
export function describeLocalKind(
entry: Pick<LocalFileEntry, "name" | "type">,
): string {
if (entry.type === "directory") return "folder";
if (entry.type === "link") return "link";
const dot = entry.name.lastIndexOf(".");
if (dot > 0 && dot < entry.name.length - 1) {
return entry.name.slice(dot + 1).toLowerCase();
}
return "file";
}
export type LocalSortField = "name" | "modified" | "size" | "kind";
export function sortLocalEntries(
entries: LocalFileEntry[],
field: LocalSortField,
order: "asc" | "desc",
): LocalFileEntry[] {
const dir = order === "asc" ? 1 : -1;
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: "base",
});
return [...entries].sort((a, b) => {
// Folders always group first, matching the remote grid.
const aDir = a.type === "directory" ? 0 : 1;
const bDir = b.type === "directory" ? 0 : 1;
if (aDir !== bDir) return aDir - bDir;
let cmp = 0;
switch (field) {
case "modified":
cmp = (a.modifiedTimestamp ?? 0) - (b.modifiedTimestamp ?? 0);
break;
case "size":
cmp = a.size - b.size;
break;
case "kind":
cmp = collator.compare(describeLocalKind(a), describeLocalKind(b));
break;
default:
cmp = 0;
}
if (cmp === 0) cmp = collator.compare(a.name, b.name);
return cmp * dir;
});
}
const MONTH_ABBREVIATIONS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
/**
* Formats a local mtime the same way the backend formats remote entries
* (`formatMtime` in src/backend/hosts/file-manager/utils.ts, i.e. `ls -l`
* style): `Sep 11 16:25` for the last six months, `Sep 11 2025` before
* that — so both panes read alike.
*/
export function formatLocalModified(
timestamp?: number,
now: Date = new Date(),
): string {
if (!timestamp) return "--";
const date = new Date(timestamp);
if (Number.isNaN(date.getTime())) return "--";
const month = MONTH_ABBREVIATIONS[date.getMonth()];
const day = date.getDate().toString().padStart(2, " ");
const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000);
if (date > sixMonthsAgo) {
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
return `${month} ${day} ${hours}:${minutes}`;
}
return `${month} ${day} ${date.getFullYear()}`;
}
// ---------------------------------------------------------------------------
// Parallel transfers
export const TRANSFER_CONCURRENCY_STORAGE_KEY =
"termix:file-manager:transfer-concurrency";
export const DEFAULT_TRANSFER_CONCURRENCY = 4;
export const MAX_TRANSFER_CONCURRENCY = 8;
export function clampTransferConcurrency(value: unknown): number {
const n = Math.floor(Number(value));
if (!Number.isFinite(n)) return DEFAULT_TRANSFER_CONCURRENCY;
return Math.min(MAX_TRANSFER_CONCURRENCY, Math.max(1, n));
}
/** How many files are transferred at the same time (1 = one after another). */
export function getTransferConcurrency(): number {
try {
const raw = localStorage.getItem(TRANSFER_CONCURRENCY_STORAGE_KEY);
return raw === null
? DEFAULT_TRANSFER_CONCURRENCY
: clampTransferConcurrency(raw);
} catch {
return DEFAULT_TRANSFER_CONCURRENCY;
}
}
export function setTransferConcurrency(value: number): number {
const clamped = clampTransferConcurrency(value);
try {
localStorage.setItem(TRANSFER_CONCURRENCY_STORAGE_KEY, String(clamped));
} catch {
// storage unavailable
}
return clamped;
}
/**
* Runs `worker` over `items` with at most `limit` in flight, preserving the
* original order of dispatch. Stops dispatching new items once `shouldStop()`
* returns true; items already in flight run to completion (the caller
* cancels those through their own transfer ids). Never rejects because of a
* single item: worker errors are the worker's business.
*/
export async function runWithConcurrency<T>(
items: readonly T[],
limit: number,
worker: (item: T, index: number) => Promise<void>,
shouldStop: () => boolean = () => false,
): Promise<void> {
const size = Math.max(1, Math.min(limit, items.length));
let next = 0;
const lanes = Array.from({ length: size }, async () => {
while (next < items.length && !shouldStop()) {
const index = next++;
await worker(items[index], index);
}
});
await Promise.all(lanes);
}
@@ -89,6 +89,7 @@ export interface BeginTransferMonitoringOptions {
finalStatus: TransferProgressResponse,
toastId: string | number,
) => void;
onProgress?: (status: TransferProgressResponse) => void;
formatTransferMetrics?: (timings?: TransferTimings) => string;
}
@@ -226,6 +227,7 @@ function showDefaultCompletionToast(
id: toastId,
description: metrics || undefined,
className: TOAST_CLASS,
duration: undefined,
},
);
return;
@@ -236,6 +238,7 @@ function showDefaultCompletionToast(
id: toastId,
description: metrics || undefined,
className: TOAST_CLASS,
duration: undefined,
});
}
@@ -288,6 +291,7 @@ export function beginTransferProgressMonitoring(
const waitForCompletion = pollTransferUntilComplete(
transferId,
(status) => {
options.onProgress?.(status);
const { rate, stalled } = progressTracker.update(status);
renderTransferProgressToast(
progressToast,
@@ -319,6 +323,7 @@ export function beginTransferProgressMonitoring(
toast.error(`${t("transfer.transferError")}: ${message}`, {
id: progressToast,
className: TOAST_CLASS,
duration: undefined,
});
markTransferNotified(transferId);
throw error;
+208 -51
View File
@@ -1,3 +1,4 @@
import { watchGuacamoleConnectionId } from "./guacamole-session-id";
import { getErrorMessage } from "../../lib/error-message.js";
import React, {
useState,
@@ -21,11 +22,16 @@ import {
isElectron,
} from "@/main-axios.ts";
import { readConfiguredDimension } from "@/features/guacamole/guacamole-display-size.ts";
import { parseGuacamoleConfig } from "@/api/guacamole-api";
import { resolveConnectionOrigin } from "@/lib/connection-origin.ts";
import { getGuacamoleToken, parseGuacamoleConfig } from "@/api/guacamole-api";
import {
resolveConnectionOrigin,
type ConnectionOrigin,
} from "@/lib/connection-origin.ts";
import { useTranslation } from "react-i18next";
import { GuacamoleToolbar } from "@/features/guacamole/GuacamoleToolbar.tsx";
import { GuacamoleFileBrowser } from "@/features/guacamole/GuacamoleFileBrowser.tsx";
import { describeUploadError } from "@/features/guacamole/guacamole-filesystem.ts";
import { canUploadToRdpDrive } from "@/features/guacamole/guacamole-file-drop.ts";
import { Button } from "@/components/button.tsx";
import { Input } from "@/components/input.tsx";
import { PasswordInput } from "@/components/password-input.tsx";
@@ -46,14 +52,22 @@ import { ShareSessionModal } from "@/features/session-sharing/ShareSessionModal.
import type { SSHHost } from "@/types";
import { useConnectionDefaults } from "@/contexts/ConnectionDefaultsContext";
import { resolveConnectionDefaults } from "@/lib/connection-defaults";
import { needsRdpCredentialPrompt } from "@/features/guacamole/rdp-credential-prompt";
interface GuacamoleAppProps {
hostId?: string;
tabId?: string;
protocol?: "rdp" | "vnc" | "telnet";
isVisible?: boolean;
/** A quick-connect host: never saved, so the token is minted from its fields. */
quickConnectHost?: GuacamoleQuickHost;
}
/** What GuacamoleApp needs from a host that has no database row. */
export type GuacamoleQuickHost = GuacamoleAppInnerProps["hostConfig"] & {
name?: string;
};
export interface GuacamoleAppHandle {
disconnect: () => void;
isConnected: () => boolean;
@@ -62,14 +76,31 @@ export interface GuacamoleAppHandle {
}
const GuacamoleApp = React.forwardRef<GuacamoleAppHandle, GuacamoleAppProps>(
function GuacamoleApp({ hostId, tabId, protocol, isVisible = true }, ref) {
function GuacamoleApp(
{ hostId, tabId, protocol, isVisible = true, quickConnectHost },
ref,
) {
const { t } = useTranslation();
const defaults = useConnectionDefaults();
const [hostConfig, setHostConfig] = useState<SSHHost | null>(null);
const [hostConfig, setHostConfig] = useState<GuacamoleQuickHost | null>(
null,
);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!defaults.ready) return;
if (quickConnectHost) {
const connectionType = protocol ?? quickConnectHost.connectionType;
setHostConfig({
...quickConnectHost,
guacamoleConfig: resolveConnectionDefaults(
connectionType === "rdp" ? defaults.rdp : {},
{},
),
});
setLoading(false);
return;
}
if (!hostId) {
setLoading(false);
return;
@@ -93,7 +124,7 @@ const GuacamoleApp = React.forwardRef<GuacamoleAppHandle, GuacamoleAppProps>(
})
.catch(() => setHostConfig(null))
.finally(() => setLoading(false));
}, [hostId, protocol, defaults.ready, defaults.rdp]);
}, [hostId, protocol, defaults.ready, defaults.rdp, quickConnectHost]);
if (loading) {
return (
@@ -117,9 +148,9 @@ const GuacamoleApp = React.forwardRef<GuacamoleAppHandle, GuacamoleAppProps>(
return (
<ConnectionLogProvider>
<GuacamoleAppInner
hostId={parseInt(hostId, 10)}
hostId={quickConnectHost ? 0 : parseInt(hostId, 10)}
hostConfig={hostConfig}
hostName={hostConfig.name || hostConfig.ip || String(hostId)}
hostName={hostConfig.name || hostConfig.ip || String(hostId ?? "")}
tabId={tabId}
protocol={protocol}
isVisible={isVisible}
@@ -134,8 +165,21 @@ interface GuacamoleAppInnerProps {
hostId: number;
hostConfig: Pick<
SSHHost,
"connectionType" | "domain" | "guacamoleConfig" | "rdpAuthType" | "syncId"
>;
| "connectionType"
| "domain"
| "guacamoleConfig"
| "rdpAuthType"
| "authOverrides"
| "syncId"
| "connectionOrigin"
| "ip"
| "rdpPort"
| "vncPort"
| "rdpUser"
| "rdpPassword"
| "vncUser"
| "vncPassword"
> & { enableTerminalToolbar?: boolean };
hostName: string;
tabId?: string;
protocol?: "rdp" | "vnc" | "telnet";
@@ -155,6 +199,10 @@ const GuacamoleAppInner = React.forwardRef<
const [guacamoleConnectionId, setGuacamoleConnectionId] = useState<
string | null
>(null);
const [sessionLookup, setSessionLookup] = useState<{
id: string;
origin: ConnectionOrigin;
} | null>(null);
const [shareModalOpen, setShareModalOpen] = useState(false);
const [error, setError] = useState<string | null>(null);
const [connectionError, setConnectionError] = useState<string | null>(null);
@@ -165,21 +213,55 @@ const GuacamoleAppInner = React.forwardRef<
? "touchscreen"
: null,
);
useEffect(() => {
if (!isDisplayReady || !sessionLookup) return;
return watchGuacamoleConnectionId(
sessionLookup.id,
sessionLookup.origin,
setGuacamoleConnectionId,
);
}, [isDisplayReady, sessionLookup]);
const displayRef = useRef<GuacamoleDisplayHandle>(null);
const [displayZoom, setDisplayZoom] = useState(1);
const [filesystem, setFilesystem] = useState<Guacamole.Object | null>(null);
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
const [toolbarHidden, setToolbarHidden] = useState(false);
const [pendingUploads, setPendingUploads] = useState<File[]>([]);
const guacConfig = parseGuacamoleConfig(hostConfig.guacamoleConfig);
const allowUpload = guacConfig.disableUpload !== true;
const allowDownload = guacConfig.disableDownload !== true;
// A dropped file has nowhere to go until the browser is showing the target
// directory, so opening it is part of accepting the drop.
const handleDropFiles = useCallback((files: File[]) => {
setPendingUploads(files);
setFileBrowserOpen(true);
}, []);
// Prefer the browsable filesystem's current directory. guacd may expose the
// RDP drive only through the connection-level file stream, in which case the
// standard direct upload still lands in the redirected drive.
const handleDropFiles = useCallback(
(files: File[]) => {
if (filesystem) {
setPendingUploads(files);
setFileBrowserOpen(true);
return;
}
void (async () => {
for (const file of files) {
try {
const display = displayRef.current;
if (!display) throw new Error("RDP session is not ready");
await display.uploadFile(file);
toast.success(t("guacamole.files.uploaded", { name: file.name }));
} catch (error) {
toast.error(
describeUploadError(error, (key) =>
t(`guacamole.files.${key}`, { name: file.name }),
),
);
}
}
})();
},
[filesystem, t],
);
const handleDropUnavailable = useCallback(() => {
toast.error(
@@ -194,8 +276,11 @@ const GuacamoleAppInner = React.forwardRef<
const resolvedProtocolForConnect = (protocol ??
hostConfig.connectionType ??
"rdp") as "rdp" | "vnc" | "telnet";
const needsCredentialPrompt =
resolvedProtocolForConnect === "rdp" && hostConfig.rdpAuthType === "none";
const needsCredentialPrompt = needsRdpCredentialPrompt({
protocol: resolvedProtocolForConnect,
rdpAuthType: hostConfig.rdpAuthType,
authOverrides: hostConfig.authOverrides,
});
const [promptedCredentials, setPromptedCredentials] = useState<{
username: string;
@@ -216,14 +301,22 @@ const GuacamoleAppInner = React.forwardRef<
const fetchToken = useCallback(async (): Promise<void> => {
setToken(null);
setIsDisplayReady(false);
setSessionLookup(null);
setGuacamoleConnectionId(null);
setError(null);
// Outside Electron there is only one backend, so the origin is moot and
// the API layer ignores it; inside, it decides which backend mints the
// token and therefore has to match the one the session will run on.
let resolvedOrigin: ConnectionOrigin = "local";
if (isElectron()) {
const origin = await resolveConnectionOrigin({
resolvedOrigin = await resolveConnectionOrigin({
connectionType: resolvedProtocolForConnect,
connectionOrigin: hostConfig.connectionOrigin,
});
if (origin === "remote") {
if (resolvedOrigin === "remote") {
const remoteConfig = (await window.electronAPI?.invoke?.(
"get-remote-sync-config",
)) as { serverUrl?: string } | null;
@@ -236,11 +329,9 @@ const GuacamoleAppInner = React.forwardRef<
addLog({
type: "info",
stage: "guac_guacd",
message: t("guacamole.connecting", {
type: resolvedProtocolForConnect.toUpperCase(),
}),
message: t("guacamole.checkingGuacd"),
});
const status = await getGuacdStatus();
const status = await getGuacdStatus(resolvedOrigin);
if (status.guacd.status !== "connected") {
throw new Error(t("guacamole.guacdUnavailable"));
}
@@ -248,20 +339,57 @@ const GuacamoleAppInner = React.forwardRef<
addLog({
type: "info",
stage: "guac_token",
message: t("guacamole.connecting", {
message: t("guacamole.requestingToken", {
type: resolvedProtocolForConnect.toUpperCase(),
}),
});
const result = await getGuacamoleTokenFromHost(
hostId,
protocol,
promptedCredentials ?? undefined,
hostConfig.syncId,
);
// hostId 0 is a quick-connect host: nothing to look up, mint the token
// straight from what the user typed. It cannot be shared or logged as
// host activity because there is no host row.
const result =
hostId === 0
? await getGuacamoleToken(
{
protocol: resolvedProtocolForConnect,
hostname: hostConfig.ip,
port:
resolvedProtocolForConnect === "vnc"
? hostConfig.vncPort
: hostConfig.rdpPort,
username:
resolvedProtocolForConnect === "vnc"
? hostConfig.vncUser
: hostConfig.rdpUser,
password:
resolvedProtocolForConnect === "vnc"
? hostConfig.vncPassword
: hostConfig.rdpPassword,
domain: hostConfig.domain,
ignoreCert: true,
guacamoleConfig: parseGuacamoleConfig(hostConfig.guacamoleConfig),
},
resolvedOrigin,
)
: await getGuacamoleTokenFromHost(
hostId,
resolvedOrigin,
protocol,
promptedCredentials ?? undefined,
hostConfig.syncId,
);
if (result) {
setSessionLookup(
result.termixConnectId
? { id: result.termixConnectId, origin: resolvedOrigin }
: null,
);
setToken(result.token);
setGuacamoleConnectionId(result.guacamoleConnectionId ?? null);
logActivity(resolvedProtocolForConnect, hostId, hostName).catch(() => {});
if (hostId !== 0) {
logActivity(resolvedProtocolForConnect, hostId, hostName).catch(
() => {},
);
}
}
}, [
hostId,
@@ -269,7 +397,7 @@ const GuacamoleAppInner = React.forwardRef<
protocol,
promptedCredentials,
resolvedProtocolForConnect,
hostConfig.syncId,
hostConfig,
addLog,
t,
]);
@@ -451,27 +579,52 @@ const GuacamoleAppInner = React.forwardRef<
token,
protocol: resolvedProtocol,
type: resolvedProtocol,
connectionOrigin: hostConfig.connectionOrigin,
width: configuredWidth,
height: configuredHeight,
dpi: configuredDpi,
}}
isVisible={isVisible}
touchMode={touchMode}
allowUpload={allowUpload && filesystem !== null}
allowUpload={canUploadToRdpDrive(
allowUpload,
guacConfig.enableDrive === true,
filesystem !== null,
)}
onConnect={() => setIsDisplayReady(true)}
onError={(err) => {
setConnectionError(err);
addLog({ type: "error", stage: "error", message: err });
}}
onStageChange={(stage) =>
addLog({
type: "info",
stage,
message: t("guacamole.connecting", {
type: resolvedProtocol.toUpperCase(),
}),
})
}
onStageChange={(stage) => {
const type = resolvedProtocol.toUpperCase();
switch (stage) {
case "guac_connecting":
addLog({
type: "info",
stage,
message: t("guacamole.openingSession", { type }),
});
break;
case "guac_handshake":
addLog({
type: "info",
stage,
message: t("guacamole.negotiating", { type }),
});
break;
case "guac_ready":
addLog({
type: "success",
stage,
message: t("guacamole.sessionReady", { type }),
});
break;
default:
break;
}
}}
onZoomChange={setDisplayZoom}
onFilesystem={setFilesystem}
onDropFiles={handleDropFiles}
onDropUnavailable={handleDropUnavailable}
@@ -486,15 +639,19 @@ const GuacamoleAppInner = React.forwardRef<
onClose={() => setFileBrowserOpen(false)}
/>
)}
<GuacamoleToolbar
displayRef={displayRef}
protocol={resolvedProtocol}
touchMode={touchMode}
hasFilesystem={filesystem !== null}
fileBrowserOpen={fileBrowserOpen}
onToggleFileBrowser={() => setFileBrowserOpen((open) => !open)}
onTouchModeChange={setTouchMode}
/>
{hostConfig.enableTerminalToolbar !== false && !toolbarHidden && (
<GuacamoleToolbar
displayRef={displayRef}
protocol={resolvedProtocol}
touchMode={touchMode}
hasFilesystem={filesystem !== null}
fileBrowserOpen={fileBrowserOpen}
onToggleFileBrowser={() => setFileBrowserOpen((open) => !open)}
onTouchModeChange={setTouchMode}
zoom={displayZoom}
onHide={() => setToolbarHidden(true)}
/>
)}
{shareModalOpen && guacamoleConnectionId && (
<ShareSessionModal
open={shareModalOpen}
+224 -106
View File
@@ -17,20 +17,22 @@ import { buildGuacamoleWebSocketBaseUrl } from "./guacamole-websocket-url.ts";
import {
resolveConnectionOrigin,
buildOriginWsUrl,
type ConnectionOrigin,
} from "@/lib/connection-origin.ts";
import {
isFirefoxBrowser,
isPasteShortcut,
pasteTextToRemote,
} from "./guacamole-clipboard.ts";
import { isPasteShortcut, pasteTextToRemote } from "./guacamole-clipboard.ts";
import { getGuacamoleDisplaySize } from "./guacamole-display-size.ts";
import { bindPointerInput } from "./guacamole-pointer.ts";
import {
getFileDropDisposition,
hasDraggedFiles,
} from "./guacamole-file-drop.ts";
import {
uploadFileToClient,
type GuacamoleFileStreamClient,
} from "./guacamole-filesystem.ts";
import { guacStateToStage } from "@/components/connection/connection-status.ts";
import type { ConnectionStage } from "@/types/connection-log.ts";
import { clampGuacamoleZoom, stepGuacamoleZoom } from "./guacamole-zoom.ts";
export type GuacamoleConnectionType = "rdp" | "vnc" | "telnet";
@@ -46,6 +48,12 @@ export interface GuacamoleConnectionConfig {
width?: number;
height?: number;
dpi?: number;
/**
* Which backend serves this session. Supplied by the owning app so the
* websocket dials the same backend that minted the token; omitted by
* shared/collab views, which follow the default for the connection type.
*/
connectionOrigin?: ConnectionOrigin | null;
[key: string]: unknown;
}
@@ -56,6 +64,10 @@ export interface GuacamoleDisplayHandle {
sendMouse: (x: number, y: number, buttonMask: number) => void;
setClipboard: (data: string) => void;
getFilesystem: () => Guacamole.Object | null;
uploadFile: (file: File) => Promise<void>;
zoomIn: () => number;
zoomOut: () => number;
resetZoom: () => number;
}
export type GuacamoleTouchMode = "touchscreen" | "touchpad";
@@ -72,6 +84,7 @@ interface GuacamoleDisplayProps {
onDropFiles?: (files: File[]) => void;
onDropUnavailable?: () => void;
onStageChange?: (stage: ConnectionStage) => void;
onZoomChange?: (zoom: number) => void;
}
const isDev = import.meta.env.DEV;
@@ -92,6 +105,7 @@ export const GuacamoleDisplay = forwardRef<
onDropFiles,
onDropUnavailable,
onStageChange,
onZoomChange,
},
ref,
) {
@@ -112,7 +126,10 @@ export const GuacamoleDisplay = forwardRef<
const onStageChangeRef = useRef(onStageChange);
onStageChangeRef.current = onStageChange;
const keyboardRef = useRef<Guacamole.Keyboard | null>(null);
const unbindPointerRef = useRef<(() => void) | null>(null);
const scaleRef = useRef<number>(1);
const fitScaleRef = useRef<number>(1);
const zoomRef = useRef<number>(1);
const resizeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const hasKeyboardFocusRef = useRef(false);
const windowFocusedRef = useRef(
@@ -123,8 +140,18 @@ export const GuacamoleDisplay = forwardRef<
const isConnectingRef = useRef(false);
const [isReady, setIsReady] = useState(false);
const [hasError, setHasError] = useState(false);
// RDP's guacd backend (FreeRDP) can report the Guacamole-level CONNECTED
// state from a single early sync before the actual RDP handshake with the
// remote host has finished negotiating - a handshake that can then still
// fail up to ~30s later. Waiting for a couple of real frame syncs before
// announcing the connection avoids a black screen with no connecting UI
// during that window; VNC/telnet fail before ever reaching CONNECTED, so
// they are unaffected.
const syncCountRef = useRef(0);
const disconnectClient = useCallback(() => {
unbindPointerRef.current?.();
unbindPointerRef.current = null;
const client = clientRef.current;
clientRef.current = null;
isConnectingRef.current = false;
@@ -141,6 +168,24 @@ export const GuacamoleDisplay = forwardRef<
}
}, []);
const applyZoom = useCallback(
(nextZoom: number): number => {
const zoom = clampGuacamoleZoom(nextZoom);
zoomRef.current = zoom;
const display = clientRef.current?.getDisplay();
if (display && displayRef.current) {
const scale = fitScaleRef.current * zoom;
scaleRef.current = scale;
display.scale(scale);
displayRef.current.style.width = `${display.getWidth() * scale}px`;
displayRef.current.style.height = `${display.getHeight() * scale}px`;
}
onZoomChange?.(zoom);
return zoom;
},
[onZoomChange],
);
useImperativeHandle(ref, () => ({
disconnect: disconnectClient,
isConnected: () => isReady && !hasError,
@@ -171,6 +216,17 @@ export const GuacamoleDisplay = forwardRef<
}
},
getFilesystem: () => filesystemRef.current,
uploadFile: (file: File) => {
const client = clientRef.current;
if (!client) return Promise.reject(new Error("RDP session is not ready"));
return uploadFileToClient(
client as unknown as GuacamoleFileStreamClient,
file,
);
},
zoomIn: () => applyZoom(stepGuacamoleZoom(zoomRef.current, 1)),
zoomOut: () => applyZoom(stepGuacamoleZoom(zoomRef.current, -1)),
resetZoom: () => applyZoom(1),
}));
const getWebSocketConnection = useCallback(
@@ -183,28 +239,39 @@ export const GuacamoleDisplay = forwardRef<
const connectionProtocol =
connectionConfig.protocol ?? connectionConfig.type;
// Resolved before the token is minted, not just before the socket is
// opened: the token has to come from whichever backend will serve the
// session, so both steps have to agree on the origin.
const origin = await resolveConnectionOrigin({
connectionType: connectionProtocol,
connectionOrigin: connectionConfig.connectionOrigin,
});
if (connectionConfig.token) {
token = connectionConfig.token;
} else {
const data = await getGuacamoleToken({
protocol: connectionProtocol ?? "rdp",
hostname: String(connectionConfig.hostname ?? ""),
port: connectionConfig.port,
username: connectionConfig.username,
password: connectionConfig.password,
domain: connectionConfig.domain,
security:
typeof connectionConfig.security === "string"
? connectionConfig.security
: undefined,
ignoreCert:
typeof connectionConfig.ignoreCert === "boolean"
? connectionConfig.ignoreCert
: undefined,
guacamoleConfig: connectionConfig.guacamoleConfig as Parameters<
typeof getGuacamoleToken
>[0]["guacamoleConfig"],
});
const data = await getGuacamoleToken(
{
protocol: connectionProtocol ?? "rdp",
hostname: String(connectionConfig.hostname ?? ""),
port: connectionConfig.port,
username: connectionConfig.username,
password: connectionConfig.password,
domain: connectionConfig.domain,
security:
typeof connectionConfig.security === "string"
? connectionConfig.security
: undefined,
ignoreCert:
typeof connectionConfig.ignoreCert === "boolean"
? connectionConfig.ignoreCert
: undefined,
guacamoleConfig: connectionConfig.guacamoleConfig as Parameters<
typeof getGuacamoleToken
>[0]["guacamoleConfig"],
},
origin,
);
token = data.token;
}
@@ -218,20 +285,18 @@ export const GuacamoleDisplay = forwardRef<
let wsBase: string | null;
if (isElectron()) {
const origin = await resolveConnectionOrigin({
connectionType: connectionProtocol,
});
wsBase = await buildOriginWsUrl({
const target = await buildOriginWsUrl({
origin,
localPort: 30008,
localPath: "/guacamole/websocket/",
remotePath: "/guacamole/websocket/",
includeLocalJwt: false,
includeJwt: false,
});
if (!wsBase) {
if (!target) {
onError?.(t("errors.remoteServerRequired"));
return null;
}
wsBase = target.url;
} else {
wsBase = buildGuacamoleWebSocketBaseUrl({
isDev,
@@ -315,40 +380,51 @@ export const GuacamoleDisplay = forwardRef<
};
}, [isVisible]);
const rescaleDisplay = useCallback((immediate: boolean = false) => {
if (!clientRef.current || !containerRef.current) return;
const performRescale = () => {
const rescaleDisplay = useCallback(
(immediate: boolean = false) => {
if (!clientRef.current || !containerRef.current) return;
const display = clientRef.current.getDisplay();
const cWidth = containerRef.current.clientWidth;
const cHeight = containerRef.current.clientHeight;
const displayWidth = display.getWidth();
const displayHeight = display.getHeight();
const performRescale = () => {
if (!clientRef.current || !containerRef.current) return;
if (displayWidth > 0 && displayHeight > 0 && cWidth > 0 && cHeight > 0) {
const scale = Math.min(cWidth / displayWidth, cHeight / displayHeight);
scaleRef.current = scale;
display.scale(scale);
}
};
const display = clientRef.current.getDisplay();
const cWidth = containerRef.current.clientWidth;
const cHeight = containerRef.current.clientHeight;
const displayWidth = display.getWidth();
const displayHeight = display.getHeight();
if (immediate) {
performRescale();
} else {
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
if (
displayWidth > 0 &&
displayHeight > 0 &&
cWidth > 0 &&
cHeight > 0
) {
fitScaleRef.current = Math.min(
cWidth / displayWidth,
cHeight / displayHeight,
);
applyZoom(zoomRef.current);
}
};
if (immediate) {
performRescale();
} else {
if (resizeTimeoutRef.current) {
clearTimeout(resizeTimeoutRef.current);
}
resizeTimeoutRef.current = setTimeout(performRescale, 200);
}
resizeTimeoutRef.current = setTimeout(performRescale, 200);
}
}, []);
},
[applyZoom],
);
const connect = useCallback(async () => {
if (isConnectingRef.current) return;
isConnectingRef.current = true;
setIsReady(false);
setHasError(false);
syncCountRef.current = 0;
// Let layout settle before measuring without depending on animation frames,
// which may be throttled while Electron windows or tabs are inactive.
@@ -403,12 +479,6 @@ export const GuacamoleDisplay = forwardRef<
const tunnel = new Guacamole.WebSocketTunnel(wsConnection.url);
const client = new Guacamole.Client(tunnel);
clientRef.current = client;
let connectWatchdog: ReturnType<typeof setTimeout> | null = null;
const clearConnectWatchdog = () => {
if (!connectWatchdog) return;
clearTimeout(connectWatchdog);
connectWatchdog = null;
};
const display = client.getDisplay();
const displayElement = display.getElement();
@@ -422,31 +492,32 @@ export const GuacamoleDisplay = forwardRef<
displayElement.setAttribute("tabindex", "0");
displayElement.style.outline = "none";
const useNativePasteFallback = isFirefoxBrowser();
if (useNativePasteFallback) {
displayElement.addEventListener(
"keydown",
(event) => {
if (isPasteShortcut(event)) {
event.stopImmediatePropagation();
}
},
true,
);
displayElement.addEventListener(
"paste",
(event) => {
if (clientRef.current !== client) return;
const text = event.clipboardData?.getData("text/plain");
if (!text) return;
event.preventDefault();
// Reading navigator.clipboard outside a user gesture is denied by Safari
// and commonly denied by Chromium. The paste event carries the text under
// the browser's normal permission model, so use it on every browser and
// replace the original shortcut with an ordered clipboard update + Ctrl+V.
displayElement.addEventListener(
"keydown",
(event) => {
if (isPasteShortcut(event)) {
event.stopImmediatePropagation();
pasteTextToRemote(client, text);
},
true,
);
}
}
},
true,
);
displayElement.addEventListener(
"paste",
(event) => {
if (clientRef.current !== client) return;
const text = event.clipboardData?.getData("text/plain");
if (!text) return;
event.preventDefault();
event.stopImmediatePropagation();
pasteTextToRemote(client, text);
},
true,
);
display.onresize = () => {
if (!isMountedRef.current || clientRef.current !== client) return;
@@ -474,7 +545,12 @@ export const GuacamoleDisplay = forwardRef<
client.sendMouseState(adjustedState);
};
bindPointerInput(displayElement, touchMode, sendMouseState);
unbindPointerRef.current?.();
unbindPointerRef.current = bindPointerInput(
displayElement,
touchMode,
sendMouseState,
);
const keyboard = new Guacamole.Keyboard(displayElement);
keyboardRef.current = keyboard;
@@ -508,10 +584,11 @@ export const GuacamoleDisplay = forwardRef<
case 2:
break;
case 3:
clearConnectWatchdog();
isConnectingRef.current = false;
setIsReady(true);
onConnect?.();
if (protocol !== "rdp") {
setIsReady(true);
onConnect?.();
}
// A configured resolution is the size the session should render at;
// resizing it to the container would discard it. rescaleDisplay still
// fits that fixed display into whatever space is available.
@@ -531,7 +608,6 @@ export const GuacamoleDisplay = forwardRef<
case 4:
break;
case 5:
clearConnectWatchdog();
isConnectingRef.current = false;
setIsReady(false);
setHasError(true);
@@ -545,7 +621,6 @@ export const GuacamoleDisplay = forwardRef<
client.onerror = (error: Guacamole.Status) => {
if (!isMountedRef.current || clientRef.current !== client) return;
clearConnectWatchdog();
const errorMessage = error.message || t("guacamole.connectionError");
setIsReady(false);
setHasError(true);
@@ -553,6 +628,18 @@ export const GuacamoleDisplay = forwardRef<
onError?.(errorMessage);
};
if (protocol === "rdp") {
client.onsync = () => {
if (!isMountedRef.current || clientRef.current !== client) return;
if (syncCountRef.current >= 2) return;
syncCountRef.current += 1;
if (syncCountRef.current >= 2) {
setIsReady(true);
onConnect?.();
}
};
}
client.onclipboard = (stream: Guacamole.InputStream, mimetype: string) => {
if (mimetype === "text/plain") {
const reader = new Guacamole.StringReader(stream);
@@ -603,21 +690,8 @@ export const GuacamoleDisplay = forwardRef<
};
try {
connectWatchdog = setTimeout(() => {
if (
!isMountedRef.current ||
clientRef.current !== client ||
!isConnectingRef.current
) {
return;
}
disconnectClient();
void connect();
}, 8000);
client.connect(wsConnection.query);
} catch (error) {
clearConnectWatchdog();
isConnectingRef.current = false;
if (!isMountedRef.current) return;
setIsReady(false);
@@ -631,7 +705,6 @@ export const GuacamoleDisplay = forwardRef<
onError,
refreshKeyboardHandlers,
rescaleDisplay,
disconnectClient,
connectionConfig.protocol,
connectionConfig.type,
connectionConfig.dpi,
@@ -742,7 +815,7 @@ export const GuacamoleDisplay = forwardRef<
const syncClipboard = useCallback(() => {
const client = clientRef.current;
if (!client || isFirefoxBrowser() || !navigator.clipboard?.readText) return;
if (!client || !navigator.clipboard?.readText) return;
navigator.clipboard
.readText()
.then((text) => {
@@ -762,6 +835,51 @@ export const GuacamoleDisplay = forwardRef<
}
}, [isVisible, isReady, syncClipboard]);
useEffect(() => {
const container = containerRef.current;
const protocol = connectionConfig.protocol ?? connectionConfig.type;
if (!container || !isReady || protocol !== "vnc") return;
let pinchDistance = 0;
let pinchZoom = zoomRef.current;
const distance = (touches: TouchList) =>
Math.hypot(
touches[0].clientX - touches[1].clientX,
touches[0].clientY - touches[1].clientY,
);
const onTouchStart = (event: TouchEvent) => {
if (event.touches.length !== 2) return;
event.preventDefault();
event.stopPropagation();
pinchDistance = distance(event.touches);
pinchZoom = zoomRef.current;
};
const onTouchMove = (event: TouchEvent) => {
if (event.touches.length !== 2 || pinchDistance === 0) return;
event.preventDefault();
event.stopPropagation();
applyZoom(pinchZoom * (distance(event.touches) / pinchDistance));
};
const onTouchEnd = () => {
pinchDistance = 0;
};
container.addEventListener("touchstart", onTouchStart, {
passive: false,
capture: true,
});
container.addEventListener("touchmove", onTouchMove, {
passive: false,
capture: true,
});
container.addEventListener("touchend", onTouchEnd, { capture: true });
return () => {
container.removeEventListener("touchstart", onTouchStart, true);
container.removeEventListener("touchmove", onTouchMove, true);
container.removeEventListener("touchend", onTouchEnd, true);
};
}, [applyZoom, connectionConfig.protocol, connectionConfig.type, isReady]);
useEffect(() => {
const container = containerRef.current;
if (!container || !isReady) return;
@@ -818,7 +936,7 @@ export const GuacamoleDisplay = forwardRef<
return (
<div
ref={containerRef}
className="absolute inset-0 overflow-hidden"
className="absolute inset-0 overflow-auto"
style={{ backgroundColor: "var(--bg-base)" }}
onDragEnter={handleDragEnter}
onDragOver={(event) => {
@@ -829,7 +947,7 @@ export const GuacamoleDisplay = forwardRef<
>
<div
ref={displayRef}
className="relative w-full h-full flex items-center justify-center"
className="relative flex min-h-full min-w-full items-center justify-center"
style={{
cursor: isReady ? "none" : "default",
visibility: isReady ? "visible" : "hidden",
@@ -19,6 +19,7 @@ import {
parentPath,
saveBlobAs,
uploadFile,
describeUploadError,
type RemoteFileEntry,
} from "./guacamole-filesystem.ts";
@@ -76,9 +77,9 @@ export function GuacamoleFileBrowser({
toast.success(t("guacamole.files.uploaded", { name: file.name }));
} catch (err) {
toast.error(
err instanceof Error
? err.message
: t("guacamole.files.uploadFailed", { name: file.name }),
describeUploadError(err, (key) =>
t(`guacamole.files.${key}`, { name: file.name }),
),
);
} finally {
setBusyName(null);
+64 -5
View File
@@ -16,6 +16,10 @@ import {
FolderOpen,
Touchpad,
MousePointer,
ZoomIn,
ZoomOut,
Scan,
X,
} from "lucide-react";
import {
Tooltip,
@@ -29,6 +33,11 @@ import type {
} from "@/features/guacamole/GuacamoleDisplay.tsx";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import {
detectRuntimeMetaKeyFamily,
metaKeyLabels,
type MetaKeyFamily,
} from "@/features/guacamole/guacamole-meta-key.ts";
interface GuacamoleToolbarProps {
displayRef: React.RefObject<GuacamoleDisplayHandle>;
@@ -38,6 +47,9 @@ interface GuacamoleToolbarProps {
fileBrowserOpen?: boolean;
onToggleFileBrowser?: () => void;
onTouchModeChange?: (mode: GuacamoleTouchMode) => void;
zoom?: number;
onHide?: () => void;
metaKeyFamily?: MetaKeyFamily;
}
const MODIFIER_KEYSYMS = {
@@ -73,6 +85,7 @@ function TipBtn({
<TooltipTrigger asChild>
<button
type="button"
aria-label={tooltip}
onClick={onClick}
className={cn(BTN_BASE, className)}
>
@@ -102,6 +115,7 @@ function TipIconBtn({
<TooltipTrigger asChild>
<button
type="button"
aria-label={tooltip}
onClick={onClick}
className={cn(BTN_ICON, className)}
>
@@ -123,8 +137,14 @@ export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
fileBrowserOpen = false,
onToggleFileBrowser,
onTouchModeChange,
zoom = 1,
onHide,
metaKeyFamily,
}) => {
const { t } = useTranslation();
const meta = metaKeyLabels(
metaKeyFamily ?? detectRuntimeMetaKeyFamily(protocol),
);
const [position, setPosition] = useState({ x: 0, y: 12 });
const [collapsed, setCollapsed] = useState(false);
const [showFKeys, setShowFKeys] = useState(false);
@@ -350,6 +370,37 @@ export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
</>
)}
{protocol === "vnc" && (
<>
<div className={SEP} />
<TipIconBtn
tooltip={t("guacamole.toolbar.zoomOut")}
onClick={() => displayRef.current?.zoomOut()}
>
<ZoomOut className="size-3.5" />
</TipIconBtn>
<TipBtn
tooltip={t("guacamole.toolbar.resetZoom")}
onClick={() => displayRef.current?.resetZoom()}
className="min-w-12 tabular-nums"
>
{Math.round(zoom * 100)}%
</TipBtn>
<TipIconBtn
tooltip={t("guacamole.toolbar.zoomIn")}
onClick={() => displayRef.current?.zoomIn()}
>
<ZoomIn className="size-3.5" />
</TipIconBtn>
<TipIconBtn
tooltip={t("guacamole.toolbar.fitToScreen")}
onClick={() => displayRef.current?.resetZoom()}
>
<Scan className="size-3.5" />
</TipIconBtn>
</>
)}
{/* System combos — RDP/VNC only */}
{isRdpVnc && (
<>
@@ -361,16 +412,16 @@ export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
CAD
</TipBtn>
<TipBtn
tooltip={t("guacamole.toolbar.winL")}
tooltip={t(meta.lockTooltip)}
onClick={() => sendCombo(MODIFIER_KEYSYMS.win, 0x006c)}
>
Win+L
{meta.lock}
</TipBtn>
<TipBtn
tooltip={t("guacamole.toolbar.winKey")}
tooltip={t(meta.keyTooltip)}
onClick={() => sendCombo(MODIFIER_KEYSYMS.win)}
>
Win
{meta.short}
</TipBtn>
</>
)}
@@ -392,7 +443,7 @@ export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
MODIFIER_KEYSYMS.shift,
t("guacamole.toolbar.shift"),
],
["win", MODIFIER_KEYSYMS.win, t("guacamole.toolbar.win")],
["win", MODIFIER_KEYSYMS.win, t(meta.stickyKey)],
] as [string, number, string][]
).map(([key, ks, label]) => (
<Tooltip key={key}>
@@ -531,6 +582,14 @@ export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
{t("guacamole.toolbar.collapse")}
</TooltipContent>
</Tooltip>
{onHide && (
<TipIconBtn
tooltip={t("guacamole.toolbar.hide")}
onClick={onHide}
>
<X className="size-3.5" />
</TipIconBtn>
)}
</div>
)}
</div>
@@ -13,10 +13,6 @@ export interface GuacamoleClipboardClient {
sendKeyEvent(pressed: number, keysym: number): void;
}
export function isFirefoxBrowser(userAgent = navigator.userAgent): boolean {
return /(?:Firefox|FxiOS)\//.test(userAgent);
}
export function isPasteShortcut(
event: Pick<KeyboardEvent, "altKey" | "ctrlKey" | "key" | "metaKey">,
): boolean {
@@ -12,3 +12,11 @@ export function getFileDropDisposition(
if (!hasDraggedFiles(types) || fileCount === 0) return "ignore";
return canUpload ? "upload" : "reject";
}
export function canUploadToRdpDrive(
uploadAllowed: boolean,
driveEnabled: boolean,
hasFilesystem: boolean,
): boolean {
return uploadAllowed && (driveEnabled || hasFilesystem);
}
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { describeUploadError } from "./guacamole-filesystem";
const t = (key: string) => `#${key}`;
describe("describeUploadError", () => {
it("explains guacd's refusal to open the target file as a drive-folder problem", () => {
expect(describeUploadError(new Error("FAIL (CANNOT OPEN)"), t)).toBe(
"#driveNotWritable",
);
expect(describeUploadError(new Error("FAIL (NO FS)"), t)).toBe(
"#driveUnavailable",
);
});
it("passes other messages through and falls back for unknown errors", () => {
expect(describeUploadError(new Error("disk full"), t)).toBe("disk full");
expect(describeUploadError(undefined, t)).toBe("#uploadFailed");
});
});
@@ -1,5 +1,11 @@
import Guacamole from "guacamole-common-js";
// The bundled Guacamole runtime exposes Client.createFileStream(), but the
// package's older TypeScript declaration omits it.
export interface GuacamoleFileStreamClient {
createFileStream(mimetype: string, filename: string): Guacamole.OutputStream;
}
// The root stream of a Guacamole.Object maps stream name to mimetype; a stream
// carrying that same mimetype is itself a directory.
export const STREAM_INDEX_MIMETYPE =
@@ -123,12 +129,45 @@ export function uploadFile(
file: File,
onProgress?: (sent: number, total: number) => void,
): Promise<void> {
return new Promise((resolve, reject) => {
const path = joinPath(directory, file.name);
const stream = filesystem.createOutputStream(
return writeUpload(
filesystem.createOutputStream(
file.type || "application/octet-stream",
path,
);
joinPath(directory, file.name),
),
file,
onProgress,
);
}
/**
* Uploads through Guacamole's connection-level file stream. RDP exposes this
* path even when guacd does not advertise a browsable filesystem object, so
* display drops must not depend on `Client.onfilesystem` having fired.
*/
export function uploadFileToClient(
client: GuacamoleFileStreamClient,
file: File,
onProgress?: (sent: number, total: number) => void,
): Promise<void> {
return writeUpload(createClientFileStream(client, file), file, onProgress);
}
export function createClientFileStream(
client: GuacamoleFileStreamClient,
file: File,
): Guacamole.OutputStream {
return client.createFileStream(
file.type || "application/octet-stream",
file.name,
);
}
function writeUpload(
stream: Guacamole.OutputStream,
file: File,
onProgress?: (sent: number, total: number) => void,
): Promise<void> {
return new Promise((resolve, reject) => {
const writer = new Guacamole.BlobWriter(stream);
// A rejected blob stops the writer without firing onerror or oncomplete —
@@ -163,3 +202,22 @@ export function saveBlobAs(blob: Blob, filename: string): void {
link.click();
URL.revokeObjectURL(url);
}
/**
* Turns an upload failure into something a user can act on. guacd answers a
* refused stream with an ack like "FAIL (CANNOT OPEN)" - accurate, but it
* means "the drive folder isn't writable", which is what people need to hear.
*/
export function describeUploadError(
error: unknown,
t: (key: "driveNotWritable" | "driveUnavailable" | "uploadFailed") => string,
): string {
const message = error instanceof Error ? error.message : "";
if (/cannot open|can't open|permission denied/i.test(message)) {
return t("driveNotWritable");
}
if (/no fs/i.test(message)) {
return t("driveUnavailable");
}
return message || t("uploadFailed");
}
@@ -0,0 +1,82 @@
export type MetaKeyFamily = "win" | "super" | "cmd";
export interface MetaKeyLabels {
family: MetaKeyFamily;
short: string;
lock: string;
stickyKey: string;
keyTooltip: string;
lockTooltip: string;
}
/**
* RDP is a Windows desktop, so the toolbar keeps Windows labels. VNC is used
* for Linux and macOS as often as Windows; branding those sessions with a
* Windows key is wrong, and the local device is the only OS we can see.
*/
export function detectMetaKeyFamily(
protocol: "rdp" | "vnc" | "telnet",
env: {
platform?: string;
userAgent?: string;
userAgentDataPlatform?: string;
} = {},
): MetaKeyFamily {
if (protocol === "rdp") return "win";
const uaPlatform = env.userAgentDataPlatform ?? "";
const platform = env.platform ?? "";
const userAgent = env.userAgent ?? "";
const haystack = `${uaPlatform} ${platform} ${userAgent}`;
if (/iphone|ipad|ipod|mac/i.test(haystack)) return "cmd";
if (/win/i.test(haystack)) return "win";
return "super";
}
export function detectRuntimeMetaKeyFamily(
protocol: "rdp" | "vnc" | "telnet",
): MetaKeyFamily {
if (typeof navigator === "undefined") {
return detectMetaKeyFamily(protocol);
}
const uaData = navigator as Navigator & {
userAgentData?: { platform?: string };
};
return detectMetaKeyFamily(protocol, {
platform: navigator.platform,
userAgent: navigator.userAgent,
userAgentDataPlatform: uaData.userAgentData?.platform,
});
}
export function metaKeyLabels(family: MetaKeyFamily): MetaKeyLabels {
if (family === "cmd") {
return {
family,
short: "Cmd",
lock: "Cmd+L",
stickyKey: "guacamole.toolbar.cmd",
keyTooltip: "guacamole.toolbar.cmdKey",
lockTooltip: "guacamole.toolbar.cmdL",
};
}
if (family === "super") {
return {
family,
short: "Super",
lock: "Super+L",
stickyKey: "guacamole.toolbar.super",
keyTooltip: "guacamole.toolbar.superKey",
lockTooltip: "guacamole.toolbar.superL",
};
}
return {
family,
short: "Win",
lock: "Win+L",
stickyKey: "guacamole.toolbar.win",
keyTooltip: "guacamole.toolbar.winKey",
lockTooltip: "guacamole.toolbar.winL",
};
}
+36 -8
View File
@@ -1,4 +1,8 @@
import Guacamole from "guacamole-common-js";
import {
createScrollCoalescer,
isScrollButtonState,
} from "./guacamole-scroll.js";
export type GuacamoleTouchMode = "touchscreen" | "touchpad";
@@ -16,22 +20,46 @@ export function bindPointerInput(
element: HTMLElement,
touchMode: GuacamoleTouchMode | null | undefined,
onState: (state: Guacamole.Mouse.State) => void,
): void {
): () => void {
const coalescer = createScrollCoalescer((state) => {
onState(state as Guacamole.Mouse.State);
});
let expectingScrollRelease = false;
const handleState = (state: Guacamole.Mouse.State) => {
coalescer.notePointer(state);
if (isScrollButtonState(state)) {
coalescer.ingestClick(state.down ? 1 : -1);
expectingScrollRelease = true;
return;
}
if (
expectingScrollRelease &&
!state.left &&
!state.middle &&
!state.right
) {
expectingScrollRelease = false;
return;
}
expectingScrollRelease = false;
onState(state);
};
const mouse = new Guacamole.Mouse(element);
mouse.onmousedown = mouse.onmouseup = mouse.onmousemove = onState;
mouse.onmousedown = mouse.onmouseup = mouse.onmousemove = handleState;
if (touchMode === "touchscreen") {
const touchscreen = new Guacamole.Mouse.Touchscreen(element);
touchscreen.onEach(["mousedown", "mousemove", "mouseup"], (event) =>
onState(event.state),
handleState(event.state),
);
return;
}
if (touchMode === "touchpad") {
} else if (touchMode === "touchpad") {
const touchpad = new Guacamole.Mouse.Touchpad(element);
touchpad.onEach(["mousedown", "mousemove", "mouseup"], (event) =>
onState(event.state),
handleState(event.state),
);
}
return () => coalescer.dispose();
}
@@ -0,0 +1,131 @@
/**
* guacamole-common-js turns each wheel tick into one or more mouse-button
* clicks (button 4/5). High-resolution trackpads and the library's duplicate
* wheel/mousewheel listeners can emit dozens of those clicks in a single
* gesture. Each click is two Guacamole instructions, so a laggy path (a
* Cloudflare-proxied remote session especially) queues them and the remote
* desktop keeps scrolling long after the user stopped.
*
* Cap the in-flight click count and space flushes out so scrolling stays
* usable without changing the websocket proxy.
*/
export const MAX_SCROLL_CLICKS_PER_FLUSH = 2;
export const SCROLL_FLUSH_INTERVAL_MS = 32;
export type ScrollClickDirection = 1 | -1;
export interface GuacamolePointerState {
x: number;
y: number;
left: boolean;
middle: boolean;
right: boolean;
up: boolean;
down: boolean;
}
export function clampPendingScrollClicks(
pending: number,
delta: number,
max = MAX_SCROLL_CLICKS_PER_FLUSH,
): number {
return Math.max(-max, Math.min(max, pending + delta));
}
export function takeScrollClicks(pending: number): {
clicks: number;
direction: ScrollClickDirection | 0;
} {
if (pending === 0) return { clicks: 0, direction: 0 };
const direction: ScrollClickDirection = pending < 0 ? -1 : 1;
return {
clicks: Math.min(MAX_SCROLL_CLICKS_PER_FLUSH, Math.abs(pending)),
direction,
};
}
function mouseState(
x: number,
y: number,
buttons: Pick<GuacamolePointerState, "left" | "middle" | "right">,
up: boolean,
down: boolean,
): GuacamolePointerState {
return {
x,
y,
left: buttons.left,
middle: buttons.middle,
right: buttons.right,
up,
down,
};
}
export function createScrollCoalescer(
send: (state: GuacamolePointerState) => void,
now: () => number = () => Date.now(),
schedule: (fn: () => void, ms: number) => number = (fn, ms) =>
window.setTimeout(fn, ms),
cancel: (id: number) => void = (id) => window.clearTimeout(id),
): {
notePointer: (state: GuacamolePointerState) => void;
ingestClick: (direction: ScrollClickDirection) => void;
dispose: () => void;
} {
let pending = 0;
let timer: number | null = null;
let x = 0;
let y = 0;
let buttons = { left: false, middle: false, right: false };
let lastFlushAt = 0;
const flush = () => {
timer = null;
const { clicks, direction } = takeScrollClicks(pending);
pending = 0;
if (clicks === 0 || direction === 0) return;
lastFlushAt = now();
const up = direction < 0;
const down = direction > 0;
for (let i = 0; i < clicks; i++) {
send(mouseState(x, y, buttons, up, down));
send(mouseState(x, y, buttons, false, false));
}
};
return {
notePointer(state) {
x = state.x;
y = state.y;
buttons = {
left: state.left,
middle: state.middle,
right: state.right,
};
},
ingestClick(direction) {
pending = clampPendingScrollClicks(pending, direction);
const elapsed = now() - lastFlushAt;
if (elapsed >= SCROLL_FLUSH_INTERVAL_MS) {
flush();
return;
}
if (timer == null) {
timer = schedule(flush, SCROLL_FLUSH_INTERVAL_MS - elapsed);
}
},
dispose() {
if (timer == null) return;
cancel(timer);
timer = null;
},
};
}
export function isScrollButtonState(state: {
up?: boolean;
down?: boolean;
}): boolean {
return state.up === true || state.down === true;
}
@@ -0,0 +1,31 @@
import { getGuacamoleConnectionId } from "@/api/guacamole-api";
import type { ConnectionOrigin } from "@/lib/connection-origin";
export function watchGuacamoleConnectionId(
connectId: string,
origin: ConnectionOrigin,
onReady: (id: string) => void,
): () => void {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
let attempts = 0;
const poll = async () => {
try {
const id = await getGuacamoleConnectionId(
connectId,
origin,
controller.signal,
);
if (controller.signal.aborted) return;
if (id) onReady(id);
else if (++attempts < 20) timer = setTimeout(poll, 500);
} catch {
// Session sharing discovery must not interrupt the remote display.
}
};
void poll();
return () => {
controller.abort();
clearTimeout(timer);
};
}
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { clampGuacamoleZoom, stepGuacamoleZoom } from "./guacamole-zoom.js";
describe("guacamole zoom", () => {
it("steps in predictable quarter increments", () => {
expect(stepGuacamoleZoom(1, 1)).toBe(1.25);
expect(stepGuacamoleZoom(1, -1)).toBe(0.75);
});
it("keeps toolbar and pinch zoom within usable bounds", () => {
expect(clampGuacamoleZoom(0.1)).toBe(0.5);
expect(clampGuacamoleZoom(8)).toBe(4);
});
});
@@ -0,0 +1,11 @@
export const MIN_GUACAMOLE_ZOOM = 0.5;
export const MAX_GUACAMOLE_ZOOM = 4;
export const GUACAMOLE_ZOOM_STEP = 0.25;
export function clampGuacamoleZoom(zoom: number): number {
return Math.min(MAX_GUACAMOLE_ZOOM, Math.max(MIN_GUACAMOLE_ZOOM, zoom));
}
export function stepGuacamoleZoom(zoom: number, direction: -1 | 1): number {
return clampGuacamoleZoom(zoom + direction * GUACAMOLE_ZOOM_STEP);
}
@@ -0,0 +1,17 @@
import type { HostAuthOverrides } from "@/types/auth-protocols";
export function needsRdpCredentialPrompt({
protocol,
rdpAuthType,
authOverrides,
}: {
protocol: "rdp" | "vnc" | "telnet";
rdpAuthType?: string;
authOverrides?: HostAuthOverrides;
}): boolean {
return (
protocol === "rdp" &&
rdpAuthType === "none" &&
!authOverrides?.rdp?.credentialId
);
}
@@ -0,0 +1,28 @@
/** IANA zone names use underscores, but people type and paste spaces. */
export function normalizeTimezone(timezone: string): string {
return timezone.trim().replace(/\s+/g, "_");
}
export function isValidTimezone(timezone: string): boolean {
try {
new Intl.DateTimeFormat("en-US", { timeZone: timezone });
return true;
} catch {
return false;
}
}
/**
* Normalizes the timezone a user typed and reports whether it is usable.
* A blank field is valid: it means "use local time".
*/
export function validateClockTimezone(timezone: unknown): {
timezone?: string;
valid: boolean;
} {
if (typeof timezone !== "string" || timezone.trim() === "") {
return { timezone: undefined, valid: true };
}
const normalized = normalizeTimezone(timezone);
return { timezone: normalized, valid: isValidTimezone(normalized) };
}
@@ -2,12 +2,16 @@ import { useTranslation } from "react-i18next";
import { Input } from "@/components/input";
import { Switch } from "@/components/switch";
import type { ClockConfig, WidgetEditFormProps } from "@/types/homepage-types";
import { validateClockTimezone } from "../clock-timezone";
export function ClockEditForm({
config,
onChange,
}: WidgetEditFormProps<ClockConfig>) {
const { t } = useTranslation();
const invalidTimezone = !validateClockTimezone(config.timezone).valid;
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
@@ -20,8 +24,16 @@ export function ClockEditForm({
onChange({ ...config, timezone: e.target.value || undefined })
}
placeholder="America/New_York (leave blank for local)"
className="h-8 text-sm"
aria-invalid={invalidTimezone}
className={
invalidTimezone ? "h-8 text-sm border-destructive" : "h-8 text-sm"
}
/>
{invalidTimezone && (
<p className="text-[10px] text-destructive">
{t("homepage.invalidTimezone")}
</p>
)}
</div>
<div className="flex items-center justify-between">
<label className="text-xs font-medium text-foreground">
@@ -6,6 +6,7 @@ import type {
HostStatusConfig,
WidgetEditFormProps,
} from "@/types/homepage-types";
import { Select2 } from "@/components/select2";
interface SimpleHost {
id: string;
@@ -80,7 +81,7 @@ export function HostStatusEditForm({
<label className="text-xs font-medium text-muted-foreground">
{t("homepage.host")}
</label>
<select
<Select2
className="h-8 border border-border bg-background text-sm px-2"
value={config.hostId || ""}
onChange={(e) =>
@@ -93,7 +94,7 @@ export function HostStatusEditForm({
{h.name}
</option>
))}
</select>
</Select2>
</div>
<div className="flex flex-col gap-1.5">
@@ -7,6 +7,7 @@ import type {
WidgetEditFormProps,
} from "@/types/homepage-types";
import { getSSHHosts } from "@/api/ssh-host-management-api";
import { Select2 } from "@/components/select2";
const METRICS: { id: MetricsChartMetric; label: string }[] = [
{ id: "cpu", label: "CPU" },
@@ -42,7 +43,7 @@ export function MetricsChartEditForm({
<label className="text-xs font-medium text-muted-foreground">
{t("homepage.host")}
</label>
<select
<Select2
value={config.hostId}
onChange={(e) =>
onChange({ ...config, hostId: Number(e.target.value) })
@@ -55,7 +56,7 @@ export function MetricsChartEditForm({
{h.name}
</option>
))}
</select>
</Select2>
</div>
<div className="flex flex-col gap-1">
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { getSSHHosts } from "@/api/ssh-host-management-api";
import type { SSHHostWithStatus } from "@/main-axios";
import { Select2 } from "@/components/select2";
interface SingleHostEditFormProps {
hostId: number;
@@ -28,7 +29,7 @@ export function SingleHostEditForm({
<label className="text-xs font-medium text-muted-foreground">
{t("homepage.host")}
</label>
<select
<Select2
value={hostId || ""}
onChange={(e) => onChange(Number(e.target.value))}
className="h-8 text-xs border border-border bg-background px-2"
@@ -39,7 +40,7 @@ export function SingleHostEditForm({
{h.name || h.ip}
</option>
))}
</select>
</Select2>
</div>
);
}
@@ -76,6 +76,7 @@ import { ServiceGridEditForm } from "./ServiceGridEditForm";
import { DashboardLinksEditForm } from "./DashboardLinksEditForm";
import { SearchLinksEditForm } from "./SearchLinksEditForm";
import { LinkTreeEditForm } from "./LinkTreeEditForm";
import { validateClockTimezone } from "../clock-timezone";
interface WidgetEditDialogProps {
widget: CanvasWidget | null;
@@ -100,8 +101,20 @@ export function WidgetEditDialog({
if (!widget) return null;
// Configs that need checking before they can be stored. The clock keeps the
// normalized zone rather than the raw input, so "America/New York" is filed
// as "America/New_York"; the form flags an unusable one and Save stays off.
const clockTimezone =
widget.typeId === "clock" ? validateClockTimezone(config.timezone) : null;
const configInvalid = clockTimezone ? !clockTimezone.valid : false;
const handleSave = () => {
onSave(widget.id, title || null, config);
if (configInvalid) return;
onSave(
widget.id,
title || null,
clockTimezone ? { ...config, timezone: clockTimezone.timezone } : config,
);
onClose();
};
@@ -368,7 +381,7 @@ export function WidgetEditDialog({
<Button variant="outline" size="sm" onClick={onClose}>
{t("homepage.cancel")}
</Button>
<Button size="sm" onClick={handleSave}>
<Button size="sm" onClick={handleSave} disabled={configInvalid}>
{t("homepage.save")}
</Button>
</DialogFooter>
@@ -8,9 +8,16 @@ import {
} from "@/types/homepage-types";
import { WidgetTitle } from "./WidgetTitle";
import { usePageVisibleInterval } from "@/hooks/use-page-visible-interval";
import { isValidTimezone } from "../clock-timezone";
function ClockWidget({ widget, config }: WidgetComponentProps<ClockConfig>) {
const { timezone, showSeconds, format } = config;
const { showSeconds, format } = config;
// Configs saved before the edit dialog validated timezones can still hold an
// unusable one (e.g. "America/New York"), which makes toLocaleTimeString throw.
const timezone =
config.timezone && isValidTimezone(config.timezone)
? config.timezone
: undefined;
const [now, setNow] = useState(new Date());
// Minute-level is enough without seconds; pause when the tab is backgrounded.
+13 -17
View File
@@ -56,22 +56,11 @@ import {
defaultHeightFor,
type MetricCardHistories,
} from "./cards";
import { appendGpuHistories } from "./cards/gpu-history";
import { metricsChangeKey } from "./metrics-change-key";
const HISTORY_LEN = 30;
function metricsChangeKey(data: ServerMetrics): string {
const bucket = (value: number | null | undefined) =>
value == null ? null : Math.round(value / 5) * 5;
return JSON.stringify({
cpu: bucket(data.cpu.percent),
memory: bucket(data.memory.percent),
disk: bucket(data.disk.percent),
running: data.processes?.running ?? null,
ports: data.ports?.ports?.length ?? 0,
firewall: data.firewall?.status ?? null,
});
}
interface QuickAction {
name: string;
snippetId: number;
@@ -131,6 +120,7 @@ function HostMetricsInner({
cpu: [],
memory: [],
disk: [],
gpu: {},
});
const [currentHostConfig, setCurrentHostConfig] = React.useState(hostConfig);
const [isRefreshing, setIsRefreshing] = React.useState(false);
@@ -232,7 +222,7 @@ function HostMetricsInner({
if (hostConfig?.id !== currentHostConfig?.id) {
setServerStatus("offline");
setMetrics(null);
setHistories({ cpu: [], memory: [], disk: [] });
setHistories({ cpu: [], memory: [], disk: [], gpu: {} });
}
setCurrentHostConfig(hostConfig);
}, [hostConfig?.id]);
@@ -267,6 +257,7 @@ function HostMetricsInner({
cpu: add(prev.cpu, data.cpu?.percent),
memory: add(prev.memory, data.memory?.percent),
disk: add(prev.disk, data.disk?.percent),
gpu: appendGpuHistories(prev.gpu, data.gpu?.gpus, HISTORY_LEN),
};
});
}, []);
@@ -388,6 +379,7 @@ function HostMetricsInner({
}
setMetrics(data);
pushHistory(data);
setServerStatus("online");
logServerActivity();
addLog({
@@ -451,7 +443,7 @@ function HostMetricsInner({
}
},
enabled:
isActuallyVisible &&
isPageVisible &&
metricsEnabled &&
!totpRequired &&
!!currentHostConfig?.id,
@@ -461,6 +453,10 @@ function HostMetricsInner({
const metricsRetryRef = React.useRef(metricsRetry);
metricsRetryRef.current = metricsRetry;
// Connects once per host and stays connected while this tab exists, even
// when the user switches to another tab and back. Only the browser tab
// going into the background (isPageVisible) pauses/resumes it -- switching
// between Termix tabs must not tear down and reconnect the session.
React.useEffect(() => {
if (!metricsEnabled || !currentHostConfig?.id) return;
@@ -479,7 +475,7 @@ function HostMetricsInner({
const debounce = setTimeout(() => {
if (cancelled) return;
if (isActuallyVisible) {
if (isPageVisible) {
clearLogs();
metricsRetryRef.current.reset();
metricsRetryRef.current.retryNow();
@@ -497,7 +493,7 @@ function HostMetricsInner({
stopMetricsPolling(currentHostConfig.id).catch(() => {});
}
};
}, [currentHostConfig?.id, isActuallyVisible, metricsEnabled]);
}, [currentHostConfig?.id, isPageVisible, metricsEnabled]);
// After a successful TOTP submit, resume the connect flow immediately.
React.useEffect(() => {
@@ -0,0 +1,205 @@
import { useId } from "react";
import { Gpu } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { ServerMetrics } from "@/main-axios";
import type { GpuDevice, GpuProcess } from "@/types/stats-widgets";
import { MiniStat, RadialGauge, Sparkline, StatRow } from "@/components/charts";
import { MetricCard } from "./MetricCard";
import type { GpuHistories, GpuHistory } from "./gpu-history";
const NA = "N/A";
const EMPTY_HISTORY: GpuHistory = { utilization: [], memory: [] };
function formatGiB(mib: number | null): string {
return mib === null ? NA : (mib / 1024).toFixed(1);
}
function formatVram(gpu: GpuDevice): string {
return gpu.memoryUsedMiB === null || gpu.memoryTotalMiB === null
? NA
: `${formatGiB(gpu.memoryUsedMiB)}/${formatGiB(gpu.memoryTotalMiB)}G`;
}
function formatWhole(value: number | null, unit: string): string {
return value === null ? NA : `${Math.round(value)}${unit}`;
}
function formatPower(gpu: GpuDevice): string {
if (gpu.powerDrawWatts === null && gpu.powerLimitWatts === null) return NA;
return `${formatWhole(gpu.powerDrawWatts, "")}/${formatWhole(gpu.powerLimitWatts, "")}W`;
}
function processVram(process: GpuProcess): string {
const vram =
process.memoryUsedMiB === null
? NA
: `${formatGiB(process.memoryUsedMiB)}G`;
return process.gpuIndex === null ? vram : `${vram} · GPU ${process.gpuIndex}`;
}
function executableName(path: string): string {
return path.split(/[\\/]/).pop() || path;
}
/** A captioned 0-100% sparkline, so the two trends under each GPU are told apart. */
function TrendSparkline({
caption,
data,
colorClassName,
}: {
caption: string;
data: number[];
colorClassName?: string;
}) {
const captionId = useId();
return (
<figure aria-labelledby={captionId} className="flex min-w-0 flex-col gap-1">
<figcaption
id={captionId}
className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground"
>
{caption}
</figcaption>
<Sparkline
data={data}
domain={[0, 100]}
height={36}
colorClassName={colorClassName}
/>
</figure>
);
}
function GpuDeviceRow({
gpu,
history,
}: {
gpu: GpuDevice;
history: GpuHistory;
}) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-2">
<div className="flex min-w-0 items-baseline gap-1.5 text-xs">
<span className="font-mono text-muted-foreground">#{gpu.index}</span>
<span className="truncate font-semibold">{gpu.name}</span>
</div>
<div className="flex items-center gap-4">
<RadialGauge
value={gpu.utilizationPercent}
size={96}
caption={t("hostMetrics.gpu.utilization")}
/>
<div className="flex min-w-0 flex-1 flex-col gap-2">
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
<MiniStat
caption={t("hostMetrics.gpu.memory")}
value={formatVram(gpu)}
/>
<MiniStat
caption={t("hostMetrics.gpu.temperature")}
value={formatWhole(gpu.temperatureCelsius, "°C")}
/>
<MiniStat
caption={t("hostMetrics.gpu.power")}
value={formatPower(gpu)}
/>
<MiniStat
caption={t("hostMetrics.gpu.fan")}
value={formatWhole(gpu.fanPercent, "%")}
/>
</div>
<div className="grid grid-cols-2 gap-2">
<TrendSparkline
caption={t("hostMetrics.gpu.utilization")}
data={[...history.utilization, gpu.utilizationPercent ?? 0]}
/>
<TrendSparkline
caption={t("hostMetrics.gpu.memory")}
data={[...history.memory, gpu.memoryPercent ?? 0]}
colorClassName="text-muted-foreground"
/>
</div>
</div>
</div>
</div>
);
}
export function GpuCard({
metrics,
gpuHistories,
}: {
metrics: ServerMetrics | null;
gpuHistories: GpuHistories;
}) {
const { t } = useTranslation();
const gpus = metrics?.gpu?.gpus ?? [];
const processes = metrics?.gpu?.processes ?? [];
const driverVersion = gpus[0]?.driverVersion;
return (
<MetricCard
title={t("hostMetrics.gpu.title")}
icon={<Gpu className="size-3.5" />}
action={
driverVersion ? (
<span className="font-mono text-[10px] text-muted-foreground">
{t("hostMetrics.gpu.driver", { version: driverVersion })}
</span>
) : undefined
}
scroll={gpus.length > 2 || processes.length > 6}
scrollMax={520}
>
{gpus.length === 0 ? (
<span className="text-xs text-muted-foreground">
{t("hostMetrics.gpu.noDevice")}
</span>
) : (
<div className="flex flex-col gap-4">
{gpus.map((gpu) => (
<GpuDeviceRow
key={gpu.index}
gpu={gpu}
history={gpuHistories[gpu.index] ?? EMPTY_HISTORY}
/>
))}
<div className="flex flex-col">
<span className="mb-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
{t("hostMetrics.gpu.processes")}
</span>
{processes.length === 0 ? (
<span className="text-xs text-muted-foreground">
{t("hostMetrics.gpu.noProcesses")}
</span>
) : (
<div className="flex flex-col divide-y divide-border">
{processes.map((process) => (
<StatRow
key={`${process.gpuIndex}-${process.pid}`}
label={
<span className="flex items-baseline gap-1.5">
<span title={process.name} className="text-foreground">
{executableName(process.name)}
</span>
<span className="font-mono text-[10px]">
{process.pid}
</span>
</span>
}
value={processVram(process)}
mono
/>
))}
</div>
)}
</div>
</div>
)}
</MetricCard>
);
}
@@ -3,6 +3,7 @@ import { Unplug, Search } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { ServerMetrics, ListeningPort } from "@/main-axios";
import { MetricCard } from "./MetricCard";
import { Select2 } from "@/components/select2";
function formatAddress(addr: string) {
return addr === "0.0.0.0" || addr === "*" || addr === "::" ? "*" : addr;
@@ -63,7 +64,7 @@ export function PortsCard({ metrics }: { metrics: ServerMetrics | null }) {
className="h-7 w-full border border-border bg-background pl-7 pr-2 text-xs outline-none focus:ring-1 focus:ring-ring"
/>
</div>
<select
<Select2
value={proto}
onChange={(e) => setProto(e.target.value as "all" | "tcp" | "udp")}
className="h-7 border border-border bg-background px-1 text-xs"
@@ -71,7 +72,7 @@ export function PortsCard({ metrics }: { metrics: ServerMetrics | null }) {
<option value="all">{t("hostMetrics.ports.allProtocols")}</option>
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
</Select2>
<span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">
{filtered.length}
</span>
@@ -3,6 +3,11 @@ import { useTranslation } from "react-i18next";
import type { ServerMetrics } from "@/main-axios";
import { StatRow } from "@/components/charts";
import { MetricCard } from "./MetricCard";
import { useEffect, useState } from "react";
import {
selectTemperatureSensor,
temperaturePreferenceKey,
} from "../temperature-preference";
function formatTemperature(value: number | null | undefined): string {
return typeof value === "number" && Number.isFinite(value)
@@ -12,12 +17,37 @@ function formatTemperature(value: number | null | undefined): string {
export function TemperatureCard({
metrics,
hostId,
}: {
metrics: ServerMetrics | null;
hostId: number | null;
}) {
const { t } = useTranslation();
const temperature = metrics?.temperature;
const sensors = temperature?.sensors ?? [];
const [preferredLabel, setPreferredLabel] = useState("");
useEffect(() => {
setPreferredLabel(
hostId === null
? ""
: (localStorage.getItem(temperaturePreferenceKey(hostId)) ?? ""),
);
}, [hostId]);
const preferredSensor = selectTemperatureSensor(sensors, preferredLabel);
const displayedTemperature =
preferredSensor?.celsius ?? temperature?.highestCelsius;
const displayedLabel =
preferredSensor?.label ?? t("hostMetrics.highestTemperature");
const chooseSensor = (label: string) => {
setPreferredLabel(label);
if (hostId === null) return;
const key = temperaturePreferenceKey(hostId);
if (label) localStorage.setItem(key, label);
else localStorage.removeItem(key);
};
return (
<MetricCard
@@ -29,13 +59,31 @@ export function TemperatureCard({
<div className="flex flex-col gap-3">
<div>
<div className="text-3xl font-semibold tabular-nums">
{formatTemperature(temperature?.highestCelsius)}
{formatTemperature(displayedTemperature)}
</div>
<div className="mt-1 text-xs text-muted-foreground">
{t("hostMetrics.highestTemperature")}
{displayedLabel}
</div>
</div>
{sensors.length > 1 && (
<label className="flex flex-col gap-1 text-xs text-muted-foreground">
<span>{t("hostMetrics.primaryTemperatureSensor")}</span>
<select
value={preferredSensor?.label ?? ""}
onChange={(event) => chooseSensor(event.target.value)}
className="h-8 border border-border bg-background px-2 text-xs text-foreground outline-none focus:ring-1 focus:ring-ring"
>
<option value="">{t("hostMetrics.highestTemperature")}</option>
{sensors.map((sensor) => (
<option key={sensor.label} value={sensor.label}>
{sensor.label}
</option>
))}
</select>
</label>
)}
{sensors.length === 0 ? (
<span className="text-xs text-muted-foreground">N/A</span>
) : (
@@ -0,0 +1,31 @@
import type { GpuDevice } from "@/types/stats-widgets";
export interface GpuHistory {
utilization: number[];
memory: number[];
}
/** Live sparkline series keyed by GPU index. */
export type GpuHistories = Record<number, GpuHistory>;
/**
* Appends one poll's readings to each GPU's series. GPUs missing from the poll
* lose their series so a re-enumerated device never inherits stale samples.
*/
export function appendGpuHistories(
prev: GpuHistories,
gpus: GpuDevice[] | undefined,
maxLength: number,
): GpuHistories {
const add = (arr: number[] | undefined, v: number | null) =>
[...(arr ?? []), v ?? 0].slice(-maxLength);
const next: GpuHistories = {};
for (const gpu of gpus ?? []) {
next[gpu.index] = {
utilization: add(prev[gpu.index]?.utilization, gpu.utilizationPercent),
memory: add(prev[gpu.index]?.memory, gpu.memoryPercent),
};
}
return next;
}
+12 -1
View File
@@ -16,6 +16,8 @@ import { PortsCard } from "./PortsCard";
import { ProcessesCard } from "./ProcessesCard";
import { FirewallCard } from "./FirewallCard";
import { TemperatureCard } from "./TemperatureCard";
import { GpuCard } from "./GpuCard";
import type { GpuHistories } from "./gpu-history";
import { ServiceManagerCard } from "./managers/ServiceManagerCard";
import { ProcessInspectorCard } from "./managers/ProcessInspectorCard";
import { PackageManagerCard } from "./managers/PackageManagerCard";
@@ -37,6 +39,7 @@ export interface MetricCardHistories {
cpu: number[];
memory: number[];
disk: number[];
gpu: GpuHistories;
}
export interface CardRenderContext {
@@ -80,7 +83,7 @@ function historyCard(
id: HostMetricsCardId,
labelKey: string,
Comp: HistoryMetricCard,
series: keyof MetricCardHistories,
series: "cpu" | "memory" | "disk",
): CardDefinition {
return {
id,
@@ -132,6 +135,14 @@ export const CARD_DEFINITIONS: Record<string, CardDefinition> = {
"hostMetrics.temperature",
TemperatureCard,
),
gpu: {
id: "gpu",
labelKey: "hostMetrics.gpu.title",
kind: "metric",
render: ({ metrics, histories }) => (
<GpuCard metrics={metrics} gpuHistories={histories.gpu} />
),
},
service_manager: managerCard(
"service_manager",
"hostMetrics.managers.services",
@@ -7,6 +7,7 @@ import { managerPost, type FirewallChain } from "@/main-axios";
import { useManagerData, extractError } from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { ManagerSearch } from "./ManagerToolbar";
import { Select2 } from "@/components/select2";
interface FirewallData {
type: "iptables" | "nftables" | "none";
@@ -124,21 +125,21 @@ export function FirewallManagerCard({ hostId }: { hostId: number | null }) {
{t("hostMetrics.managers.addInputRule")}
</span>
<div className="flex items-center gap-1.5">
<select
<Select2
value={proto}
onChange={(e) => setProto(e.target.value as "tcp" | "udp")}
className="h-7 border border-border bg-background px-1 text-xs"
>
<option value="tcp">tcp</option>
<option value="udp">udp</option>
</select>
</Select2>
<input
value={port}
onChange={(e) => setPort(e.target.value)}
placeholder={t("hostMetrics.ports.port")}
className="h-7 w-16 border border-border bg-background px-1.5 text-xs outline-none focus:ring-1 focus:ring-ring"
/>
<select
<Select2
value={target}
onChange={(e) =>
setTarget(e.target.value as "ACCEPT" | "DROP" | "REJECT")
@@ -148,7 +149,7 @@ export function FirewallManagerCard({ hostId }: { hostId: number | null }) {
<option>ACCEPT</option>
<option>DROP</option>
<option>REJECT</option>
</select>
</Select2>
<Button
variant="outline"
size="xs"
@@ -15,6 +15,7 @@ import { Sparkline } from "@/components/charts";
import { managerPost } from "@/main-axios";
import { useManagerData, extractError } from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { Select2 } from "@/components/select2";
interface HealthCheck {
id: string;
@@ -185,7 +186,7 @@ export function HealthCheckCard({ hostId }: { hostId: number | null }) {
placeholder={t("hostMetrics.managers.healthName")}
className="h-7 flex-1 border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
/>
<select
<Select2
value={c.type}
onChange={(e) =>
updateDraft(c.id, {
@@ -196,7 +197,7 @@ export function HealthCheckCard({ hostId }: { hostId: number | null }) {
>
<option value="tcp">TCP</option>
<option value="http">HTTP</option>
</select>
</Select2>
<button
onClick={() =>
setDraft((d) => d.filter((x) => x.id !== c.id))
@@ -5,6 +5,7 @@ import { managerGet, managerGetSub } from "@/main-axios";
import { extractError } from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { useAdaptivePolling } from "@/hooks/use-adaptive-polling";
import { Select2 } from "@/components/select2";
interface LogFiles {
common: string[];
@@ -125,16 +126,16 @@ export function LogViewerCard({ hostId }: { hostId: number | null }) {
}
>
<div className="mb-2 flex items-center gap-1.5">
<select
<Select2
value={mode}
onChange={(e) => setMode(e.target.value as Mode)}
className="h-7 border border-border bg-background px-1 text-[11px]"
>
<option value="file">{t("hostMetrics.managers.logFile")}</option>
<option value="unit">{t("hostMetrics.managers.logUnit")}</option>
</select>
</Select2>
{mode === "file" ? (
<select
<Select2
value={customPath ? "" : path}
onChange={(e) => {
setCustomPath("");
@@ -147,7 +148,7 @@ export function LogViewerCard({ hostId }: { hostId: number | null }) {
{f}
</option>
))}
</select>
</Select2>
) : (
<input
value={unit}
@@ -157,7 +158,7 @@ export function LogViewerCard({ hostId }: { hostId: number | null }) {
className="h-7 flex-1 border border-border bg-background px-2 font-mono text-[11px] outline-none focus:ring-1 focus:ring-ring"
/>
)}
<select
<Select2
value={lines}
onChange={(e) => setLines(Number(e.target.value))}
className="h-7 border border-border bg-background px-1 text-[11px]"
@@ -167,7 +168,7 @@ export function LogViewerCard({ hostId }: { hostId: number | null }) {
{n}
</option>
))}
</select>
</Select2>
</div>
{mode === "file" && (
@@ -6,6 +6,7 @@ import { managerPost } from "@/main-axios";
import { useManagerData, extractError } from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { ManagerSearch } from "./ManagerToolbar";
import { Select2 } from "@/components/select2";
interface ProcessRow {
pid: number;
@@ -120,7 +121,7 @@ export function ProcessInspectorCard({ hostId }: { hostId: number | null }) {
<ListTree className="size-3" />
{t("hostMetrics.managers.tree")}
</button>
<select
<Select2
value={sort}
onChange={(e) => setSort(e.target.value as SortKey)}
disabled={tree}
@@ -129,7 +130,7 @@ export function ProcessInspectorCard({ hostId }: { hostId: number | null }) {
<option value="cpu">CPU</option>
<option value="mem">MEM</option>
<option value="pid">PID</option>
</select>
</Select2>
</>
}
>
@@ -164,7 +165,8 @@ export function ProcessInspectorCard({ hostId }: { hostId: number | null }) {
{depth > 0 && (
<span className="text-muted-foreground/40">└ </span>
)}
{p.command}
{/* `comm` is capped at 15 chars by the kernel; the full command line is in args. */}
{p.args || p.command}
</span>
<button
onClick={() => kill(p.pid, "TERM")}
@@ -9,6 +9,7 @@ import {
extractError,
} from "./useManagerData";
import { ManagerCardShell } from "./ManagerCardShell";
import { Select2 } from "@/components/select2";
interface CertInfo {
client: string;
@@ -221,7 +222,7 @@ export function SslManagerCard({ hostId }: { hostId: number | null }) {
className="h-7 w-full border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
/>
<div className="flex items-center gap-1.5">
<select
<Select2
value={challenge}
onChange={(e) => setChallenge(e.target.value as Challenge)}
className="h-7 flex-1 border border-border bg-background px-1 text-xs"
@@ -233,7 +234,7 @@ export function SslManagerCard({ hostId }: { hostId: number | null }) {
{t("hostMetrics.managers.sslHttpWebroot")}
</option>
<option value="dns">{t("hostMetrics.managers.sslDns")}</option>
</select>
</Select2>
</div>
{challenge === "http-webroot" && (
<input
@@ -0,0 +1,24 @@
import type { ServerMetrics } from "@/main-axios";
/**
* Coarse fingerprint of a metrics poll. Adaptive polling backs off while it
* stays the same, so it must move whenever something a card shows changes.
*/
export function metricsChangeKey(data: ServerMetrics): string {
const bucket = (value: number | null | undefined) =>
value == null ? null : Math.round(value / 5) * 5;
return JSON.stringify({
cpu: bucket(data.cpu.percent),
memory: bucket(data.memory.percent),
disk: bucket(data.disk.percent),
running: data.processes?.running ?? null,
ports: data.ports?.ports?.length ?? 0,
firewall: data.firewall?.status ?? null,
gpus:
data.gpu?.gpus?.map((gpu) => [
bucket(gpu.utilizationPercent),
bucket(gpu.memoryPercent),
]) ?? [],
gpuProcesses: data.gpu?.processes?.length ?? 0,
});
}
@@ -0,0 +1,12 @@
import type { TemperatureSensor } from "@/types/stats-widgets";
export function selectTemperatureSensor(
sensors: TemperatureSensor[],
preferredLabel: string,
) {
return sensors.find((sensor) => sensor.label === preferredLabel) ?? null;
}
export function temperaturePreferenceKey(hostId: number) {
return `termix-host-metrics:${hostId}:temperature-sensor`;
}
@@ -1,10 +1,20 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { FitAddon } from "@xterm/addon-fit";
import { ClipboardAddon } from "@xterm/addon-clipboard";
import { useXTerm } from "react-xtermjs";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { useTheme } from "@/components/theme-provider";
import { resolveTermixThemeColors } from "@/features/terminal/terminal-theme";
import { DEFAULT_TERMINAL_CONFIG, TERMINAL_FONTS } from "@/lib/terminal-themes";
import { getMacLineNavigationSequence } from "@/lib/mac-line-navigation";
import { ensureTerminalFontsLoaded } from "@/features/terminal/terminal-global-styles";
import {
handleTerminalClipboardKeyEvent,
createTerminalContextMenuHandler,
} from "@/features/terminal/terminal-clipboard";
import { RobustClipboardProvider } from "@/lib/clipboard-provider";
import { copyToClipboard, readFromClipboard } from "@/lib/clipboard";
export function LocalTerminal({
instanceId,
@@ -13,6 +23,12 @@ export function LocalTerminal({
instanceId: string;
isVisible: boolean;
}) {
const { t } = useTranslation();
// Read via a ref inside the session-lifecycle effect below so a language
// change (which gives react-i18next a new `t` identity) doesn't tear down
// the running local shell and spawn a new session.
const tRef = useRef(t);
tRef.current = t;
const { theme: appTheme } = useTheme();
const { instance: terminal, ref: xtermRef } = useXTerm();
const fitAddonRef = useRef<FitAddon | null>(null);
@@ -55,10 +71,51 @@ export function LocalTerminal({
useEffect(() => {
if (!terminal || !window.electronAPI?.isElectron) return;
const fitAddon = new FitAddon();
const clipboardProvider = new RobustClipboardProvider();
const clipboardAddon = new ClipboardAddon(undefined, clipboardProvider);
fitAddonRef.current = fitAddon;
terminal.loadAddon(fitAddon);
terminal.loadAddon(clipboardAddon);
fitAddon.fit();
async function writeTextToClipboard(text: string): Promise<boolean> {
const ok = await copyToClipboard(text);
if (!ok) toast.error(tRef.current("terminal.clipboardWriteFailed"));
return ok;
}
async function readTextFromClipboard(): Promise<string> {
const text = await readFromClipboard();
if (!text) toast.error(tRef.current("terminal.clipboardReadFailed"));
return text;
}
const clipboardActions = { writeTextToClipboard, readTextFromClipboard };
terminal.attachCustomKeyEventHandler((e: KeyboardEvent): boolean => {
if (e.type !== "keydown") return true;
const sequence = getMacLineNavigationSequence(e);
if (sequence) {
e.preventDefault();
e.stopPropagation();
terminal.input(sequence, true);
return false;
}
// No native "paste" event listener here (unlike the SSH terminal), so
// plain Ctrl/Cmd+V reads the clipboard explicitly rather than relying
// on the browser's own paste event.
return handleTerminalClipboardKeyEvent(e, terminal, clipboardActions, {
plainPasteMode: "explicit",
});
});
const handleContextMenu = createTerminalContextMenuHandler(
terminal,
clipboardActions,
);
const element = xtermRef.current;
element?.addEventListener("contextmenu", handleContextMenu);
let disposed = false;
let removeData = () => {};
let removeExit = () => {};
@@ -98,10 +155,13 @@ export function LocalTerminal({
if (xtermRef.current) observer.observe(xtermRef.current);
return () => {
disposed = true;
terminal.attachCustomKeyEventHandler(() => true);
observer.disconnect();
input.dispose();
removeData();
removeExit();
element?.removeEventListener("contextmenu", handleContextMenu);
clipboardProvider.dispose();
const sessionId = sessionIdRef.current;
sessionIdRef.current = null;
if (sessionId) window.electronAPI.closeLocalTerminal(sessionId);
@@ -244,23 +244,27 @@ function ProxmoxStatsInner({
retry.markFailed();
}
},
enabled: isActuallyVisible && !notEnabled && !!currentHostConfig?.id,
enabled: isPageVisible && !notEnabled && !!currentHostConfig?.id,
autoStart: false,
});
const retryRef = React.useRef(retry);
retryRef.current = retry;
// Connects once per host and stays connected while this tab exists, even
// when the user switches to another tab and back. Only the browser tab
// going into the background (isPageVisible) pauses/resumes it -- switching
// between Termix tabs must not tear down and reconnect the session.
React.useEffect(() => {
if (notEnabled || !currentHostConfig?.id) return;
let cancelled = false;
const debounce = setTimeout(() => {
if (isActuallyVisible && !cancelled) {
if (isPageVisible && !cancelled) {
clearLogs();
retryRef.current.reset();
retryRef.current.retryNow();
} else if (!isActuallyVisible) {
} else if (!isPageVisible) {
stopPollingRef.current?.();
stopPollingRef.current = null;
if (currentHostConfig?.id) {
@@ -280,7 +284,7 @@ function ProxmoxStatsInner({
stopProxmoxStatsPolling(currentHostConfig.id).catch(() => {});
}
};
}, [currentHostConfig?.id, notEnabled, isActuallyVisible]);
}, [currentHostConfig?.id, notEnabled, isPageVisible]);
const wrapperStyle: React.CSSProperties = embedded
? { opacity: isVisible ? 1 : 0, height: "100%", width: "100%" }
+6 -4
View File
@@ -10,6 +10,7 @@ import { FitAddon } from "@xterm/addon-fit";
import { useTranslation } from "react-i18next";
import { TriangleAlert } from "lucide-react";
import { isElectron } from "@/lib/electron";
import { websocketAuthProtocols } from "@/lib/ws-auth";
import { useTheme } from "@/components/theme-provider";
import { resolveTermixThemeColors } from "@/features/terminal/terminal-theme";
import { DEFAULT_TERMINAL_CONFIG, TERMINAL_FONTS } from "@/lib/terminal-themes";
@@ -102,9 +103,7 @@ export const Serial = forwardRef<SerialHandle, SerialProps>(function Serial(
const buildWsUrl = useCallback(() => {
// Serial is always local -- the device is physically attached to this
// desktop machine, so it never routes through a remote server.
const token = localStorage.getItem("jwt");
const base = "ws://127.0.0.1:30011";
return token ? `${base}?token=${encodeURIComponent(token)}` : base;
return "ws://127.0.0.1:30011";
}, []);
const disconnectWs = useCallback(() => {
@@ -124,7 +123,10 @@ export const Serial = forwardRef<SerialHandle, SerialProps>(function Serial(
return;
}
const ws = new WebSocket(url);
const ws = new WebSocket(
url,
websocketAuthProtocols(localStorage.getItem("jwt")),
);
wsRef.current = ws;
ws.onopen = () => {
Loaded 100 of 692 files, more files were not shown because too many files have changed in this diff. Show more