mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-30 07:05:24 +00:00
release-2.9.0 (#1532)
* fix(macos): skip single-instance lock in Mac App Store builds (#1454)
fix(macos): skip single-instance lock in Mac App Store builds
* Fix/backend optional sharp (#1455)
Fix/backend optional sharp
* feat: issue #1218 (#1218)
https://github.com/Termix-SSH/Support/issues/1218
* feat: Add option to use saved global custom theme under Connection Defaults (#1209)
https://github.com/Termix-SSH/Support/issues/1209
* feat: Add Fleet Sharing functionality to the UI (#1228)
https://github.com/Termix-SSH/Support/issues/1228
* feat: Add a list view to the Docker management page (#1237)
https://github.com/Termix-SSH/Support/issues/1237
* feat: issue #1264 (#1264)
https://github.com/Termix-SSH/Support/issues/1264
* feat: 2FA With FortiToken (#1288)
https://github.com/Termix-SSH/Support/issues/1288
* feat: Allow to disable showing paths to folders (#1274)
https://github.com/Termix-SSH/Support/issues/1274
* feat: Sync Network Graph between Desktop and Remote Server (#1245)
https://github.com/Termix-SSH/Support/issues/1245
* feat: Version Number on offline servers (#1291)
https://github.com/Termix-SSH/Support/issues/1291
* feat: Support OrbStack Docker socket path on macOS / Fix "Docker is not installed" on mac... (#1302)
https://github.com/Termix-SSH/Support/issues/1302
* feat: Sidebar host click should focus existing tab instead of opening a new connection (#1289)
https://github.com/Termix-SSH/Support/issues/1289
* fix: Search in side bar shows overlapping hosts when grouped by tags (#1303)
https://github.com/Termix-SSH/Support/issues/1303
* fix: I can't send a file on its own. (#1304)
https://github.com/Termix-SSH/Support/issues/1304
* fix: sudo password not autofilling (#1248)
https://github.com/Termix-SSH/Support/issues/1248
* fix: node-MainThread (#1300)
https://github.com/Termix-SSH/Support/issues/1300
* fix: Tunnel authentication with shared credentials (#1295)
https://github.com/Termix-SSH/Support/issues/1295
* fix: host key updates not syncing, metrics 404 race on first connect
Host key writes never bumped updatedAt so sync never picked them up.
Also retry the first metrics fetch briefly instead of failing right away.
* chore: increment ver
* feat: add category and icon fields to plugin manifest schema
* ci(deps): bump the github-actions group with 2 updates (#1458)
Bumps the github-actions group with 2 updates: [crowdin/github-action](https://github.com/crowdin/github-action) and [actions/github-script](https://github.com/actions/github-script).
Updates `crowdin/github-action` from 2 to 3
- [Release notes](https://github.com/crowdin/github-action/releases)
- [Commits](https://github.com/crowdin/github-action/compare/v2...v3)
Updates `actions/github-script` from 7 to 9
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)
---
updated-dependencies:
- dependency-name: crowdin/github-action
dependency-version: '3'
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: github-actions
- dependency-name: actions/github-script
dependency-version: '9'
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: github-actions
...
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 13 updates (#1459)
Bumps the dev-patch-updates group with 13 updates:
| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.11.0` | `6.11.1` |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.1` | `6.7.2` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.9` | `6.43.12` |
| [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` |
| [@testing-library/react](https://github.com/testing-library/react-testing-library) | `16.3.2` | `16.3.3` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.5` | `14.6.7` |
| [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2) | `1.15.5` | `1.15.6` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.1.0` | `6.1.1` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.1` | `3.34.3` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.4` | `0.5.7` |
| [i18next](https://github.com/i18next/i18next) | `26.4.0` | `26.4.2` |
| [prettier](https://github.com/prettier/prettier) | `3.9.6` | `3.9.8` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.0.12` | `17.0.14` |
Updates `@codemirror/commands` from 6.11.0 to 6.11.1
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)
Updates `@codemirror/search` from 6.7.1 to 6.7.2
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)
Updates `@codemirror/view` from 6.43.9 to 6.43.12
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)
Updates `@testing-library/dom` from 10.4.1 to 10.4.2
- [Release notes](https://github.com/testing-library/dom-testing-library/releases)
- [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2)
Updates `@testing-library/react` from 16.3.2 to 16.3.3
- [Release notes](https://github.com/testing-library/react-testing-library/releases)
- [Changelog](https://github.com/testing-library/react-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/react-testing-library/compare/v16.3.2...v16.3.3)
Updates `@testing-library/user-event` from 14.6.5 to 14.6.7
- [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.5...v14.6.7)
Updates `@types/ssh2` from 1.15.5 to 1.15.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2)
Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1
- [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.1/packages/plugin-react)
Updates `cytoscape` from 3.34.1 to 3.34.3
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.1...v3.34.3)
Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7
- [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.4...v0.5.7)
Updates `i18next` from 26.4.0 to 26.4.2
- [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.4.0...v26.4.2)
Updates `prettier` from 3.9.6 to 3.9.8
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.8)
Updates `react-i18next` from 17.0.12 to 17.0.14
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.0.12...v17.0.14)
---
updated-dependencies:
- dependency-name: "@codemirror/commands"
dependency-version: 6.11.1
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@codemirror/search"
dependency-version: 6.7.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
dependency-version: 6.43.12
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@testing-library/dom"
dependency-version: 10.4.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@testing-library/react"
dependency-version: 16.3.3
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.7
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@types/ssh2"
dependency-version: 1.15.6
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: "@vitejs/plugin-react"
dependency-version: 6.1.1
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: cytoscape
dependency-version: 3.34.3
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.7
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: i18next
dependency-version: 26.4.2
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: prettier
dependency-version: 3.9.8
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: dev-patch-updates
- dependency-name: react-i18next
dependency-version: 17.0.14
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 6 updates (#1461)
Bumps the prod-patch-updates group with 6 updates:
| Package | From | To |
| --- | --- | --- |
| [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.10` | `3.14.13` |
| [compression](https://github.com/expressjs/compression) | `1.8.1` | `1.8.2` |
| [jose](https://github.com/panva/jose) | `6.2.9` | `6.2.12` |
| [jszip](https://github.com/Stuk/jszip) | `3.10.1` | `3.10.2` |
| [socks](https://github.com/JoshGlazebrook/socks) | `2.8.9` | `2.8.10` |
| [undici](https://github.com/nodejs/undici) | `8.10.0` | `8.10.2` |
Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13
- [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.13/packages/react-virtual)
Updates `compression` from 1.8.1 to 1.8.2
- [Release notes](https://github.com/expressjs/compression/releases)
- [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2)
Updates `jose` from 6.2.9 to 6.2.12
- [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.9...v6.2.12)
Updates `jszip` from 3.10.1 to 3.10.2
- [Changelog](https://github.com/Stuk/jszip/blob/main/CHANGES.md)
- [Commits](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2)
Updates `socks` from 2.8.9 to 2.8.10
- [Release notes](https://github.com/JoshGlazebrook/socks/releases)
- [Commits](https://github.com/JoshGlazebrook/socks/compare/2.8.9...2.8.10)
Updates `undici` from 8.10.0 to 8.10.2
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2)
---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
dependency-version: 3.14.13
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: compression
dependency-version: 1.8.2
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: jose
dependency-version: 6.2.12
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: jszip
dependency-version: 3.10.2
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: socks
dependency-version: 2.8.10
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: prod-patch-updates
- dependency-name: undici
dependency-version: 8.10.2
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>
* feat: add plugin worker protocol, bootstrap and plugin_storage table
Worker-side ctx proxy plus the message envelope it talks over, and the
per-plugin key/value table behind ctx.storage with migrations for all
three dialects. Rows cascade with the plugin so uninstalling leaves
nothing behind.
* feat: add allowlisted host view for plugins
An allowlist rather than a list of fields to strip. A blocklist rots:
the moment a new secret-bearing column lands on SSHHost it starts
leaking silently. With an allowlist a new field stays invisible to
plugins until someone adds it here on purpose.
* feat: add plugin loader with manifest validation and crash restart
Validates an unpacked plugin, spawns a worker_threads worker and manages
activate/deactivate/crash-restart with backoff, disabling after three
tries.
The crash counter clears only after a plugin stays up past a stability
window, not on activation. Clearing it on activation let a plugin that
activates cleanly and then dies restart forever, because every attempt
looked like the first.
loader.ts documents what the worker boundary does and does not buy you.
Node's permission model is process-wide, not per-worker, so it cannot be
enabled for plugin workers alone and is not claimed here.
* feat: route internal events through a shared plugin event bus
Formalises three ad-hoc publish paths that already existed:
automation-events.ts, metrics/automation-bridge.ts and the
hostSessionStatus singleton, now the host.session.status topic.
Both invariants the old code relied on are preserved. Publishing stays
fire-and-forget, so a failing subscriber cannot disturb a metrics poll or
a host delete. The automations engine subscribes to the bus at scheduler
start instead of being imported ad hoc, which keeps the edge
one-directional: automations may import repositories, hosts modules must
not import automations.
* feat: add plugin ctx broker with permission gate and audit
Every ctx call a plugin makes is checked against its granted
capabilities, performed by the main thread, then audited. A capability
must be both declared in the manifest and granted in the database, so
widening a plugin's reach always needs a new manifest the user can see,
never just a database row.
Audit attribution is set by the broker, not the plugin. The plugin
supplies only the details, so it cannot forge the actor.
fix: stop plugin workers seeing plaintext credentials in error messages
A failing ctx.ssh.connect handed the worker the raw error from deep in
the SSH stack, which embeds the connect config. The worker received, in
full:
Authentication failed for root using password <SECRET>
where <SECRET> was the host's real plaintext password. Any plugin with
ssh.exec could read it by catching the error, defeating the whole point
of the handle-based ssh API.
Errors crossing the boundary are now sanitised. Only PluginFacingError
and PluginPermissionError, both authored here, reach a plugin verbatim;
anything else becomes a generic message and the real one goes to the
log. This uses a marker class rather than matching on message text,
because matching would start leaking again the moment an upstream error
happened to contain a familiar phrase.
Covered by credential-isolation.test.ts, which plants a sentinel in
every secret-bearing field and asserts it appears in no message the
worker ever receives.
* feat: dispatch plugin HTTP routes and wire the runtime into startup
ctx.http.route now registers a real router on the /plugin-api/:pluginId
dispatcher, replacing its stub 404. A plugin never touches the Express
req/res: it gets a plain summary and returns a plain object, so sockets
and session cookies stay on this side of the boundary. Authorization and
cookie headers are not forwarded.
Plugins load last in the start-up sequence, after the server is fully
wired, and are terminated before the database on shutdown so none can
outlive it. A plugin that fails to load cannot stop the backend.
fix: correct the nginx plugin-api location regex
The pattern was ^/plugin-api/(/.*)?$, which needs a double slash and so
never matched /plugin-api/<id>/<route>. Every other block in the file
uses ^/prefix(/.*)?$. Left alone, plugin routes would work in dev and
404 only behind Docker.
* fix: update stale SFTP transfer test for single file destination paths
The test still asserted transferToHost was called with the destination
directory "/srv". Commit 7727fa09 (#1304) deliberately changed a single
file transfer to send the full destination path including the filename,
so the correct expectation is "/srv/remote-1.txt". The code was right
and the test was left behind.
* feat: ship the ssh terminal as a first-party in-process plugin
Adds a hardcoded process:transport-owner tier so the terminal can own its
WebSocket server and ssh2 clients, which cannot cross the worker boundary.
* feat: ship docker as a first-party in-process plugin
Moves docker backend and frontend into plugins/docker/, alongside
ssh-terminal. Adds a host editor tab seam, a dashboard card registry,
and a build step to compile plugin backends into dist.
* feat: ship host metrics as a first-party in-process plugin
* fix: harden plugin auth and add per-request identity for ctx calls
Require auth on /plugin-api, gate plugin enable/grant/revoke routes
behind admin.plugins.manage, and thread the calling user through
worker ctx.hosts/ctx.ssh calls instead of always using the install
owner. Also adds the plugin permissions grant/revoke UI.
* feat: ship the AI assistant as a first-party in-process plugin
Moves src/backend/ai and its routes into plugins/ai, mounted through a
small /ai dispatcher instead of its own port. Moves the ai-enabled and
ai-private-endpoints settings routes out of user-settings-routes.ts
into the plugin too, so it has no leftover core dependents.
* fix: remove compiled plugin JS left behind in plugins/ after build
copy-bundled-plugins.cjs compiled and rewrote plugin backend TS in
place, copied it to dist/plugins, but never deleted the .js it had
just emitted next to the .ts sources. Those files shadowed the real
source for vitest/tsx and had import paths rewritten for the dist
layout, so tests failed with "Cannot find module" once a local build
had run. Affects docker, host-metrics and ai, not just this one.
* feat: add a permission-gated backend service registry for plugins
* feat: add a permission-gated UI action registry and action slots for plugins
Moves the terminal toolbar's hardwired AI button into a slot the ssh-terminal
plugin offers and the ai plugin fills, gated on ai.services.use.
* feat: add cross-plugin secret references gated by the provider's RBAC permission
* feat: move proxmox discovery/import/sync into a first-party plugin
* feat: move remote desktop (RDP/VNC/Telnet) into a first-party plugin
Relocates guacamole backend/frontend source and tests into
plugins/remote-desktop, following the ssh-terminal/docker pattern.
* feat: wire remote-desktop plugin into core and rename i18n keys
Repoints core consumers (dispatcher, collab, session-sharing, tab
utils) at the plugin, adds isTabTypeAvailable gating for rdp/vnc/
telnet, widens hostCapability to accept an array, and renames the
guacamole i18n namespace to remoteDesktop.
* feat: move fleets into a first-party plugin
* feat: move automations into a first-party plugin
* feat: remove legacy alert rules, superseded by automations
Alert rules already auto-migrate into automations on boot and the old
engine stands down after. Deletes the rule/firing tables, routes, UI,
and AI tools; keeps notification channels since automations still use
them. Also fixes automations' notify step, which still called the
deleted repository.
* feat: move network topology into a first-party plugin
* feat: move tailscale device discovery and settings into a plugin
Adds plugins/tailscale/ with a devices sidebar tab, admin settings
section, and re-auth dialog. Host Metrics tailscale manager card and
SSH re-auth banner parsing stay in core.
* feat: move workspaces into a first-party plugin
* feat: move web endpoint into a first-party plugin
* feat: collapse plugin runtime to one tier behind a plugin SDK
* feat: make each plugin an npm workspace built by a termix-plugin CLI
* feat: give plugins their own tables, migrations and sync entities
* feat: serve plugin http and websockets from one mount instead of ports
* feat: namespace plugin permissions and keep them valid when a plugin is off
* feat: give plugins their own settings and one settings screen
* feat: load plugin frontends at runtime and remove plugin ids from the shell
* fix: mock the ai status fetch in its activate test
* feat: add auth extension points and one ssh connect pipeline
* feat: rebuild workspaces as the reference plugin
* fix: gate second factors after SSO/LDAP behind an admin setting
* feat: convert network-topology to a full plugin (B1)
* feat: move snippets backend and tables into a plugin (B2)
* feat: point core frontend snippets pickers at the plugin (B2)
* feat: add the snippets plugin (B2)
* feat: wire ai, automations, fleets and ssh-terminal to snippets (B2)
* feat: finish the tailscale plugin, including SSH auth (B3)
* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)
* chore: update proxmox and host-metrics locale files for B5
* chore: regenerate drizzle migration journals for B5
* feat: add ctx.hosts create/update to the SDK, host-metrics drops proxmox
* feat: move proxmox node stats and collectors into the proxmox plugin
* feat: drop proxmox host columns, use plugin settings instead
* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)
* feat: convert file manager into a plugin
* feat: convert ssh tunnels into a plugin
* feat: finish the web-endpoint plugin, add ctx.desktop (B8)
* feat: move the terminal fully into the ssh-terminal plugin (B9)
* feat: convert tmux monitoring into a plugin (B10)
* feat: convert serial console into the serial plugin
* feat: move session sharing and collab rooms into a plugin (B12)
* feat: turn session recording into a plugin (B13)
* feat: finish the remote-desktop plugin (B14)
* feat: finish the host-metrics plugin, move host status into core (B16)
* feat: finish the docker plugin (B15)
* feat: finish the automations plugin (B17)
* feat: finish the ai plugin (B18)
* feat: finish the homepage plugin, move service links and canvas out of core (B19)
* feat: convert wake-on-lan into a plugin (B20)
* feat: convert secret-sources into a plugin (B20)
* feat: move totp and passkeys into plugins (C1)
* feat: move sso and ldap logins into plugins (C2)
* feat: move opkssh and warpgate into plugins (C3)
* feat: move step-ca into a plugin (C4)
* feat: move vault ssh signing into a plugin (C5)
* feat: move termix identity into a plugin (C6)
* feat: move acme certificate automation into a plugin (C7)
* fix: finish 2.9.0 plugin moves and get every check green
* chore: lock the plugin boundary and remove 2.9.0 leftovers
* fix: harden the plugin runtime after the 2.9.0 security review
* feat: add plugin packing, signing, pinned trust and tmxplug bundling
* test: prove 2.8 to 2.9.0 upgrade is lossless and fix what it caught
* fix: give bundled plugin backends a real require for CJS deps
* feat: improve UI loading time and jitter
* feat: show credential sharing inline in the sidebar like host sharing
* feat: tailscale add host and copy ip, fix outbound fetch hang and plugin ESM warning
* feat: unify alerts into one plugin, channels, rules and inbox
* feat: rebuild desktop sync as linked server accounts, fix packaged plugin bundles and UI scaling
* fix: set blacksmith builder cache-key to stop broken gha cache fallback
* fix: link plugin-sdk workspace before npm ci in docker deps stage
* fix: link every plugin workspace before npm ci in docker deps stage
* fix(host-metrics): exclude image and firmware filesystems (#1469)
* fix(host-metrics): exclude image and firmware filesystems
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(hosts): normalize imported jump host references (#1470)
* fix(hosts): normalize imported jump host references
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(ci): build plugin SDK and repair MySQL settings migration (#1471)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): keep inline rename consistent (#1476)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): keep inline rename consistent
* fix(dashboard): reuse translated host status labels (#1475)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(dashboard): reuse translated host status labels
* docs(api): clarify local and remote version fields (#1474)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* docs(api): clarify local and remote version fields
* fix(file-manager): preserve selected backgrounds on hover (#1473)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): preserve selection feedback on hover
* test(ui): await dialog focus cleanup before teardown
* fix(file-manager): restore Ctrl/Cmd+F file search (#1472)
* fix(ci): build plugin SDK before dependent checks
* fix(mysql): keep plugin settings scope indexes within limits
* test(mysql): refresh reviewed plugin upgrade SQL
* fix(file-manager): focus file search with Ctrl or Cmd F
* fix: keep rounded-full circular in production builds
* fix(file-manager): cancel uploads and stop remote writes (#1477)
* fix(file-manager): cancel uploads and stop remote writes
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): apply compact density to directory tree (#1478)
* fix(file-manager): apply compact density to directory tree
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): preserve font sizes in compact mode (#1480)
* fix(file-manager): preserve font sizes in compact mode
* test(css): exercise the configured PostCSS plugin chain
* fix(file-manager): prioritize file names in narrow lists (#1483)
* fix(file-manager): prioritize file names in narrow lists
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* fix(remote-desktop): probe the saved host guacd endpoint (#1481)
* fix(remote-desktop): probe the saved host guacd endpoint
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* fix(homepage): check allowlisted private service reachability (#1479)
* fix(homepage): check allowlisted private service reachability
* test(css): exercise the configured PostCSS plugin chain
* fix(remote-desktop): stop unsolicited clipboard read prompts (#1482)
* fix(remote-desktop): read clipboard only on explicit paste
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* chore: simplify plugin readmes, changelogs and manifest descriptions
* fix: keep plugins loaded after signing in from the login screen
* fix(file-manager): accept OS file drops over existing rows (#1484)
* fix(file-manager): accept OS file drops over existing rows
* test(file-manager): target the file label in drop tests
* test(css): exercise the configured PostCSS plugin chain
* test(identity): preserve full Ed25519 public keys in fixtures
* test(remote-desktop): always mutate ciphertext in tamper test
* fix(file-manager): pipeline SFTP download reads (#1485)
* feat: add plugin sdk build to beta release
* fix: make link-store secret check immune to random base64 matches
* fix(ldap): preserve the directory-provided bind DN (#1486)
* fix: compute beta changes across dev branches and move the beta tag
* chore: untrack plugin sdk ARCHITECTURE.md
* chore: remove references to plugin sdk ARCHITECTURE.md
* feat: merge host editor terminal tabs into one owned by ssh-terminal
* feat: add descriptions to plugin host enable toggles
* fix(file-manager): show download progress in file viewers (#1487)
* fix(electron): signal backend readiness over IPC (#1488)
* fix(split-screen): allow layout creation without randomUUID (#1490)
* fix(split-screen): allow layout creation without randomUUID
* test(credentials): avoid flaky Ed25519 key generation
* fix(sidebar): remeasure visible rows after density changes (#1489)
* fix(sidebar): remeasure visible rows after density changes
* test(credentials): avoid flaky Ed25519 key generation
* feat(split-screen): redesign split screen with free-form panes and pane picker
* feat(sidebar): add host click behavior setting, default to always opening a new tab
* feat(snippets): redesign panel to match the host list
* fix(session-recording): stop session logs panel from refetching in a loop
* feat(snippets): bring back sharing, target hosts and drag reorder
* feat(ssh-terminal): add toolbar position, start state, display and fade host settings
* feat(ssh-terminal): add host setting to turn off password prompt auto-fill
* fix(ai): stop streams getting cut off and keep tool steps across messages
* feat: improve quick connect system using plugin api
* fix: proxmox guest sync, startup snippet sync, drop dead cloudflare ssh transport
* feat: move terminal settings, look and ssh tools into ssh-terminal plugin
* feat: move snippets, keybinding actions and macros out of core into plugins
* feat: store rdp, vnc and telnet logins in a generic per-protocol table
* feat: type the plugin host record, move plugin strings out of core and add lint checks
* feat: replace core homepage widget registry with generic extension points
* feat: plugins only see their own host settings in the browser
* feat: harden plugin api for separate repos, signed updates and generic external login
* fix: keep plugin css below core utilities and version plugin assets by their css
* fix: load and save plugin host settings in the editor and tighten settings row spacing
* feat: redesign user host defaults system
* fix(remote-desktop): release held keys on focus loss (#1498)
* fix(session-sharing): replace local presentation after takeover (#1500)
* fix(file-manager): refresh disk usage with directory listing (#1503)
* fix(ssh-terminal): preserve input order during local echo reconciliation (#1505)
* feat(remote-desktop): expose display zoom controls for RDP (#1514)
* fix(file-manager): restore text selection and copying in Markdown previews (#1518)
* fix(sidebar): keep compact host addresses visible (#1524)
* fix(hosts): preserve plugin settings when reopening the editor (#1499)
* fix(ssh-terminal): close owner sockets when presentations unmount (#1501)
* fix(session-sharing): synchronize shared SSH terminal dimensions (#1502)
* fix(session-sharing): show participant presence in member terminals (#1504)
* fix(ai): sync provider configuration and keys across linked devices (#1506)
* feat(ssh-terminal): add a duplicate tab action (#1510)
* feat(file-manager): allow disabling move-to-trash confirmation (#1511)
* feat(file-manager): default to the remote login directory (#1512)
* feat(homepage): synchronize canvas layouts across devices (#1515)
* fix(shortcuts): prevent accidental double-Shift palette activation (#1519)
* feat(tmux-monitor): add a unified multi-host view (#1520)
* fix(electron): allow explicit quit with active connections (#1522)
* feat: reconnect all disconnected terminal tabs (#1523)
* fix(hosts): preserve recording and sharing settings in the dev editor (#1509)
* fix(database): preserve RDP domain during startup backfill (#1497)
* feat(sidebar): add keyboard type-ahead search for hosts (#1516)
* feat(automations): add per-host maintenance mode and recurring schedules (#1521)
* feat(tmux): add a per-host mouse toggle and preserve remote configuration (#1513)
* fix(session-sharing): use the linked server for desktop meetings and links (#1507)
* fix(tunnels): support TOTP for client tunnels and jump hosts (#1508)
* fix: type errors and lint failures from merged plugin prs
* feat(installer): make the Windows desktop shortcut optional (#1517)
* fix: ship the plugin sdk and serialport in desktop builds
* fix: prefer ipv4 when resolving ssh host names (#1365)
* fix: readable terminal selection with the light theme (#1319)
* fix: build desktop session share links on the linked server (#1350)
* fix: show meeting guests to members and hide the roster from guests (#1353)
* fix: reliable file manager saves with sudo prompt and no base64 guessing (#1335)
* fix: show disk usage for the mount being browsed (#1347)
* fix: load the linux tray icon reliably and log tray failures (#1332)
* fix: cover the gnome close path in the desktop quit test (#1332)
* fix: prompt for jump host TOTP in terminal, file manager and metrics (#1312)
* feat: optional auto reconnect for dropped ssh sessions (#1321)
* feat: tighter compact host rows with inline tags (#1325)
* feat: bring back the alert feed homepage widget
* feat: pick target terminals for snippets again
* feat: share button on connection tabs again
* feat: recent servers list when linking the desktop app
* feat: list the fixed app shortcuts in keyboard shortcuts
* fix: translate hardcoded toasts and drop em dashes from ui text
* fix: translate leftover hardcoded ui text
* fix: toolbar files button opens at the shell directory again
* fix: show the remote desktop note under connection origin again
* chore: openapi docs for host metrics manager routes
* chore: openapi docs for undocumented routes and fix two broken doc blocks
* fix: declare terminal.listSessions use for snippet targets
* revert: drop the alert feed widget, the notification center replaces it
* feat: restore the alert feed homepage widget
* fix: quick connect fills the host address from plugin auth editors like tailscale
* fix: docker container logs use the base background color
* chore: fix dependabot alerts and apply safe npm upgrades
* fix: proxmox stats tab reads its switch from plugin host settings
* fix: count plugin ssh logins toward host status and stop showing reachable as a warning
* fix: hide the built-in source pill in the host editor
* fix: host status shows online when the port answers and only warns on a failed login
* fix: drop the top border on the split layout menu
* fix: host defaults tabs sit where the host editor puts them and skip plugins with nothing to default
* fix: remote desktop auth method labels and notes for vnc and telnet
* fix: add description to the web endpoint enable switch
* fix: crowdin sync and pretranslate for plugin locales, run plugin tests on release
* feat: move telemetry out of core into a usage statistics plugin
* fix: recent activity card no longer cuts off host names early
* fix: remove duplicate top border on split screen menu
* fix: redesign session log player controls, fix tooltip overlap and drop dot separators
* fix: file manager and sftp text showing raw i18n keys
* fix: onboarding rerunning for existing users after upgrading
* fix: fleet detail buttons overflowing the sidebar
* fix: session log player scrolling off screen horizontally
* fix: network graph lag when adding hosts and on every render
* fix: maintenance index name, shared host read only view and badge polling
* fix: meeting tabs, workspace tab merging, rail panels as tabs and general ui lag
* chore: update release notes
* fix: remote desktop tabs reconnecting on every tab switch
* fix: build plugin sdk before linting in release workflow
* chore: lint, format, and bump version to 2.9.0
* chore: skip crowdin pre-translate in release for now
* chore: sync Crowdin translations for 2.9.0
---------
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Koi <38512047+datlt4@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
This commit is contained in:
4405 files changed
+1341026
-289722
No files matched your search
@@ -0,0 +1,58 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
getUserSecondFactors: vi.fn(),
|
||||
resetUserSecondFactors: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/api/auth-methods-api", () => api);
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, opts?: Record<string, unknown>) =>
|
||||
opts?.plugin ? `${key}:${opts.plugin}` : key,
|
||||
}),
|
||||
}));
|
||||
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
import { AdminSecondFactorsSection } from "@/sidebar/AdminSecondFactorsSection";
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe("AdminSecondFactorsSection", () => {
|
||||
it("shows a factor whose plugin is off and resets after confirming", async () => {
|
||||
api.getUserSecondFactors.mockResolvedValue([
|
||||
{
|
||||
pluginId: "totp",
|
||||
factorId: "totp",
|
||||
labelKey: "factor",
|
||||
available: true,
|
||||
},
|
||||
{ pluginId: "yubi", factorId: "otp", labelKey: null, available: false },
|
||||
]);
|
||||
api.resetUserSecondFactors.mockResolvedValue(undefined);
|
||||
const onReset = vi.fn();
|
||||
const requestConfirm = vi.fn((_message: string, onConfirm: () => void) =>
|
||||
onConfirm(),
|
||||
);
|
||||
render(
|
||||
<AdminSecondFactorsSection
|
||||
userId="u1"
|
||||
username="alice"
|
||||
heading={<h2>factors</h2>}
|
||||
requestConfirm={requestConfirm}
|
||||
onReset={onReset}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
await screen.findByText("admin.secondFactorUnavailable"),
|
||||
).toBeTruthy();
|
||||
// A plugin's label resolves in its own namespace.
|
||||
expect(screen.getByText("totp:factor")).toBeTruthy();
|
||||
fireEvent.click(screen.getByText("admin.resetSecondFactors"));
|
||||
expect(requestConfirm).toHaveBeenCalled();
|
||||
await waitFor(() =>
|
||||
expect(api.resetUserSecondFactors).toHaveBeenCalledWith("u1"),
|
||||
);
|
||||
expect(onReset).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,43 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { AdminTouchInputSection } from "../../sidebar/AdminTouchInputSection";
|
||||
import { TOUCH_INPUT_DEFAULTS } from "@/types/touch-input-settings";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
describe("AdminTouchInputSection", () => {
|
||||
it("shows simple defaults, keeps tunables collapsed, and resets", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onReset = vi.fn();
|
||||
render(
|
||||
<AdminTouchInputSection
|
||||
open
|
||||
onToggle={vi.fn()}
|
||||
settings={{ ...TOUCH_INPUT_DEFAULTS }}
|
||||
setSettings={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
onReset={onReset}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("admin.touchEnabled")).toBeTruthy();
|
||||
expect(screen.queryByLabelText("admin.touchDragThreshold")).toBeNull();
|
||||
await user.click(screen.getByText("admin.touchAdvanced"));
|
||||
expect(
|
||||
(screen.getByLabelText("admin.touchDragThreshold") as HTMLInputElement)
|
||||
.value,
|
||||
).toBe("6");
|
||||
expect(
|
||||
(
|
||||
screen.getByLabelText(
|
||||
"admin.touchMaximumTicksPerFrame",
|
||||
) as HTMLInputElement
|
||||
).value,
|
||||
).toBe("4");
|
||||
await user.click(screen.getByText("admin.touchResetDefaults"));
|
||||
expect(onReset).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -10,12 +10,7 @@ const api = vi.hoisted(() => ({
|
||||
adminDeleteUserHost: vi.fn(async () => ({})),
|
||||
adminGetUserCredentials: vi.fn(async () => [] as unknown[]),
|
||||
adminDeleteUserCredential: vi.fn(async () => ({})),
|
||||
adminGetUserSnippets: vi.fn(async () => [] as unknown[]),
|
||||
adminCreateUserSnippet: vi.fn(async () => ({})),
|
||||
adminUpdateUserSnippet: vi.fn(async () => ({})),
|
||||
adminDeleteUserSnippet: vi.fn(async () => ({})),
|
||||
adminResetUserPassword: vi.fn(async () => ({ dataWiped: false })),
|
||||
adminDisableUserTotp: vi.fn(async () => ({})),
|
||||
adminExportUserData: vi.fn(async () => ({})),
|
||||
getSessions: vi.fn(async () => ({ sessions: [] as unknown[] })),
|
||||
revokeSession: vi.fn(async () => ({})),
|
||||
@@ -56,7 +51,6 @@ function makeUser(overrides: Partial<AdminUser> = {}): AdminUser {
|
||||
isOidc: false,
|
||||
passwordHash: "hash",
|
||||
dataUnlocked: true,
|
||||
totpEnabled: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -72,7 +66,7 @@ function renderPanel(
|
||||
onBack={callbacks.onBack ?? vi.fn()}
|
||||
onOpenHostTab={callbacks.onOpenHostTab as never}
|
||||
onUserDeleted={callbacks.onUserDeleted ?? vi.fn()}
|
||||
onTotpDisabled={callbacks.onTotpDisabled ?? vi.fn()}
|
||||
onSecondFactorsReset={callbacks.onSecondFactorsReset ?? vi.fn()}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
@@ -89,7 +83,6 @@ describe("AdminUserManagePanel", () => {
|
||||
"admin.manageTabAccount",
|
||||
"admin.manageTabHosts",
|
||||
"admin.manageTabCredentials",
|
||||
"admin.manageTabSnippets",
|
||||
"admin.manageTabSessions",
|
||||
"admin.manageTabDanger",
|
||||
]) {
|
||||
@@ -99,7 +92,6 @@ describe("AdminUserManagePanel", () => {
|
||||
await waitFor(() => {
|
||||
expect(api.adminGetUserHosts).toHaveBeenCalledWith("u2");
|
||||
expect(api.adminGetUserCredentials).toHaveBeenCalledWith("u2");
|
||||
expect(api.adminGetUserSnippets).toHaveBeenCalledWith("u2");
|
||||
expect(api.getUserRoles).toHaveBeenCalledWith("u2");
|
||||
});
|
||||
});
|
||||
@@ -115,7 +107,6 @@ describe("AdminUserManagePanel", () => {
|
||||
|
||||
expect(api.adminGetUserHosts).not.toHaveBeenCalled();
|
||||
expect(api.adminGetUserCredentials).not.toHaveBeenCalled();
|
||||
expect(api.adminGetUserSnippets).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists the user's hosts and opens a tab via the connect button", async () => {
|
||||
@@ -144,43 +135,43 @@ describe("AdminUserManagePanel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("disables TOTP through the confirm dialog", async () => {
|
||||
const onTotpDisabled = vi.fn();
|
||||
renderPanel(makeUser({ totpEnabled: true }), { onTotpDisabled });
|
||||
|
||||
expect(screen.getByText("admin.totpStatusEnabled")).toBeTruthy();
|
||||
await userEvent.click(screen.getByText("admin.disableTotp"));
|
||||
await userEvent.click(screen.getByText("common.confirm"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.adminDisableUserTotp).toHaveBeenCalledWith("u2");
|
||||
expect(onTotpDisabled).toHaveBeenCalled();
|
||||
it("shows a tab a plugin contributes, with the user it manages", async () => {
|
||||
const { registerSlotContribution } =
|
||||
await import("../../shell/action-registry");
|
||||
const dispose = registerSlotContribution("admin.userTabs", {
|
||||
actionId: "fixture.adminTab",
|
||||
titleKey: "fixture.tabTitle",
|
||||
kind: "component",
|
||||
component: ((props: { user: AdminUser }) => (
|
||||
<div>managing {props.user.username}</div>
|
||||
)) as never,
|
||||
});
|
||||
expect(screen.getByText("admin.totpStatusDisabled")).toBeTruthy();
|
||||
try {
|
||||
renderPanel(makeUser());
|
||||
await userEvent.click(screen.getByText("fixture.tabTitle"));
|
||||
expect(screen.getByText("managing bob")).toBeTruthy();
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a snippet for the target user", async () => {
|
||||
renderPanel(makeUser());
|
||||
|
||||
await userEvent.click(screen.getByText("admin.manageTabSnippets"));
|
||||
await userEvent.click(screen.getByText("admin.addSnippetForUser"));
|
||||
await userEvent.type(
|
||||
screen.getByPlaceholderText("admin.snippetNamePlaceholder"),
|
||||
"restart",
|
||||
);
|
||||
await userEvent.type(
|
||||
screen.getByPlaceholderText("admin.snippetContentPlaceholder"),
|
||||
"systemctl restart nginx",
|
||||
);
|
||||
await userEvent.click(screen.getByText("common.save"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.adminCreateUserSnippet).toHaveBeenCalledWith("u2", {
|
||||
name: "restart",
|
||||
content: "systemctl restart nginx",
|
||||
folder: null,
|
||||
});
|
||||
it("shows the locked notice instead of a plugin tab while data is locked", async () => {
|
||||
const { registerSlotContribution } =
|
||||
await import("../../shell/action-registry");
|
||||
const dispose = registerSlotContribution("admin.userTabs", {
|
||||
actionId: "fixture.adminTab",
|
||||
titleKey: "fixture.tabTitle",
|
||||
kind: "component",
|
||||
component: (() => <div>plugin content</div>) as never,
|
||||
});
|
||||
try {
|
||||
renderPanel(makeUser({ dataUnlocked: false }));
|
||||
await userEvent.click(screen.getByText("fixture.tabTitle"));
|
||||
expect(screen.queryByText("plugin content")).toBeNull();
|
||||
expect(screen.getByText("admin.dataLockedNotice")).toBeTruthy();
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("deletes the user from the danger tab after confirmation", async () => {
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
} from "@testing-library/react";
|
||||
import type { NotificationChannel } from "@/api/alerts-api";
|
||||
|
||||
const alertsApi = vi.hoisted(() => ({
|
||||
getAlertFirings: vi.fn(async () => []),
|
||||
acknowledgeAlertFiring: vi.fn(async () => {}),
|
||||
acknowledgeAllAlertFirings: vi.fn(async () => {}),
|
||||
getAlertRules: vi.fn(async () => []),
|
||||
getNotificationChannels: vi.fn(async () => [] as NotificationChannel[]),
|
||||
deleteAlertRule: vi.fn(async () => {}),
|
||||
deleteNotificationChannel: vi.fn(async () => {}),
|
||||
testNotificationChannel: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@/api/alerts-api", () => alertsApi);
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (_key: string, fallback?: string) => fallback ?? _key,
|
||||
}),
|
||||
}));
|
||||
|
||||
// A real (non-null) fake so tests can see what channels actually reach the
|
||||
// rule dialog, instead of only asserting the API call count.
|
||||
vi.mock("../../sidebar/AlertRuleDialog", () => ({
|
||||
AlertRuleDialog: ({
|
||||
open,
|
||||
channels,
|
||||
}: {
|
||||
open: boolean;
|
||||
channels: NotificationChannel[];
|
||||
}) =>
|
||||
open ? (
|
||||
<div data-testid="rule-dialog-channels">
|
||||
{channels.length === 0
|
||||
? "no channels"
|
||||
: channels.map((c) => c.name).join(",")}
|
||||
</div>
|
||||
) : null,
|
||||
}));
|
||||
vi.mock("../../sidebar/NotificationChannelDialog", () => ({
|
||||
NotificationChannelDialog: () => null,
|
||||
}));
|
||||
|
||||
import { AlertsPanel } from "../../sidebar/AlertsPanel";
|
||||
|
||||
function channel(
|
||||
overrides: Partial<NotificationChannel> = {},
|
||||
): NotificationChannel {
|
||||
return {
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "ntfy",
|
||||
type: "ntfy",
|
||||
config: "{}",
|
||||
enabled: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
alertsApi.getAlertFirings.mockReset().mockResolvedValue([]);
|
||||
alertsApi.getAlertRules.mockReset().mockResolvedValue([]);
|
||||
alertsApi.getNotificationChannels.mockReset().mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("AlertsPanel - notification channels", () => {
|
||||
it("loads notification channels on mount, before the Channels tab is ever opened", async () => {
|
||||
alertsApi.getNotificationChannels.mockResolvedValue([channel()]);
|
||||
|
||||
render(<AlertsPanel />);
|
||||
|
||||
// Regression: channels used to only load once the user switched to the
|
||||
// "channels" tab, so editing a rule before ever visiting that tab showed
|
||||
// an empty channel picker even though channels existed.
|
||||
await waitFor(() => {
|
||||
expect(alertsApi.getNotificationChannels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it("populates the rule dialog's channel picker without ever visiting the Channels tab", async () => {
|
||||
alertsApi.getNotificationChannels.mockResolvedValue([
|
||||
channel({ id: 1, name: "ntfy-home" }),
|
||||
channel({ id: 2, name: "webhook-slack" }),
|
||||
]);
|
||||
|
||||
render(<AlertsPanel />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertsApi.getNotificationChannels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Go straight to Rules and open the "new rule" dialog, skipping Channels
|
||||
// entirely, this is exactly the sequence the original bug broke.
|
||||
fireEvent.click(screen.getByText("Rules"));
|
||||
fireEvent.click(screen.getByText("Add"));
|
||||
|
||||
expect(screen.getByTestId("rule-dialog-channels").textContent).toBe(
|
||||
"ntfy-home,webhook-slack",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not refetch channels again when switching to the Rules tab", async () => {
|
||||
render(<AlertsPanel />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertsApi.getNotificationChannels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Switching tabs only reloads rules here, not channels, since channels
|
||||
// were already fetched on mount by the fix under test.
|
||||
fireEvent.click(screen.getByText("Rules"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(alertsApi.getAlertRules).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(alertsApi.getNotificationChannels).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { Bell, Boxes } from "lucide-react";
|
||||
import { AppRail } from "../../sidebar/AppRail";
|
||||
import { RailBadge } from "../../sidebar/RailBadge";
|
||||
import {
|
||||
registerRailItem,
|
||||
resetRegisteredRailItems,
|
||||
} from "../../sidebar/rail-items";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-permissions", () => ({
|
||||
usePermissions: () => ({ has: () => true, loaded: true }),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
resetRegisteredRailItems();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
function renderRail(onRailClick = vi.fn()) {
|
||||
render(
|
||||
<AppRail
|
||||
railView="hosts"
|
||||
sidebarOpen={false}
|
||||
username="alice"
|
||||
isAdmin={false}
|
||||
onRailClick={onRailClick}
|
||||
onLogout={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
return onRailClick;
|
||||
}
|
||||
|
||||
describe("AppRail", () => {
|
||||
it("puts a footer item above the profile with its badge", async () => {
|
||||
registerRailItem({
|
||||
id: "inbox",
|
||||
icon: Bell,
|
||||
labelKey: "test.inbox",
|
||||
placement: "footer",
|
||||
useBadge: () => 3,
|
||||
pluginId: "demo",
|
||||
});
|
||||
registerRailItem({
|
||||
id: "boxes",
|
||||
icon: Boxes,
|
||||
labelKey: "test.boxes",
|
||||
pluginId: "demo",
|
||||
});
|
||||
const onRailClick = renderRail();
|
||||
|
||||
const inbox = screen.getByTitle("test.inbox");
|
||||
const profile = screen.getAllByTitle("nav.userProfile")[0];
|
||||
const boxes = screen.getByTitle("test.boxes");
|
||||
// Footer items render after the main list and before the profile.
|
||||
expect(
|
||||
boxes.compareDocumentPosition(inbox) & Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
inbox.compareDocumentPosition(profile) & Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
).toBeTruthy();
|
||||
expect(inbox.textContent).toContain("3");
|
||||
|
||||
await userEvent.click(inbox);
|
||||
expect(onRailClick).toHaveBeenCalledWith("inbox");
|
||||
});
|
||||
|
||||
it("hides a footer item the user hid from Navigation", () => {
|
||||
localStorage.setItem("hiddenRailTabs", JSON.stringify(["inbox"]));
|
||||
registerRailItem({
|
||||
id: "inbox",
|
||||
icon: Bell,
|
||||
labelKey: "test.inbox",
|
||||
placement: "footer",
|
||||
pluginId: "demo",
|
||||
});
|
||||
renderRail();
|
||||
expect(screen.queryByTitle("test.inbox")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("RailBadge", () => {
|
||||
it("shows nothing for zero", () => {
|
||||
const { container } = render(<RailBadge useBadge={() => 0} />);
|
||||
expect(container.textContent).toBe("");
|
||||
});
|
||||
|
||||
it("caps a large count", () => {
|
||||
render(<RailBadge useBadge={() => 150} />);
|
||||
expect(screen.getByText("99+")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
} from "@testing-library/react";
|
||||
import { render, screen, waitFor, cleanup } from "@testing-library/react";
|
||||
import type { ActiveSessionInfo } from "@/api/open-tabs-api";
|
||||
|
||||
const mainAxios = vi.hoisted(() => ({
|
||||
@@ -23,136 +17,62 @@ vi.mock("react-i18next", () => ({
|
||||
}));
|
||||
|
||||
import { ConnectionsPanel } from "../../sidebar/ConnectionsPanel";
|
||||
|
||||
function sharedSession(
|
||||
overrides: Partial<ActiveSessionInfo> = {},
|
||||
): ActiveSessionInfo {
|
||||
return {
|
||||
sessionId: "sess-shared-1",
|
||||
hostId: 5,
|
||||
hostName: "prod-db",
|
||||
tabInstanceId: null,
|
||||
isConnected: true,
|
||||
createdAt: Date.now(),
|
||||
isOwnSession: false,
|
||||
sharedByUsername: "alice",
|
||||
permissionLevel: "read-only",
|
||||
shareId: "share-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
import {
|
||||
registerSlotContribution,
|
||||
resetActionRegistry,
|
||||
} from "../../shell/action-registry";
|
||||
|
||||
beforeEach(() => {
|
||||
mainAxios.getActiveSessions.mockReset();
|
||||
mainAxios.getActiveSessions.mockResolvedValue([]);
|
||||
mainAxios.deleteOpenTab.mockReset();
|
||||
resetActionRegistry();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
describe("ConnectionsPanel - shared with me", () => {
|
||||
it("renders a shared-with-me row for sessions the current user does not own", async () => {
|
||||
mainAxios.getActiveSessions.mockResolvedValue([sharedSession()]);
|
||||
function renderPanel() {
|
||||
return render(
|
||||
<ConnectionsPanel
|
||||
tabs={[]}
|
||||
activeTabId=""
|
||||
allHosts={[]}
|
||||
backgroundTabRecords={[]}
|
||||
onSwitchToTab={() => {}}
|
||||
onCloseTab={() => {}}
|
||||
onReopenTab={() => {}}
|
||||
onForgetBackground={() => {}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
render(
|
||||
<ConnectionsPanel
|
||||
tabs={[]}
|
||||
activeTabId=""
|
||||
allHosts={[]}
|
||||
backgroundTabRecords={[]}
|
||||
onSwitchToTab={() => {}}
|
||||
onCloseTab={() => {}}
|
||||
onReopenTab={() => {}}
|
||||
onForgetBackground={() => {}}
|
||||
/>,
|
||||
);
|
||||
describe("ConnectionsPanel - plugin sections", () => {
|
||||
it("renders what plugins add to connections.sections, even with no tabs", async () => {
|
||||
const Section = vi.fn(({ search }: { search?: string }) => (
|
||||
<div>plugin section {JSON.stringify(search)}</div>
|
||||
));
|
||||
registerSlotContribution("connections.sections", {
|
||||
actionId: "demo.section",
|
||||
titleKey: "demo.section",
|
||||
kind: "component",
|
||||
component: Section as never,
|
||||
});
|
||||
|
||||
renderPanel();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("connections.sectionSharedWithMe")).toBeTruthy();
|
||||
expect(screen.getByText('plugin section ""')).toBeTruthy();
|
||||
});
|
||||
expect(screen.getByText("prod-db")).toBeTruthy();
|
||||
expect(
|
||||
screen.getByText('connections.sharedBy:{"username":"alice"}'),
|
||||
).toBeTruthy();
|
||||
expect(screen.getByText("connections.noConnections")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not show own sessions in the shared-with-me section", async () => {
|
||||
mainAxios.getActiveSessions.mockResolvedValue([
|
||||
sharedSession({
|
||||
isOwnSession: true,
|
||||
sharedByUsername: null,
|
||||
shareId: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
render(
|
||||
<ConnectionsPanel
|
||||
tabs={[]}
|
||||
activeTabId=""
|
||||
allHosts={[]}
|
||||
backgroundTabRecords={[]}
|
||||
onSwitchToTab={() => {}}
|
||||
onCloseTab={() => {}}
|
||||
onReopenTab={() => {}}
|
||||
onForgetBackground={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
it("renders only the empty state without plugin sections", async () => {
|
||||
renderPanel();
|
||||
await waitFor(() => {
|
||||
expect(mainAxios.getActiveSessions).toHaveBeenCalled();
|
||||
});
|
||||
expect(screen.queryByText("connections.sectionSharedWithMe")).toBeNull();
|
||||
});
|
||||
|
||||
it("dispatches onJoinSharedSession with the session when Join is clicked", async () => {
|
||||
const session = sharedSession();
|
||||
mainAxios.getActiveSessions.mockResolvedValue([session]);
|
||||
const onJoinSharedSession = vi.fn();
|
||||
|
||||
render(
|
||||
<ConnectionsPanel
|
||||
tabs={[]}
|
||||
activeTabId=""
|
||||
allHosts={[]}
|
||||
backgroundTabRecords={[]}
|
||||
onSwitchToTab={() => {}}
|
||||
onCloseTab={() => {}}
|
||||
onReopenTab={() => {}}
|
||||
onForgetBackground={() => {}}
|
||||
onJoinSharedSession={onJoinSharedSession}
|
||||
/>,
|
||||
);
|
||||
|
||||
const joinButton = await screen.findByText("connections.join");
|
||||
fireEvent.click(joinButton);
|
||||
|
||||
expect(onJoinSharedSession).toHaveBeenCalledWith(session);
|
||||
});
|
||||
|
||||
it("shows a read-write badge for read-write shared sessions", async () => {
|
||||
mainAxios.getActiveSessions.mockResolvedValue([
|
||||
sharedSession({ permissionLevel: "read-write" }),
|
||||
]);
|
||||
|
||||
render(
|
||||
<ConnectionsPanel
|
||||
tabs={[]}
|
||||
activeTabId=""
|
||||
allHosts={[]}
|
||||
backgroundTabRecords={[]}
|
||||
onSwitchToTab={() => {}}
|
||||
onCloseTab={() => {}}
|
||||
onReopenTab={() => {}}
|
||||
onForgetBackground={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText("sessionSharing.permissionLevel.readWrite"),
|
||||
).toBeTruthy();
|
||||
});
|
||||
expect(screen.getByText("connections.noConnections")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import {
|
||||
FixedShortcutsList,
|
||||
fixedShortcuts,
|
||||
} from "@/sidebar/FixedShortcutsList";
|
||||
|
||||
describe("FixedShortcutsList", () => {
|
||||
it("lists every shell shortcut with its keys", () => {
|
||||
render(<FixedShortcutsList />);
|
||||
expect(
|
||||
screen.getByText("newUi.sidebar.keybindings.fixed.splitRight"),
|
||||
).toBeTruthy();
|
||||
expect(screen.getAllByText("Shift").length).toBeGreaterThan(3);
|
||||
expect(fixedShortcuts().map((s) => s.labelKey)).toContain("jumpTab");
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,7 @@ vi.mock("react-i18next", () => ({
|
||||
|
||||
import { HostAuthOverrideModal } from "../../sidebar/HostAuthOverrideModal";
|
||||
import { canOverrideHostAuth } from "../../sidebar/host-permissions";
|
||||
import { registerHostProtocol } from "../../sidebar/host-protocols";
|
||||
|
||||
const host = {
|
||||
id: "42",
|
||||
@@ -48,7 +49,7 @@ const host = {
|
||||
ownerAuthShared: false,
|
||||
},
|
||||
},
|
||||
} as Host;
|
||||
} as unknown as Host;
|
||||
|
||||
beforeEach(() => {
|
||||
api.getCredentials.mockReset();
|
||||
@@ -102,8 +103,8 @@ describe("HostAuthOverrideModal", () => {
|
||||
fireEvent.click(screen.getByText("common.save"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.getHostAuthOverride).toHaveBeenCalledWith(42, "ssh");
|
||||
expect(api.setHostAuthOverride).toHaveBeenCalledWith(42, "ssh", 8);
|
||||
expect(api.getHostAuthOverride).toHaveBeenCalledWith(42, "ssh", null);
|
||||
expect(api.setHostAuthOverride).toHaveBeenCalledWith(42, "ssh", 8, null);
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
});
|
||||
@@ -127,7 +128,12 @@ describe("HostAuthOverrideModal", () => {
|
||||
fireEvent.click(screen.getByText("common.save"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(api.setHostAuthOverride).toHaveBeenCalledWith(42, "ssh", null);
|
||||
expect(api.setHostAuthOverride).toHaveBeenCalledWith(
|
||||
42,
|
||||
"ssh",
|
||||
null,
|
||||
null,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,7 +165,7 @@ describe("HostAuthOverrideModal", () => {
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("loads credentials and overrides from the remote server for remote-only shared hosts", async () => {
|
||||
it("loads credentials and overrides from the server for a synced shared copy", async () => {
|
||||
remote.get.mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
@@ -176,7 +182,7 @@ describe("HostAuthOverrideModal", () => {
|
||||
<HostAuthOverrideModal
|
||||
open
|
||||
onOpenChange={() => {}}
|
||||
host={{ ...host, id: "-42" }}
|
||||
host={{ ...host, sharedCopy: true, syncId: "host-sync-42" } as Host}
|
||||
protocol="ssh"
|
||||
/>,
|
||||
);
|
||||
@@ -187,7 +193,11 @@ describe("HostAuthOverrideModal", () => {
|
||||
expect((select as HTMLSelectElement).value).toBe("19");
|
||||
expect(remote.get).toHaveBeenCalledWith("/credentials");
|
||||
expect(api.getCredentials).not.toHaveBeenCalled();
|
||||
expect(api.getHostAuthOverride).toHaveBeenCalledWith(-42, "ssh", true);
|
||||
expect(api.getHostAuthOverride).toHaveBeenCalledWith(
|
||||
42,
|
||||
"ssh",
|
||||
"host-sync-42",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders empty and load-error states", async () => {
|
||||
@@ -238,9 +248,27 @@ describe("canOverrideHostAuth", () => {
|
||||
expect(
|
||||
canOverrideHostAuth({ ...host, enableSsh: false } as Host, "ssh"),
|
||||
).toBe(false);
|
||||
const dispose = registerHostProtocol({
|
||||
id: "rdp",
|
||||
pluginId: "demo",
|
||||
settingKey: "enableRdp",
|
||||
defaultPort: 3389,
|
||||
titleKey: "rdp",
|
||||
icon: () => null,
|
||||
});
|
||||
expect(
|
||||
canOverrideHostAuth({ ...host, enableRdp: true } as Host, "rdp"),
|
||||
canOverrideHostAuth(
|
||||
{ ...host, pluginSettings: { demo: { enableRdp: true } } } as Host,
|
||||
"rdp",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(canOverrideHostAuth(host, "rdp")).toBe(false);
|
||||
dispose();
|
||||
expect(
|
||||
canOverrideHostAuth(
|
||||
{ ...host, pluginSettings: { demo: { enableRdp: true } } } as Host,
|
||||
"rdp",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { HostCredentialList } from "@/sidebar/HostCredentialList";
|
||||
import type { Credential, Host } from "@/types/ui-types";
|
||||
|
||||
vi.mock("@/main-axios", () => ({
|
||||
getCredentialDetails: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
function makeCredential(overrides: Partial<Credential> = {}): Credential {
|
||||
return {
|
||||
id: "1",
|
||||
name: "Deploy Key",
|
||||
username: "ubuntu",
|
||||
type: "key",
|
||||
folder: "Shared",
|
||||
tags: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHost(overrides: Partial<Host>): Host {
|
||||
return {
|
||||
id: "host-1",
|
||||
name: "prod-api",
|
||||
username: "ubuntu",
|
||||
ip: "10.0.0.1",
|
||||
port: 22,
|
||||
folder: "",
|
||||
online: false,
|
||||
cpu: null,
|
||||
ram: null,
|
||||
lastAccess: "",
|
||||
authType: "credential",
|
||||
enableTerminal: true,
|
||||
enableTerminalToolbar: true,
|
||||
enableAiAssistant: false,
|
||||
enableCommandHistory: true,
|
||||
enableTunnel: false,
|
||||
serverTunnels: [],
|
||||
enableFileManager: true,
|
||||
enableDocker: false,
|
||||
enableProxmox: false,
|
||||
enableProxmoxStats: false,
|
||||
enableTmuxMonitor: false,
|
||||
quickActions: [],
|
||||
enableSsh: true,
|
||||
enableRdp: false,
|
||||
enableVnc: false,
|
||||
enableTelnet: false,
|
||||
sshPort: 22,
|
||||
rdpPort: 3389,
|
||||
vncPort: 5900,
|
||||
telnetPort: 23,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function renderOpenedList({
|
||||
credentials = [makeCredential()],
|
||||
hosts = [],
|
||||
}: {
|
||||
credentials?: Credential[];
|
||||
hosts?: Host[];
|
||||
} = {}) {
|
||||
render(
|
||||
<HostCredentialList
|
||||
credentialFolders={["Shared"]}
|
||||
filteredCredentials={credentials}
|
||||
credentialsLoading={false}
|
||||
allHosts={hosts}
|
||||
editingFolderName={null}
|
||||
editingFolderValue=""
|
||||
termixIdLinkedIds={new Set()}
|
||||
onEditingFolderNameChange={vi.fn()}
|
||||
onEditingFolderValueChange={vi.fn()}
|
||||
onRenameFolder={vi.fn()}
|
||||
onDeployCredential={vi.fn()}
|
||||
onEditCredential={vi.fn()}
|
||||
onDeleteCredential={vi.fn()}
|
||||
onAddCredential={vi.fn()}
|
||||
onConfirmDialogChange={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByText("Shared"));
|
||||
}
|
||||
|
||||
describe("HostCredentialList credential usage", () => {
|
||||
it("shows the SSH host using a credential", async () => {
|
||||
await renderOpenedList({
|
||||
hosts: [makeHost({ id: "host-1", name: "prod-api", credentialId: "1" })],
|
||||
});
|
||||
|
||||
expect(screen.getByText("prod-api")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows two host names and a compact remaining count", async () => {
|
||||
await renderOpenedList({
|
||||
hosts: [
|
||||
makeHost({ id: "host-1", name: "prod-api", credentialId: "1" }),
|
||||
makeHost({ id: "host-2", name: "jump-box", credentialId: "1" }),
|
||||
makeHost({ id: "host-3", name: "worker-01", credentialId: "1" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(screen.getByText("prod-api")).toBeTruthy();
|
||||
expect(screen.getByText("jump-box")).toBeTruthy();
|
||||
expect(screen.getByText("+1")).toBeTruthy();
|
||||
expect(screen.queryByText("worker-01")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not show host chips when no SSH host uses the credential", async () => {
|
||||
await renderOpenedList();
|
||||
|
||||
expect(screen.queryByLabelText(/^Used by /)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not count non-SSH protocol credential ids", async () => {
|
||||
await renderOpenedList({
|
||||
hosts: [
|
||||
makeHost({
|
||||
id: "host-1",
|
||||
name: "rdp-only",
|
||||
authType: "password",
|
||||
credentialId: undefined,
|
||||
rdpCredentialId: "1",
|
||||
enableSsh: false,
|
||||
enableRdp: true,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(screen.queryByText("rdp-only")).toBeNull();
|
||||
expect(screen.queryByLabelText(/^Used by /)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { registerHostProtocol } from "../../sidebar/host-protocols";
|
||||
import {
|
||||
applyHostDraft,
|
||||
createHostEditorForm,
|
||||
buildHostEditorPayload,
|
||||
omitOwnerSshAuthFromSharedEdit,
|
||||
@@ -7,6 +9,7 @@ import {
|
||||
type HostProtocols,
|
||||
} from "../../sidebar/HostEditorData";
|
||||
import type { Host } from "@/types/ui-types";
|
||||
import { HOST_PROTOCOL_SECRET_KEPT } from "@termix/plugin-sdk/frontend";
|
||||
|
||||
const sshOnly: HostProtocols = {
|
||||
enableSsh: true,
|
||||
@@ -22,20 +25,6 @@ const rdpOnly: HostProtocols = {
|
||||
enableTelnet: false,
|
||||
};
|
||||
|
||||
const vncOnly: HostProtocols = {
|
||||
enableSsh: false,
|
||||
enableRdp: false,
|
||||
enableVnc: true,
|
||||
enableTelnet: false,
|
||||
};
|
||||
|
||||
const telnetOnly: HostProtocols = {
|
||||
enableSsh: false,
|
||||
enableRdp: false,
|
||||
enableVnc: false,
|
||||
enableTelnet: true,
|
||||
};
|
||||
|
||||
describe("omitOwnerSshAuthFromSharedEdit", () => {
|
||||
it("keeps editable host settings but removes all owner SSH authentication fields", () => {
|
||||
const form = createHostEditorForm(null);
|
||||
@@ -49,7 +38,6 @@ describe("omitOwnerSshAuthFromSharedEdit", () => {
|
||||
key: "owner-key",
|
||||
keyPassword: "owner-passphrase",
|
||||
keyType: "ssh-ed25519",
|
||||
vaultProfileId: "9",
|
||||
overrideCredentialUsername: true,
|
||||
shareSshAuth: true,
|
||||
sudoPassword: "owner-sudo",
|
||||
@@ -64,12 +52,10 @@ describe("omitOwnerSshAuthFromSharedEdit", () => {
|
||||
expect(sharedEdit.name).toBe(payload.name);
|
||||
expect(sharedEdit.ip).toBe("10.0.0.42");
|
||||
expect(sharedEdit.notes).toBe("editable");
|
||||
expect(sharedEdit.terminalConfig?.sudoPassword).toBeUndefined();
|
||||
expect(sharedEdit.terminalConfig?.agentSocketPath).toBeUndefined();
|
||||
expect(sharedEdit.sshOptions?.agentSocketPath).toBeUndefined();
|
||||
for (const field of [
|
||||
"authType",
|
||||
"credentialId",
|
||||
"vaultProfileId",
|
||||
"overrideCredentialUsername",
|
||||
"shareSshAuth",
|
||||
"password",
|
||||
@@ -127,32 +113,6 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
expect(payload.password).toBe("newpass");
|
||||
});
|
||||
|
||||
it("drops the vaultProfileId when switching a host away from vault auth", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
authType: "password" as const,
|
||||
password: "newpass",
|
||||
vaultProfileId: "9",
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.vaultProfileId).toBeNull();
|
||||
expect(payload.password).toBe("newpass");
|
||||
});
|
||||
|
||||
it("sends vaultProfileId when authType is vault", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
authType: "vault" as const,
|
||||
vaultProfileId: "9",
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.vaultProfileId).toBe(9);
|
||||
});
|
||||
|
||||
it("sends credentialId and optional password when authType is credential", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
@@ -195,10 +155,7 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload.sshOptions as unknown as Record<string, unknown> | null;
|
||||
|
||||
expect(tc?.agentSocketPath).toBe("/run/user/1000/gnupg/S.gpg-agent.ssh");
|
||||
expect(payload.password).toBeNull();
|
||||
@@ -213,10 +170,7 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload.sshOptions as unknown as Record<string, unknown> | null;
|
||||
|
||||
expect(tc?.agentSocketPath).toBeNull();
|
||||
});
|
||||
@@ -230,15 +184,12 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload.sshOptions as unknown as Record<string, unknown> | null;
|
||||
|
||||
expect(tc?.agentSocketPath).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves agentIdentity in terminalConfig when authType is agent", () => {
|
||||
it("preserves agentIdentity in sshOptions when authType is agent", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
authType: "agent" as const,
|
||||
@@ -246,10 +197,7 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload.sshOptions as unknown as Record<string, unknown> | null;
|
||||
|
||||
expect(tc?.agentIdentity).toBe(
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA test-key",
|
||||
@@ -265,15 +213,12 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload.sshOptions as unknown as Record<string, unknown> | null;
|
||||
|
||||
expect(tc?.agentIdentity).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps agentIdentity in terminalConfig for shared edits (not owner-private)", () => {
|
||||
it("keeps agentIdentity in sshOptions for shared edits (not owner-private)", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
authType: "agent" as const,
|
||||
@@ -283,27 +228,10 @@ describe("buildHostEditorPayload auth field isolation", () => {
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const sharedEdit = omitOwnerSshAuthFromSharedEdit(payload);
|
||||
|
||||
expect(sharedEdit.terminalConfig?.agentIdentity).toBe(
|
||||
expect(sharedEdit.sshOptions?.agentIdentity).toBe(
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA test-key",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves sudo password autofill settings", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
sudoPasswordAutoFill: true,
|
||||
sudoPassword: "sudo-secret",
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
|
||||
expect(tc?.sudoPasswordAutoFill).toBe(true);
|
||||
expect(tc?.sudoPassword).toBe("sudo-secret");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sudo password persistence indicator", () => {
|
||||
@@ -319,10 +247,7 @@ describe("sudo password persistence indicator", () => {
|
||||
const form = { ...createHostEditorForm(host) };
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload as unknown as Record<string, unknown>;
|
||||
|
||||
expect(tc?.sudoPassword).toBeUndefined();
|
||||
expect(JSON.parse(JSON.stringify(tc))).not.toHaveProperty("sudoPassword");
|
||||
@@ -336,15 +261,12 @@ describe("sudo password persistence indicator", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload as unknown as Record<string, unknown>;
|
||||
|
||||
expect(tc?.sudoPassword).toBe("new-sudo-pass");
|
||||
});
|
||||
|
||||
it("sends null to explicitly clear a saved sudo password", () => {
|
||||
it("sends an empty value to explicitly clear a saved sudo password", () => {
|
||||
const host = { hasSudoPassword: true } as Host;
|
||||
const form = {
|
||||
...createHostEditorForm(host),
|
||||
@@ -352,262 +274,133 @@ describe("sudo password persistence indicator", () => {
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
const tc = payload.terminalConfig as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
> | null;
|
||||
const tc = payload as unknown as Record<string, unknown>;
|
||||
|
||||
expect(tc?.sudoPassword).toBeNull();
|
||||
expect(tc?.sudoPassword).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Proxmox / Proxmox Stats independent toggles", () => {
|
||||
it("defaults enableProxmoxStats to false with sane pollInterval/nodeName defaults", () => {
|
||||
const form = createHostEditorForm(null);
|
||||
|
||||
expect(form.enableProxmoxStats).toBe(false);
|
||||
expect(form.proxmoxStatsConfig).toEqual({
|
||||
pollInterval: 60,
|
||||
nodeName: null,
|
||||
});
|
||||
expect(form.enableProxmox).toBe(false);
|
||||
});
|
||||
|
||||
it("seeds both configs independently from an existing host", () => {
|
||||
describe("plugin host settings", () => {
|
||||
it("keeps them on the form and out of the host payload", () => {
|
||||
const host = {
|
||||
enableProxmox: true,
|
||||
proxmoxConfig: { windowsPatterns: "win", dockerPatterns: "docker" },
|
||||
enableProxmoxStats: true,
|
||||
proxmoxStatsConfig: { pollInterval: 30, nodeName: "pve-custom" },
|
||||
pluginSettings: { proxmox: { enableProxmox: true } },
|
||||
} as unknown as Host;
|
||||
|
||||
const form = createHostEditorForm(host);
|
||||
|
||||
expect(form.enableProxmox).toBe(true);
|
||||
expect(form.enableProxmoxStats).toBe(true);
|
||||
expect(form.proxmoxStatsConfig).toEqual({
|
||||
pollInterval: 30,
|
||||
nodeName: "pve-custom",
|
||||
});
|
||||
});
|
||||
|
||||
it("nulls proxmoxStatsConfig in the payload when enableProxmoxStats is off, regardless of enableProxmox", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
enableProxmox: true,
|
||||
proxmoxConfig: {
|
||||
defaultCredentialId: null,
|
||||
defaultAuthType: "password",
|
||||
windowsPatterns: "win",
|
||||
dockerPatterns: "docker",
|
||||
preferredPrefixes: "",
|
||||
},
|
||||
enableProxmoxStats: false,
|
||||
proxmoxStatsConfig: { pollInterval: 45, nodeName: "leftover" },
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.enableProxmox).toBe(true);
|
||||
expect(payload.proxmoxConfig).not.toBeNull();
|
||||
expect(payload.enableProxmoxStats).toBe(false);
|
||||
expect(payload.proxmoxStatsConfig).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps proxmoxConfig null in the payload when enableProxmox is off, even though enableProxmoxStats is on", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
enableProxmox: false,
|
||||
enableProxmoxStats: true,
|
||||
proxmoxStatsConfig: { pollInterval: 90, nodeName: "pve1" },
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.enableProxmox).toBe(false);
|
||||
expect(payload.proxmoxConfig).toBeNull();
|
||||
expect(payload.enableProxmoxStats).toBe(true);
|
||||
expect(payload.proxmoxStatsConfig).toEqual({
|
||||
pollInterval: 90,
|
||||
nodeName: "pve1",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the source identity when editing an imported Proxmox guest", () => {
|
||||
const source = {
|
||||
source: "proxmox" as const,
|
||||
sourceHostId: 7,
|
||||
node: "pve1",
|
||||
vmid: 101,
|
||||
type: "qemu" as const,
|
||||
lastSeenAt: "2026-08-14T00:00:00.000Z",
|
||||
lastStatus: "running",
|
||||
missingSince: null,
|
||||
};
|
||||
const form = {
|
||||
...createHostEditorForm({
|
||||
enableProxmox: false,
|
||||
proxmoxConfig: { source },
|
||||
} as unknown as Host),
|
||||
name: "Edited guest",
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.enableProxmox).toBe(false);
|
||||
expect(payload.proxmoxConfig).toEqual({ source });
|
||||
});
|
||||
|
||||
it("sends both configs when both toggles are on", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
enableProxmox: true,
|
||||
proxmoxConfig: {
|
||||
defaultCredentialId: null,
|
||||
defaultAuthType: "password",
|
||||
windowsPatterns: "win",
|
||||
dockerPatterns: "docker",
|
||||
preferredPrefixes: "",
|
||||
},
|
||||
enableProxmoxStats: true,
|
||||
proxmoxStatsConfig: { pollInterval: 60, nodeName: null },
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload.enableProxmox).toBe(true);
|
||||
expect(payload.proxmoxConfig).not.toBeNull();
|
||||
expect(payload.enableProxmoxStats).toBe(true);
|
||||
expect(payload.proxmoxStatsConfig).toEqual({
|
||||
pollInterval: 60,
|
||||
nodeName: null,
|
||||
});
|
||||
expect(form.pluginSettings).toEqual({ proxmox: { enableProxmox: true } });
|
||||
expect(payload).not.toHaveProperty("enableProxmox");
|
||||
expect(payload).not.toHaveProperty("pluginSettings");
|
||||
});
|
||||
});
|
||||
|
||||
describe("RDP/VNC/Telnet password persistence indicator", () => {
|
||||
it("seeds a sentinel value when the host reports a saved rdp password", () => {
|
||||
const host = {
|
||||
hasRdpPassword: true,
|
||||
rdpAuthType: "direct",
|
||||
} as Host;
|
||||
|
||||
const form = createHostEditorForm(host);
|
||||
|
||||
expect(form.rdpPassword).toBe("existing_rdp_password");
|
||||
});
|
||||
|
||||
it("does not send the rdp sentinel back to the backend unchanged", () => {
|
||||
const host = { hasRdpPassword: true, rdpAuthType: "direct" } as Host;
|
||||
const form = { ...createHostEditorForm(host) };
|
||||
|
||||
const payload = buildHostEditorPayload(form, rdpOnly);
|
||||
|
||||
expect(payload.rdpPassword).toBeNull();
|
||||
});
|
||||
|
||||
it("sends a newly typed rdp password", () => {
|
||||
const host = { hasRdpPassword: true, rdpAuthType: "direct" } as Host;
|
||||
const form = {
|
||||
...createHostEditorForm(host),
|
||||
rdpPassword: "new-rdp-pass",
|
||||
};
|
||||
|
||||
const payload = buildHostEditorPayload(form, rdpOnly);
|
||||
|
||||
expect(payload.rdpPassword).toBe("new-rdp-pass");
|
||||
});
|
||||
|
||||
it("seeds a sentinel value when the host reports a saved vnc password", () => {
|
||||
const host = { hasVncPassword: true, vncAuthType: "direct" } as Host;
|
||||
const form = createHostEditorForm(host);
|
||||
|
||||
expect(form.vncPassword).toBe("existing_vnc_password");
|
||||
});
|
||||
|
||||
it("does not send the vnc sentinel back to the backend unchanged", () => {
|
||||
const host = { hasVncPassword: true, vncAuthType: "direct" } as Host;
|
||||
const form = { ...createHostEditorForm(host) };
|
||||
|
||||
const payload = buildHostEditorPayload(form, vncOnly);
|
||||
|
||||
expect(payload.vncPassword).toBeNull();
|
||||
});
|
||||
|
||||
it("seeds a sentinel value when the host reports a saved telnet password", () => {
|
||||
const host = {
|
||||
hasTelnetPassword: true,
|
||||
telnetAuthType: "direct",
|
||||
} as Host;
|
||||
const form = createHostEditorForm(host);
|
||||
|
||||
expect(form.telnetPassword).toBe("existing_telnet_password");
|
||||
});
|
||||
|
||||
it("does not send the telnet sentinel back to the backend unchanged", () => {
|
||||
const host = {
|
||||
hasTelnetPassword: true,
|
||||
telnetAuthType: "direct",
|
||||
} as Host;
|
||||
const form = { ...createHostEditorForm(host) };
|
||||
|
||||
const payload = buildHostEditorPayload(form, telnetOnly);
|
||||
|
||||
expect(payload.telnetPassword).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("user connection defaults", () => {
|
||||
const defaults = {
|
||||
terminal: { fontSize: 18, cursorBlink: false },
|
||||
rdp: { colorDepth: 24, disableCopy: true },
|
||||
describe("plugin protocol logins", () => {
|
||||
const spice = {
|
||||
id: "spice",
|
||||
pluginId: "spice-plugin",
|
||||
settingKey: "enableSpice",
|
||||
defaultPort: 5930,
|
||||
titleKey: "spice",
|
||||
icon: () => null,
|
||||
};
|
||||
|
||||
it("shows inherited values without persisting them as host overrides", () => {
|
||||
const host = {
|
||||
enableSsh: true,
|
||||
enableRdp: true,
|
||||
terminalConfig: { autoTmux: true },
|
||||
guacamoleConfig: { enableAudioInput: true },
|
||||
} as Host;
|
||||
const form = createHostEditorForm(host, undefined, defaults);
|
||||
|
||||
expect(form).toMatchObject({
|
||||
fontSize: 18,
|
||||
cursorBlink: false,
|
||||
inheritTerminalAppearance: true,
|
||||
inheritRemoteDesktopDefaults: true,
|
||||
guacamoleConfig: {
|
||||
colorDepth: 24,
|
||||
disableCopy: true,
|
||||
enableAudioInput: true,
|
||||
const spiceOn: HostProtocols = { enableSsh: false, enableSpice: true };
|
||||
const spiceOff: HostProtocols = { enableSsh: true, enableSpice: false };
|
||||
const saved = {
|
||||
protocolAuth: {
|
||||
spice: {
|
||||
authType: "direct",
|
||||
credentialId: null,
|
||||
username: "viewer",
|
||||
fields: { display: "0" },
|
||||
hasPassword: true,
|
||||
secretFieldKeys: ["ticket"],
|
||||
},
|
||||
});
|
||||
},
|
||||
} as unknown as Host;
|
||||
|
||||
const payload = buildHostEditorPayload(form, {
|
||||
...sshOnly,
|
||||
enableRdp: true,
|
||||
it("holds a saved password and secret fields behind the placeholder", () => {
|
||||
const form = createHostEditorForm(saved);
|
||||
|
||||
expect(form.protocolAuth.spice).toEqual({
|
||||
authType: "direct",
|
||||
credentialId: "",
|
||||
username: "viewer",
|
||||
password: HOST_PROTOCOL_SECRET_KEPT,
|
||||
fields: { display: "0", ticket: HOST_PROTOCOL_SECRET_KEPT },
|
||||
});
|
||||
expect(payload.terminalConfig).toMatchObject({ autoTmux: true });
|
||||
expect(payload.terminalConfig).not.toHaveProperty("fontSize");
|
||||
expect(payload.guacamoleConfig).toEqual({ enableAudioInput: true });
|
||||
});
|
||||
|
||||
it("keeps explicit host overrides above user defaults", () => {
|
||||
const host = {
|
||||
enableSsh: true,
|
||||
enableRdp: true,
|
||||
terminalConfig: { fontSize: 12 },
|
||||
guacamoleConfig: { colorDepth: 32 },
|
||||
} as Host;
|
||||
const form = createHostEditorForm(host, undefined, defaults);
|
||||
it("leaves unchanged secrets out of the payload", () => {
|
||||
const dispose = registerHostProtocol(spice);
|
||||
try {
|
||||
const payload = buildHostEditorPayload(
|
||||
createHostEditorForm(saved),
|
||||
spiceOn,
|
||||
);
|
||||
expect(payload.protocolAuth?.spice).toEqual({
|
||||
authType: "direct",
|
||||
credentialId: null,
|
||||
username: "viewer",
|
||||
fields: { display: "0" },
|
||||
});
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
expect(form).toMatchObject({
|
||||
fontSize: 12,
|
||||
inheritTerminalAppearance: false,
|
||||
inheritRemoteDesktopDefaults: false,
|
||||
guacamoleConfig: { colorDepth: 32, disableCopy: true },
|
||||
});
|
||||
it("sends a newly typed password", () => {
|
||||
const dispose = registerHostProtocol(spice);
|
||||
try {
|
||||
const form = createHostEditorForm(saved);
|
||||
form.protocolAuth.spice.password = "new-pass";
|
||||
const payload = buildHostEditorPayload(form, spiceOn);
|
||||
expect(payload.protocolAuth?.spice?.password).toBe("new-pass");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("sends only the credential for a credential login", () => {
|
||||
const dispose = registerHostProtocol(spice);
|
||||
try {
|
||||
const form = createHostEditorForm(saved);
|
||||
form.protocolAuth.spice = {
|
||||
...form.protocolAuth.spice,
|
||||
authType: "credential",
|
||||
credentialId: "7",
|
||||
};
|
||||
const login = buildHostEditorPayload(form, spiceOn).protocolAuth?.spice;
|
||||
expect(login).toMatchObject({
|
||||
authType: "credential",
|
||||
credentialId: 7,
|
||||
username: null,
|
||||
});
|
||||
expect(login).not.toHaveProperty("password");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("removes the login of a protocol switched off", () => {
|
||||
const dispose = registerHostProtocol(spice);
|
||||
try {
|
||||
const payload = buildHostEditorPayload(
|
||||
createHostEditorForm(saved),
|
||||
spiceOff,
|
||||
);
|
||||
expect(payload.protocolAuth).toEqual({ spice: null });
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves a protocol no running plugin registered alone", () => {
|
||||
const payload = buildHostEditorPayload(
|
||||
createHostEditorForm(saved),
|
||||
spiceOn,
|
||||
);
|
||||
expect(payload.protocolAuth).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -629,20 +422,6 @@ describe("createHostEditorForm credentialId", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("createHostEditorForm auto-tmux", () => {
|
||||
it("inherits the admin default for a new host but keeps an existing host's own choice", () => {
|
||||
expect(createHostEditorForm(null, { autoTmux: true }).autoTmux).toBe(true);
|
||||
expect(createHostEditorForm(null, {}).autoTmux).toBe(false);
|
||||
|
||||
const host = {
|
||||
id: "1",
|
||||
name: "box",
|
||||
terminalConfig: { autoTmux: false },
|
||||
} as unknown as Host;
|
||||
expect(createHostEditorForm(host, { autoTmux: true }).autoTmux).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// Support#1240: RDP/VNC/Telnet can now originate from the desktop, so the
|
||||
// control has to appear for hosts that enable only those protocols -- it used
|
||||
// to be gated on SSH alone.
|
||||
@@ -672,17 +451,92 @@ describe("connectionOriginAppliesTo", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("macOS Option character defaults", () => {
|
||||
it("leaves Option available for keyboard-layout characters by default", () => {
|
||||
const form = createHostEditorForm(null);
|
||||
expect(form.macOptionIsMeta).toBe(false);
|
||||
expect(
|
||||
buildHostEditorPayload(form, sshOnly).terminalConfig?.macOptionIsMeta,
|
||||
).toBe(false);
|
||||
describe("terminal fields", () => {
|
||||
it("sends no terminalConfig, and the SSH options on their own", () => {
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
keepaliveInterval: 30,
|
||||
agentForwarding: true,
|
||||
environmentVariables: [{ key: "LANG", value: "C" }],
|
||||
};
|
||||
const payload = buildHostEditorPayload(form, sshOnly);
|
||||
|
||||
expect(payload).not.toHaveProperty("terminalConfig");
|
||||
expect(payload.sshOptions).toMatchObject({
|
||||
keepaliveInterval: 30,
|
||||
keepaliveCountMax: 5,
|
||||
allowLegacyAlgorithms: true,
|
||||
agentForwarding: true,
|
||||
environmentVariables: [{ key: "LANG", value: "C" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an explicitly saved Meta preference", () => {
|
||||
const host = { terminalConfig: { macOptionIsMeta: true } } as Host;
|
||||
expect(createHostEditorForm(host).macOptionIsMeta).toBe(true);
|
||||
it("reads a host's SSH options back into the form", () => {
|
||||
const host = {
|
||||
sshOptions: { keepaliveInterval: 15, allowLegacyAlgorithms: false },
|
||||
terminalConfig: { startupSnippetId: 2 },
|
||||
} as unknown as Host;
|
||||
const form = createHostEditorForm(host);
|
||||
|
||||
expect(form.keepaliveInterval).toBe(15);
|
||||
expect(form.allowLegacyAlgorithms).toBe(false);
|
||||
expect(form).not.toHaveProperty("startupSnippetId");
|
||||
});
|
||||
|
||||
it("leaves the terminal fields out with SSH off", () => {
|
||||
const payload = buildHostEditorPayload(createHostEditorForm(null), rdpOnly);
|
||||
expect(payload).not.toHaveProperty("terminalConfig");
|
||||
expect(payload).not.toHaveProperty("sshOptions");
|
||||
expect(payload).not.toHaveProperty("sudoPassword");
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin protocols", () => {
|
||||
it("uses the first protocol switched on as the host's type and port without SSH", () => {
|
||||
const dispose = registerHostProtocol({
|
||||
id: "demo-desktop",
|
||||
pluginId: "demo",
|
||||
settingKey: "enableDemo",
|
||||
portKey: "demoPort",
|
||||
defaultPort: 3389,
|
||||
titleKey: "demo",
|
||||
icon: () => null,
|
||||
});
|
||||
const form = {
|
||||
...createHostEditorForm(null),
|
||||
pluginSettings: { demo: { demoPort: 3390 } },
|
||||
};
|
||||
const payload = buildHostEditorPayload(form, {
|
||||
enableSsh: false,
|
||||
enableDemo: true,
|
||||
});
|
||||
dispose();
|
||||
expect(payload.connectionType).toBe("demo-desktop");
|
||||
expect(payload.port).toBe(3390);
|
||||
expect(payload.enableSsh).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyHostDraft", () => {
|
||||
it("fills a new host's form from a plugin draft", () => {
|
||||
const form = applyHostDraft(createHostEditorForm(null), {
|
||||
name: "box",
|
||||
ip: "100.64.0.1",
|
||||
port: 2222,
|
||||
username: "luke",
|
||||
authType: "tailscale",
|
||||
});
|
||||
expect(form).toMatchObject({
|
||||
name: "box",
|
||||
ip: "100.64.0.1",
|
||||
sshPort: 2222,
|
||||
username: "luke",
|
||||
authType: "tailscale",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves the form alone without a draft", () => {
|
||||
const form = createHostEditorForm(null);
|
||||
expect(applyHostDraft(form, undefined)).toBe(form);
|
||||
});
|
||||
});
|
||||
@@ -1,186 +0,0 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { WebEndpoint, WebUiConfig } from "@/types/index";
|
||||
|
||||
const isElectron = vi.hoisted(() => vi.fn(() => true));
|
||||
vi.mock("@/lib/electron", () => ({ isElectron }));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, vars?: Record<string, unknown>) =>
|
||||
vars ? `${key}:${JSON.stringify(vars)}` : key,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { HostEditorWebUiSection } from "@/sidebar/HostEditorWebUiSection";
|
||||
|
||||
function endpoint(overrides: Partial<WebEndpoint> = {}): WebEndpoint {
|
||||
return {
|
||||
id: "e1",
|
||||
label: "Proxmox",
|
||||
scheme: "https",
|
||||
port: 8006,
|
||||
path: "/",
|
||||
access: "direct",
|
||||
render: "external",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function setup(
|
||||
config: WebUiConfig = { endpoints: [] },
|
||||
{
|
||||
enableWebUi = true,
|
||||
tunnelAvailable = true,
|
||||
}: { enableWebUi?: boolean; tunnelAvailable?: boolean } = {},
|
||||
) {
|
||||
const setField = vi.fn();
|
||||
render(
|
||||
<HostEditorWebUiSection
|
||||
enableWebUi={enableWebUi}
|
||||
webUiConfig={config}
|
||||
tunnelAvailable={tunnelAvailable}
|
||||
setField={setField}
|
||||
/>,
|
||||
);
|
||||
return setField;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isElectron.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("HostEditorWebUiSection", () => {
|
||||
it("hides the endpoint list until the feature is enabled", () => {
|
||||
setup({ endpoints: [endpoint()] }, { enableWebUi: false });
|
||||
expect(screen.queryByLabelText("hosts.webUiLabel")).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText("hosts.webUiAddEndpoint"),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds an endpoint with a non-colliding label", () => {
|
||||
const setField = setup({
|
||||
endpoints: [endpoint({ label: "hosts.webUiNewEndpointLabel" })],
|
||||
});
|
||||
fireEvent.click(screen.getByText("hosts.webUiAddEndpoint"));
|
||||
|
||||
const [, value] = setField.mock.calls[0];
|
||||
const added = (value as WebUiConfig).endpoints[1];
|
||||
// Labels identify an endpoint in the sidebar picker, so a fresh row must
|
||||
// not silently duplicate one already there.
|
||||
expect(added.label).toBe("hosts.webUiNewEndpointLabel 2");
|
||||
expect(added.id).toBeTruthy();
|
||||
});
|
||||
|
||||
it("stops adding at the cap", () => {
|
||||
const many = Array.from({ length: 16 }, (_, i) =>
|
||||
endpoint({ id: `e${i}`, label: `E${i}` }),
|
||||
);
|
||||
setup({ endpoints: many });
|
||||
expect(screen.getByText("hosts.webUiAddEndpoint")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("refuses to commit a port the normalizer would drop", () => {
|
||||
// Number("") is 0, which the normalizer rejects -- committing it would
|
||||
// silently discard the endpoint on save with no error shown.
|
||||
const setField = setup({ endpoints: [endpoint()] });
|
||||
fireEvent.change(screen.getByLabelText("hosts.webUiPort"), {
|
||||
target: { value: "" },
|
||||
});
|
||||
expect(setField).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("hosts.webUiPort"), {
|
||||
target: { value: "9000" },
|
||||
});
|
||||
expect((setField.mock.calls[0][1] as WebUiConfig).endpoints[0].port).toBe(
|
||||
9000,
|
||||
);
|
||||
});
|
||||
|
||||
it("shows the bind-host fields only for a tunnel endpoint", () => {
|
||||
setup({ endpoints: [endpoint({ access: "direct" })] });
|
||||
expect(screen.queryByLabelText("hosts.bindHost")).not.toBeInTheDocument();
|
||||
|
||||
cleanup();
|
||||
setup({ endpoints: [endpoint({ access: "tunnel" })] });
|
||||
expect(screen.getByLabelText("hosts.bindHost")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("hosts.webUiLocalPort")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("warns that a non-loopback bind is unauthenticated exposure", () => {
|
||||
setup({ endpoints: [endpoint({ access: "tunnel", bindHost: "0.0.0.0" })] });
|
||||
expect(screen.getByText("hosts.webUiBindHostExposed")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not warn about exposure for a loopback bind", () => {
|
||||
setup({
|
||||
endpoints: [endpoint({ access: "tunnel", bindHost: "127.0.0.1" })],
|
||||
});
|
||||
expect(
|
||||
screen.queryByText("hosts.webUiBindHostExposed"),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("warns at config time that a loopback bind is unreachable from a browser", () => {
|
||||
isElectron.mockReturnValue(false);
|
||||
setup({ endpoints: [endpoint({ access: "tunnel" })] });
|
||||
// Said while configuring, not only when the tab fails to load.
|
||||
expect(
|
||||
screen.getByText("hosts.webUiBindHostUnreachable"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("warns at config time about the session-cookie collision", () => {
|
||||
// The page host in jsdom is "localhost", which HAS a loopback alias, so
|
||||
// force a host that does not to reach the second refusal.
|
||||
isElectron.mockReturnValue(false);
|
||||
const realLocation = window.location;
|
||||
Object.defineProperty(window, "location", {
|
||||
configurable: true,
|
||||
get: () => ({ ...realLocation, hostname: "termix.example.com" }),
|
||||
});
|
||||
|
||||
setup({ endpoints: [endpoint({ access: "tunnel", bindHost: "0.0.0.0" })] });
|
||||
expect(
|
||||
screen.getByText("hosts.webUiBindHostSharesSessionCookie"),
|
||||
).toBeInTheDocument();
|
||||
|
||||
Object.defineProperty(window, "location", {
|
||||
configurable: true,
|
||||
value: realLocation,
|
||||
});
|
||||
});
|
||||
|
||||
it("explains why tunnelling is unavailable rather than leaving a dead option", () => {
|
||||
// A disabled control with no stated reason reads as the dropdown being
|
||||
// broken.
|
||||
setup({ endpoints: [endpoint()] }, { tunnelAvailable: false });
|
||||
expect(
|
||||
screen.getByText("hosts.webUiAccessTunnelUnavailable"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("reports a row the normalizer would drop", () => {
|
||||
setup({ endpoints: [endpoint({ label: " " })] });
|
||||
expect(
|
||||
screen.getByText(/hosts.webUiErrorLabelRequired/),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("removes an endpoint", () => {
|
||||
const setField = setup({
|
||||
endpoints: [endpoint(), endpoint({ id: "e2", label: "NAS" })],
|
||||
});
|
||||
fireEvent.click(screen.getAllByLabelText("hosts.webUiRemoveEndpoint")[0]);
|
||||
expect((setField.mock.calls[0][1] as WebUiConfig).endpoints).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect((setField.mock.calls[0][1] as WebUiConfig).endpoints[0].id).toBe(
|
||||
"e2",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,37 @@ const mainAxios = vi.hoisted(() => ({
|
||||
|
||||
vi.mock("@/main-axios", () => mainAxios);
|
||||
|
||||
// The remote-desktop plugin declares its gateway password as a secret key.
|
||||
vi.mock("@/plugin-host/plugin-store", () => ({
|
||||
usePluginStore: () => ({
|
||||
loaded: true,
|
||||
settled: true,
|
||||
records: new Map([
|
||||
[
|
||||
"remote-desktop",
|
||||
{
|
||||
frontend: "active",
|
||||
summary: {
|
||||
id: "remote-desktop",
|
||||
contributes: {
|
||||
settings: {
|
||||
host: {
|
||||
fields: [
|
||||
{
|
||||
key: "guacamoleConfig",
|
||||
secretKeys: ["gateway-password"],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
]),
|
||||
}),
|
||||
}));
|
||||
|
||||
const i18n = vi.hoisted(() => ({
|
||||
t: (key: string, opts?: Record<string, unknown>) =>
|
||||
opts ? `${key}:${JSON.stringify(opts)}` : key,
|
||||
@@ -45,24 +76,6 @@ function sshHost(
|
||||
pin: false,
|
||||
authType: "password",
|
||||
connectionType: "ssh",
|
||||
enableTerminal: true,
|
||||
enableSessionLogging: false,
|
||||
enableCommandHistory: false,
|
||||
enableTunnel: false,
|
||||
enableFileManager: false,
|
||||
enableDocker: false,
|
||||
enableProxmox: false,
|
||||
enableProxmoxStats: false,
|
||||
enableTmuxMonitor: false,
|
||||
enableTerminalToolbar: true,
|
||||
enableAiAssistant: false,
|
||||
showTerminalInSidebar: true,
|
||||
showFileManagerInSidebar: false,
|
||||
showTunnelInSidebar: false,
|
||||
showDockerInSidebar: false,
|
||||
showServerStatsInSidebar: false,
|
||||
defaultPath: "",
|
||||
tunnelConnections: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
status: "online",
|
||||
@@ -80,9 +93,13 @@ function rawPayload() {
|
||||
port: 22,
|
||||
username: "deploy",
|
||||
password: "hunter2",
|
||||
guacamoleConfig: {
|
||||
"gateway-hostname": "gw.example.com",
|
||||
"gateway-password": "gw-secret",
|
||||
pluginSettings: {
|
||||
"remote-desktop": {
|
||||
guacamoleConfig: {
|
||||
"gateway-hostname": "gw.example.com",
|
||||
"gateway-password": "gw-secret",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -211,6 +228,10 @@ describe("HostExportDialog - credential handling", () => {
|
||||
expect(text).toContain("gw.example.com");
|
||||
|
||||
const parsed = JSON.parse(text);
|
||||
expect(parsed.hosts[0].guacamoleConfig["gateway-password"]).toBeNull();
|
||||
expect(
|
||||
parsed.hosts[0].pluginSettings["remote-desktop"].guacamoleConfig[
|
||||
"gateway-password"
|
||||
],
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,19 +3,6 @@ import type { SSHHostWithStatus } from "@/main-axios";
|
||||
import { sshHostToHost } from "@/sidebar/HostManagerData";
|
||||
|
||||
describe("sshHostToHost", () => {
|
||||
it("preserves the Wake-on-LAN broadcast address for editing", () => {
|
||||
const host = sshHostToHost({
|
||||
id: 1,
|
||||
name: "server",
|
||||
ip: "192.168.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
wolBroadcastAddress: "192.168.0.255",
|
||||
} as SSHHostWithStatus);
|
||||
|
||||
expect(host.wolBroadcastAddress).toBe("192.168.0.255");
|
||||
});
|
||||
|
||||
it.each(["local", "remote"] as const)(
|
||||
"preserves the %s connection origin for editing",
|
||||
(connectionOrigin) => {
|
||||
@@ -45,4 +32,33 @@ describe("sshHostToHost", () => {
|
||||
expect(host.id).toBe("-12");
|
||||
expect(host.isShared).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps every plugin's host settings so the editor can load them", () => {
|
||||
const pluginSettings = {
|
||||
docker: { enableDocker: true, containerRuntime: "podman" },
|
||||
"tmux-monitor": { enableTmuxMonitor: true },
|
||||
};
|
||||
const host = sshHostToHost({
|
||||
id: 3,
|
||||
name: "box",
|
||||
ip: "10.0.0.3",
|
||||
port: 22,
|
||||
username: "root",
|
||||
pluginSettings,
|
||||
} as unknown as SSHHostWithStatus);
|
||||
|
||||
expect(host.pluginSettings).toEqual(pluginSettings);
|
||||
});
|
||||
|
||||
it("defaults plugin settings to an empty map", () => {
|
||||
const host = sshHostToHost({
|
||||
id: 4,
|
||||
name: "bare",
|
||||
ip: "10.0.0.4",
|
||||
port: 22,
|
||||
username: "root",
|
||||
} as SSHHostWithStatus);
|
||||
|
||||
expect(host.pluginSettings).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SSH_GROUP_TABS, makeHostSshSubTabs } from "@/sidebar/HostManagerTabs";
|
||||
|
||||
describe("the Web UI editor tab", () => {
|
||||
it("is an SSH sub-tab, beside Docker and Tunnels", () => {
|
||||
const ids = makeHostSshSubTabs((key) => key).map((tab) => tab.id);
|
||||
expect(ids).toContain("web-ui");
|
||||
// Placed after docker, before proxmox -- the grouping the user approved.
|
||||
expect(ids.indexOf("web-ui")).toBe(ids.indexOf("docker") + 1);
|
||||
});
|
||||
|
||||
it("is in the SSH group, so it follows SSH availability", () => {
|
||||
// Deliberate asymmetry with the sidebar, which gates on enableWebUi alone
|
||||
// because a direct endpoint needs no SSH. A host with SSH off cannot
|
||||
// configure endpoints; that is accepted, not an oversight.
|
||||
expect(SSH_GROUP_TABS.has("web-ui")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
|
||||
const saved = vi.hoisted(() => ({ value: null as string | null }));
|
||||
|
||||
vi.mock("@/api/open-tabs-api", async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getUserPreferences: async () => ({ customKeybindings: saved.value }),
|
||||
}));
|
||||
vi.mock("@/main-axios", () => ({ saveUserPreferences: vi.fn() }));
|
||||
|
||||
const { KeybindingsDialog } = await import("../../sidebar/KeybindingsDialog");
|
||||
const {
|
||||
registerKeybindingAction,
|
||||
registerKeybindingDefault,
|
||||
resetKeybindingRegistry,
|
||||
} = await import("../../shell/keybinding-registry");
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
resetKeybindingRegistry();
|
||||
saved.value = null;
|
||||
});
|
||||
|
||||
const combo = {
|
||||
key: "k",
|
||||
isCode: false,
|
||||
ctrl: true,
|
||||
alt: false,
|
||||
shift: false,
|
||||
meta: false,
|
||||
};
|
||||
|
||||
describe("KeybindingsDialog", () => {
|
||||
it("lists registered defaults and keeps a binding whose plugin is off", async () => {
|
||||
registerKeybindingDefault({
|
||||
id: "default-x",
|
||||
pluginId: "sample",
|
||||
combo,
|
||||
descriptionKey: "sample:builtInX",
|
||||
});
|
||||
saved.value = JSON.stringify([
|
||||
{
|
||||
id: "a",
|
||||
combo,
|
||||
action: { type: "gone.action" },
|
||||
enabled: true,
|
||||
createdAt: "",
|
||||
updatedAt: "",
|
||||
},
|
||||
]);
|
||||
render(<KeybindingsDialog open onOpenChange={() => {}} />);
|
||||
expect(await screen.findByText("sample:builtInX")).toBeTruthy();
|
||||
expect(
|
||||
await screen.findByText("newUi.sidebar.keybindings.unavailableAction"),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("offers every registered action and draws the chosen one's editor", async () => {
|
||||
registerKeybindingAction({
|
||||
id: "sample.send",
|
||||
pluginId: "sample",
|
||||
labelKey: "sample:send",
|
||||
scope: "session",
|
||||
editor: () => <span>sample editor</span>,
|
||||
});
|
||||
render(<KeybindingsDialog open onOpenChange={() => {}} />);
|
||||
fireEvent.click(
|
||||
await screen.findByText("newUi.sidebar.keybindings.addBinding"),
|
||||
);
|
||||
const select = (await screen.findByRole("option", { name: "sample:send" }))
|
||||
.parentElement as HTMLSelectElement;
|
||||
expect([...select.options].map((option) => option.value)).toContain(
|
||||
"nextTab",
|
||||
);
|
||||
fireEvent.change(select, { target: { value: "sample.send" } });
|
||||
expect(await screen.findByText("sample editor")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
waitFor,
|
||||
} from "@testing-library/react";
|
||||
import { FolderSearch, Monitor, Server, Terminal } from "lucide-react";
|
||||
|
||||
vi.mock("@/api/credentials-api", () => ({
|
||||
getCredentials: vi.fn(async () => []),
|
||||
}));
|
||||
vi.mock("@/api/auth-methods-api", () => ({
|
||||
getSshAuthProviders: vi.fn(async () => []),
|
||||
}));
|
||||
const authMocks = vi.hoisted(() => ({
|
||||
providers: [] as Record<string, unknown>[],
|
||||
editors: [] as Record<string, unknown>[],
|
||||
}));
|
||||
vi.mock("@/hooks/useSshAuthProviders", () => ({
|
||||
useSshAuthProviders: () => ({ providers: authMocks.providers }),
|
||||
}));
|
||||
vi.mock("@/plugin-host/auth-registry", () => ({
|
||||
useSshAuthEditors: () => authMocks.editors,
|
||||
}));
|
||||
vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string, opts?: Record<string, unknown>) =>
|
||||
opts ? `${key}:${JSON.stringify(opts)}` : key,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { QuickConnectPanel } from "../../sidebar/QuickConnectPanel";
|
||||
import {
|
||||
registerHostAction,
|
||||
resetHostContributions,
|
||||
} from "../../sidebar/host-contributions";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
authMocks.providers = [];
|
||||
authMocks.editors = [];
|
||||
resetHostContributions();
|
||||
});
|
||||
|
||||
function registerDefaults() {
|
||||
registerHostAction({
|
||||
id: "terminal",
|
||||
titleKey: "nav.terminal",
|
||||
icon: Terminal,
|
||||
kind: "connect",
|
||||
priority: 100,
|
||||
tabType: "terminal",
|
||||
when: (host) => !!host.enableSsh,
|
||||
});
|
||||
registerHostAction({
|
||||
id: "files",
|
||||
titleKey: "nav.files",
|
||||
icon: FolderSearch,
|
||||
kind: "open",
|
||||
tabType: "files",
|
||||
quickConnect: true,
|
||||
when: (host) => !!host.enableSsh,
|
||||
});
|
||||
registerHostAction({
|
||||
id: "docker",
|
||||
titleKey: "nav.docker",
|
||||
icon: Server,
|
||||
kind: "open",
|
||||
tabType: "docker",
|
||||
when: (host) => !!host.enableSsh,
|
||||
});
|
||||
registerHostAction({
|
||||
id: "rdp",
|
||||
titleKey: "hosts.tabRdp",
|
||||
icon: Monitor,
|
||||
kind: "connect",
|
||||
priority: 50,
|
||||
tabType: "rdp",
|
||||
when: () => false,
|
||||
});
|
||||
}
|
||||
|
||||
const buttonName = (key: string) =>
|
||||
`newUi.sidebar.quickConnect.connectToAction:${JSON.stringify({ name: key })}`;
|
||||
|
||||
describe("QuickConnectPanel", () => {
|
||||
it("offers every usable connect target and opt-in tool", () => {
|
||||
registerDefaults();
|
||||
render(<QuickConnectPanel onConnect={vi.fn()} />);
|
||||
expect(screen.getByText(buttonName("nav.terminal"))).toBeTruthy();
|
||||
expect(screen.getByText(buttonName("nav.files"))).toBeTruthy();
|
||||
expect(screen.queryByText(buttonName("nav.docker"))).toBeNull();
|
||||
expect(screen.queryByText(buttonName("hosts.tabRdp"))).toBeNull();
|
||||
});
|
||||
|
||||
it("opens the chosen tab for the typed address", async () => {
|
||||
registerDefaults();
|
||||
const onConnect = vi.fn();
|
||||
render(<QuickConnectPanel onConnect={onConnect} />);
|
||||
fireEvent.change(
|
||||
screen.getByPlaceholderText("newUi.sidebar.quickConnect.hostPlaceholder"),
|
||||
{ target: { value: "10.0.0.1" } },
|
||||
);
|
||||
fireEvent.click(screen.getByText(buttonName("nav.files")));
|
||||
await waitFor(() => expect(onConnect).toHaveBeenCalledTimes(1));
|
||||
const [host, type] = onConnect.mock.calls[0];
|
||||
expect(type).toBe("files");
|
||||
expect(host).toMatchObject({ ip: "10.0.0.1", username: "root", port: 22 });
|
||||
});
|
||||
|
||||
it("connects with the top target on Enter", () => {
|
||||
registerDefaults();
|
||||
const onConnect = vi.fn();
|
||||
render(<QuickConnectPanel onConnect={onConnect} />);
|
||||
const input = screen.getByPlaceholderText(
|
||||
"newUi.sidebar.quickConnect.hostPlaceholder",
|
||||
);
|
||||
fireEvent.change(input, { target: { value: "example.com" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(onConnect).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ip: "example.com" }),
|
||||
"terminal",
|
||||
);
|
||||
});
|
||||
|
||||
it("does nothing without an address", () => {
|
||||
registerDefaults();
|
||||
const onConnect = vi.fn();
|
||||
render(<QuickConnectPanel onConnect={onConnect} />);
|
||||
fireEvent.click(screen.getByText(buttonName("nav.terminal")));
|
||||
expect(onConnect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("says so when nothing can connect", () => {
|
||||
render(<QuickConnectPanel onConnect={vi.fn()} />);
|
||||
expect(
|
||||
screen.getByText("newUi.sidebar.quickConnect.noTarget"),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("lets a plugin auth editor fill the host address", async () => {
|
||||
registerDefaults();
|
||||
authMocks.providers = [
|
||||
{
|
||||
type: "password",
|
||||
labelKey: "password",
|
||||
available: true,
|
||||
quickConnect: true,
|
||||
},
|
||||
{
|
||||
type: "tailnet",
|
||||
labelKey: "tailnet",
|
||||
available: true,
|
||||
quickConnect: true,
|
||||
},
|
||||
];
|
||||
authMocks.editors = [
|
||||
{
|
||||
id: "tailnet",
|
||||
component: ({
|
||||
setField,
|
||||
}: {
|
||||
setField: (k: string, v: unknown) => void;
|
||||
}) => (
|
||||
<button type="button" onClick={() => setField("ip", "100.64.0.5")}>
|
||||
pick device
|
||||
</button>
|
||||
),
|
||||
},
|
||||
];
|
||||
const onConnect = vi.fn();
|
||||
render(<QuickConnectPanel onConnect={onConnect} />);
|
||||
fireEvent.change(screen.getByDisplayValue("password"), {
|
||||
target: { value: "tailnet" },
|
||||
});
|
||||
fireEvent.click(screen.getByText("pick device"));
|
||||
const input = screen.getByPlaceholderText(
|
||||
"newUi.sidebar.quickConnect.hostPlaceholder",
|
||||
) as HTMLInputElement;
|
||||
expect(input.value).toBe("100.64.0.5");
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(onConnect).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ip: "100.64.0.5", authType: "tailnet" }),
|
||||
"terminal",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -22,11 +22,8 @@ vi.mock("react-i18next", () => ({
|
||||
|
||||
// Panel-level dependencies that are irrelevant to AccordionSection but would
|
||||
// otherwise be pulled in by importing the module.
|
||||
vi.mock("@/settings/RemoteSyncPanel.tsx", () => ({
|
||||
RemoteSyncPanel: () => null,
|
||||
}));
|
||||
vi.mock("@/user/C2STunnelPresetManager", () => ({
|
||||
C2STunnelPresetManager: () => null,
|
||||
vi.mock("@/plugin-host/shell-bridge", () => ({
|
||||
shell: { openRailView: vi.fn() },
|
||||
}));
|
||||
vi.mock("@/i18n/i18n", () => ({
|
||||
changeAppLanguage: vi.fn(),
|
||||
@@ -42,7 +39,11 @@ import {
|
||||
NewApiKeyDialog,
|
||||
} from "../../sidebar/UserProfilePanel";
|
||||
|
||||
afterEach(cleanup);
|
||||
afterEach(async () => {
|
||||
cleanup();
|
||||
// Radix restores focus on a timer; let it finish before jsdom is torn down.
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 0));
|
||||
});
|
||||
|
||||
function renderSection(hidden: boolean, open = false, onToggle = vi.fn()) {
|
||||
render(
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defaultTrigger } from "@/sidebar/automations/TriggerCard";
|
||||
import { emptyDraft } from "@/sidebar/automations/AutomationEditor";
|
||||
import { newStepId } from "@/sidebar/automations/editor-types";
|
||||
import { AUTOMATION_DEFINITION_VERSION } from "@/types/automations";
|
||||
|
||||
describe("emptyDraft", () => {
|
||||
it("starts on a metric threshold with no steps", () => {
|
||||
const draft = emptyDraft();
|
||||
expect(draft.name).toBe("");
|
||||
expect(draft.enabled).toBe(true);
|
||||
expect(draft.definition.version).toBe(AUTOMATION_DEFINITION_VERSION);
|
||||
expect(draft.definition.trigger.kind).toBe("metric_threshold");
|
||||
expect(draft.definition.steps).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("defaultTrigger", () => {
|
||||
it("gives every trigger kind a usable starting shape", () => {
|
||||
expect(defaultTrigger("metric_threshold")).toMatchObject({
|
||||
kind: "metric_threshold",
|
||||
operator: ">",
|
||||
cooldownMinutes: 15,
|
||||
});
|
||||
expect(defaultTrigger("host_status")).toMatchObject({
|
||||
kind: "host_status",
|
||||
to: "offline",
|
||||
});
|
||||
expect(defaultTrigger("health_check")).toMatchObject({
|
||||
kind: "health_check",
|
||||
to: "failing",
|
||||
});
|
||||
expect(defaultTrigger("schedule")).toMatchObject({ kind: "schedule" });
|
||||
expect(defaultTrigger("docker_event")).toMatchObject({
|
||||
kind: "docker_event",
|
||||
event: "exited",
|
||||
});
|
||||
expect(defaultTrigger("webhook")).toMatchObject({ kind: "webhook" });
|
||||
});
|
||||
|
||||
it("defaults a schedule to a valid cron expression", () => {
|
||||
const trigger = defaultTrigger("schedule");
|
||||
expect(trigger).toHaveProperty("cron");
|
||||
// Five fields, which is what the backend parser requires.
|
||||
expect(
|
||||
String((trigger as { cron: string }).cron).split(/\s+/),
|
||||
).toHaveLength(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("newStepId", () => {
|
||||
it("produces distinct ids", () => {
|
||||
const ids = new Set(Array.from({ length: 100 }, () => newStepId()));
|
||||
expect(ids.size).toBe(100);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHostEditorForm } from "@/sidebar/HostEditorData";
|
||||
import {
|
||||
applyDefaultToForm,
|
||||
changedKeys,
|
||||
classifyForm,
|
||||
draftOwnKeys,
|
||||
formValueForKey,
|
||||
ownPluginValues,
|
||||
withAllNamespaces,
|
||||
withOwnKeys,
|
||||
withoutOwnKey,
|
||||
} from "@/sidebar/host-defaults/form-mapping";
|
||||
|
||||
const form = () => createHostEditorForm(null);
|
||||
|
||||
describe("host defaults on the editor form", () => {
|
||||
it("reads core keys in the API's shape", () => {
|
||||
const base = {
|
||||
...form(),
|
||||
authType: "credential" as const,
|
||||
credentialId: "7",
|
||||
};
|
||||
expect(formValueForKey(base, "core.auth")).toEqual({
|
||||
authType: "credential",
|
||||
credentialId: 7,
|
||||
overrideCredentialUsername: false,
|
||||
agentSocketPath: null,
|
||||
agentIdentity: null,
|
||||
});
|
||||
expect(formValueForKey(base, "core.sshPort")).toBe(22);
|
||||
});
|
||||
|
||||
it("puts a default's value back on the form", () => {
|
||||
let next = applyDefaultToForm(form(), "core.socks5", {
|
||||
useSocks5: true,
|
||||
socks5ProxyChain: [{ host: "a", port: 1080, type: "socks5" }],
|
||||
});
|
||||
expect(next.useSocks5).toBe(true);
|
||||
expect(next.socks5ProxyMode).toBe("chain");
|
||||
next = applyDefaultToForm(next, "core.jumpHosts", [{ hostId: 4 }]);
|
||||
expect(next.jumpHosts).toEqual([{ hostId: "4" }]);
|
||||
next = applyDefaultToForm(next, "term.fontSize", 18);
|
||||
expect(next.pluginSettings.term.fontSize).toBe(18);
|
||||
});
|
||||
|
||||
it("finds the keys an edit changed", () => {
|
||||
const before = form();
|
||||
const after = { ...before, sshPort: 2222, keySubTab: "upload" as const };
|
||||
expect(
|
||||
changedKeys(before, after, ["core.sshPort", "core.auth", "term.x"]),
|
||||
).toEqual(["core.sshPort"]);
|
||||
});
|
||||
|
||||
it("classifies what differs from the defaults as the host's own", () => {
|
||||
const current = { ...form(), sshPort: 2222 };
|
||||
expect(
|
||||
classifyForm(
|
||||
current,
|
||||
{
|
||||
"core.sshPort": { value: 22 },
|
||||
"core.statusCheckEnabled": { value: true },
|
||||
},
|
||||
["core.sshPort", "core.statusCheckEnabled", "core.username"],
|
||||
),
|
||||
).toEqual({ core: ["sshPort", "username"] });
|
||||
});
|
||||
|
||||
it("adds and removes own keys", () => {
|
||||
const own = withOwnKeys({}, ["core.sshPort", "term.a"]);
|
||||
expect(own).toEqual({ core: ["sshPort"], term: ["a"] });
|
||||
expect(withoutOwnKey(own, "term.a")).toEqual({
|
||||
core: ["sshPort"],
|
||||
term: [],
|
||||
});
|
||||
expect(
|
||||
withAllNamespaces(own, new Map([["x.y", { namespace: "x" }]])),
|
||||
).toEqual({ core: ["sshPort"], term: ["a"], x: [] });
|
||||
});
|
||||
|
||||
it("sends only the plugin values a host sets itself", () => {
|
||||
const keys = new Map<string, unknown>([
|
||||
["term.a", {}],
|
||||
["term.b", {}],
|
||||
]);
|
||||
expect(
|
||||
ownPluginValues(
|
||||
{ term: { a: 1, b: 2, enableRdp: true } },
|
||||
{ term: ["a"] },
|
||||
keys,
|
||||
),
|
||||
).toEqual({ term: { a: 1, enableRdp: true } });
|
||||
expect(ownPluginValues({ term: { a: 1 } }, null, keys)).toEqual({
|
||||
term: { a: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("makes what a plugin's draft filled in the new host's own", () => {
|
||||
expect(draftOwnKeys({ port: 2222, username: "u" })).toEqual({
|
||||
core: ["sshPort", "username"],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Puzzle } from "lucide-react";
|
||||
import {
|
||||
getHostEditorSection,
|
||||
hostEditorSectionList,
|
||||
isSshGroupTab,
|
||||
makeHostSshSubTabs,
|
||||
makeHostTabs,
|
||||
registerHostEditorSection,
|
||||
resetHostEditorSections,
|
||||
} from "@/sidebar/HostManagerTabs";
|
||||
|
||||
const FAKE_TAB_ID = "__test_plugin_host_editor_tab__";
|
||||
|
||||
function FakeTabComponent() {
|
||||
return null;
|
||||
}
|
||||
|
||||
afterEach(() => resetHostEditorSections());
|
||||
|
||||
describe("host editor sections", () => {
|
||||
it("is not registered by default", () => {
|
||||
expect(getHostEditorSection(FAKE_TAB_ID)).toBeUndefined();
|
||||
expect(hostEditorSectionList()).toEqual([]);
|
||||
});
|
||||
|
||||
it("registers and disposes a section", () => {
|
||||
const dispose = registerHostEditorSection({
|
||||
id: FAKE_TAB_ID,
|
||||
group: "ssh",
|
||||
labelKey: "nav.fakePluginItem",
|
||||
icon: Puzzle,
|
||||
component: FakeTabComponent,
|
||||
});
|
||||
expect(getHostEditorSection(FAKE_TAB_ID)?.component).toBe(FakeTabComponent);
|
||||
dispose();
|
||||
expect(getHostEditorSection(FAKE_TAB_ID)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("puts an SSH-group section in the second strip, by order", () => {
|
||||
registerHostEditorSection({
|
||||
id: FAKE_TAB_ID,
|
||||
group: "ssh",
|
||||
labelKey: "nav.fakePluginItem",
|
||||
order: 1000,
|
||||
component: FakeTabComponent,
|
||||
});
|
||||
const ids = makeHostSshSubTabs((key) => key).map((tab) => tab.id);
|
||||
expect(ids.at(-1)).toBe(FAKE_TAB_ID);
|
||||
// What made registered SSH-group tabs unreachable before: the editor
|
||||
// only recognised a fixed list of SSH-group ids.
|
||||
expect(isSshGroupTab(FAKE_TAB_ID)).toBe(true);
|
||||
expect(makeHostTabs((key) => key).map((tab) => tab.id)).not.toContain(
|
||||
FAKE_TAB_ID,
|
||||
);
|
||||
});
|
||||
|
||||
it("shows a top-level section only for the protocols it asks for", () => {
|
||||
registerHostEditorSection({
|
||||
id: FAKE_TAB_ID,
|
||||
group: "top",
|
||||
labelKey: "nav.fakePluginItem",
|
||||
order: 20,
|
||||
visible: (protocols) => !!protocols.enableFake,
|
||||
component: FakeTabComponent,
|
||||
});
|
||||
const tabs = (protocols: Record<string, boolean>) =>
|
||||
makeHostTabs((key) => key, protocols).map((tab) => tab.id);
|
||||
expect(tabs({})).toEqual(["general", "ssh"]);
|
||||
expect(tabs({ enableFake: true })).toEqual(["general", "ssh", FAKE_TAB_ID]);
|
||||
expect(isSshGroupTab(FAKE_TAB_ID)).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a section whose visible throws as hidden", () => {
|
||||
registerHostEditorSection({
|
||||
id: FAKE_TAB_ID,
|
||||
group: "top",
|
||||
labelKey: "nav.fakePluginItem",
|
||||
visible: () => {
|
||||
throw new Error("broken plugin");
|
||||
},
|
||||
component: FakeTabComponent,
|
||||
});
|
||||
expect(makeHostTabs((key) => key, {}).map((tab) => tab.id)).not.toContain(
|
||||
FAKE_TAB_ID,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -6,15 +6,20 @@ import {
|
||||
SECRET_KEYS,
|
||||
type ExportPayload,
|
||||
type FieldGroup,
|
||||
pluginSecretKeys,
|
||||
} from "../../sidebar/host-export-payload";
|
||||
|
||||
// What the remote-desktop manifest declares for its guacamoleConfig field.
|
||||
const RDP_SECRETS = {
|
||||
"remote-desktop": { guacamoleConfig: ["gateway-password"] },
|
||||
};
|
||||
|
||||
const ALL_GROUPS = new Set<FieldGroup>([
|
||||
"connection",
|
||||
"notes",
|
||||
"tags",
|
||||
"tunnels",
|
||||
"proxy",
|
||||
"jumpHosts",
|
||||
"quickActions",
|
||||
"featureFlags",
|
||||
"advanced",
|
||||
]);
|
||||
@@ -62,6 +67,14 @@ function shareRaw(): ExportPayload {
|
||||
};
|
||||
}
|
||||
|
||||
function gatewayConfig(host: Record<string, unknown>): Record<string, unknown> {
|
||||
const plugins = host.pluginSettings as Record<
|
||||
string,
|
||||
Record<string, unknown>
|
||||
>;
|
||||
return plugins["remote-desktop"].guacamoleConfig as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function rdpRaw(): ExportPayload {
|
||||
return {
|
||||
hosts: [
|
||||
@@ -72,9 +85,13 @@ function rdpRaw(): ExportPayload {
|
||||
port: 3389,
|
||||
username: "admin",
|
||||
password: null,
|
||||
guacamoleConfig: {
|
||||
"gateway-hostname": "gw.example.com",
|
||||
"gateway-password": "gw-secret",
|
||||
pluginSettings: {
|
||||
"remote-desktop": {
|
||||
guacamoleConfig: {
|
||||
"gateway-hostname": "gw.example.com",
|
||||
"gateway-password": "gw-secret",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -197,22 +214,28 @@ describe("buildExportPayload", () => {
|
||||
});
|
||||
|
||||
it("nulls the guacamole gateway password when credentials are excluded", () => {
|
||||
const out = buildExportPayload(rdpRaw(), null, ALL_GROUPS, false);
|
||||
const config = out.hosts[0].guacamoleConfig as Record<string, unknown>;
|
||||
const out = buildExportPayload(
|
||||
rdpRaw(),
|
||||
null,
|
||||
ALL_GROUPS,
|
||||
false,
|
||||
RDP_SECRETS,
|
||||
);
|
||||
const config = gatewayConfig(out.hosts[0]);
|
||||
expect(config["gateway-password"]).toBeNull();
|
||||
expect(config["gateway-hostname"]).toBe("gw.example.com");
|
||||
});
|
||||
|
||||
it("keeps the guacamole gateway password when credentials are included", () => {
|
||||
const out = buildExportPayload(rdpRaw(), null, ALL_GROUPS, true);
|
||||
const config = out.hosts[0].guacamoleConfig as Record<string, unknown>;
|
||||
const config = gatewayConfig(out.hosts[0]);
|
||||
expect(config["gateway-password"]).toBe("gw-secret");
|
||||
});
|
||||
|
||||
it("does not mutate the source payload when nulling nested secrets", () => {
|
||||
const raw = rdpRaw();
|
||||
buildExportPayload(raw, null, ALL_GROUPS, false);
|
||||
const config = raw.hosts[0].guacamoleConfig as Record<string, unknown>;
|
||||
buildExportPayload(raw, null, ALL_GROUPS, false, RDP_SECRETS);
|
||||
const config = gatewayConfig(raw.hosts[0]);
|
||||
expect(config["gateway-password"]).toBe("gw-secret");
|
||||
});
|
||||
|
||||
@@ -259,8 +282,8 @@ describe("maskSecrets", () => {
|
||||
});
|
||||
|
||||
it("masks the guacamole gateway password", () => {
|
||||
const out = maskSecrets(rdpRaw());
|
||||
const config = out.hosts[0].guacamoleConfig as Record<string, unknown>;
|
||||
const out = maskSecrets(rdpRaw(), RDP_SECRETS);
|
||||
const config = gatewayConfig(out.hosts[0]);
|
||||
expect(config["gateway-password"]).toBe("<included>");
|
||||
expect(config["gateway-hostname"]).toBe("gw.example.com");
|
||||
expect(JSON.stringify(out)).not.toContain("gw-secret");
|
||||
@@ -275,3 +298,26 @@ describe("maskSecrets", () => {
|
||||
expect(JSON.stringify(out)).not.toContain("proxy-secret-2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pluginSecretKeys", () => {
|
||||
it("reads secretKeys off each plugin's host fields", () => {
|
||||
expect(
|
||||
pluginSecretKeys([
|
||||
{
|
||||
id: "remote-desktop",
|
||||
contributes: {
|
||||
settings: {
|
||||
host: {
|
||||
fields: [
|
||||
{ key: "guacamoleConfig", secretKeys: ["gateway-password"] },
|
||||
{ key: "enableRdp" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ id: "docker", contributes: null },
|
||||
]),
|
||||
).toEqual(RDP_SECRETS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
enabledHostProtocols,
|
||||
hostProtocolFlags,
|
||||
protocolPort,
|
||||
registerHostProtocol,
|
||||
withProtocolSettings,
|
||||
type HostProtocolDef,
|
||||
} from "../../sidebar/host-protocols";
|
||||
|
||||
const desktop: HostProtocolDef = {
|
||||
id: "demo-desktop",
|
||||
pluginId: "demo",
|
||||
settingKey: "enableDemo",
|
||||
portKey: "demoPort",
|
||||
defaultPort: 3389,
|
||||
titleKey: "demo:title",
|
||||
icon: () => null,
|
||||
};
|
||||
|
||||
let dispose: (() => void) | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
dispose?.();
|
||||
dispose = null;
|
||||
});
|
||||
|
||||
describe("host protocols", () => {
|
||||
it("reads a protocol's switch from its plugin's host settings", () => {
|
||||
dispose = registerHostProtocol(desktop);
|
||||
const host = {
|
||||
enableSsh: false,
|
||||
pluginSettings: { demo: { enableDemo: true } },
|
||||
};
|
||||
expect(hostProtocolFlags(host)).toEqual({
|
||||
enableSsh: false,
|
||||
enableDemo: true,
|
||||
});
|
||||
expect(enabledHostProtocols(host).map((p) => p.id)).toEqual([
|
||||
"demo-desktop",
|
||||
]);
|
||||
expect(hostProtocolFlags(null)).toEqual({
|
||||
enableSsh: true,
|
||||
enableDemo: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default port", () => {
|
||||
expect(protocolPort({ demo: { demoPort: 3390 } }, desktop)).toBe(3390);
|
||||
expect(protocolPort({ demo: { demoPort: "x" } }, desktop)).toBe(3389);
|
||||
expect(protocolPort(undefined, desktop)).toBe(3389);
|
||||
});
|
||||
|
||||
it("writes the editor's switches into each owner's settings", () => {
|
||||
dispose = registerHostProtocol(desktop);
|
||||
expect(
|
||||
withProtocolSettings(
|
||||
{ demo: { demoPort: 3390 }, other: { a: 1 } },
|
||||
{ enableSsh: true, enableDemo: true },
|
||||
),
|
||||
).toEqual({
|
||||
demo: { demoPort: 3390, enableDemo: true },
|
||||
other: { a: 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it("forgets a protocol once its plugin unregisters it", () => {
|
||||
dispose = registerHostProtocol(desktop);
|
||||
dispose();
|
||||
dispose = null;
|
||||
expect(
|
||||
enabledHostProtocols({ pluginSettings: { demo: { enableDemo: true } } }),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { PluginSummary } from "@/api/plugins-api";
|
||||
import { sshHostToHost } from "@/sidebar/HostManagerData";
|
||||
import { createHostEditorForm } from "@/sidebar/HostEditorData";
|
||||
import { HostPluginSections } from "@/settings/HostPluginSections";
|
||||
import recording from "../../../../plugins/session-recording/manifest.json";
|
||||
import sharing from "../../../../plugins/session-sharing/manifest.json";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
afterEach(cleanup);
|
||||
|
||||
describe.each([
|
||||
{ manifest: recording, key: "enableSessionRecording" },
|
||||
{ manifest: sharing, key: "allowSessionSharing" },
|
||||
])("$key after reopening a host", ({ manifest, key }) => {
|
||||
it.each([false, true])(
|
||||
"preserves the saved switch %s in the editor and its next change",
|
||||
(saved) => {
|
||||
const pluginSettings = {
|
||||
"session-recording": { enableSessionRecording: saved },
|
||||
"session-sharing": { allowSessionSharing: saved },
|
||||
"ssh-terminal": { enableCommandHistory: false },
|
||||
};
|
||||
const host = sshHostToHost({
|
||||
id: 1,
|
||||
name: "server",
|
||||
ip: "192.0.2.1",
|
||||
port: 22,
|
||||
username: "alice",
|
||||
folder: "",
|
||||
tags: [],
|
||||
pin: false,
|
||||
authType: "password",
|
||||
status: "online",
|
||||
createdAt: "2026-09-29T00:00:00Z",
|
||||
updatedAt: "2026-09-29T00:00:00Z",
|
||||
pluginSettings,
|
||||
});
|
||||
const form = createHostEditorForm(host);
|
||||
const setValue = vi.fn();
|
||||
render(
|
||||
<HostPluginSections
|
||||
plugins={[
|
||||
{
|
||||
...manifest,
|
||||
enabled: true,
|
||||
state: "running",
|
||||
} as unknown as PluginSummary,
|
||||
]}
|
||||
values={form.pluginSettings}
|
||||
setValue={setValue}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
expect(setValue).toHaveBeenCalledWith(manifest.id, key, !saved);
|
||||
// These are the values HostEditor writes through each plugin's host settings API.
|
||||
expect(form.pluginSettings).toEqual(pluginSettings);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { PluginSummary } from "@/api/plugins-api";
|
||||
import { sshHostToHost } from "@/sidebar/HostManagerData";
|
||||
import { createHostEditorForm } from "@/sidebar/HostEditorData";
|
||||
import { HostPluginSections } from "@/settings/HostPluginSections";
|
||||
import manifest from "../../../../plugins/session-sharing/manifest.json";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
describe("host sharing settings on reopening the editor", () => {
|
||||
it.each([false, true])("retains the saved sharing value %s", (saved) => {
|
||||
const pluginSettings = {
|
||||
"session-sharing": { allowSessionSharing: saved },
|
||||
"ssh-terminal": { enableCommandHistory: false },
|
||||
};
|
||||
const host = sshHostToHost({
|
||||
id: 1,
|
||||
name: "server",
|
||||
ip: "192.0.2.1",
|
||||
port: 22,
|
||||
username: "alice",
|
||||
folder: "",
|
||||
tags: [],
|
||||
pin: false,
|
||||
authType: "password",
|
||||
status: "online",
|
||||
createdAt: "2026-09-29T00:00:00Z",
|
||||
updatedAt: "2026-09-29T00:00:00Z",
|
||||
pluginSettings,
|
||||
});
|
||||
const form = createHostEditorForm(host);
|
||||
const setValue = vi.fn();
|
||||
render(
|
||||
<HostPluginSections
|
||||
plugins={[
|
||||
{
|
||||
...manifest,
|
||||
enabled: true,
|
||||
state: "running",
|
||||
} as unknown as PluginSummary,
|
||||
]}
|
||||
values={form.pluginSettings}
|
||||
setValue={setValue}
|
||||
/>,
|
||||
);
|
||||
|
||||
// The toggle starts from the server value, including false despite its true default.
|
||||
fireEvent.click(screen.getByRole("button"));
|
||||
expect(setValue).toHaveBeenCalledWith(
|
||||
"session-sharing",
|
||||
"allowSessionSharing",
|
||||
!saved,
|
||||
);
|
||||
expect(form.pluginSettings).toEqual(pluginSettings);
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* Validates the plugin extension seam introduced for a future plugin loader:
|
||||
* registerRailItem/unregisterRailItem in rail-items.ts, and
|
||||
* registerTabComponent/unregisterTabComponent in tabUtils.tsx.
|
||||
*
|
||||
* This does NOT test a real feature. There is no plugin loader yet -- this
|
||||
* registers a fake rail item and a fake tab component, confirms they render
|
||||
* through the normal AppRail/tab-content paths, then unregisters them. If
|
||||
* this test ever needs deleting because the seam changed shape, that's fine;
|
||||
* it exists to prove the seam works, not to protect a shipped feature.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { Puzzle } from "lucide-react";
|
||||
import {
|
||||
registerRailItem,
|
||||
unregisterRailItem,
|
||||
visibleRailItems,
|
||||
} from "@/sidebar/rail-items";
|
||||
import {
|
||||
registerTabComponent,
|
||||
unregisterTabComponent,
|
||||
renderTabContent,
|
||||
} from "@/shell/tabUtils";
|
||||
import { AppRail } from "@/sidebar/AppRail";
|
||||
import type { Tab } from "@/types/ui-types";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/api/alerts-api", () => ({
|
||||
getAlertFirings: vi.fn().mockResolvedValue([]),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-ai-availability", () => ({
|
||||
useAiAvailability: () => ({ userEnabled: false }),
|
||||
}));
|
||||
|
||||
const FAKE_TAB_ID = "__test_plugin_tab__";
|
||||
|
||||
function FakePluginTabComponent({ tab }: { tab: Tab }) {
|
||||
return <div data-testid="fake-plugin-tab">plugin tab for {tab.id}</div>;
|
||||
}
|
||||
|
||||
describe("plugin extension seam", () => {
|
||||
afterEach(() => {
|
||||
unregisterRailItem(FAKE_TAB_ID);
|
||||
unregisterTabComponent(FAKE_TAB_ID);
|
||||
});
|
||||
|
||||
it("merges a runtime-registered rail item into visibleRailItems", () => {
|
||||
expect(visibleRailItems().map((i) => i.id)).not.toContain(FAKE_TAB_ID);
|
||||
|
||||
registerRailItem({
|
||||
id: FAKE_TAB_ID,
|
||||
icon: Puzzle,
|
||||
labelKey: "nav.fakePluginItem",
|
||||
kind: "tab",
|
||||
});
|
||||
|
||||
expect(visibleRailItems().map((i) => i.id)).toContain(FAKE_TAB_ID);
|
||||
|
||||
unregisterRailItem(FAKE_TAB_ID);
|
||||
expect(visibleRailItems().map((i) => i.id)).not.toContain(FAKE_TAB_ID);
|
||||
});
|
||||
|
||||
it("renders a registered rail item as a clickable button in AppRail", async () => {
|
||||
registerRailItem({
|
||||
id: FAKE_TAB_ID,
|
||||
icon: Puzzle,
|
||||
labelKey: "nav.fakePluginItem",
|
||||
kind: "tab",
|
||||
});
|
||||
|
||||
const onOpenTab = vi.fn();
|
||||
render(
|
||||
<AppRail
|
||||
railView="hosts"
|
||||
sidebarOpen={false}
|
||||
splitMode="none"
|
||||
username="test"
|
||||
isAdmin={false}
|
||||
onRailClick={vi.fn()}
|
||||
onOpenTab={onOpenTab}
|
||||
onLogout={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => screen.getByText("nav.fakePluginItem"));
|
||||
screen.getByText("nav.fakePluginItem").closest("button")?.click();
|
||||
expect(onOpenTab).toHaveBeenCalledWith(FAKE_TAB_ID);
|
||||
});
|
||||
|
||||
it("opens a registered plugin tab id through the tab-component registry", async () => {
|
||||
const loader = vi.fn().mockResolvedValue({
|
||||
default: FakePluginTabComponent,
|
||||
});
|
||||
registerTabComponent(FAKE_TAB_ID, loader);
|
||||
|
||||
const tab: Tab = {
|
||||
id: "tab-1",
|
||||
instanceId: "instance-1",
|
||||
type: FAKE_TAB_ID,
|
||||
label: "Fake plugin tab",
|
||||
openedAt: Date.now(),
|
||||
};
|
||||
|
||||
const content = renderTabContent(tab);
|
||||
render(<>{content}</>);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("fake-plugin-tab")).toBeTruthy(),
|
||||
);
|
||||
expect(loader).toHaveBeenCalledOnce();
|
||||
|
||||
unregisterTabComponent(FAKE_TAB_ID);
|
||||
});
|
||||
|
||||
it("renders nothing for an unregistered plugin tab id", () => {
|
||||
const tab: Tab = {
|
||||
id: "tab-2",
|
||||
instanceId: "instance-2",
|
||||
type: "__totally_unknown_tab_type__",
|
||||
label: "Unknown tab",
|
||||
openedAt: Date.now(),
|
||||
};
|
||||
|
||||
expect(renderTabContent(tab)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
createQuickConnectHost,
|
||||
isQuickConnectHost,
|
||||
quickConnectGuacHost,
|
||||
quickConnectHostToPayload,
|
||||
quickConnectTargets,
|
||||
} from "../../sidebar/quick-connect-host";
|
||||
import type { HostActionDef } from "../../sidebar/host-contributions";
|
||||
|
||||
describe("quick connect host", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
@@ -62,59 +63,116 @@ describe("createQuickConnectHost for remote desktop protocols", () => {
|
||||
expect(isQuickConnectHost(host)).toBe(true);
|
||||
expect(host).toMatchObject({
|
||||
enableSsh: true,
|
||||
enableRdp: false,
|
||||
sshPort: 2222,
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("builds an RDP host that GuacamoleApp can mint a token from", () => {
|
||||
const desktop = {
|
||||
id: "demo-desktop",
|
||||
pluginId: "demo",
|
||||
settingKey: "enableDemo",
|
||||
portKey: "demoPort",
|
||||
defaultPort: 3389,
|
||||
titleKey: "demo",
|
||||
icon: () => null,
|
||||
};
|
||||
|
||||
it("builds a plugin protocol host with its switch and port in plugin settings", () => {
|
||||
const host = createQuickConnectHost({
|
||||
ip: "10.0.0.2",
|
||||
port: 3390,
|
||||
username: "admin",
|
||||
authType: "password",
|
||||
password: "pw",
|
||||
protocol: "rdp",
|
||||
protocol: desktop,
|
||||
domain: "CORP",
|
||||
});
|
||||
expect(host).toMatchObject({
|
||||
enableSsh: false,
|
||||
enableRdp: true,
|
||||
enableVnc: false,
|
||||
rdpPort: 3390,
|
||||
rdpUser: "admin",
|
||||
rdpPassword: "pw",
|
||||
domain: "CORP",
|
||||
pluginSettings: { demo: { enableDemo: true, demoPort: 3390 } },
|
||||
});
|
||||
expect(quickConnectGuacHost(host)).toMatchObject({
|
||||
ip: "10.0.0.2",
|
||||
connectionType: "rdp",
|
||||
rdpPort: 3390,
|
||||
rdpUser: "admin",
|
||||
rdpPassword: "pw",
|
||||
domain: "CORP",
|
||||
// The unsaved login travels to the protocol's tab as it is.
|
||||
expect(host.quickConnectLogin).toEqual({
|
||||
protocol: "demo-desktop",
|
||||
username: "admin",
|
||||
password: "pw",
|
||||
fields: { domain: "CORP" },
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a VNC host with the password on the VNC fields", () => {
|
||||
it("carries the fields a plugin's SSH auth editor filled in", () => {
|
||||
const host = createQuickConnectHost({
|
||||
ip: "10.0.0.3",
|
||||
port: 5901,
|
||||
username: "",
|
||||
authType: "password",
|
||||
password: "vncpw",
|
||||
protocol: "vnc",
|
||||
ip: "100.64.0.9",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "tailnet-login",
|
||||
authFields: { pluginSettings: { demo: { profileId: 3 } } },
|
||||
});
|
||||
expect(host.authType).toBe("tailnet-login");
|
||||
expect(host.password).toBeUndefined();
|
||||
expect(host).toMatchObject({
|
||||
enableVnc: true,
|
||||
vncPort: 5901,
|
||||
vncPassword: "vncpw",
|
||||
});
|
||||
expect(quickConnectGuacHost(host)).toMatchObject({
|
||||
connectionType: "vnc",
|
||||
vncPort: 5901,
|
||||
vncPassword: "vncpw",
|
||||
pluginSettings: { demo: { profileId: 3 } },
|
||||
});
|
||||
});
|
||||
|
||||
it("marks only hosts core can save", () => {
|
||||
const base = { ip: "10.0.0.2", port: 22, username: "root" };
|
||||
expect(
|
||||
createQuickConnectHost({ ...base, authType: "password" })
|
||||
.quickConnectSavable,
|
||||
).toBe(true);
|
||||
expect(
|
||||
createQuickConnectHost({ ...base, authType: "tailscale" })
|
||||
.quickConnectSavable,
|
||||
).toBe(false);
|
||||
expect(
|
||||
createQuickConnectHost({
|
||||
...base,
|
||||
authType: "password",
|
||||
authFields: { extra: true },
|
||||
}).quickConnectSavable,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("quickConnectTargets", () => {
|
||||
const action = (over: Partial<HostActionDef>): HostActionDef => ({
|
||||
id: "x",
|
||||
titleKey: "x",
|
||||
icon: () => null,
|
||||
kind: "open",
|
||||
when: () => true,
|
||||
...over,
|
||||
});
|
||||
const host = createQuickConnectHost({
|
||||
ip: "10.0.0.3",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
|
||||
it("puts connect actions first by priority, then opted-in tools", () => {
|
||||
const targets = quickConnectTargets(
|
||||
[
|
||||
action({ id: "files", tabType: "files", quickConnect: true }),
|
||||
action({ id: "docker", tabType: "docker" }),
|
||||
action({ id: "vnc", kind: "connect", priority: 40, tabType: "vnc" }),
|
||||
action({ id: "term", kind: "connect", priority: 100, tabType: "t" }),
|
||||
action({ id: "run-only", kind: "connect", priority: 200 }),
|
||||
action({
|
||||
id: "off",
|
||||
kind: "connect",
|
||||
tabType: "off",
|
||||
when: () => false,
|
||||
}),
|
||||
],
|
||||
host,
|
||||
);
|
||||
expect(targets.map((target) => target.id)).toEqual([
|
||||
"term",
|
||||
"vnc",
|
||||
"files",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,26 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Boxes } from "lucide-react";
|
||||
import {
|
||||
HIDEABLE_RAIL_IDS,
|
||||
PROMOTABLE_IDS,
|
||||
hideableRailIds,
|
||||
permittedRailItems,
|
||||
promotableIds,
|
||||
RAIL_ITEMS,
|
||||
RAIL_UTILITY_ITEMS,
|
||||
RIGHT_DOCKABLE_IDS,
|
||||
registerRailItem,
|
||||
resetRegisteredRailItems,
|
||||
rightDockableIds,
|
||||
railItemLabel,
|
||||
visibleRailItems,
|
||||
} from "@/sidebar/rail-items";
|
||||
import { WORKSPACE_CAPTURABLE_TYPES } from "@/shell/workspaceUtils";
|
||||
import type { TabType } from "@/types/ui-types";
|
||||
import { isCapturableTabType } from "@/shell/shell-layout";
|
||||
import { registerPanel, resetPanels } from "@/shell/panel-registry";
|
||||
import en from "@/locales/en.json";
|
||||
|
||||
afterEach(() => {
|
||||
resetRegisteredRailItems();
|
||||
resetPanels();
|
||||
});
|
||||
|
||||
function lookup(key: string): unknown {
|
||||
return key
|
||||
.split(".")
|
||||
@@ -43,39 +52,30 @@ describe("RAIL_ITEMS", () => {
|
||||
// Guards against a destination silently disappearing now that the rail,
|
||||
// the settings toggles, the sidebar titles and the mobile bar all read
|
||||
// from this one list.
|
||||
// "sftp" moved to the file-manager plugin's own registerRailItem,
|
||||
// "port-forwarding" to the tunnels plugin's, "serial" to the serial
|
||||
// plugin's, "collab" to the session-sharing plugin's, and "session-logs"
|
||||
// to the session-recording plugin's, "termix-id" to the termix-identity
|
||||
// plugin's, "ssh-tools" and "macros" to the ssh-terminal plugin's.
|
||||
expect(RAIL_ITEMS.map((item) => item.id)).toEqual([
|
||||
"hosts",
|
||||
"credentials",
|
||||
"port-forwarding",
|
||||
"termix-id",
|
||||
"connections",
|
||||
"collab",
|
||||
"quick-connect",
|
||||
"serial",
|
||||
"ssh-tools",
|
||||
"sftp",
|
||||
"snippets",
|
||||
"macros",
|
||||
"fleets",
|
||||
"automations",
|
||||
"ai",
|
||||
"history",
|
||||
"session-logs",
|
||||
"split-screen",
|
||||
"workspaces",
|
||||
"local-terminal",
|
||||
"network_graph",
|
||||
"sync",
|
||||
]);
|
||||
});
|
||||
|
||||
it("exposes every rail item as hideable", () => {
|
||||
expect(HIDEABLE_RAIL_IDS).toEqual(RAIL_ITEMS.map((item) => item.id));
|
||||
it("exposes every visible rail item as hideable", () => {
|
||||
expect(hideableRailIds()).toEqual(
|
||||
visibleRailItems().map((item) => item.id),
|
||||
);
|
||||
});
|
||||
|
||||
it("marks exactly the four mobile primary slots", () => {
|
||||
it("marks core's mobile primary slots", () => {
|
||||
expect(
|
||||
RAIL_ITEMS.filter((item) => item.mobilePrimary).map((item) => item.id),
|
||||
).toEqual(["hosts", "quick-connect", "ssh-tools", "snippets"]);
|
||||
).toEqual(["hosts", "quick-connect"]);
|
||||
});
|
||||
|
||||
it("marks the panels that can open as a tab", () => {
|
||||
@@ -83,23 +83,13 @@ describe("RAIL_ITEMS", () => {
|
||||
[...RAIL_ITEMS, ...RAIL_UTILITY_ITEMS]
|
||||
.filter((item) => item.promotable)
|
||||
.map((item) => item.id),
|
||||
).toEqual([
|
||||
"termix-id",
|
||||
"ssh-tools",
|
||||
"snippets",
|
||||
"macros",
|
||||
"automations",
|
||||
"ai",
|
||||
"history",
|
||||
"session-logs",
|
||||
"alerts",
|
||||
]);
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("derives PROMOTABLE_IDS from the promotable flag", () => {
|
||||
it("derives promotableIds from the promotable flag", () => {
|
||||
// The header button and the hint both gate on this list, so a drift here
|
||||
// silently hides the feature for that panel.
|
||||
expect(PROMOTABLE_IDS).toEqual(
|
||||
expect(promotableIds()).toEqual(
|
||||
[...RAIL_ITEMS, ...RAIL_UTILITY_ITEMS]
|
||||
.filter((item) => item.promotable)
|
||||
.map((item) => item.id),
|
||||
@@ -112,34 +102,80 @@ describe("RAIL_ITEMS", () => {
|
||||
for (const item of [...RAIL_ITEMS, ...RAIL_UTILITY_ITEMS]) {
|
||||
if (!item.promotable) continue;
|
||||
expect(
|
||||
WORKSPACE_CAPTURABLE_TYPES,
|
||||
isCapturableTabType(item.id),
|
||||
`${item.id} is promotable but not workspace-capturable`,
|
||||
).toContain(item.id as TabType);
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the mounted-but-hidden panels out of the right dock", () => {
|
||||
// Hosts, credentials and fleets stay mounted while hidden and share editing
|
||||
// state, so a second live instance in the right dock would fight the first.
|
||||
for (const id of ["hosts", "credentials", "fleets"]) {
|
||||
for (const id of ["hosts", "credentials"]) {
|
||||
expect(
|
||||
RIGHT_DOCKABLE_IDS,
|
||||
rightDockableIds(),
|
||||
`${id} must not be right-dockable`,
|
||||
).not.toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
it("only offers reference panels in the right dock", () => {
|
||||
expect(RIGHT_DOCKABLE_IDS).toEqual([
|
||||
"connections",
|
||||
"ssh-tools",
|
||||
"snippets",
|
||||
"macros",
|
||||
"ai",
|
||||
"history",
|
||||
"session-logs",
|
||||
"alerts",
|
||||
]);
|
||||
expect(rightDockableIds()).toEqual(["connections"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("registered rail items", () => {
|
||||
const item = (id: string, extra: object = {}) => ({
|
||||
id,
|
||||
icon: Boxes,
|
||||
labelKey: `nav.${id}`,
|
||||
pluginId: "p",
|
||||
...extra,
|
||||
});
|
||||
|
||||
it("places items after their anchor, keeping their own order", () => {
|
||||
registerRailItem(item("second", { after: "connections", order: 2 }));
|
||||
registerRailItem(item("first", { after: "connections", order: 1 }));
|
||||
const ids = visibleRailItems().map((entry) => entry.id);
|
||||
const at = ids.indexOf("connections");
|
||||
expect(ids.slice(at + 1, at + 3)).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
it("goes to the end when its anchor does not exist", () => {
|
||||
registerRailItem(item("orphan", { after: "nowhere" }));
|
||||
expect(visibleRailItems().at(-1)?.id).toBe("orphan");
|
||||
});
|
||||
|
||||
it("feeds its flags into the promotable, dock and hideable lists", () => {
|
||||
registerRailItem(item("docked", { promotable: true, rightDockable: true }));
|
||||
registerPanel({ id: "docked", component: () => null });
|
||||
registerRailItem(item("pinned", { hideable: false }));
|
||||
expect(promotableIds()).toContain("docked");
|
||||
expect(rightDockableIds()).toContain("docked");
|
||||
expect(hideableRailIds()).toContain("docked");
|
||||
expect(hideableRailIds()).not.toContain("pinned");
|
||||
});
|
||||
|
||||
it("drops a hidden item everywhere without unregistering it", () => {
|
||||
registerRailItem(item("off", { hidden: true, promotable: true }));
|
||||
registerPanel({ id: "off", component: () => null });
|
||||
expect(visibleRailItems().map((entry) => entry.id)).not.toContain("off");
|
||||
expect(hideableRailIds()).not.toContain("off");
|
||||
expect(promotableIds()).not.toContain("off");
|
||||
});
|
||||
|
||||
it("labels a registered item by its own key", () => {
|
||||
registerRailItem(item("labelled"));
|
||||
expect(railItemLabel("labelled", (key) => `t:${key}`)).toBe(
|
||||
"t:nav.labelled",
|
||||
);
|
||||
});
|
||||
|
||||
it("disposes only the entry it registered", () => {
|
||||
const dispose = registerRailItem(item("same", { order: 1 }));
|
||||
registerRailItem(item("same", { order: 2 }));
|
||||
dispose();
|
||||
expect(visibleRailItems().map((entry) => entry.id)).toContain("same");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -157,15 +193,27 @@ describe("railItemLabel", () => {
|
||||
delete (window as { IS_ELECTRON?: boolean }).IS_ELECTRON;
|
||||
});
|
||||
|
||||
const desktopOnly = {
|
||||
id: "desktop-only",
|
||||
icon: Boxes,
|
||||
labelKey: "nav.desktopOnly",
|
||||
pluginId: "p",
|
||||
electronOnly: true,
|
||||
};
|
||||
|
||||
it("hides electron-only destinations in the browser build", () => {
|
||||
const dispose = registerRailItem(desktopOnly);
|
||||
const ids = visibleRailItems().map((item) => item.id);
|
||||
expect(ids).not.toContain("local-terminal");
|
||||
dispose();
|
||||
expect(ids).not.toContain("desktop-only");
|
||||
});
|
||||
|
||||
it("shows electron-only destinations in the desktop app", () => {
|
||||
(window as { IS_ELECTRON?: boolean }).IS_ELECTRON = true;
|
||||
const dispose = registerRailItem(desktopOnly);
|
||||
const ids = visibleRailItems().map((item) => item.id);
|
||||
expect(ids).toContain("local-terminal");
|
||||
dispose();
|
||||
expect(ids).toContain("desktop-only");
|
||||
});
|
||||
|
||||
it("keeps every non-electron item in both builds", () => {
|
||||
@@ -181,3 +229,39 @@ describe("railItemLabel", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("permittedRailItems", () => {
|
||||
const items = [
|
||||
{ id: "open", icon: Boxes, labelKey: "nav.hosts" },
|
||||
{
|
||||
id: "gated",
|
||||
icon: Boxes,
|
||||
labelKey: "nav.hosts",
|
||||
permission: "demo.use",
|
||||
},
|
||||
];
|
||||
|
||||
it("hides an item gated on a permission the user lacks", () => {
|
||||
const ids = permittedRailItems(items, {
|
||||
loaded: true,
|
||||
has: () => false,
|
||||
}).map((item) => item.id);
|
||||
expect(ids).toEqual(["open"]);
|
||||
});
|
||||
|
||||
it("shows it once the user holds the permission", () => {
|
||||
const ids = permittedRailItems(items, {
|
||||
loaded: true,
|
||||
has: (permission) => permission === "demo.use",
|
||||
}).map((item) => item.id);
|
||||
expect(ids).toEqual(["open", "gated"]);
|
||||
});
|
||||
|
||||
it("keeps gated items hidden until permissions have loaded", () => {
|
||||
const ids = permittedRailItems(items, {
|
||||
loaded: false,
|
||||
has: () => true,
|
||||
}).map((item) => item.id);
|
||||
expect(ids).toEqual(["open"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* The role editor's permission catalog: plugin grouping, the disabled state,
|
||||
* and what actually gets saved.
|
||||
*
|
||||
* The behaviour that matters is that a disabled plugin's permission stays
|
||||
* ticked and stays in the payload. Dropping it would silently revoke a grant
|
||||
* just because the plugin happened to be off.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
|
||||
import { AdminRolesSection } from "../../sidebar/AdminManagementSections";
|
||||
import type { PermissionCatalogEntry, Role } from "../../main-axios";
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
getPermissionsCatalog: vi.fn(),
|
||||
updateRole: vi.fn(
|
||||
async (_roleId: number, _update: { permissions?: string[] }) => ({}),
|
||||
),
|
||||
deleteRole: vi.fn(async () => ({})),
|
||||
getRoleMembers: vi.fn(async () => ({ members: [] as unknown[] })),
|
||||
getSessions: vi.fn(async () => ({ sessions: [] as unknown[] })),
|
||||
revokeSession: vi.fn(async () => ({})),
|
||||
}));
|
||||
|
||||
vi.mock("@/main-axios", () => api);
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("sonner", () => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
const CATALOG: PermissionCatalogEntry[] = [
|
||||
{
|
||||
group: "hosts",
|
||||
labelKey: "admin.rolePermissions.groups.hosts",
|
||||
permissions: ["hosts.view", "hosts.create"],
|
||||
},
|
||||
{
|
||||
group: "ai",
|
||||
pluginId: "ai",
|
||||
label: "AI Assistant",
|
||||
icon: "Sparkles",
|
||||
enabled: false,
|
||||
permissions: ["ai.use"],
|
||||
items: [
|
||||
{
|
||||
permission: "ai.use",
|
||||
titleKey: "permissions.use.title",
|
||||
descriptionKey: "permissions.use.description",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "automations",
|
||||
pluginId: "automations",
|
||||
label: "Automations",
|
||||
icon: "Workflow",
|
||||
enabled: true,
|
||||
permissions: ["automations.run"],
|
||||
items: [
|
||||
{
|
||||
permission: "automations.run",
|
||||
titleKey: "permissions.run.title",
|
||||
descriptionKey: "permissions.run.description",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function makeRole(permissions: string[]): Role {
|
||||
return {
|
||||
id: 7,
|
||||
name: "operators",
|
||||
displayName: "Operators",
|
||||
description: null,
|
||||
isSystem: false,
|
||||
permissions,
|
||||
createdAt: "",
|
||||
updatedAt: "",
|
||||
};
|
||||
}
|
||||
|
||||
function renderSection(role: Role) {
|
||||
return render(
|
||||
<AdminRolesSection
|
||||
open
|
||||
onToggle={() => {}}
|
||||
roles={[role]}
|
||||
setRoles={() => {}}
|
||||
showCreateRole={false}
|
||||
setShowCreateRole={() => {}}
|
||||
newRoleName=""
|
||||
setNewRoleName={() => {}}
|
||||
newRoleDisplayName=""
|
||||
setNewRoleDisplayName={() => {}}
|
||||
newRoleDescription=""
|
||||
setNewRoleDescription={() => {}}
|
||||
handleCreateRole={() => {}}
|
||||
createRoleLoading={false}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
async function openEditor(role: Role) {
|
||||
const user = userEvent.setup();
|
||||
renderSection(role);
|
||||
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: /admin.rolePermissions.editAction/i }),
|
||||
);
|
||||
await waitFor(() => expect(api.getPermissionsCatalog).toHaveBeenCalled());
|
||||
return user;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
api.getPermissionsCatalog.mockResolvedValue({ catalog: CATALOG });
|
||||
});
|
||||
|
||||
describe("role permission groups", () => {
|
||||
it("labels a core group by its i18n key, not the raw wildcard", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(screen.getByText("admin.rolePermissions.groups.hosts")).toBeTruthy();
|
||||
expect(screen.queryByText("hosts.*")).toBeNull();
|
||||
});
|
||||
|
||||
it("labels a plugin group with the plugin's display name", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(screen.getByText("AI Assistant")).toBeTruthy();
|
||||
expect(screen.getByText("Automations")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows a plugin permission's title beside its raw id", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(screen.getByText("automations:permissions.run.title")).toBeTruthy();
|
||||
expect(screen.getByText("automations.run")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("marks a disabled plugin's group", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(
|
||||
screen.getByText("admin.rolePermissions.pluginDisabled"),
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not mark an enabled plugin's group", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(
|
||||
screen.getAllByText("admin.rolePermissions.pluginDisabled"),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("lists a group once per catalog entry", async () => {
|
||||
await openEditor(makeRole([]));
|
||||
|
||||
expect(screen.getAllByText("AI Assistant")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saving a role", () => {
|
||||
// The regression A5 fixes: the permission must survive the round trip even
|
||||
// though its plugin is disabled.
|
||||
it("keeps a disabled plugin's permission in the payload", async () => {
|
||||
const role = makeRole(["hosts.view", "ai.use"]);
|
||||
const user = await openEditor(role);
|
||||
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: /admin.rolePermissions.save/i }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(api.updateRole).toHaveBeenCalled());
|
||||
const [, payload] = api.updateRole.mock.calls[0];
|
||||
expect(payload.permissions).toContain("ai.use");
|
||||
expect(payload.permissions).toContain("hosts.view");
|
||||
});
|
||||
|
||||
it("still lets a disabled plugin's permission be revoked deliberately", async () => {
|
||||
const role = makeRole(["hosts.view", "ai.use"]);
|
||||
const user = await openEditor(role);
|
||||
|
||||
await user.click(screen.getByText("ai.use"));
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: /admin.rolePermissions.save/i }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(api.updateRole).toHaveBeenCalled());
|
||||
const [, payload] = api.updateRole.mock.calls[0];
|
||||
expect(payload.permissions).not.toContain("ai.use");
|
||||
expect(payload.permissions).toContain("hosts.view");
|
||||
});
|
||||
});
|
||||
@@ -25,14 +25,6 @@ function host(id: string, name: string): Host {
|
||||
authType: "password",
|
||||
pin: false,
|
||||
enableSsh: true,
|
||||
enableTerminal: true,
|
||||
enableTunnel: false,
|
||||
enableFileManager: true,
|
||||
enableDocker: false,
|
||||
enableRdp: false,
|
||||
enableVnc: false,
|
||||
enableTelnet: false,
|
||||
quickActions: [],
|
||||
} as Host;
|
||||
}
|
||||
|
||||
@@ -133,6 +125,34 @@ describe("collectVisibleRows with sub-host nesting", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectVisibleRows with group-by views", () => {
|
||||
it("gives each occurrence of a multi-tag host a distinct parentPath", () => {
|
||||
// Group-by-tags puts the same host under one synthetic folder per tag,
|
||||
// so a host with two tags shows up twice in the tree with the same id.
|
||||
const multiTagHost = host("9", "shared-box");
|
||||
const tree: (Host | HostFolder)[] = [
|
||||
{
|
||||
name: "prod",
|
||||
path: "__group__:tag:prod",
|
||||
children: [multiTagHost],
|
||||
},
|
||||
{
|
||||
name: "web",
|
||||
path: "__group__:tag:web",
|
||||
children: [multiTagHost],
|
||||
},
|
||||
];
|
||||
const rows = collectVisibleRows(
|
||||
tree,
|
||||
"",
|
||||
new Set(["__group__:tag:prod", "__group__:tag:web"]),
|
||||
);
|
||||
const hostRows = rows.filter((r) => !isFolder(r.item));
|
||||
expect(hostRows).toHaveLength(2);
|
||||
expect(hostRows[0].parentPath).not.toBe(hostRows[1].parentPath);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildReorderRows", () => {
|
||||
it("keys folders by path and hosts by id", () => {
|
||||
const folder: HostFolder = {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
} from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Host } from "@/types/ui-types";
|
||||
import { registerHostAction } from "@/sidebar/host-contributions";
|
||||
import { LOCAL_ADAPTIVE_PREFERENCES_KEY } from "@/lib/local-adaptive-preferences";
|
||||
|
||||
const { markTabSurfaceUsedMock, preloadTabSurfaceMock } = vi.hoisted(() => ({
|
||||
@@ -35,7 +42,6 @@ vi.mock("@/hooks/use-status-color-scheme", () => ({
|
||||
|
||||
vi.mock("@/main-axios", () => ({
|
||||
getHostPassword: vi.fn(),
|
||||
wakeOnLan: vi.fn(),
|
||||
}));
|
||||
|
||||
import { HostItem } from "../../../../sidebar/tree/HostItem/HostItem";
|
||||
@@ -60,12 +66,9 @@ const baseHost: Host = {
|
||||
enableCommandHistory: true,
|
||||
enableTunnel: true,
|
||||
enableFileManager: true,
|
||||
enableDocker: true,
|
||||
enableRdp: true,
|
||||
enableVnc: true,
|
||||
enableTelnet: true,
|
||||
macAddress: "aa:bb:cc:dd:ee:ff",
|
||||
quickActions: [],
|
||||
} as unknown as Host;
|
||||
|
||||
const noop = () => {};
|
||||
@@ -140,7 +143,6 @@ describe("HostItem density parity", () => {
|
||||
0,
|
||||
);
|
||||
expect(screen.getAllByText("hosts.shareHost").length).toBeGreaterThan(0);
|
||||
expect(screen.getByText("hosts.wakeOnLanAction")).toBeTruthy();
|
||||
});
|
||||
|
||||
it.each(["comfortable", "compact"] as const)(
|
||||
@@ -154,20 +156,26 @@ describe("HostItem density parity", () => {
|
||||
);
|
||||
|
||||
it.each(["comfortable", "compact"] as const)(
|
||||
"exposes RDP, VNC, and Telnet quick-launch buttons in %s density",
|
||||
"exposes plugin connect actions as quick-launch buttons in %s density",
|
||||
(density) => {
|
||||
renderHostItem(density);
|
||||
expect(screen.getByTitle("hosts.connectRdp")).toBeTruthy();
|
||||
expect(screen.getByTitle("hosts.connectVnc")).toBeTruthy();
|
||||
expect(screen.getByTitle("hosts.connectTelnet")).toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["comfortable", "compact"] as const)(
|
||||
"exposes the wake-on-LAN button when a MAC address is set, in %s density",
|
||||
(density) => {
|
||||
renderHostItem(density);
|
||||
expect(screen.getByTitle("hosts.wakeOnLanAction")).toBeTruthy();
|
||||
const Icon = (() => null) as never;
|
||||
const disposers = ["desk", "screen"].map((id) =>
|
||||
registerHostAction({
|
||||
id,
|
||||
titleKey: `fixture.${id}`,
|
||||
icon: Icon,
|
||||
kind: "connect",
|
||||
tabType: id,
|
||||
when: () => true,
|
||||
}),
|
||||
);
|
||||
try {
|
||||
renderHostItem(density);
|
||||
expect(screen.getByTitle("fixture.desk")).toBeTruthy();
|
||||
expect(screen.getByTitle("fixture.screen")).toBeTruthy();
|
||||
} finally {
|
||||
disposers.forEach((dispose) => dispose());
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -179,6 +187,30 @@ describe("HostItem density parity", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["hover", "click", "always", "actionsOnly"] as const)(
|
||||
"keeps the compact host address visible with %s actions",
|
||||
(trayTrigger) => {
|
||||
const props = {
|
||||
host: baseHost,
|
||||
onOpenTab: noop,
|
||||
onDelete: noop,
|
||||
onDuplicate: noop,
|
||||
density: "compact" as const,
|
||||
trayTrigger,
|
||||
};
|
||||
const { rerender } = render(<HostItem {...props} />);
|
||||
expect(screen.getByText(baseHost.ip).classList.contains("hidden")).toBe(
|
||||
false,
|
||||
);
|
||||
rerender(<HostItem {...props} isHovered />);
|
||||
expect(screen.getByText(baseHost.ip).classList.contains("hidden")).toBe(
|
||||
false,
|
||||
);
|
||||
rerender(<HostItem {...props} isTrayOpen selectionMode />);
|
||||
expect(screen.getAllByText(baseHost.ip)).toHaveLength(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("shows tags in both densities when showTags is true", () => {
|
||||
renderHostItem("comfortable");
|
||||
expect(screen.getByText("prod")).toBeTruthy();
|
||||
@@ -187,6 +219,13 @@ describe("HostItem density parity", () => {
|
||||
expect(screen.getByText("prod")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("puts compact tags on the name row instead of their own line", () => {
|
||||
renderHostItem("compact");
|
||||
const tag = screen.getByText("prod");
|
||||
expect(tag.dataset.testid).toBe("host-inline-tag");
|
||||
expect(tag.closest("[data-drag-label]")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("hides tags in both densities when showTags is false", () => {
|
||||
render(
|
||||
<HostItem
|
||||
@@ -203,17 +242,118 @@ describe("HostItem density parity", () => {
|
||||
});
|
||||
|
||||
it("learns repeated local actions and preloads the preferred host tool", () => {
|
||||
renderHostItem("comfortable");
|
||||
const filesButton = screen.getByTitle("Files");
|
||||
fireEvent.click(filesButton);
|
||||
fireEvent.click(filesButton);
|
||||
fireEvent.click(filesButton);
|
||||
const Icon = (() => null) as never;
|
||||
const dispose = registerHostAction({
|
||||
id: "tmux_monitor",
|
||||
titleKey: "Tmux Monitor",
|
||||
icon: Icon,
|
||||
kind: "open",
|
||||
tabType: "tmux_monitor",
|
||||
when: () => true,
|
||||
});
|
||||
try {
|
||||
renderHostItem("comfortable");
|
||||
const tmuxButton = screen.getByTitle("Tmux Monitor");
|
||||
fireEvent.click(tmuxButton);
|
||||
fireEvent.click(tmuxButton);
|
||||
fireEvent.click(tmuxButton);
|
||||
|
||||
const hostRow = screen.getByText("web-01").closest(".cursor-pointer");
|
||||
expect(hostRow).toBeTruthy();
|
||||
fireEvent.pointerEnter(hostRow!);
|
||||
const hostRow = screen.getByText("web-01").closest(".cursor-pointer");
|
||||
expect(hostRow).toBeTruthy();
|
||||
fireEvent.pointerEnter(hostRow!);
|
||||
|
||||
expect(preloadTabSurfaceMock).toHaveBeenCalledWith("terminal");
|
||||
expect(preloadTabSurfaceMock).toHaveBeenCalledWith("files");
|
||||
// No plugin registered a connect action, so only the learned tool preloads.
|
||||
expect(preloadTabSurfaceMock).not.toHaveBeenCalledWith("");
|
||||
expect(preloadTabSurfaceMock).toHaveBeenCalledWith("tmux_monitor");
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("HostItem click behavior", () => {
|
||||
function setup(
|
||||
hostClickBehavior:
|
||||
"newTab" | "focusExisting" | "focusExistingDoubleClickNew",
|
||||
) {
|
||||
const Icon = (() => null) as never;
|
||||
const dispose = registerHostAction({
|
||||
id: "terminal_test",
|
||||
titleKey: "Terminal",
|
||||
icon: Icon,
|
||||
kind: "connect",
|
||||
tabType: "terminal",
|
||||
when: () => true,
|
||||
});
|
||||
const onOpenTab = vi.fn();
|
||||
render(
|
||||
<HostItem
|
||||
host={baseHost}
|
||||
onOpenTab={onOpenTab}
|
||||
onDelete={noop}
|
||||
onDuplicate={noop}
|
||||
hostClickBehavior={hostClickBehavior}
|
||||
/>,
|
||||
);
|
||||
const row = screen.getByText("web-01").closest(".cursor-pointer")!;
|
||||
return { onOpenTab, row, dispose };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("always opens a new tab by default", () => {
|
||||
const { onOpenTab, row, dispose } = setup("newTab");
|
||||
try {
|
||||
fireEvent.click(row);
|
||||
expect(onOpenTab).toHaveBeenCalledWith("terminal", { forceNewTab: true });
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("switches to the open tab when set to focus existing", () => {
|
||||
const { onOpenTab, row, dispose } = setup("focusExisting");
|
||||
try {
|
||||
fireEvent.click(row);
|
||||
expect(onOpenTab).toHaveBeenCalledWith("terminal", {
|
||||
forceNewTab: false,
|
||||
});
|
||||
fireEvent.click(row, { ctrlKey: true });
|
||||
expect(onOpenTab).toHaveBeenLastCalledWith("terminal", {
|
||||
forceNewTab: true,
|
||||
});
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("switches on a single click and opens a new tab on a double click", () => {
|
||||
vi.useFakeTimers();
|
||||
const { onOpenTab, row, dispose } = setup("focusExistingDoubleClickNew");
|
||||
try {
|
||||
fireEvent.click(row, { detail: 1 });
|
||||
expect(onOpenTab).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
vi.runAllTimers();
|
||||
});
|
||||
expect(onOpenTab).toHaveBeenCalledTimes(1);
|
||||
expect(onOpenTab).toHaveBeenCalledWith("terminal", {
|
||||
forceNewTab: false,
|
||||
});
|
||||
|
||||
onOpenTab.mockClear();
|
||||
fireEvent.click(row, { detail: 1 });
|
||||
fireEvent.click(row, { detail: 2 });
|
||||
fireEvent.doubleClick(row);
|
||||
act(() => {
|
||||
vi.runAllTimers();
|
||||
});
|
||||
expect(onOpenTab).toHaveBeenCalledTimes(1);
|
||||
expect(onOpenTab).toHaveBeenCalledWith("terminal", { forceNewTab: true });
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getSshActions } from "@/sidebar/tree/HostItem/HostItem";
|
||||
import type { Host } from "@/types/ui-types";
|
||||
import type { WebEndpoint } from "@/types/index";
|
||||
|
||||
function endpoint(overrides: Partial<WebEndpoint> = {}): WebEndpoint {
|
||||
return {
|
||||
id: "e1",
|
||||
label: "Proxmox",
|
||||
scheme: "https",
|
||||
port: 8006,
|
||||
path: "/",
|
||||
access: "direct",
|
||||
render: "embedded",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function host(overrides: Partial<Host> = {}): Host {
|
||||
return {
|
||||
id: "7",
|
||||
ip: "10.0.0.5",
|
||||
name: "nas",
|
||||
enableSsh: false,
|
||||
enableWebUi: false,
|
||||
...overrides,
|
||||
} as unknown as Host;
|
||||
}
|
||||
|
||||
const webActions = (h: Host) =>
|
||||
getSshActions(h).filter((action) => action.type === "web-endpoint");
|
||||
|
||||
describe("the sidebar Web UI entry", () => {
|
||||
it("is absent when the feature is off, even with endpoints configured", () => {
|
||||
expect(
|
||||
webActions(
|
||||
host({ enableWebUi: false, webUiConfig: { endpoints: [endpoint()] } }),
|
||||
),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("is absent when enabled but no endpoints exist", () => {
|
||||
expect(
|
||||
webActions(host({ enableWebUi: true, webUiConfig: { endpoints: [] } })),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("appears without SSH, unlike every other entry", () => {
|
||||
// A direct endpoint needs no SSH at all; SSH matters only per-endpoint,
|
||||
// for tunnel access, which the open route enforces.
|
||||
const actions = getSshActions(
|
||||
host({
|
||||
enableSsh: false,
|
||||
enableWebUi: true,
|
||||
webUiConfig: { endpoints: [endpoint()] },
|
||||
}),
|
||||
);
|
||||
expect(actions.filter((a) => a.type === "web-endpoint")).toHaveLength(1);
|
||||
expect(actions.filter((a) => a.type === "terminal")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("is ONE entry carrying the label and id when there is a single endpoint", () => {
|
||||
const [action] = webActions(
|
||||
host({
|
||||
enableWebUi: true,
|
||||
webUiConfig: { endpoints: [endpoint({ label: "Proxmox" })] },
|
||||
}),
|
||||
);
|
||||
expect(action.label).toBe("Proxmox");
|
||||
expect(action.endpointId).toBe("e1");
|
||||
});
|
||||
|
||||
it("is still ONE entry, with no id, when there are several", () => {
|
||||
// A host may declare up to 16; a row of 16 identical globes is unusable.
|
||||
// No endpointId is what makes the click surface a picker instead.
|
||||
const endpoints = Array.from({ length: 16 }, (_, i) =>
|
||||
endpoint({ id: `e${i}`, label: `Endpoint ${i}` }),
|
||||
);
|
||||
const actions = webActions(
|
||||
host({ enableWebUi: true, webUiConfig: { endpoints } }),
|
||||
);
|
||||
expect(actions).toHaveLength(1);
|
||||
expect(actions[0].endpointId).toBeUndefined();
|
||||
expect(actions[0].label).toBe("Web UI");
|
||||
});
|
||||
|
||||
it("comes last, after the SSH connection actions", () => {
|
||||
const actions = getSshActions(
|
||||
host({
|
||||
enableSsh: true,
|
||||
enableTerminal: true,
|
||||
enableWebUi: true,
|
||||
webUiConfig: { endpoints: [endpoint()] },
|
||||
} as Partial<Host>),
|
||||
);
|
||||
expect(actions[actions.length - 1].type).toBe("web-endpoint");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { registerHostProtocol } from "@/sidebar/host-protocols";
|
||||
import type { Host } from "@/types/ui-types";
|
||||
import {
|
||||
buildStatusTooltip,
|
||||
statusCheckEnabled,
|
||||
} from "@/sidebar/tree/HostItem/HostItem";
|
||||
|
||||
// Minimal host factory – only the fields buildStatusTooltip reads.
|
||||
function makeHost(overrides: Partial<Host> = {}): Host {
|
||||
return {
|
||||
id: 1,
|
||||
name: "test-host",
|
||||
ip: "127.0.0.1",
|
||||
username: "user",
|
||||
enableSsh: true,
|
||||
enableRdp: false,
|
||||
enableVnc: false,
|
||||
enableTelnet: false,
|
||||
statusCheckEnabled: true,
|
||||
...overrides,
|
||||
} as unknown as Host;
|
||||
}
|
||||
|
||||
// Translator that returns human-readable labels, not key paths.
|
||||
// This is what the review asked for: assert the rendered labels,
|
||||
// not the key paths the translator falls back to when a resource is missing.
|
||||
const t = (key: string): string =>
|
||||
({
|
||||
"hosts.status.available": "Available",
|
||||
"hosts.status.reachable": "Reachable, not authenticated",
|
||||
"hosts.status.offline": "Offline",
|
||||
"hosts.status.monitoringDisabled": "Monitoring disabled",
|
||||
})[key] ?? key;
|
||||
|
||||
describe("buildStatusTooltip", () => {
|
||||
it("returns the translated 'Available' label for online status", () => {
|
||||
const host = makeHost();
|
||||
const tooltip = buildStatusTooltip(host, "online", t);
|
||||
expect(tooltip).toContain("Available");
|
||||
expect(tooltip).not.toContain("hosts.status.");
|
||||
});
|
||||
|
||||
it("returns the translated 'Reachable, not authenticated' label for reachable status", () => {
|
||||
const host = makeHost();
|
||||
const tooltip = buildStatusTooltip(host, "reachable", t);
|
||||
expect(tooltip).toContain("Reachable, not authenticated");
|
||||
expect(tooltip).not.toContain("hosts.status.");
|
||||
});
|
||||
|
||||
it("returns the translated 'Offline' label for offline status", () => {
|
||||
const host = makeHost();
|
||||
const tooltip = buildStatusTooltip(host, "offline", t);
|
||||
expect(tooltip).toContain("Offline");
|
||||
expect(tooltip).not.toContain("hosts.status.");
|
||||
});
|
||||
|
||||
it("returns 'Monitoring disabled' when status check is disabled", () => {
|
||||
const host = makeHost({ statusCheckEnabled: false });
|
||||
const tooltip = buildStatusTooltip(host, "online", t);
|
||||
expect(tooltip).toBe("Monitoring disabled");
|
||||
});
|
||||
|
||||
it("includes protocol names in the tooltip when protocols are enabled", () => {
|
||||
const dispose = registerHostProtocol({
|
||||
id: "demo-desktop",
|
||||
pluginId: "demo",
|
||||
settingKey: "enableDemo",
|
||||
defaultPort: 3389,
|
||||
titleKey: "Demo Desktop",
|
||||
icon: () => null,
|
||||
});
|
||||
const host = makeHost({
|
||||
enableSsh: true,
|
||||
pluginSettings: { demo: { enableDemo: true } },
|
||||
});
|
||||
const tooltip = buildStatusTooltip(host, "online", t);
|
||||
dispose();
|
||||
expect(tooltip).toContain("SSH");
|
||||
expect(tooltip).toContain("Demo Desktop");
|
||||
expect(tooltip).toContain("Available");
|
||||
});
|
||||
|
||||
it("returns just the status label when no protocols are enabled", () => {
|
||||
const host = makeHost({ enableSsh: false });
|
||||
const tooltip = buildStatusTooltip(host, "online", t);
|
||||
expect(tooltip).toBe("Available");
|
||||
});
|
||||
|
||||
it("does not render key paths when a translator is supplied", () => {
|
||||
const host = makeHost();
|
||||
const tooltip = buildStatusTooltip(host, "online", t);
|
||||
// The tooltip must never show the raw key path – that means the
|
||||
// translation resource is missing, which is the bug #1265 fixed.
|
||||
expect(tooltip).not.toMatch(/hosts\.status\./);
|
||||
});
|
||||
});
|
||||
|
||||
describe("statusCheckEnabled", () => {
|
||||
it("returns true when statusCheckEnabled is not set (default)", () => {
|
||||
const host = makeHost({ statusCheckEnabled: undefined });
|
||||
expect(statusCheckEnabled(host)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when statusCheckEnabled is explicitly false", () => {
|
||||
const host = makeHost({ statusCheckEnabled: false });
|
||||
expect(statusCheckEnabled(host)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useHostSpeedSearch } from "@/sidebar/tree/hooks/useHostSpeedSearch";
|
||||
|
||||
function SearchList({ activate }: { activate: (index: number) => void }) {
|
||||
const search = useHostSpeedSearch();
|
||||
return (
|
||||
<div
|
||||
data-testid="list"
|
||||
tabIndex={0}
|
||||
onKeyDown={(event) =>
|
||||
search.onKeyDown(
|
||||
event,
|
||||
search.text === "missing" ? 0 : 2,
|
||||
activate,
|
||||
() => {},
|
||||
)
|
||||
}
|
||||
>
|
||||
<input aria-label="unrelated editor" />
|
||||
<div
|
||||
contentEditable
|
||||
suppressContentEditableWarning
|
||||
data-testid="editable"
|
||||
/>
|
||||
{search.open && (
|
||||
<input
|
||||
aria-label="search"
|
||||
ref={search.inputRef}
|
||||
value={search.text}
|
||||
onChange={(event) => search.change(event.target.value)}
|
||||
/>
|
||||
)}
|
||||
<span data-testid="selection">{search.index}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe("host speed search keyboard", () => {
|
||||
it("starts from typing, navigates matches and closes with Escape", () => {
|
||||
const activate = vi.fn();
|
||||
render(<SearchList activate={activate} />);
|
||||
fireEvent.keyDown(screen.getByTestId("list"), { key: "a" });
|
||||
const input = screen.getByLabelText("search");
|
||||
expect((input as HTMLInputElement).value).toBe("a");
|
||||
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(activate).toHaveBeenLastCalledWith(1);
|
||||
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||
expect(screen.getByTestId("selection").textContent).toBe("0");
|
||||
fireEvent.keyDown(input, { key: "ArrowUp" });
|
||||
expect(screen.getByTestId("selection").textContent).toBe("1");
|
||||
fireEvent.keyDown(input, { key: "Escape" });
|
||||
expect(screen.queryByLabelText("search")).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts committed IME text without treating composition Enter as connect", () => {
|
||||
const activate = vi.fn();
|
||||
render(<SearchList activate={activate} />);
|
||||
fireEvent.keyDown(screen.getByTestId("list"), { key: "/" });
|
||||
const input = screen.getByLabelText("search");
|
||||
fireEvent.change(input, { target: { value: "服务器" } });
|
||||
fireEvent.keyDown(input, { key: "Enter", isComposing: true, keyCode: 229 });
|
||||
expect(activate).not.toHaveBeenCalled();
|
||||
expect((input as HTMLInputElement).value).toBe("服务器");
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(activate).toHaveBeenCalledWith(0);
|
||||
});
|
||||
|
||||
it("ignores other editors and modified shortcuts", () => {
|
||||
render(<SearchList activate={vi.fn()} />);
|
||||
fireEvent.keyDown(screen.getByLabelText("unrelated editor"), { key: "a" });
|
||||
fireEvent.keyDown(screen.getByTestId("editable"), { key: "b" });
|
||||
fireEvent.keyDown(screen.getByTestId("list"), { key: "c", ctrlKey: true });
|
||||
expect(screen.queryByLabelText("search")).toBeNull();
|
||||
});
|
||||
|
||||
it("resets selection after editing and does not open anything with no matches", () => {
|
||||
const activate = vi.fn();
|
||||
render(<SearchList activate={activate} />);
|
||||
fireEvent.keyDown(screen.getByTestId("list"), { key: "/" });
|
||||
const input = screen.getByLabelText("search");
|
||||
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||
fireEvent.change(input, { target: { value: "missing" } });
|
||||
expect(screen.getByTestId("selection").textContent).toBe("0");
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(activate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { act, fireEvent, render } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import type { Host, HostFolder } from "@/types/ui-types";
|
||||
import { SidebarTree } from "@/sidebar/tree/SidebarTree";
|
||||
|
||||
vi.mock("@/lib/host-connection-tabs", () => ({
|
||||
resolveHostTabType: () => "terminal",
|
||||
}));
|
||||
vi.mock("@/main-axios", () => ({}));
|
||||
vi.mock("@/api/plugins-api", () => ({}));
|
||||
vi.mock("@/settings/HostPluginSections", () => ({
|
||||
usePluginHostSections: () => [],
|
||||
}));
|
||||
vi.mock("@/contexts/UiPreferencesContext", () => ({
|
||||
useAreaPreferences: () => ({ showResourceBars: false, rowActions: "hover" }),
|
||||
}));
|
||||
vi.mock("@/sidebar/FolderMetadataDialog", () => ({
|
||||
FolderMetadataDialog: () => null,
|
||||
}));
|
||||
vi.mock("@/sidebar/HostShareModal", () => ({ HostShareModal: () => null }));
|
||||
vi.mock("@/sidebar/tree/FolderItem/FolderItem", () => ({
|
||||
FolderItem: () => <div>Folder</div>,
|
||||
folderHostCount: () => 1,
|
||||
}));
|
||||
vi.mock("@/sidebar/tree/HostItem/HostItem", () => ({
|
||||
HostItem: () => <div>Host</div>,
|
||||
}));
|
||||
|
||||
const observers: Array<{
|
||||
callback: ResizeObserverCallback;
|
||||
nodes: Set<Element>;
|
||||
}> = [];
|
||||
let hostHeight = 55;
|
||||
function rect(element: Element): DOMRect {
|
||||
const index = element.getAttribute("data-index");
|
||||
const height = index === "0" ? 40 : index === "1" ? hostHeight : 600;
|
||||
return {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 300,
|
||||
height,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 300,
|
||||
bottom: height,
|
||||
toJSON() {},
|
||||
};
|
||||
}
|
||||
function resize(rows: Element[]) {
|
||||
act(() => {
|
||||
for (const observer of observers) {
|
||||
const entries = rows
|
||||
.filter((row) => observer.nodes.has(row))
|
||||
.map(
|
||||
(target) =>
|
||||
({
|
||||
target,
|
||||
borderBoxSize: [
|
||||
{ blockSize: rect(target).height, inlineSize: 300 },
|
||||
],
|
||||
}) as unknown as ResizeObserverEntry,
|
||||
);
|
||||
if (entries.length) observer.callback(entries, {} as ResizeObserver);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem("hostOpenFolders", JSON.stringify(["group"]));
|
||||
hostHeight = 55;
|
||||
observers.length = 0;
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
nodes = new Set<Element>();
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
observers.push({ callback, nodes: this.nodes });
|
||||
}
|
||||
observe(node: Element) {
|
||||
this.nodes.add(node);
|
||||
}
|
||||
unobserve(node: Element) {
|
||||
this.nodes.delete(node);
|
||||
}
|
||||
disconnect() {
|
||||
this.nodes.clear();
|
||||
}
|
||||
},
|
||||
);
|
||||
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
|
||||
function () {
|
||||
return rect(this);
|
||||
},
|
||||
);
|
||||
vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(600);
|
||||
vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(300);
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it("keeps an unchanged folder's measured height after changing density", () => {
|
||||
const host = {
|
||||
id: "1",
|
||||
name: "Host",
|
||||
ip: "example.com",
|
||||
username: "test",
|
||||
} as Host;
|
||||
const children = [
|
||||
{ name: "group", path: "group", children: [host] },
|
||||
] as HostFolder[];
|
||||
const props = {
|
||||
children,
|
||||
onOpenTab: vi.fn(),
|
||||
onEditHost: vi.fn(),
|
||||
selectionMode: false,
|
||||
onToggleSelectionMode: vi.fn(),
|
||||
};
|
||||
const view = render(<SidebarTree {...props} density="comfortable" />);
|
||||
const rows = () =>
|
||||
Array.from(view.container.querySelectorAll("[data-index]"));
|
||||
expect(rows()).toHaveLength(2);
|
||||
resize(rows());
|
||||
expect((rows()[1] as HTMLElement).style.transform).toBe("translateY(40px)");
|
||||
hostHeight = 30;
|
||||
view.rerender(<SidebarTree {...props} density="compact" />);
|
||||
// Folder height is unchanged, so the browser only reports the host resize.
|
||||
resize([rows()[1]]);
|
||||
expect((rows()[1] as HTMLElement).style.transform).toBe("translateY(40px)");
|
||||
});
|
||||
|
||||
it("finds a host inside a closed folder and opens the keyboard-selected match", () => {
|
||||
const alpha = {
|
||||
id: "1",
|
||||
name: "alpha",
|
||||
ip: "192.0.2.1",
|
||||
username: "u",
|
||||
} as Host;
|
||||
const beta = {
|
||||
id: "2",
|
||||
name: "beta",
|
||||
ip: "192.0.2.2",
|
||||
username: "u",
|
||||
} as Host;
|
||||
const onOpenTab = vi.fn();
|
||||
const view = render(
|
||||
<SidebarTree
|
||||
children={[{ name: "closed", path: "closed", children: [alpha, beta] }]}
|
||||
onOpenTab={onOpenTab}
|
||||
onEditHost={vi.fn()}
|
||||
selectionMode={false}
|
||||
onToggleSelectionMode={vi.fn()}
|
||||
hostClickBehavior="focusExisting"
|
||||
/>,
|
||||
);
|
||||
const list = view.getByLabelText("hosts.speedSearchList");
|
||||
expect(view.container.querySelectorAll("[data-index]")).toHaveLength(1);
|
||||
fireEvent.keyDown(list, { key: "a" });
|
||||
const search = view.getByLabelText("hosts.speedSearch");
|
||||
expect(document.activeElement).toBe(search);
|
||||
expect(view.container.querySelectorAll("[data-index]")).toHaveLength(3);
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
expect(onOpenTab).toHaveBeenCalledWith(beta, "terminal", {
|
||||
forceNewTab: false,
|
||||
});
|
||||
fireEvent.keyDown(search, { key: "Escape" });
|
||||
expect(view.queryByLabelText("hosts.speedSearch")).toBeNull();
|
||||
expect(view.container.querySelectorAll("[data-index]")).toHaveLength(1);
|
||||
expect(document.activeElement).toBe(list);
|
||||
});
|
||||
Reference in new issue
Block a user