mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 06:35: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,65 @@
|
||||
import { CircleSlash } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePluginStore } from "./plugin-store";
|
||||
import { unregisteredViewStatus, type ViewKind } from "./view-ownership";
|
||||
|
||||
/**
|
||||
* Stands in for a tab, panel or card whose plugin is not running.
|
||||
*
|
||||
* A saved tab of a plugin that was switched off or removed must neither crash
|
||||
* the shell nor vanish without a word, so it renders this until the plugin is
|
||||
* back, at which point the real view takes over in place.
|
||||
*/
|
||||
export function PluginViewPlaceholder({
|
||||
kind,
|
||||
viewId,
|
||||
compact = false,
|
||||
}: {
|
||||
kind: ViewKind;
|
||||
viewId: string;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// Subscribing re-renders this when plugin state changes.
|
||||
usePluginStore();
|
||||
const { status, owner } = unregisteredViewStatus(kind, viewId);
|
||||
const name = owner?.summary.name ?? viewId;
|
||||
|
||||
if (status === "loading") {
|
||||
return (
|
||||
<div
|
||||
className="flex h-full w-full items-center justify-center"
|
||||
aria-label={t("plugins.runtime.loading", { name })}
|
||||
>
|
||||
<div className="size-5 rounded-full border-2 border-muted-foreground/30 border-t-muted-foreground/70 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const title =
|
||||
status === "failed"
|
||||
? t("plugins.runtime.failed", { name })
|
||||
: owner
|
||||
? t("plugins.runtime.needsPlugin", { name })
|
||||
: t("plugins.runtime.needsUnknownPlugin");
|
||||
const hint =
|
||||
status === "failed"
|
||||
? t("plugins.runtime.failedHint")
|
||||
: status === "disabled"
|
||||
? t("plugins.runtime.disabledHint")
|
||||
: t("plugins.runtime.missingHint");
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="plugin-view-placeholder"
|
||||
data-status={status}
|
||||
className={`flex h-full w-full flex-col items-center justify-center gap-2 text-center ${compact ? "p-3" : "p-6"}`}
|
||||
>
|
||||
<CircleSlash className="size-6 text-muted-foreground/40" />
|
||||
<span className="text-sm font-semibold text-muted-foreground">
|
||||
{title}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground/70">{hint}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type {
|
||||
Disposer,
|
||||
PluginManifest,
|
||||
TermixApp,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
PLUGIN_SETTINGS_CHANGED_EVENT,
|
||||
type PluginContributions,
|
||||
} from "@/api/plugins-api";
|
||||
import { registerRailItem } from "@/sidebar/rail-items";
|
||||
import { registerTabType, type TabRenderProps } from "@/shell/tab-registry";
|
||||
import { registerPanel, type PanelRenderProps } from "@/shell/panel-registry";
|
||||
import {
|
||||
registerHostEditorSection,
|
||||
type HostEditorSectionRenderProps,
|
||||
} from "@/sidebar/HostManagerTabs";
|
||||
import {
|
||||
registerHostAction,
|
||||
registerHostBadge,
|
||||
registerHostContextMenuItem,
|
||||
} from "@/sidebar/host-contributions";
|
||||
import {
|
||||
registerPaletteEntry,
|
||||
registerPaletteGroup,
|
||||
type PaletteItemDef,
|
||||
} from "@/shell/palette-registry";
|
||||
import {
|
||||
registerKeybindingAction,
|
||||
registerKeybindingDefault,
|
||||
type KeybindingEditorProps,
|
||||
} from "@/shell/keybinding-registry";
|
||||
import { registerHostProtocol } from "@/sidebar/host-protocols";
|
||||
import {
|
||||
registerDashboardCard,
|
||||
type DashboardCardRenderProps,
|
||||
} from "@/dashboard/dashboard-cards-registry";
|
||||
import { registerExtension } from "./extension-registry";
|
||||
import { registerSettingsComponent } from "@/settings/settings-components";
|
||||
import {
|
||||
declareActionSlot,
|
||||
invokeAction,
|
||||
registerAction,
|
||||
registerSlotContribution,
|
||||
} from "@/shell/action-registry";
|
||||
import { pluginApiFor, pluginFetch, pluginWsUrl } from "@/lib/plugin-transport";
|
||||
import { registerPluginComponent } from "./component-registry";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
registerLoginMethod,
|
||||
registerSecondFactor,
|
||||
registerSshAuthEditor,
|
||||
} from "./auth-registry";
|
||||
import {
|
||||
pluginHostBridge,
|
||||
resolvePluginPermission,
|
||||
toPluginHostRecord,
|
||||
} from "./bridge";
|
||||
import { shell, shellHost, tabsApi } from "./shell-bridge";
|
||||
import { onRemoteServerChange, remoteServerUrl } from "./desktop";
|
||||
import { isElectron } from "@/lib/electron";
|
||||
import { withPluginScope, withIconBoundary, guardCallback } from "./scope";
|
||||
import {
|
||||
scopeHostArgs,
|
||||
scopeHostCallback,
|
||||
scopeHostFields,
|
||||
} from "./host-scope";
|
||||
import { manifestDeclares, type ViewKind } from "./view-ownership";
|
||||
import { pluginKey } from "@/lib/plugin-i18n";
|
||||
import { hasPermission } from "@/hooks/use-permissions";
|
||||
import i18n from "@/i18n/i18n";
|
||||
|
||||
export interface PluginAppHandle {
|
||||
app: TermixApp;
|
||||
/** Runs every disposer, newest first, isolating failures. */
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the object a plugin's `activate(app)` receives.
|
||||
*
|
||||
* Every registration goes into one bag, so disabling the plugin removes all
|
||||
* of it whatever the plugin's own `deactivate` does. Components are wrapped
|
||||
* in the plugin's scope as they are registered, which is what gives the SDK
|
||||
* hooks their plugin id and keeps a crash inside the plugin's own box.
|
||||
*/
|
||||
export function createPluginApp(
|
||||
pluginId: string,
|
||||
manifest: PluginManifest,
|
||||
contributes: PluginContributions | null,
|
||||
options: { guest?: boolean } = {},
|
||||
): PluginAppHandle {
|
||||
const bag: Disposer[] = [];
|
||||
let disposed = false;
|
||||
|
||||
const track = (disposer: Disposer): Disposer => {
|
||||
// An activate that outlived its timeout, or ran on after a disable, still
|
||||
// registers things. Nothing will dispose them later, so undo them now.
|
||||
if (disposed) {
|
||||
try {
|
||||
disposer();
|
||||
} catch {
|
||||
// A failing disposer must not throw into the plugin's activate.
|
||||
}
|
||||
return () => {};
|
||||
}
|
||||
bag.push(disposer);
|
||||
return () => {
|
||||
const index = bag.indexOf(disposer);
|
||||
if (index >= 0) bag.splice(index, 1);
|
||||
disposer();
|
||||
};
|
||||
};
|
||||
|
||||
const scoped = <P extends object>(component: ComponentType<P>) =>
|
||||
withPluginScope(pluginId, component);
|
||||
|
||||
const key = (value: string) => pluginKey(pluginId, value);
|
||||
|
||||
// Every host a plugin callback receives carries only this plugin's settings.
|
||||
const hostCallback = <F extends (...args: never[]) => unknown>(
|
||||
fn: F | undefined,
|
||||
): F | undefined => scopeHostCallback(fn, pluginId);
|
||||
|
||||
const requireDeclared = (kind: ViewKind, id: string, what: string) => {
|
||||
if (!manifestDeclares(contributes, kind, id)) {
|
||||
const field =
|
||||
kind === "tab"
|
||||
? "contributes.tabs"
|
||||
: kind === "panel"
|
||||
? "contributes.panels or contributes.tabs"
|
||||
: "contributes.dashboardCards";
|
||||
throw new Error(
|
||||
`${pluginId}: ${what} "${id}" is not declared in manifest ${field}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const app: TermixApp = {
|
||||
pluginId,
|
||||
manifest,
|
||||
guest: !!options.guest,
|
||||
|
||||
registerRailItem(item) {
|
||||
requireDeclared("panel", item.id, "rail item");
|
||||
return track(
|
||||
registerRailItem({
|
||||
id: item.id,
|
||||
icon: withIconBoundary(
|
||||
pluginId,
|
||||
item.icon as unknown as LucideIcon,
|
||||
) as unknown as LucideIcon,
|
||||
labelKey: key(item.titleKey),
|
||||
kind: item.kind === "tab" ? "tab" : undefined,
|
||||
hideable: item.hideable,
|
||||
simplePreset: item.simplePreset,
|
||||
promotable: item.promotable,
|
||||
rightDockable: item.rightDockable,
|
||||
mobilePrimary: item.mobilePrimary,
|
||||
electronOnly: item.electronOnly,
|
||||
separatorAfter: item.separatorAfter ?? true,
|
||||
hidden: item.hidden,
|
||||
after: item.after,
|
||||
order: item.order,
|
||||
placement: item.placement,
|
||||
useBadge: item.useBadge,
|
||||
pluginId,
|
||||
permission: item.permission
|
||||
? resolvePluginPermission(pluginId, item.permission)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerPanel(id, component, options) {
|
||||
requireDeclared("panel", id, "panel");
|
||||
return track(
|
||||
registerPanel({
|
||||
id,
|
||||
pluginId,
|
||||
component: scoped(
|
||||
component as unknown as ComponentType<PanelRenderProps>,
|
||||
),
|
||||
keepMounted: options?.keepMounted,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerTab(type, component, options = {}) {
|
||||
requireDeclared("tab", type, "tab type");
|
||||
return track(
|
||||
registerTabType({
|
||||
id: type,
|
||||
pluginId,
|
||||
component: scoped(
|
||||
component as unknown as ComponentType<TabRenderProps>,
|
||||
),
|
||||
icon: withIconBoundary(pluginId, options.icon as never) as never,
|
||||
titleKey: options.titleKey ? key(options.titleKey) : undefined,
|
||||
requiresHost: options.requiresHost,
|
||||
noHostMessageKey: options.noHostMessageKey
|
||||
? key(options.noHostMessageKey)
|
||||
: undefined,
|
||||
persistent: options.persistent,
|
||||
singleton: options.singleton,
|
||||
session: options.session,
|
||||
hostless: options.hostless,
|
||||
restore: options.restore as never,
|
||||
activityTypes: options.activityTypes,
|
||||
standalone: options.standalone
|
||||
? scoped(options.standalone)
|
||||
: undefined,
|
||||
standaloneViews: options.standaloneViews,
|
||||
panelFrame: options.panelFrame,
|
||||
inLayouts: options.inLayouts,
|
||||
commandTarget: options.commandTarget,
|
||||
ownBackground: options.ownBackground,
|
||||
multiInstance: options.multiInstance,
|
||||
preload: options.preload,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerHostEditorSection(section) {
|
||||
return track(
|
||||
registerHostEditorSection({
|
||||
id: section.id,
|
||||
pluginId,
|
||||
group: section.group,
|
||||
labelKey: key(section.titleKey),
|
||||
icon: withIconBoundary(pluginId, section.icon as never) as never,
|
||||
order: section.order,
|
||||
visible: section.visible,
|
||||
defaults: section.defaults,
|
||||
component: scoped(
|
||||
section.component as unknown as ComponentType<HostEditorSectionRenderProps>,
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerHostAction(action) {
|
||||
return track(
|
||||
registerHostAction({
|
||||
...action,
|
||||
titleKey: key(action.titleKey),
|
||||
pluginId,
|
||||
icon: withIconBoundary(pluginId, action.icon as never) as never,
|
||||
when: hostCallback(action.when) as never,
|
||||
run: hostCallback(action.run) as never,
|
||||
// Called while the host list renders, so a throw must not escape.
|
||||
label: guardCallback(
|
||||
pluginId,
|
||||
hostCallback(
|
||||
action.label as ((...args: unknown[]) => unknown) | undefined,
|
||||
),
|
||||
undefined,
|
||||
) as never,
|
||||
items: guardCallback(
|
||||
pluginId,
|
||||
action.items
|
||||
? (...args: unknown[]) =>
|
||||
(
|
||||
action.items as (
|
||||
...a: unknown[]
|
||||
) => { run: (...a: never[]) => unknown }[]
|
||||
)(...scopeHostArgs(args, pluginId))?.map((item) => ({
|
||||
...item,
|
||||
run: hostCallback(item.run),
|
||||
}))
|
||||
: undefined,
|
||||
undefined,
|
||||
) as never,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerHostProtocol(protocol) {
|
||||
return track(
|
||||
registerHostProtocol({
|
||||
...protocol,
|
||||
pluginId,
|
||||
titleKey: key(protocol.titleKey),
|
||||
descriptionKey: protocol.descriptionKey
|
||||
? key(protocol.descriptionKey)
|
||||
: undefined,
|
||||
connectionOriginNoteKey: protocol.connectionOriginNoteKey
|
||||
? key(protocol.connectionOriginNoteKey)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerHostBadge(badge) {
|
||||
return track(
|
||||
registerHostBadge({
|
||||
id: badge.id,
|
||||
pluginId,
|
||||
when: hostCallback(badge.when) as never,
|
||||
component: scoped(badge.component) as never,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerHostContextMenuItem(item) {
|
||||
return track(
|
||||
registerHostContextMenuItem({
|
||||
...item,
|
||||
titleKey: key(item.titleKey),
|
||||
pluginId,
|
||||
when: hostCallback(item.when) as never,
|
||||
run: hostCallback(item.run) as never,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerPaletteEntry(entry) {
|
||||
return track(
|
||||
registerPaletteEntry({
|
||||
...entry,
|
||||
titleKey: key(entry.titleKey),
|
||||
pluginId,
|
||||
when: hostCallback(entry.when) as never,
|
||||
run: hostCallback(entry.run) as never,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerPaletteGroup(group) {
|
||||
return track(
|
||||
registerPaletteGroup({
|
||||
id: group.id,
|
||||
pluginId,
|
||||
titleKey: key(group.titleKey),
|
||||
order: group.order,
|
||||
showWhenEmpty: group.showWhenEmpty,
|
||||
load: group.load as unknown as () => Promise<PaletteItemDef[]>,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerKeybindingAction(action) {
|
||||
const declared = (manifest.contributes?.keybindingActions ?? []).some(
|
||||
(entry) => entry.id === action.id,
|
||||
);
|
||||
if (!declared) {
|
||||
throw new Error(
|
||||
`${pluginId}: keybinding action "${action.id}" is not declared in manifest contributes.keybindingActions`,
|
||||
);
|
||||
}
|
||||
const validate = action.validate;
|
||||
return track(
|
||||
registerKeybindingAction({
|
||||
id: action.id,
|
||||
pluginId,
|
||||
labelKey: key(action.titleKey),
|
||||
scope: action.scope ?? "session",
|
||||
editor: action.editor
|
||||
? (scoped(action.editor) as ComponentType<KeybindingEditorProps>)
|
||||
: undefined,
|
||||
summary: action.summary
|
||||
? (scoped(action.summary) as ComponentType<KeybindingEditorProps>)
|
||||
: undefined,
|
||||
validate: validate
|
||||
? (value) => {
|
||||
const problem = validate(value);
|
||||
return problem ? key(problem) : null;
|
||||
}
|
||||
: undefined,
|
||||
run: action.run,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerKeybindingDefault(binding) {
|
||||
return track(
|
||||
registerKeybindingDefault({
|
||||
id: binding.id,
|
||||
pluginId,
|
||||
combo: binding.combo,
|
||||
descriptionKey: key(binding.descriptionKey),
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerDashboardCard(card) {
|
||||
requireDeclared("card", card.id, "dashboard card");
|
||||
return track(
|
||||
registerDashboardCard({
|
||||
id: card.id,
|
||||
pluginId,
|
||||
titleKey: key(card.titleKey),
|
||||
defaultHeight: card.defaultHeight,
|
||||
defaultPanel: card.defaultPanel,
|
||||
component: scoped(
|
||||
card.component as unknown as ComponentType<DashboardCardRenderProps>,
|
||||
),
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerExtension(pointId, extension) {
|
||||
const components = extension.components
|
||||
? Object.fromEntries(
|
||||
Object.entries(extension.components).map(([name, component]) => [
|
||||
name,
|
||||
scoped(component),
|
||||
]),
|
||||
)
|
||||
: undefined;
|
||||
return track(
|
||||
registerExtension(pointId, { ...extension, components, pluginId }),
|
||||
);
|
||||
},
|
||||
|
||||
listHosts: () => pluginHostBridge.core.listHosts(pluginId),
|
||||
|
||||
getHost(hostId) {
|
||||
const host = shellHost(hostId);
|
||||
return host ? toPluginHostRecord(host, pluginId) : undefined;
|
||||
},
|
||||
|
||||
registerSettingsComponent(componentId, component) {
|
||||
return track(
|
||||
registerSettingsComponent(pluginId, componentId, scoped(component)),
|
||||
);
|
||||
},
|
||||
|
||||
registerAction(id, handler, options = {}) {
|
||||
return track(
|
||||
registerAction(id, hostCallback(handler), {
|
||||
permission: options.permission
|
||||
? resolvePluginPermission(pluginId, options.permission)
|
||||
: undefined,
|
||||
pluginId,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
declareActionSlot(slot) {
|
||||
return track(declareActionSlot(slot));
|
||||
},
|
||||
|
||||
registerSlotContribution(slotId, contribution) {
|
||||
return track(
|
||||
registerSlotContribution(slotId, {
|
||||
...contribution,
|
||||
titleKey: key(contribution.titleKey),
|
||||
descriptionKey: contribution.descriptionKey
|
||||
? key(contribution.descriptionKey)
|
||||
: undefined,
|
||||
component: contribution.component
|
||||
? scoped(contribution.component)
|
||||
: undefined,
|
||||
when: contribution.when
|
||||
? (context: Record<string, unknown>) =>
|
||||
contribution.when!(scopeHostFields(context, pluginId))
|
||||
: undefined,
|
||||
pluginId,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
invokeAction: (id, ...args) => invokeAction(id, ...args),
|
||||
|
||||
registerComponent(id, component) {
|
||||
return track(registerPluginComponent(id, scoped(component)));
|
||||
},
|
||||
|
||||
registerSshAuthEditor(editor) {
|
||||
return track(
|
||||
registerSshAuthEditor({
|
||||
id: editor.authType,
|
||||
pluginId,
|
||||
titleKey: key(editor.titleKey),
|
||||
hintKey: editor.hintKey ? key(editor.hintKey) : undefined,
|
||||
component: editor.component
|
||||
? (scoped(editor.component) as never)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerLoginMethod(method) {
|
||||
return track(
|
||||
registerLoginMethod({
|
||||
...method,
|
||||
titleKey: key(method.titleKey),
|
||||
pluginId,
|
||||
component: scoped(method.component) as never,
|
||||
enrollment: method.enrollment
|
||||
? (scoped(method.enrollment) as never)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
registerSecondFactorUI(factor) {
|
||||
return track(
|
||||
registerSecondFactor({
|
||||
...factor,
|
||||
titleKey: key(factor.titleKey),
|
||||
pluginId,
|
||||
component: scoped(factor.component) as never,
|
||||
enrollment: factor.enrollment
|
||||
? (scoped(factor.enrollment) as never)
|
||||
: undefined,
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
t: ((key: string, options?: Record<string, unknown> | string) =>
|
||||
i18n.t(
|
||||
pluginKey(pluginId, key),
|
||||
options as Record<string, unknown>,
|
||||
)) as TermixApp["t"],
|
||||
hasPermission: async (permission) => {
|
||||
try {
|
||||
return await hasPermission(
|
||||
resolvePluginPermission(pluginId, permission),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
api: pluginHostBridge.getApi(pluginId),
|
||||
apiFor: (origin) =>
|
||||
pluginApiFor(
|
||||
pluginId,
|
||||
origin as never,
|
||||
pluginHostBridge.getApi(pluginId) as never,
|
||||
) as unknown as TermixApp["api"],
|
||||
fetch: (path, init) => pluginFetch(pluginId, path, init),
|
||||
wsUrl: (path, options) =>
|
||||
pluginWsUrl(pluginId, path, options as never) as ReturnType<
|
||||
TermixApp["wsUrl"]
|
||||
>,
|
||||
|
||||
tabs: {
|
||||
...tabsApi,
|
||||
openTab: shell.openTab as TermixApp["tabs"]["openTab"],
|
||||
openSingletonTab: shell.openSingletonTab,
|
||||
connectHost: shell.connectHost as TermixApp["tabs"]["connectHost"],
|
||||
closeTab: shell.closeTab,
|
||||
onChange: (listener) => track(tabsApi.onChange(listener)),
|
||||
onReady: (listener) => track(tabsApi.onReady(listener)),
|
||||
},
|
||||
|
||||
desktop: {
|
||||
available: isElectron(),
|
||||
remoteServerUrl,
|
||||
onRemoteServerChange: (listener) => track(onRemoteServerChange(listener)),
|
||||
},
|
||||
|
||||
onSettingsChanged: (listener) => {
|
||||
const handler = (event: Event) => {
|
||||
const detail = (event as CustomEvent).detail as {
|
||||
pluginId?: string;
|
||||
scope: "admin" | "user" | "host";
|
||||
hostId?: number;
|
||||
};
|
||||
if (detail?.pluginId !== pluginId) return;
|
||||
listener({ scope: detail.scope, hostId: detail.hostId });
|
||||
};
|
||||
window.addEventListener(PLUGIN_SETTINGS_CHANGED_EVENT, handler);
|
||||
return track(() =>
|
||||
window.removeEventListener(PLUGIN_SETTINGS_CHANGED_EVENT, handler),
|
||||
);
|
||||
},
|
||||
|
||||
onDispose(dispose) {
|
||||
if (disposed) {
|
||||
dispose();
|
||||
return;
|
||||
}
|
||||
bag.push(dispose);
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
app,
|
||||
dispose() {
|
||||
disposed = true;
|
||||
while (bag.length > 0) {
|
||||
const disposer = bag.pop()!;
|
||||
try {
|
||||
disposer();
|
||||
} catch (error) {
|
||||
console.error(`[plugins] ${pluginId}: a disposer threw`, error);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { ComponentType } from "react";
|
||||
import type {
|
||||
LoginMethodUIProps,
|
||||
SecondFactorUIProps,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { createRegistry } from "@/lib/registry";
|
||||
|
||||
/**
|
||||
* Auth UI plugins contribute.
|
||||
*
|
||||
* SSH auth editors render in the host and credential editors when their auth
|
||||
* type is picked. Login methods render on the login screen for methods the
|
||||
* server reports as enabled; second factors render in the step after a first
|
||||
* login. Either kind may bring an enrolment section for Settings > Security.
|
||||
*/
|
||||
export interface SshAuthEditorDef {
|
||||
/** The authType value stored on the host. */
|
||||
id: string;
|
||||
pluginId?: string;
|
||||
titleKey: string;
|
||||
hintKey?: string;
|
||||
component?: ComponentType<{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
form: any;
|
||||
setField: (key: string, value: unknown) => void;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface LoginMethodDef {
|
||||
id: string;
|
||||
pluginId?: string;
|
||||
titleKey: string;
|
||||
icon?: ComponentType<{ className?: string }>;
|
||||
component: ComponentType<LoginMethodUIProps>;
|
||||
/** Also drawn under the password form. */
|
||||
placement?: "inline";
|
||||
enrollment?: ComponentType<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface SecondFactorDef {
|
||||
id: string;
|
||||
pluginId?: string;
|
||||
titleKey: string;
|
||||
component: ComponentType<SecondFactorUIProps>;
|
||||
enrollment?: ComponentType<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const sshAuthEditors = createRegistry<SshAuthEditorDef>();
|
||||
const loginMethods = createRegistry<LoginMethodDef>();
|
||||
const secondFactors = createRegistry<SecondFactorDef>();
|
||||
|
||||
export const registerSshAuthEditor = sshAuthEditors.register;
|
||||
export const useSshAuthEditors = sshAuthEditors.useList;
|
||||
|
||||
export const registerLoginMethod = loginMethods.register;
|
||||
export const getLoginMethodUI = loginMethods.get;
|
||||
export const useLoginMethods = loginMethods.useList;
|
||||
export const listLoginMethodUIs = loginMethods.list;
|
||||
|
||||
export const registerSecondFactor = secondFactors.register;
|
||||
export const getSecondFactorUI = secondFactors.get;
|
||||
export const useSecondFactors = secondFactors.useList;
|
||||
export const listSecondFactorUIs = secondFactors.list;
|
||||
@@ -0,0 +1,465 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { isElectron } from "@/lib/electron";
|
||||
import { readStatusColorScheme } from "@/hooks/use-status-color-scheme";
|
||||
import { enabledHostProtocols } from "@/sidebar/host-protocols";
|
||||
import { useHostActions } from "@/sidebar/host-contributions";
|
||||
import { tabTypeForActivity, useTabTypes } from "@/shell/tab-registry";
|
||||
import { getExtension, useExtensions } from "./extension-registry";
|
||||
import { useTranslation as useI18nTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
__setPluginHost,
|
||||
type ExtensionContribution,
|
||||
type HostActionContribution,
|
||||
type PluginHostBridge,
|
||||
type PluginHostRecord,
|
||||
type SettingsScope,
|
||||
type SettingsState,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { usePermissions } from "@/hooks/use-permissions";
|
||||
import { useTheme } from "@/components/theme-provider";
|
||||
import { createPluginApi, pluginApiFor } from "@/lib/plugin-transport";
|
||||
import {
|
||||
getPluginAdminSettings,
|
||||
getPluginHostSettings,
|
||||
getPluginUserSettings,
|
||||
updatePluginAdminSettings,
|
||||
updatePluginHostSettings,
|
||||
updatePluginUserSettings,
|
||||
} from "@/api/plugins-api";
|
||||
import { getCookie, getUserInfo, setCookie } from "@/main-axios";
|
||||
import { logActivity } from "@/api/dashboard-api";
|
||||
import { getCredentials, getHostPassword } from "@/api/credentials-api";
|
||||
import { getSSHHosts } from "@/api/ssh-host-management-api";
|
||||
import {
|
||||
getUserPreferences,
|
||||
parseCustomKeybindings,
|
||||
patchOpenTab,
|
||||
} from "@/api/open-tabs-api";
|
||||
import { runKeybindingAction } from "@/shell/keybinding-registry";
|
||||
import { usePluginScope } from "./scope";
|
||||
import { knownPluginIds, usePluginStore } from "./plugin-store";
|
||||
import { useUiPreferencesContext } from "@/contexts/UiPreferencesContext";
|
||||
import type { UiPluginPresets } from "@/types/ui-preferences";
|
||||
import { tabsApi, useShellHosts } from "./shell-bridge";
|
||||
import { invokeAction } from "@/shell/action-registry";
|
||||
import { useSshAuthProviders } from "@/hooks/useSshAuthProviders";
|
||||
import { useActionSlot } from "@/hooks/use-action-slot";
|
||||
import { usePluginComponent } from "./component-registry";
|
||||
import { useOptionalHostStatusEntry } from "@/lib/ServerStatusContext";
|
||||
|
||||
/**
|
||||
* Core permission groups, mirroring RESERVED_PERMISSION_PREFIXES in the SDK
|
||||
* manifest module, which is not imported here because it pulls semver into
|
||||
* the browser bundle. A plugin's own namespace is covered by knownPluginIds()
|
||||
* below.
|
||||
*/
|
||||
const CORE_PERMISSION_GROUPS = ["hosts", "credentials", "admin"];
|
||||
|
||||
/**
|
||||
* Resolves a permission the way the backend's ctx.rbac does: a short name
|
||||
* belongs to the plugin, while a full id in a core group or another plugin's
|
||||
* namespace is taken as given.
|
||||
*/
|
||||
export function resolvePluginPermission(
|
||||
pluginId: string,
|
||||
permission: string,
|
||||
): string {
|
||||
if (permission.startsWith(`${pluginId}.`)) return permission;
|
||||
const head = permission.split(".")[0];
|
||||
if (
|
||||
permission.includes(".") &&
|
||||
(CORE_PERMISSION_GROUPS.includes(head) ||
|
||||
(head !== pluginId && knownPluginIds().includes(head)))
|
||||
) {
|
||||
return permission;
|
||||
}
|
||||
return `${pluginId}.${permission}`;
|
||||
}
|
||||
|
||||
const apiClients = new Map<string, ReturnType<typeof createPluginApi>>();
|
||||
|
||||
/** Test seam: renderWithApp's `api` option stands in for the real client. */
|
||||
export function setPluginApiForTesting(
|
||||
pluginId: string,
|
||||
client: ReturnType<typeof createPluginApi> | null,
|
||||
): void {
|
||||
if (client) apiClients.set(pluginId, client);
|
||||
else apiClients.delete(pluginId);
|
||||
}
|
||||
|
||||
function getApi(pluginId: string) {
|
||||
let client = apiClients.get(pluginId);
|
||||
if (!client) {
|
||||
client = createPluginApi(pluginId);
|
||||
apiClients.set(pluginId, client);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
|
||||
let currentUser: Promise<{
|
||||
userId: string;
|
||||
username: string;
|
||||
isAdmin: boolean;
|
||||
} | null> | null = null;
|
||||
|
||||
function loadCurrentUser() {
|
||||
if (!currentUser) {
|
||||
currentUser = getUserInfo()
|
||||
.then((info) => ({
|
||||
userId: info.userId,
|
||||
username: info.username,
|
||||
isAdmin: !!info.is_admin,
|
||||
}))
|
||||
.catch(() => {
|
||||
currentUser = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return currentUser;
|
||||
}
|
||||
|
||||
const SETTINGS_READERS: Record<
|
||||
SettingsScope,
|
||||
(pluginId: string, hostId?: number) => Promise<Record<string, unknown>>
|
||||
> = {
|
||||
admin: (pluginId) => getPluginAdminSettings(pluginId),
|
||||
user: (pluginId) => getPluginUserSettings(pluginId),
|
||||
host: (pluginId, hostId) => getPluginHostSettings(pluginId, hostId!),
|
||||
};
|
||||
|
||||
const SETTINGS_WRITERS: Record<
|
||||
SettingsScope,
|
||||
(
|
||||
pluginId: string,
|
||||
values: Record<string, unknown>,
|
||||
hostId?: number,
|
||||
) => Promise<Record<string, unknown>>
|
||||
> = {
|
||||
admin: (pluginId, values) => updatePluginAdminSettings(pluginId, values),
|
||||
user: (pluginId, values) => updatePluginUserSettings(pluginId, values),
|
||||
host: (pluginId, values, hostId) =>
|
||||
updatePluginHostSettings(pluginId, hostId!, values),
|
||||
};
|
||||
|
||||
/** Both host shapes the shell holds: its own list and the API's. */
|
||||
type ShellHost = Omit<Partial<PluginHostRecord>, "id" | "parentHostId"> & {
|
||||
id: string | number;
|
||||
parentHostId?: string | number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The shell's host as the SDK types it. Copied field by field, so a core
|
||||
* field reaches plugins only once it is part of PluginHostRecord.
|
||||
*/
|
||||
export function toHostRecord(host: ShellHost): PluginHostRecord {
|
||||
return {
|
||||
id: String(host.id),
|
||||
name: host.name ?? "",
|
||||
ip: host.ip ?? "",
|
||||
port: host.port,
|
||||
username: host.username,
|
||||
folder: host.folder,
|
||||
tags: host.tags,
|
||||
pin: host.pin,
|
||||
notes: host.notes,
|
||||
syncId: host.syncId,
|
||||
parentHostId: host.parentHostId == null ? null : String(host.parentHostId),
|
||||
authType: host.authType,
|
||||
credentialId: host.credentialId,
|
||||
overrideCredentialUsername: host.overrideCredentialUsername,
|
||||
connectionType: host.connectionType,
|
||||
connectionOrigin: host.connectionOrigin,
|
||||
enableSsh: host.enableSsh,
|
||||
sshPort: host.sshPort,
|
||||
jumpHosts: host.jumpHosts?.map((jump) => ({ hostId: jump.hostId })),
|
||||
statusCheckEnabled: host.statusCheckEnabled,
|
||||
statusCheckInterval: host.statusCheckInterval,
|
||||
sshOptions: host.sshOptions,
|
||||
pluginSettings: host.pluginSettings,
|
||||
protocolAuth: host.protocolAuth,
|
||||
quickConnectLogin: host.quickConnectLogin,
|
||||
quickConnectSavable: host.quickConnectSavable,
|
||||
instanceId: host.instanceId,
|
||||
status: host.status,
|
||||
online: host.online,
|
||||
isShared: host.isShared,
|
||||
permissionLevel: host.permissionLevel,
|
||||
sharedExpiresAt: host.sharedExpiresAt,
|
||||
ownerUsername: host.ownerUsername,
|
||||
authOverrides: host.authOverrides,
|
||||
sharedCopy: host.sharedCopy,
|
||||
localOnly: host.localOnly,
|
||||
};
|
||||
}
|
||||
|
||||
/** The host as one plugin sees it: only that plugin's settings. */
|
||||
export function toPluginHostRecord(
|
||||
host: ShellHost,
|
||||
pluginId: string | null,
|
||||
): PluginHostRecord {
|
||||
const record = toHostRecord(host);
|
||||
const own = pluginId ? host.pluginSettings?.[pluginId] : undefined;
|
||||
record.pluginSettings = own && pluginId ? { [pluginId]: own } : {};
|
||||
return record;
|
||||
}
|
||||
|
||||
export const pluginHostBridge: PluginHostBridge = {
|
||||
usePluginId() {
|
||||
const pluginId = usePluginScope();
|
||||
if (!pluginId) {
|
||||
throw new Error(
|
||||
"SDK hooks can only be used inside a component a plugin registered",
|
||||
);
|
||||
}
|
||||
return pluginId;
|
||||
},
|
||||
|
||||
useTranslation(pluginId) {
|
||||
const { t, i18n } = useI18nTranslation(pluginId);
|
||||
return {
|
||||
t: t as unknown as (
|
||||
key: string,
|
||||
options?: Record<string, unknown> | string,
|
||||
) => string,
|
||||
language: i18n.language,
|
||||
};
|
||||
},
|
||||
|
||||
usePermission(pluginId, permission) {
|
||||
const { has, loaded } = usePermissions();
|
||||
return loaded && has(resolvePluginPermission(pluginId, permission));
|
||||
},
|
||||
|
||||
useSettings(pluginId, scope, hostId) {
|
||||
const numericHostId =
|
||||
hostId === undefined ? undefined : Number.parseInt(String(hostId), 10);
|
||||
const [state, setState] = useState<{
|
||||
values: Record<string, unknown>;
|
||||
loaded: boolean;
|
||||
}>({ values: {}, loaded: false });
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
if (scope === "host" && !Number.isFinite(numericHostId)) return;
|
||||
SETTINGS_READERS[scope](pluginId, numericHostId)
|
||||
.then((values) => {
|
||||
if (!cancelled) setState({ values, loaded: true });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setState((prev) => ({ ...prev, loaded: true }));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [pluginId, scope, numericHostId]);
|
||||
|
||||
const save = useCallback(
|
||||
async (values: Record<string, unknown>) => {
|
||||
const saved = await SETTINGS_WRITERS[scope](
|
||||
pluginId,
|
||||
values,
|
||||
numericHostId,
|
||||
);
|
||||
setState({ values: saved, loaded: true });
|
||||
},
|
||||
[pluginId, scope, numericHostId],
|
||||
);
|
||||
|
||||
return useMemo<SettingsState>(() => ({ ...state, save }), [state, save]);
|
||||
},
|
||||
|
||||
useHost(hostId) {
|
||||
const pluginId = usePluginScope();
|
||||
const { hosts } = useShellHosts();
|
||||
return useMemo(() => {
|
||||
if (hostId === undefined || hostId === null) return null;
|
||||
const found = hosts.find((host) => host.id === String(hostId));
|
||||
return found ? toPluginHostRecord(found, pluginId) : null;
|
||||
}, [hosts, hostId, pluginId]);
|
||||
},
|
||||
|
||||
useHosts() {
|
||||
const pluginId = usePluginScope();
|
||||
const { hosts, loaded } = useShellHosts();
|
||||
return useMemo(
|
||||
() => ({
|
||||
hosts: hosts.map((host) => toPluginHostRecord(host, pluginId)),
|
||||
loaded,
|
||||
}),
|
||||
[hosts, loaded, pluginId],
|
||||
);
|
||||
},
|
||||
|
||||
useCurrentUser() {
|
||||
const [user, setUser] = useState<{
|
||||
userId: string;
|
||||
username: string;
|
||||
isAdmin: boolean;
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
loadCurrentUser().then((next) => {
|
||||
if (!cancelled) setUser(next);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
return user;
|
||||
},
|
||||
|
||||
useTheme() {
|
||||
const { theme } = useTheme();
|
||||
if (theme === "light") return { theme: "light" };
|
||||
if ((theme as string) === "system" && typeof window !== "undefined") {
|
||||
return {
|
||||
theme: window.matchMedia?.("(prefers-color-scheme: light)").matches
|
||||
? "light"
|
||||
: "dark",
|
||||
};
|
||||
}
|
||||
return { theme: "dark" };
|
||||
},
|
||||
|
||||
toast: {
|
||||
success: (message) => toast.success(message),
|
||||
error: (message) => toast.error(message),
|
||||
info: (message) => toast.info(message),
|
||||
warning: (message) => toast.warning(message),
|
||||
},
|
||||
|
||||
getApi: (pluginId) => getApi(pluginId),
|
||||
getApiFor: (pluginId, origin) =>
|
||||
pluginApiFor(
|
||||
pluginId,
|
||||
origin as "local" | "remote" | undefined,
|
||||
getApi(pluginId) as never,
|
||||
) as never,
|
||||
|
||||
useTabs: () => tabsApi,
|
||||
|
||||
invokeAction: (id, ...args) => invokeAction(id, ...args),
|
||||
|
||||
useSshAuthTypes: () => {
|
||||
const { providers, loaded } = useSshAuthProviders();
|
||||
return {
|
||||
loaded,
|
||||
types: providers
|
||||
.filter((option) => option.available)
|
||||
.map((option) => ({
|
||||
type: option.type,
|
||||
labelKey: option.editorTitleKey ?? option.labelKey,
|
||||
pluginId: option.pluginId,
|
||||
credentialType: option.credentialType,
|
||||
supportsBackground: option.supportsBackground,
|
||||
quickConnect: option.quickConnect === true,
|
||||
})),
|
||||
};
|
||||
},
|
||||
|
||||
useSlotContributions: (slotId, context) => useActionSlot(slotId, context),
|
||||
|
||||
hostProtocols: (record) => [
|
||||
...(record.enableSsh !== false ? ["ssh"] : []),
|
||||
...enabledHostProtocols(
|
||||
record as { pluginSettings?: Record<string, Record<string, unknown>> },
|
||||
).map((protocol) => protocol.id),
|
||||
],
|
||||
|
||||
usePluginComponent: (id) => usePluginComponent(id),
|
||||
|
||||
useHostStatus: (hostId) => {
|
||||
const entry = useOptionalHostStatusEntry(hostId);
|
||||
if (!entry) return null;
|
||||
return {
|
||||
status: entry.status === "degraded" ? "unknown" : entry.status,
|
||||
...(entry.reason ? { reason: entry.reason } : {}),
|
||||
};
|
||||
},
|
||||
|
||||
useHostActions: () => useHostActions() as unknown as HostActionContribution[],
|
||||
|
||||
useActivityTypes: () => {
|
||||
const defs = useTabTypes();
|
||||
const types = new Set<string>();
|
||||
for (const def of defs) {
|
||||
for (const type of def.activityTypes ?? []) types.add(type);
|
||||
}
|
||||
return [...types];
|
||||
},
|
||||
|
||||
activityTarget: (type) => {
|
||||
const def = tabTypeForActivity(type);
|
||||
if (!def) return undefined;
|
||||
return { icon: def.icon, tab: def.id, titleKey: def.titleKey };
|
||||
},
|
||||
|
||||
useExtensions: (pointId) => useExtensions(pointId) as ExtensionContribution[],
|
||||
getExtension: (pointId, id) =>
|
||||
getExtension(pointId, id) as ExtensionContribution | undefined,
|
||||
|
||||
usePluginUiPreferences: (pluginId) => {
|
||||
const ctx = useUiPreferencesContext();
|
||||
const store = usePluginStore();
|
||||
const presets = store.records.get(pluginId)?.summary.contributes
|
||||
?.uiPresets as UiPluginPresets | undefined;
|
||||
const values = ctx
|
||||
? ctx.resolvePlugin(pluginId, presets)
|
||||
: { ...(presets?.balanced ?? {}) };
|
||||
return {
|
||||
values,
|
||||
set: (key, value) => ctx?.setPluginOverride(pluginId, key, value),
|
||||
};
|
||||
},
|
||||
|
||||
core: {
|
||||
logActivity: async (type, hostId, hostName) => {
|
||||
await logActivity(type, hostId, hostName);
|
||||
},
|
||||
getHostPassword: async (hostId, field) =>
|
||||
(await getHostPassword(hostId, field)) ?? null,
|
||||
patchOpenTab: (instanceId, updates) => patchOpenTab(instanceId, updates),
|
||||
getCustomKeybindings: async () =>
|
||||
parseCustomKeybindings((await getUserPreferences()).customKeybindings),
|
||||
runKeybindingAction: (action, context) =>
|
||||
runKeybindingAction(action, context),
|
||||
getClientPreference: (name) => getCookie(name),
|
||||
setClientPreference: (name, value) => {
|
||||
void setCookie(name, value, 365);
|
||||
},
|
||||
listHosts: async (pluginId) =>
|
||||
(await getSSHHosts({ includeStatus: false })).map((host) =>
|
||||
toPluginHostRecord(host, pluginId ?? null),
|
||||
),
|
||||
notifyHostsChanged: () => {
|
||||
window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
|
||||
},
|
||||
getHostStatusColorScheme: () => readStatusColorScheme(),
|
||||
getLocalAuthToken: () => {
|
||||
if (!isElectron()) return null;
|
||||
try {
|
||||
return localStorage.getItem("jwt");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
listCredentials: async () => {
|
||||
const raw = await getCredentials();
|
||||
const list = Array.isArray(raw)
|
||||
? raw
|
||||
: ((raw as { credentials?: unknown[] }).credentials ?? []);
|
||||
return (list as Record<string, unknown>[]).map((c) => ({
|
||||
id: Number(c.id),
|
||||
name: String(c.name ?? ""),
|
||||
username: typeof c.username === "string" ? c.username : undefined,
|
||||
authType: typeof c.authType === "string" ? c.authType : undefined,
|
||||
}));
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Installs the bridge. Idempotent. */
|
||||
export function installPluginHostBridge(): void {
|
||||
__setPluginHost(pluginHostBridge);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createElement,
|
||||
useSyncExternalStore,
|
||||
type ComponentType,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
/**
|
||||
* Components a plugin offers other code by id, through app.registerComponent.
|
||||
*
|
||||
* The owner decides what the component is and the caller decides where it
|
||||
* goes: the ssh-terminal plugin offers "terminal.view", and the collab room,
|
||||
* the homepage SSH widget and the file manager render it without importing
|
||||
* the terminal. While the owner is off the id resolves to nothing and the
|
||||
* caller's fallback shows instead.
|
||||
*/
|
||||
|
||||
type AnyComponent = ComponentType<Record<string, unknown>>;
|
||||
|
||||
const components = new Map<string, AnyComponent>();
|
||||
const listeners = new Set<() => void>();
|
||||
let version = 0;
|
||||
|
||||
function notify(): void {
|
||||
version += 1;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
export function registerPluginComponent(
|
||||
id: string,
|
||||
component: AnyComponent,
|
||||
): () => void {
|
||||
components.set(id, component);
|
||||
notify();
|
||||
return () => {
|
||||
if (components.get(id) === component) {
|
||||
components.delete(id);
|
||||
notify();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
/** The component registered under an id, re-rendering when that changes. */
|
||||
export function usePluginComponent(id: string): AnyComponent | undefined {
|
||||
useSyncExternalStore(subscribe, () => version);
|
||||
return components.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the component another plugin registered under `id`, with the rest
|
||||
* of the props passed through, or `fallback` while nobody has registered it.
|
||||
*/
|
||||
export function PluginComponent({
|
||||
id,
|
||||
fallback = null,
|
||||
...props
|
||||
}: {
|
||||
id: string;
|
||||
fallback?: ReactNode;
|
||||
[prop: string]: unknown;
|
||||
}): ReactNode {
|
||||
const Component = usePluginComponent(id);
|
||||
if (!Component) return fallback as ReactNode;
|
||||
return createElement(Component, props);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/** app.desktop: the server this desktop is linked to, for plugins. */
|
||||
|
||||
import { getLinkedSession } from "@/lib/linked-server";
|
||||
import { SYNC_CHANGED_EVENT } from "@/lib/sync-events";
|
||||
|
||||
type RemoteServerSource = () => string | null | Promise<string | null>;
|
||||
|
||||
let testSource: RemoteServerSource | null = null;
|
||||
|
||||
/** renderWithApp's stand-in for the linked server. */
|
||||
export function setRemoteServerUrlForTesting(
|
||||
source: RemoteServerSource | null,
|
||||
): void {
|
||||
testSource = source;
|
||||
}
|
||||
|
||||
export async function remoteServerUrl(): Promise<string | null> {
|
||||
if (testSource) return (await testSource()) ?? null;
|
||||
return (await getLinkedSession())?.serverUrl ?? null;
|
||||
}
|
||||
|
||||
export function onRemoteServerChange(listener: () => void): () => void {
|
||||
const handler = () => listener();
|
||||
window.addEventListener(SYNC_CHANGED_EVENT, handler);
|
||||
return () => window.removeEventListener(SYNC_CHANGED_EVENT, handler);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createRegistry, type Registry } from "@/lib/registry";
|
||||
|
||||
/**
|
||||
* Named lists any plugin can add to through app.registerExtension. The plugin
|
||||
* that reads a point decides its id and item shape; core only stores them, so
|
||||
* contributions survive the reader being off and core never learns what a
|
||||
* point is for.
|
||||
*/
|
||||
export interface RegisteredExtension {
|
||||
id: string;
|
||||
pluginId?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const points = new Map<string, Registry<RegisteredExtension>>();
|
||||
|
||||
function point(id: string): Registry<RegisteredExtension> {
|
||||
let registry = points.get(id);
|
||||
if (!registry) {
|
||||
registry = createRegistry<RegisteredExtension>();
|
||||
points.set(id, registry);
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
export function registerExtension(
|
||||
pointId: string,
|
||||
extension: RegisteredExtension,
|
||||
): () => void {
|
||||
return point(pointId).register(extension);
|
||||
}
|
||||
|
||||
export function getExtension(
|
||||
pointId: string,
|
||||
id: string,
|
||||
): RegisteredExtension | undefined {
|
||||
return point(pointId).get(id);
|
||||
}
|
||||
|
||||
export function listExtensions(pointId: string): RegisteredExtension[] {
|
||||
return point(pointId).list();
|
||||
}
|
||||
|
||||
export function useExtensions(pointId: string): RegisteredExtension[] {
|
||||
return point(pointId).useList();
|
||||
}
|
||||
|
||||
export function resetExtensions(): void {
|
||||
for (const registry of points.values()) registry.reset();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { shellHost } from "./shell-bridge";
|
||||
|
||||
type SettingsBag = Record<string, Record<string, unknown> | undefined>;
|
||||
type HostLike = { id: string | number; pluginSettings?: SettingsBag };
|
||||
|
||||
/**
|
||||
* A plugin sees only its own host settings. Another plugin's settings reach
|
||||
* it through that plugin's actions or services, never by reading the host,
|
||||
* so a plugin can rename a setting without breaking its neighbours.
|
||||
*
|
||||
* Settings come from the shell's own copy of the host when it has one, so a
|
||||
* host one plugin hands another (through an action or a tab) is re-read for
|
||||
* the receiver instead of arriving with the sender's slice.
|
||||
*/
|
||||
export function isHostLike(value: unknown): value is HostLike {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
if (!("id" in value)) return false;
|
||||
return "pluginSettings" in value || ("ip" in value && "port" in value);
|
||||
}
|
||||
|
||||
const cache = new WeakMap<
|
||||
object,
|
||||
Map<string, { source: SettingsBag | undefined; scoped: object }>
|
||||
>();
|
||||
|
||||
export function scopeHost<T>(value: T, pluginId: string): T {
|
||||
if (!isHostLike(value)) return value;
|
||||
const full = (shellHost(value.id)?.pluginSettings ?? value.pluginSettings) as
|
||||
SettingsBag | undefined;
|
||||
let perPlugin = cache.get(value);
|
||||
const hit = perPlugin?.get(pluginId);
|
||||
// Same object in, same object out, so a plugin's effects keyed on the
|
||||
// host don't re-run on every render.
|
||||
if (hit && hit.source === full) return hit.scoped as T;
|
||||
const own = full?.[pluginId];
|
||||
const scoped = { ...value, pluginSettings: own ? { [pluginId]: own } : {} };
|
||||
if (!perPlugin) {
|
||||
perPlugin = new Map();
|
||||
cache.set(value, perPlugin);
|
||||
}
|
||||
perPlugin.set(pluginId, { source: full, scoped });
|
||||
return scoped as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scopes each argument that is a host, and the `host` / `sshHost` fields of
|
||||
* an argument that is a request object such as `{ host, appTheme }`.
|
||||
*/
|
||||
export function scopeHostArgs<A extends unknown[]>(
|
||||
args: A,
|
||||
pluginId: string,
|
||||
): A {
|
||||
return args.map((arg) =>
|
||||
isHostLike(arg) ? scopeHost(arg, pluginId) : scopeHostFields(arg, pluginId),
|
||||
) as A;
|
||||
}
|
||||
|
||||
// The prop and field names hosts travel under between core and plugins.
|
||||
const HOST_FIELDS = ["host", "sshHost", "hostConfig"] as const;
|
||||
|
||||
/** Scopes the host fields of a props, context or request object. */
|
||||
export function scopeHostFields<T>(value: T, pluginId: string): T {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return value;
|
||||
const record = value as Record<string, unknown>;
|
||||
let next: Record<string, unknown> | null = null;
|
||||
for (const field of HOST_FIELDS) {
|
||||
if (!(field in record)) continue;
|
||||
const scoped = scopeHost(record[field], pluginId);
|
||||
if (scoped === record[field]) continue;
|
||||
next ??= { ...record };
|
||||
next[field] = scoped;
|
||||
}
|
||||
return (next ?? value) as T;
|
||||
}
|
||||
|
||||
/** Wraps a plugin callback so any host it is called with is scoped. */
|
||||
export function scopeHostCallback<F extends (...args: never[]) => unknown>(
|
||||
fn: F | undefined,
|
||||
pluginId: string,
|
||||
): F | undefined {
|
||||
if (!fn) return fn;
|
||||
return ((...args: never[]) =>
|
||||
fn(...(scopeHostArgs(args as unknown[], pluginId) as never[]))) as F;
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
import type { ResourceKey } from "i18next";
|
||||
import type {
|
||||
FrontendModule,
|
||||
PluginManifest,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import i18n, { setPluginLocaleResolver } from "@/i18n/i18n";
|
||||
import { getPlugins, type PluginSummary } from "@/api/plugins-api";
|
||||
import { getBackendUrl } from "@/main-axios";
|
||||
import { createPluginApp, type PluginAppHandle } from "./app";
|
||||
import { installPluginHostBridge } from "./bridge";
|
||||
import {
|
||||
getPluginRecord,
|
||||
getPluginStoreState,
|
||||
markPluginsSettled,
|
||||
setFrontendState,
|
||||
setPluginSummaries,
|
||||
} from "./plugin-store";
|
||||
import { workspaceFrontends, workspaceLocales } from "./workspace-plugins";
|
||||
import { syncHostFeatureTabs } from "@/settings/host-feature-tabs";
|
||||
|
||||
/**
|
||||
* Loads plugin frontends into the running shell.
|
||||
*
|
||||
* After login, and whenever plugin state may have changed, it fetches
|
||||
* GET /plugins and reconciles: plugins that are now enabled are imported and
|
||||
* activated in dependency order, plugins that are no longer enabled are
|
||||
* deactivated and everything they registered is removed. No reload either way.
|
||||
*
|
||||
* A plugin whose import or activate throws is marked failed and cleaned up;
|
||||
* the others carry on.
|
||||
*/
|
||||
|
||||
interface ActivePlugin {
|
||||
id: string;
|
||||
assetVersion: string | null;
|
||||
handle: PluginAppHandle;
|
||||
module: FrontendModule;
|
||||
cssLink: HTMLLinkElement | null;
|
||||
}
|
||||
|
||||
export interface PluginLoaderDeps {
|
||||
fetchPlugins: () => Promise<PluginSummary[]>;
|
||||
importFrontend: (summary: PluginSummary) => Promise<FrontendModule>;
|
||||
loadLocale: (
|
||||
summary: PluginSummary,
|
||||
file: string,
|
||||
) => Promise<ResourceKey | null>;
|
||||
/** Adds the plugin stylesheet; returns the element to remove later. */
|
||||
injectCss: (summary: PluginSummary) => HTMLLinkElement | null;
|
||||
}
|
||||
|
||||
const active = new Map<string, ActivePlugin>();
|
||||
/** Bundle version that failed, so the same broken bundle is not retried. */
|
||||
const failedVersions = new Map<string, string | null>();
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
let deps: PluginLoaderDeps | null = null;
|
||||
let started = false;
|
||||
let guestMode = false;
|
||||
|
||||
function assetUrl(summary: PluginSummary, file: string): string {
|
||||
const version = summary.assetVersion
|
||||
? `?v=${encodeURIComponent(summary.assetVersion)}`
|
||||
: "";
|
||||
return getBackendUrl(
|
||||
`/plugin-assets/${encodeURIComponent(summary.id)}/${file}${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Absolute URL, so import() resolves it against the page, not this module. */
|
||||
function absolute(url: string): string {
|
||||
return new URL(url, window.location.href).href;
|
||||
}
|
||||
|
||||
const defaultDeps: PluginLoaderDeps = {
|
||||
fetchPlugins: getPlugins,
|
||||
|
||||
async importFrontend(summary) {
|
||||
const workspace = workspaceFrontends[summary.id];
|
||||
if (workspace) return (await workspace()) as FrontendModule;
|
||||
return (await import(
|
||||
/* @vite-ignore */ absolute(assetUrl(summary, "frontend.js"))
|
||||
)) as FrontendModule;
|
||||
},
|
||||
|
||||
async loadLocale(summary, file) {
|
||||
const workspace = workspaceLocales[summary.id]?.[file];
|
||||
if (workspace) return (await workspace()) as ResourceKey;
|
||||
const hasFile = summary.locales?.includes(file);
|
||||
if (!hasFile) return null;
|
||||
const path = file === "en" ? "en.json" : `translated/${file}.json`;
|
||||
const response = await fetch(
|
||||
absolute(assetUrl(summary, `locales/${path}`)),
|
||||
);
|
||||
if (!response.ok) return null;
|
||||
return (await response.json()) as ResourceKey;
|
||||
},
|
||||
|
||||
injectCss(summary) {
|
||||
if (!summary.css || typeof document === "undefined") return null;
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.href = absolute(assetUrl(summary, "frontend.css"));
|
||||
link.dataset.plugin = summary.id;
|
||||
document.head.appendChild(link);
|
||||
return link;
|
||||
},
|
||||
};
|
||||
|
||||
function currentDeps(): PluginLoaderDeps {
|
||||
return deps ?? defaultDeps;
|
||||
}
|
||||
|
||||
/** Test seam: swaps how plugins are fetched, imported and localized. */
|
||||
export function configurePluginLoader(next: Partial<PluginLoaderDeps>): void {
|
||||
deps = { ...defaultDeps, ...next };
|
||||
}
|
||||
|
||||
function serverAllowsFrontend(summary: PluginSummary): boolean {
|
||||
return (
|
||||
summary.enabled &&
|
||||
summary.state !== "failed" &&
|
||||
summary.state !== "blocked" &&
|
||||
!!summary.frontend
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enabled plugins in an order where each comes after its dependencies. A
|
||||
* cycle or a missing hard dependency leaves the plugin out, marked blocked.
|
||||
*/
|
||||
export function orderForActivation(summaries: PluginSummary[]): {
|
||||
order: PluginSummary[];
|
||||
blocked: Map<string, string>;
|
||||
} {
|
||||
const byId = new Map(summaries.map((summary) => [summary.id, summary]));
|
||||
const order: PluginSummary[] = [];
|
||||
const blocked = new Map<string, string>();
|
||||
const state = new Map<string, "visiting" | "done">();
|
||||
|
||||
const visit = (summary: PluginSummary): boolean => {
|
||||
const mark = state.get(summary.id);
|
||||
if (mark === "done") return !blocked.has(summary.id);
|
||||
if (mark === "visiting") {
|
||||
blocked.set(summary.id, "dependency cycle");
|
||||
return false;
|
||||
}
|
||||
state.set(summary.id, "visiting");
|
||||
|
||||
for (const dependency of Object.keys(summary.dependencies ?? {})) {
|
||||
const target = byId.get(dependency);
|
||||
if (!target || !serverAllowsFrontend(target) || !visit(target)) {
|
||||
blocked.set(summary.id, `needs ${dependency}`);
|
||||
}
|
||||
}
|
||||
for (const dependency of Object.keys(summary.optionalDependencies ?? {})) {
|
||||
const target = byId.get(dependency);
|
||||
if (target && serverAllowsFrontend(target)) visit(target);
|
||||
}
|
||||
|
||||
state.set(summary.id, "done");
|
||||
if (blocked.has(summary.id)) return false;
|
||||
order.push(summary);
|
||||
return true;
|
||||
};
|
||||
|
||||
for (const summary of summaries) {
|
||||
if (serverAllowsFrontend(summary)) visit(summary);
|
||||
}
|
||||
return { order, blocked };
|
||||
}
|
||||
|
||||
async function deactivate(pluginId: string): Promise<void> {
|
||||
const plugin = active.get(pluginId);
|
||||
if (!plugin) return;
|
||||
active.delete(pluginId);
|
||||
try {
|
||||
await plugin.module.deactivate?.();
|
||||
} catch (error) {
|
||||
console.error(`[plugins] ${pluginId}: deactivate threw`, error);
|
||||
}
|
||||
// Runs even when deactivate threw or does not exist.
|
||||
plugin.handle.dispose();
|
||||
plugin.cssLink?.remove();
|
||||
setFrontendState(pluginId, "inactive");
|
||||
}
|
||||
|
||||
const ACTIVATE_TIMEOUT_MS = 15_000;
|
||||
|
||||
function withTimeout<T>(
|
||||
promise: Promise<T>,
|
||||
ms: number,
|
||||
message: string,
|
||||
): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(message)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
async function activate(summary: PluginSummary): Promise<void> {
|
||||
const loader = currentDeps();
|
||||
setFrontendState(summary.id, "loading");
|
||||
|
||||
let cssLink: HTMLLinkElement | null = null;
|
||||
let handle: PluginAppHandle | null = null;
|
||||
try {
|
||||
const module = await loader.importFrontend(summary);
|
||||
if (typeof module?.activate !== "function") {
|
||||
throw new Error("frontend entry does not export activate(app)");
|
||||
}
|
||||
cssLink = loader.injectCss(summary);
|
||||
handle = createPluginApp(
|
||||
summary.id,
|
||||
manifestFor(summary),
|
||||
summary.contributes,
|
||||
{ guest: guestMode },
|
||||
);
|
||||
// A plugin whose activate never settles would hold up every plugin
|
||||
// queued after it, so it fails instead.
|
||||
await withTimeout(
|
||||
Promise.resolve(module.activate(handle.app)),
|
||||
ACTIVATE_TIMEOUT_MS,
|
||||
`activate() did not finish within ${ACTIVATE_TIMEOUT_MS / 1000}s`,
|
||||
);
|
||||
active.set(summary.id, {
|
||||
id: summary.id,
|
||||
assetVersion: summary.assetVersion ?? null,
|
||||
handle,
|
||||
module,
|
||||
cssLink,
|
||||
});
|
||||
failedVersions.delete(summary.id);
|
||||
setFrontendState(summary.id, "active");
|
||||
} catch (error) {
|
||||
// A failed activate is still cleaned up, and its deactivate is not
|
||||
// called: it never finished starting.
|
||||
handle?.dispose();
|
||||
cssLink?.remove();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`[plugins] ${summary.id} failed to start`, error);
|
||||
failedVersions.set(summary.id, summary.assetVersion ?? null);
|
||||
setFrontendState(summary.id, "failed", message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The manifest subset the browser has. The full one stays on the server. */
|
||||
function manifestFor(summary: PluginSummary): PluginManifest {
|
||||
return {
|
||||
id: summary.id,
|
||||
name: summary.name,
|
||||
version: summary.version,
|
||||
description: "",
|
||||
author: { name: "" },
|
||||
license: "",
|
||||
category: "",
|
||||
engine: { termix: "", api: "1" },
|
||||
capabilities: summary.capabilities ?? [],
|
||||
dependencies: summary.dependencies,
|
||||
optionalDependencies: summary.optionalDependencies,
|
||||
contributes: summary.contributes as PluginManifest["contributes"],
|
||||
icon: summary.icon,
|
||||
};
|
||||
}
|
||||
|
||||
const loadedNamespaceVersions = new Map<string, string>();
|
||||
|
||||
async function loadNamespaces(summaries: PluginSummary[]): Promise<void> {
|
||||
// Only a plugin that is new or was upgraded while the app was open needs
|
||||
// its strings fetched again.
|
||||
const ids = summaries
|
||||
.filter(
|
||||
(summary) =>
|
||||
loadedNamespaceVersions.get(summary.id) !== namespaceVersion(summary),
|
||||
)
|
||||
.map((summary) => summary.id);
|
||||
if (ids.length === 0) return;
|
||||
await i18n.reloadResources(undefined, ids).catch(() => {});
|
||||
await i18n.loadNamespaces(ids).catch(() => {});
|
||||
for (const summary of summaries) {
|
||||
loadedNamespaceVersions.set(summary.id, namespaceVersion(summary));
|
||||
}
|
||||
}
|
||||
|
||||
function namespaceVersion(summary: PluginSummary): string {
|
||||
return `${summary.version}|${summary.assetVersion ?? ""}`;
|
||||
}
|
||||
|
||||
async function reconcile(summaries: PluginSummary[]): Promise<void> {
|
||||
setPluginSummaries(summaries);
|
||||
await loadNamespaces(summaries);
|
||||
|
||||
const { order, blocked } = orderForActivation(summaries);
|
||||
const wanted = new Map(order.map((summary) => [summary.id, summary]));
|
||||
|
||||
// Dependents go first, so nothing outlives what it depends on.
|
||||
for (const id of [...active.keys()].reverse()) {
|
||||
const next = wanted.get(id);
|
||||
const current = active.get(id)!;
|
||||
if (!next || (next.assetVersion ?? null) !== current.assetVersion) {
|
||||
await deactivate(id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, reason] of blocked) {
|
||||
if (getPluginRecord(id)?.frontend !== "blocked") {
|
||||
setFrontendState(id, "blocked", reason);
|
||||
}
|
||||
}
|
||||
|
||||
// A plugin that was switched off gets a fresh attempt when it comes back.
|
||||
for (const id of [...failedVersions.keys()]) {
|
||||
if (!wanted.has(id)) failedVersions.delete(id);
|
||||
}
|
||||
|
||||
await activateConcurrently(order);
|
||||
// After activation, so a plugin that registered its own host editor
|
||||
// section is not given a second, generated one.
|
||||
syncHostFeatureTabs(summaries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Activates every plugin in `order`, running independent plugins in
|
||||
* parallel instead of one at a time. Each plugin still waits for its own
|
||||
* hard dependencies to finish activating first (success or failure - a
|
||||
* blocked or failed dependency must not hang its dependents forever).
|
||||
*/
|
||||
async function activateConcurrently(order: PluginSummary[]): Promise<void> {
|
||||
const byId = new Map(order.map((summary) => [summary.id, summary]));
|
||||
const started = new Map<string, Promise<void>>();
|
||||
|
||||
const run = (summary: PluginSummary): Promise<void> => {
|
||||
const existing = started.get(summary.id);
|
||||
if (existing) return existing;
|
||||
|
||||
const task = (async () => {
|
||||
const dependencyIds = Object.keys(summary.dependencies ?? {});
|
||||
await Promise.all(
|
||||
dependencyIds.map((id) => {
|
||||
const dependency = byId.get(id);
|
||||
return dependency ? run(dependency) : Promise.resolve();
|
||||
}),
|
||||
);
|
||||
|
||||
if (active.has(summary.id)) return;
|
||||
// Do not retry a bundle that already failed until it changes.
|
||||
if (
|
||||
failedVersions.has(summary.id) &&
|
||||
failedVersions.get(summary.id) === (summary.assetVersion ?? null)
|
||||
) {
|
||||
setFrontendState(
|
||||
summary.id,
|
||||
"failed",
|
||||
getPluginRecord(summary.id)?.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await activate(summary);
|
||||
})();
|
||||
|
||||
started.set(summary.id, task);
|
||||
return task;
|
||||
};
|
||||
|
||||
await Promise.all(order.map(run));
|
||||
}
|
||||
|
||||
function enqueue(task: () => Promise<void>): Promise<void> {
|
||||
queue = queue.then(task, task);
|
||||
return queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches plugin state and brings the loaded frontends in line with it. Safe
|
||||
* to call as often as needed; calls run one after another.
|
||||
*/
|
||||
export function syncPlugins(summaries?: PluginSummary[]): Promise<void> {
|
||||
return enqueue(async () => {
|
||||
let list = summaries;
|
||||
if (!list) {
|
||||
try {
|
||||
list = await currentDeps().fetchPlugins();
|
||||
} catch (error) {
|
||||
console.error("[plugins] could not load the plugin list", error);
|
||||
// The shell must not wait on plugins forever.
|
||||
if (!getPluginStoreState().loaded) setPluginSummaries([]);
|
||||
markPluginsSettled();
|
||||
return;
|
||||
}
|
||||
}
|
||||
await reconcile(list);
|
||||
markPluginsSettled();
|
||||
});
|
||||
}
|
||||
|
||||
/** Fired by anything that changes plugin state, e.g. the admin toggle. */
|
||||
const PLUGINS_CHANGED_EVENT = "termix:plugins-changed";
|
||||
|
||||
let lastFocusSync = 0;
|
||||
const FOCUS_SYNC_INTERVAL_MS = 30_000;
|
||||
|
||||
function onPluginsChanged() {
|
||||
void syncPlugins();
|
||||
}
|
||||
|
||||
function onFocus() {
|
||||
const now = Date.now();
|
||||
if (now - lastFocusSync < FOCUS_SYNC_INTERVAL_MS) return;
|
||||
lastFocusSync = now;
|
||||
void syncPlugins();
|
||||
}
|
||||
|
||||
async function fetchGuestPlugins(): Promise<PluginSummary[]> {
|
||||
const response = await fetch(getBackendUrl("/plugins/public"));
|
||||
if (!response.ok) return [];
|
||||
const body = (await response.json()) as unknown;
|
||||
return Array.isArray(body) ? (body as PluginSummary[]) : [];
|
||||
}
|
||||
|
||||
let guestViewsRequest: Promise<string[]> | null = null;
|
||||
|
||||
/**
|
||||
* The `?view=` names enabled guest plugins serve to anonymous pages, so the
|
||||
* entry point can tell a guest link from a signed-in full-screen view
|
||||
* without knowing any plugin.
|
||||
*/
|
||||
export function fetchGuestViews(): Promise<string[]> {
|
||||
guestViewsRequest ??= fetchGuestPlugins()
|
||||
.then((plugins) =>
|
||||
plugins.flatMap(
|
||||
(plugin) =>
|
||||
(plugin.contributes as { guestViews?: string[] } | undefined)
|
||||
?.guestViews ?? [],
|
||||
),
|
||||
)
|
||||
.catch(() => []);
|
||||
return guestViewsRequest;
|
||||
}
|
||||
|
||||
async function fetchPreLoginPlugins(): Promise<PluginSummary[]> {
|
||||
const response = await fetch(getBackendUrl("/plugins/public-manifest"));
|
||||
if (!response.ok) return [];
|
||||
const body = (await response.json()) as unknown;
|
||||
return Array.isArray(body) ? (body as PluginSummary[]) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the plugins the login screen needs (login methods and second
|
||||
* factors) before anyone has signed in. After sign-in the full runtime
|
||||
* reconciles, keeping these active when their bundle has not changed.
|
||||
*/
|
||||
export async function startPreLoginPlugins(): Promise<void> {
|
||||
installPluginHostBridge();
|
||||
let list: PluginSummary[];
|
||||
try {
|
||||
list = await fetchPreLoginPlugins();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (list.length === 0 || started) return;
|
||||
setPluginLocaleResolver((namespace, _language, file) => {
|
||||
const summary = getPluginRecord(namespace)?.summary;
|
||||
if (!summary) return Promise.resolve(null);
|
||||
return currentDeps().loadLocale(summary, file);
|
||||
});
|
||||
await enqueue(async () => {
|
||||
// Once signed in the full sync owns the list, and reconciling this
|
||||
// subset would unload everything else. Auth remounts during the
|
||||
// post-login fade, so this runs after sign-in every time.
|
||||
if (started) return;
|
||||
await reconcile(list);
|
||||
markPluginsSettled();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the runtime. Idempotent. `guest` is for anonymous pages (shared
|
||||
* session links): only plugins declaring contributes.guest load, from the
|
||||
* public list, and nothing is refetched on focus.
|
||||
*/
|
||||
export function startPluginRuntime(
|
||||
options: { guest?: boolean } = {},
|
||||
): Promise<void> {
|
||||
installPluginHostBridge();
|
||||
if (options.guest) {
|
||||
guestMode = true;
|
||||
if (!deps) configurePluginLoader({ fetchPlugins: fetchGuestPlugins });
|
||||
return syncPlugins();
|
||||
}
|
||||
setPluginLocaleResolver((namespace, _language, file) => {
|
||||
const summary = getPluginRecord(namespace)?.summary;
|
||||
if (!summary) return Promise.resolve(null);
|
||||
return currentDeps().loadLocale(summary, file);
|
||||
});
|
||||
|
||||
if (!started && typeof window !== "undefined") {
|
||||
started = true;
|
||||
lastFocusSync = Date.now();
|
||||
window.addEventListener(PLUGINS_CHANGED_EVENT, onPluginsChanged);
|
||||
window.addEventListener("focus", onFocus);
|
||||
}
|
||||
return syncPlugins();
|
||||
}
|
||||
|
||||
/** Deactivates every plugin, on logout. */
|
||||
export function stopPluginRuntime(): Promise<void> {
|
||||
if (started && typeof window !== "undefined") {
|
||||
started = false;
|
||||
window.removeEventListener(PLUGINS_CHANGED_EVENT, onPluginsChanged);
|
||||
window.removeEventListener("focus", onFocus);
|
||||
}
|
||||
return enqueue(async () => {
|
||||
for (const id of [...active.keys()].reverse()) await deactivate(id);
|
||||
});
|
||||
}
|
||||
|
||||
export function isPluginFrontendActive(pluginId: string): boolean {
|
||||
return active.has(pluginId);
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export async function resetPluginLoader(): Promise<void> {
|
||||
await stopPluginRuntime();
|
||||
deps = null;
|
||||
queue = Promise.resolve();
|
||||
failedVersions.clear();
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { PluginSummary } from "@/api/plugins-api";
|
||||
|
||||
/**
|
||||
* What the browser knows about each plugin: the server's summary plus how
|
||||
* far its frontend got.
|
||||
*
|
||||
* `frontend` is separate from the server state on purpose. A plugin can be
|
||||
* enabled and healthy on the server while its bundle failed to import, and
|
||||
* the shell has to show that as failed rather than as missing.
|
||||
*/
|
||||
export type FrontendState =
|
||||
"none" | "loading" | "active" | "failed" | "blocked" | "inactive";
|
||||
|
||||
export interface PluginRecord {
|
||||
summary: PluginSummary;
|
||||
frontend: FrontendState;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface StoreState {
|
||||
/** False until the first GET /plugins answers. */
|
||||
loaded: boolean;
|
||||
/**
|
||||
* True once every enabled frontend has been tried at least once. The shell
|
||||
* restores saved tabs only after this, so plugin tabs come back as
|
||||
* themselves rather than as placeholders.
|
||||
*/
|
||||
settled: boolean;
|
||||
records: ReadonlyMap<string, PluginRecord>;
|
||||
}
|
||||
|
||||
let state: StoreState = { loaded: false, settled: false, records: new Map() };
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function commit(next: StoreState): void {
|
||||
state = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function subscribePluginStore(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function getPluginStoreState(): StoreState {
|
||||
return state;
|
||||
}
|
||||
|
||||
export function usePluginStore(): StoreState {
|
||||
return useSyncExternalStore(
|
||||
subscribePluginStore,
|
||||
getPluginStoreState,
|
||||
getPluginStoreState,
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces the summaries, keeping each plugin's frontend state. */
|
||||
export function setPluginSummaries(summaries: PluginSummary[]): void {
|
||||
const records = new Map<string, PluginRecord>();
|
||||
let changed = !state.loaded || summaries.length !== state.records.size;
|
||||
for (const summary of summaries) {
|
||||
const previous = state.records.get(summary.id);
|
||||
// A periodic re-sync usually returns the same list; keeping the old
|
||||
// records lets subscribers skip a re-render.
|
||||
if (
|
||||
previous &&
|
||||
JSON.stringify(previous.summary) === JSON.stringify(summary)
|
||||
) {
|
||||
records.set(summary.id, previous);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
records.set(summary.id, {
|
||||
summary,
|
||||
frontend: previous?.frontend ?? "none",
|
||||
error: previous?.error,
|
||||
});
|
||||
}
|
||||
if (!changed) return;
|
||||
commit({ ...state, loaded: true, records });
|
||||
}
|
||||
|
||||
export function markPluginsSettled(): void {
|
||||
if (!state.settled) commit({ ...state, settled: true });
|
||||
}
|
||||
|
||||
export function setFrontendState(
|
||||
pluginId: string,
|
||||
frontend: FrontendState,
|
||||
error?: string,
|
||||
): void {
|
||||
const record = state.records.get(pluginId);
|
||||
if (!record) return;
|
||||
if (record.frontend === frontend && record.error === error) return;
|
||||
const records = new Map(state.records);
|
||||
records.set(pluginId, { ...record, frontend, error });
|
||||
commit({ ...state, records });
|
||||
}
|
||||
|
||||
export function getPluginRecord(pluginId: string): PluginRecord | undefined {
|
||||
return state.records.get(pluginId);
|
||||
}
|
||||
|
||||
/** Resolves once plugins have settled; at once if they already have. */
|
||||
export function settledPromise(): Promise<void> {
|
||||
if (state.settled) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
const unsubscribe = subscribePluginStore(() => {
|
||||
if (!state.settled) return;
|
||||
unsubscribe();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Plugin ids known to the server, used to resolve permission namespaces. */
|
||||
export function knownPluginIds(): string[] {
|
||||
return [...state.records.keys()];
|
||||
}
|
||||
|
||||
/** Test seam. */
|
||||
export function resetPluginStore(): void {
|
||||
commit({ loaded: false, settled: false, records: new Map() });
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
/* eslint-disable react-refresh/only-export-components */
|
||||
import {
|
||||
Component,
|
||||
createContext,
|
||||
Suspense,
|
||||
useContext,
|
||||
type ComponentType,
|
||||
type ErrorInfo,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { scopeHostFields } from "./host-scope";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getPluginRecord } from "./plugin-store";
|
||||
|
||||
const PluginScopeContext = createContext<string | null>(null);
|
||||
|
||||
/** The plugin whose component is rendering, or null in core UI. */
|
||||
export function usePluginScope(): string | null {
|
||||
return useContext(PluginScopeContext);
|
||||
}
|
||||
|
||||
function CrashNotice({
|
||||
pluginId,
|
||||
onRetry,
|
||||
}: {
|
||||
pluginId: string;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const name = getPluginRecord(pluginId)?.summary.name ?? pluginId;
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground">
|
||||
<span>{t("plugins.runtime.crashed", { name })}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs underline underline-offset-2 hover:text-foreground"
|
||||
onClick={onRetry}
|
||||
>
|
||||
{t("plugins.runtime.retry")}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BoundaryProps {
|
||||
pluginId: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** A plugin component that throws takes down itself, never the shell. */
|
||||
class PluginErrorBoundary extends Component<BoundaryProps, { error: boolean }> {
|
||||
state = { error: false };
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { error: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo) {
|
||||
console.error(
|
||||
`[plugins] ${this.props.pluginId} crashed while rendering`,
|
||||
error,
|
||||
info.componentStack,
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
return (
|
||||
<CrashNotice
|
||||
pluginId={this.props.pluginId}
|
||||
onRetry={() => this.setState({ error: false })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function PluginScope({
|
||||
pluginId,
|
||||
children,
|
||||
}: {
|
||||
pluginId: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<PluginScopeContext.Provider value={pluginId}>
|
||||
<PluginErrorBoundary pluginId={pluginId}>
|
||||
<Suspense fallback={null}>{children}</Suspense>
|
||||
</PluginErrorBoundary>
|
||||
</PluginScopeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a plugin's component once, at registration, so every place the shell
|
||||
* renders it gets the plugin id for the SDK hooks and an error boundary,
|
||||
* without each call site having to remember.
|
||||
*/
|
||||
export function withPluginScope<P extends object>(
|
||||
pluginId: string,
|
||||
Inner: ComponentType<P>,
|
||||
): ComponentType<P> {
|
||||
function Scoped(props: P) {
|
||||
return (
|
||||
<PluginScope pluginId={pluginId}>
|
||||
<Inner {...scopeHostFields(props, pluginId)} />
|
||||
</PluginScope>
|
||||
);
|
||||
}
|
||||
Scoped.displayName = `Plugin(${pluginId}:${Inner.displayName ?? Inner.name ?? "Component"})`;
|
||||
return Scoped;
|
||||
}
|
||||
|
||||
/** Renders nothing when a plugin's icon throws, instead of a crash notice. */
|
||||
class IconBoundary extends Component<BoundaryProps, { error: boolean }> {
|
||||
state = { error: false };
|
||||
|
||||
static getDerivedStateFromError() {
|
||||
return { error: true };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error) {
|
||||
console.error(`[plugins] ${this.props.pluginId} icon failed`, error);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.state.error ? null : this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A plugin icon the shell renders inline (rail, tab strip, host row). Small
|
||||
* enough that a broken one should just disappear, not take the row with it.
|
||||
*/
|
||||
export function withIconBoundary<P extends object>(
|
||||
pluginId: string,
|
||||
Icon: ComponentType<P> | undefined,
|
||||
): ComponentType<P> | undefined {
|
||||
if (!Icon) return undefined;
|
||||
function SafeIcon(props: P) {
|
||||
return (
|
||||
<IconBoundary pluginId={pluginId}>
|
||||
<Icon {...props} />
|
||||
</IconBoundary>
|
||||
);
|
||||
}
|
||||
SafeIcon.displayName = `PluginIcon(${pluginId})`;
|
||||
return SafeIcon;
|
||||
}
|
||||
|
||||
/**
|
||||
* A plugin callback core calls while rendering, such as a host action's
|
||||
* label. A throw is logged and answered with `fallback`, so one plugin
|
||||
* cannot break the host list.
|
||||
*/
|
||||
export function guardCallback<A extends unknown[], R>(
|
||||
pluginId: string,
|
||||
fn: ((...args: A) => R) | undefined,
|
||||
fallback: R,
|
||||
): ((...args: A) => R) | undefined {
|
||||
if (!fn) return undefined;
|
||||
return (...args: A) => {
|
||||
try {
|
||||
return fn(...args);
|
||||
} catch (error) {
|
||||
console.error(`[plugins] ${pluginId} callback failed`, error);
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* @termix/plugin-sdk/ui: the shell's components, for plugins.
|
||||
*
|
||||
* Everything exported here is public API. A plugin builds its UI from these
|
||||
* so it looks like the rest of the app and picks up theme changes, and it
|
||||
* receives the shell's own instances through the import map, never a copy.
|
||||
*
|
||||
* The list is deliberate. It covers what the bundled plugins use today: the
|
||||
* shadcn primitives, the composites for metrics, connection screens and
|
||||
* settings rows, and the contexts a connection surface needs. Adding to it is
|
||||
* a contract change. Removing from it breaks plugins.
|
||||
*/
|
||||
|
||||
// Primitives
|
||||
export { Alert, AlertDescription, AlertTitle } from "@/components/alert";
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogPortal,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/alert-dialog";
|
||||
export { Badge } from "@/components/badge";
|
||||
export { Button, type ButtonProps } from "@/components/button";
|
||||
export {
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/card";
|
||||
export { Checkbox } from "@/components/checkbox";
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/dialog";
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/dropdown-menu";
|
||||
export { Input } from "@/components/input";
|
||||
export { Label } from "@/components/label";
|
||||
export { PasswordInput } from "@/components/password-input";
|
||||
export {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/popover";
|
||||
export { ScrollArea, ScrollBar } from "@/components/scroll-area";
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/select";
|
||||
export { Select2 } from "@/components/select2";
|
||||
export { Separator } from "@/components/separator";
|
||||
export { Skeleton } from "@/components/skeleton";
|
||||
export { Slider } from "@/components/slider";
|
||||
export { Switch } from "@/components/switch";
|
||||
export { Textarea, type TextareaProps } from "@/components/textarea";
|
||||
export {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/tooltip";
|
||||
|
||||
// Composites
|
||||
export { FakeSwitch, SectionCard, SettingRow } from "@/components/section-card";
|
||||
export { MetricCard } from "@/components/metric-card";
|
||||
export {
|
||||
BarSeries,
|
||||
MiniStat,
|
||||
RadialGauge,
|
||||
Sparkline,
|
||||
StatRow,
|
||||
type BarSeriesItem,
|
||||
type BarSeriesProps,
|
||||
type RadialGaugeProps,
|
||||
type SparklineProps,
|
||||
} from "@/components/charts";
|
||||
export { LineChart, type LineChartSeries } from "@/components/charts/LineChart";
|
||||
export {
|
||||
CardGridCanvas,
|
||||
ColumnCountStepper,
|
||||
} from "@/components/card-grid/CardGridCanvas";
|
||||
export {
|
||||
type GridCardCatalogEntry,
|
||||
type GridColSpan,
|
||||
type GridLayout,
|
||||
type GridSlot,
|
||||
} from "@/components/card-grid/types";
|
||||
export { ConnectionScreen } from "@/components/connection/ConnectionScreen";
|
||||
export { type ConnectionStatus } from "@/components/connection/connection-status";
|
||||
export {
|
||||
FullScreenAppWrapper,
|
||||
type FullScreenAppPhase,
|
||||
} from "@/components/FullScreenAppWrapper";
|
||||
|
||||
// Connection surfaces
|
||||
export {
|
||||
ConnectionLogProvider,
|
||||
useConnectionLog,
|
||||
useOptionalConnectionLog,
|
||||
} from "@/ssh/connection-log/ConnectionLogContext";
|
||||
export { TOTPDialog, type MFAPromptMode } from "@/ssh/dialogs/TOTPDialog";
|
||||
export { SSHAuthDialog } from "@/ssh/dialogs/SSHAuthDialog";
|
||||
export { BrowserSignInDialog } from "@/ssh/dialogs/BrowserSignInDialog";
|
||||
|
||||
// Design tokens: the colour swatches folders, workspaces and tags pick from.
|
||||
export { FOLDER_COLORS } from "@/lib/theme";
|
||||
|
||||
// Shell context
|
||||
export { useTabs, useTabsSafe } from "@/shell/TabContext";
|
||||
|
||||
// Slots: a plugin can offer places for other plugins to fill.
|
||||
export { ActionSlot, ComponentSlot } from "@/shell/ActionSlot";
|
||||
|
||||
// A plugin's manifest host settings, drawn inside its own host editor section.
|
||||
export {
|
||||
HostFeatureFields,
|
||||
type HostFeatureFieldsProps,
|
||||
} from "@/settings/HostPluginSections";
|
||||
|
||||
// Host defaults in a host editor section: where a field's value comes from,
|
||||
// and whether the section is editing a level of defaults rather than a host.
|
||||
export {
|
||||
HostDefaultBadge,
|
||||
DefaultsOnly as HostDefaultField,
|
||||
useIsDefaultsEditor,
|
||||
} from "@/lib/host-defaults-context";
|
||||
|
||||
// Components other plugins offer by id (app.registerComponent), rendered with
|
||||
// a fallback while their plugin is off.
|
||||
export { PluginComponent } from "@/plugin-host/component-registry";
|
||||
export { PluginViewPlaceholder } from "@/plugin-host/PluginViewPlaceholder";
|
||||
|
||||
// More primitives and hooks.
|
||||
export { cn } from "@/lib/utils";
|
||||
export {
|
||||
runAdaptivePolling,
|
||||
getPollingEnvironmentMultiplier,
|
||||
} from "@/lib/adaptive-polling";
|
||||
export {
|
||||
Sheet,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetTrigger,
|
||||
} from "@/components/sheet";
|
||||
// The frame and filter box every host manager card uses.
|
||||
export {
|
||||
ManagerCardShell,
|
||||
ManagerSearch,
|
||||
type ManagerCardError,
|
||||
} from "@/components/manager-card";
|
||||
export { useConfirmation } from "@/hooks/use-confirmation";
|
||||
export { useAdaptivePolling } from "@/hooks/use-adaptive-polling";
|
||||
// Homepage widget pieces, for plugins that register a widget.
|
||||
export { WidgetTitle } from "@/lib/widget-title";
|
||||
export { runVisibleInterval } from "@/lib/visible-interval";
|
||||
export { useIsMobile } from "@/hooks/use-mobile";
|
||||
export { EmptyState } from "@/components/empty-state";
|
||||
export { PassphraseDialog } from "@/ssh/dialogs/PassphraseDialog";
|
||||
export { HostKeyVerificationDialog } from "@/ssh/dialogs/HostKeyVerificationDialog";
|
||||
|
||||
// Clipboard helpers and the app theme, shared by every terminal-like surface.
|
||||
// The terminal look itself (themes, fonts, the preview) is the ssh-terminal
|
||||
// plugin's, offered through its "terminal.*" actions and components.
|
||||
export { copyToClipboard, readFromClipboard } from "@/lib/clipboard";
|
||||
export { RobustClipboardProvider } from "@/lib/clipboard-provider";
|
||||
export { useTheme as useAppTheme } from "@/components/theme-provider";
|
||||
|
||||
// Keyboard handling the shell shares with a terminal, so app shortcuts keep
|
||||
// working while a terminal has focus.
|
||||
export { findMatchingKeybinding } from "@/lib/keybinding-match";
|
||||
export { globalShortcutHandler } from "@/lib/global-shortcut-handler";
|
||||
export { isMacPlatform, isTabJumpHotkey } from "@/lib/tab-jump-hotkey";
|
||||
export {
|
||||
type CustomKeybinding,
|
||||
type KeyCombo,
|
||||
type KeybindingAction,
|
||||
type KeybindingActionType,
|
||||
} from "@/types/keybindings";
|
||||
|
||||
// Connection helpers: which backend a host's session dials, and the pieces
|
||||
// the desktop app needs to reach it.
|
||||
export { isElectron } from "@/lib/electron";
|
||||
export {
|
||||
resolveConnectionOrigin,
|
||||
type ConnectionOrigin,
|
||||
} from "@/lib/connection-origin";
|
||||
export { pluginWsUrl } from "@/lib/plugin-transport";
|
||||
export {
|
||||
buildOriginWsUrl,
|
||||
type WebSocketConnectionTarget,
|
||||
} from "@/lib/connection-origin";
|
||||
export { getBasePath } from "@/lib/base-path";
|
||||
export type { ConnectionStage } from "@/types/connection-log";
|
||||
export {
|
||||
hydrateLocalSharedHostAuth,
|
||||
resolveRemoteHostId,
|
||||
} from "@/lib/remote-server-api";
|
||||
export { remoteServerUrl as linkedServerUrl } from "@/plugin-host/desktop";
|
||||
|
||||
// Dashboard reads. The calls a plugin makes on the user's behalf (recent
|
||||
// activity, sudo autofill, open tabs, keybindings) are typed in
|
||||
// @termix/plugin-sdk/frontend instead.
|
||||
export {
|
||||
getRecentActivity,
|
||||
getUptime,
|
||||
type RecentActivityItem,
|
||||
type UptimeInfo,
|
||||
} from "@/api/dashboard-api";
|
||||
export {
|
||||
getVersionInfo,
|
||||
getDatabaseHealth,
|
||||
type VersionInfo,
|
||||
} from "@/api/system-status-api";
|
||||
|
||||
// Keyboard hints, the connection log panel and a named console logger.
|
||||
export { Kbd, KbdKey, KbdSeparator } from "@/components/kbd";
|
||||
export { ConnectionLogPanel } from "@/components/connection/ConnectionLogPanel";
|
||||
export type { LogEntry } from "@/types/connection-log";
|
||||
export { createFrontendLogger, type LogContext } from "@/lib/frontend-logger";
|
||||
|
||||
// One budget for background work across the whole app (preloads, prefetches).
|
||||
export {
|
||||
getAdaptiveResourceBudget,
|
||||
markAdaptiveResourceUsed,
|
||||
runAdaptiveBackgroundTask,
|
||||
} from "@/lib/adaptive-resource-budget";
|
||||
|
||||
// The id this browser sends as X-Termix-Device-ID.
|
||||
export { getDeviceId } from "@/lib/device-id";
|
||||
|
||||
// A host that is never saved, for connecting to an address straight away.
|
||||
export { createQuickConnectHost } from "@/sidebar/quick-connect-host";
|
||||
@@ -0,0 +1,148 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { Host } from "@/types/ui-types";
|
||||
import type { TabShellCallbacks } from "@/shell/tab-registry";
|
||||
|
||||
/**
|
||||
* The live shell, as plugins see it.
|
||||
*
|
||||
* AppShell owns tabs and hosts in React state. It publishes callbacks and
|
||||
* the host list here on every render, and plugin code (the app object, the
|
||||
* SDK hooks, registered host actions) calls through this module, so nothing
|
||||
* has to be threaded through props into a plugin.
|
||||
*/
|
||||
type Layout = { version: number; [key: string]: unknown };
|
||||
|
||||
export interface ShellLayoutProvider {
|
||||
getLayout: () => Layout | null;
|
||||
applyLayout: (
|
||||
layout: Layout,
|
||||
options?: { name?: string },
|
||||
) => Promise<{ skipped: string[] }>;
|
||||
}
|
||||
|
||||
let callbacks: TabShellCallbacks | null = null;
|
||||
let layoutProvider: ShellLayoutProvider | null = null;
|
||||
let hosts: Host[] = [];
|
||||
let hostsLoaded = false;
|
||||
let ready = false;
|
||||
|
||||
const hostListeners = new Set<() => void>();
|
||||
const changeListeners = new Set<() => void>();
|
||||
const readyListeners = new Set<() => void>();
|
||||
|
||||
export function setShellCallbacks(next: TabShellCallbacks | null): void {
|
||||
callbacks = next;
|
||||
}
|
||||
|
||||
export function setShellLayoutProvider(next: ShellLayoutProvider | null): void {
|
||||
layoutProvider = next;
|
||||
}
|
||||
|
||||
export function setShellHosts(next: Host[], loaded = true): void {
|
||||
if (next === hosts && loaded === hostsLoaded) return;
|
||||
hosts = next;
|
||||
hostsLoaded = loaded;
|
||||
hostSnapshot = { hosts, loaded: hostsLoaded };
|
||||
for (const listener of hostListeners) listener();
|
||||
}
|
||||
|
||||
let hostSnapshot = { hosts, loaded: hostsLoaded };
|
||||
|
||||
export function useShellHosts(): { hosts: Host[]; loaded: boolean } {
|
||||
return useSyncExternalStore(
|
||||
(listener) => {
|
||||
hostListeners.add(listener);
|
||||
return () => hostListeners.delete(listener);
|
||||
},
|
||||
() => hostSnapshot,
|
||||
() => hostSnapshot,
|
||||
);
|
||||
}
|
||||
|
||||
export function notifyTabsChanged(): void {
|
||||
for (const listener of changeListeners) listener();
|
||||
}
|
||||
|
||||
/** Called once the shell has restored its tabs. Late listeners fire at once. */
|
||||
export function notifyShellReady(): void {
|
||||
if (ready) return;
|
||||
ready = true;
|
||||
for (const listener of readyListeners) listener();
|
||||
}
|
||||
|
||||
function subscribe(set: Set<() => void>, listener: () => void): () => void {
|
||||
set.add(listener);
|
||||
return () => {
|
||||
set.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
/**
|
||||
* A plugin hands back the typed record it got from the SDK, which carries
|
||||
* fewer fields than the shell's own host. A tab should get the shell's host,
|
||||
* with whatever the plugin set on top.
|
||||
*/
|
||||
export function withShellHost(host: Host | null): Host | null {
|
||||
if (!host) return host;
|
||||
const own = shellHost(host.id);
|
||||
if (!own || own === host) return host;
|
||||
const merged: Record<string, unknown> = { ...own };
|
||||
for (const [key, value] of Object.entries(host)) {
|
||||
if (value !== undefined) merged[key] = value;
|
||||
}
|
||||
// A plugin only ever holds its own slice of the settings.
|
||||
merged.pluginSettings = own.pluginSettings;
|
||||
return merged as Host;
|
||||
}
|
||||
|
||||
/** The shell's own copy of a saved host, with every plugin's settings. */
|
||||
export function shellHost(id: string | number | undefined): Host | undefined {
|
||||
if (id === undefined || id === null) return undefined;
|
||||
return hosts.find((entry) => String(entry.id) === String(id));
|
||||
}
|
||||
|
||||
/** Forwards to the mounted shell; a no-op before it mounts or after logout. */
|
||||
export const shell: TabShellCallbacks = {
|
||||
openTab: (host, ...rest) => callbacks?.openTab(withShellHost(host), ...rest),
|
||||
openSingletonTab: (...args) => callbacks?.openSingletonTab(...args),
|
||||
connectHost: (host, ...rest) =>
|
||||
callbacks?.connectHost(withShellHost(host), ...rest),
|
||||
closeTab: (...args) => callbacks?.closeTab(...args),
|
||||
renameTab: (...args) => callbacks?.renameTab(...args),
|
||||
openRailView: (...args) => callbacks?.openRailView(...args),
|
||||
closeRailView: (...args) => callbacks?.closeRailView(...args),
|
||||
openHostEditor: (...args) => callbacks?.openHostEditor?.(...args),
|
||||
saveQuickConnect: (...args) =>
|
||||
callbacks?.saveQuickConnect?.(...args) ?? Promise.resolve(),
|
||||
};
|
||||
|
||||
export const tabsApi = {
|
||||
openTab: shell.openTab,
|
||||
openSingletonTab: shell.openSingletonTab,
|
||||
connectHost: shell.connectHost,
|
||||
closeTab: shell.closeTab,
|
||||
openRailView: shell.openRailView,
|
||||
getLayout: () => layoutProvider?.getLayout() ?? null,
|
||||
applyLayout: (layout: Layout, options?: { name?: string }) =>
|
||||
layoutProvider
|
||||
? layoutProvider.applyLayout(layout, options)
|
||||
: Promise.resolve({ skipped: [] as string[] }),
|
||||
onChange: (listener: () => void) => subscribe(changeListeners, listener),
|
||||
onReady: (listener: () => void) => {
|
||||
if (ready) {
|
||||
listener();
|
||||
return noop;
|
||||
}
|
||||
return subscribe(readyListeners, listener);
|
||||
},
|
||||
};
|
||||
|
||||
/** Test seam, and on logout. */
|
||||
export function resetShellBridge(): void {
|
||||
callbacks = null;
|
||||
layoutProvider = null;
|
||||
ready = false;
|
||||
setShellHosts([], false);
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
/**
|
||||
* The Termix side of @termix/plugin-sdk/testing's renderWithApp.
|
||||
*
|
||||
* Activates a plugin against the real registries, the real app object and
|
||||
* the real SDK bridge, then renders whatever it registered with Testing
|
||||
* Library. Shell calls are recorded rather than performed, since there is no
|
||||
* AppShell in a unit test.
|
||||
*/
|
||||
|
||||
import type { ReactElement } from "react";
|
||||
import { render } from "@testing-library/react";
|
||||
import type {
|
||||
HostActionContribution,
|
||||
PluginManifest,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import type {
|
||||
FrontendPluginModule,
|
||||
RenderWithAppOptions,
|
||||
RenderedPluginApp,
|
||||
ShellCall,
|
||||
} from "@termix/plugin-sdk/testing";
|
||||
import i18n from "@/i18n/i18n";
|
||||
import type { PluginSummary } from "@/api/plugins-api";
|
||||
import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { setPermissionsForTesting } from "@/hooks/use-permissions";
|
||||
import {
|
||||
getTabType,
|
||||
listTabTypes,
|
||||
type TabShellCallbacks,
|
||||
} from "@/shell/tab-registry";
|
||||
import { getPanel, listPanels } from "@/shell/panel-registry";
|
||||
import { listRegisteredRailItems } from "@/sidebar/rail-items";
|
||||
import { hostActionsFor, listHostActions } from "@/sidebar/host-contributions";
|
||||
import { listHostProtocols } from "@/sidebar/host-protocols";
|
||||
import {
|
||||
getHostEditorSection,
|
||||
hostEditorSectionList,
|
||||
} from "@/sidebar/HostManagerTabs";
|
||||
import {
|
||||
getRegisteredDashboardCard,
|
||||
registeredDashboardCardList,
|
||||
} from "@/dashboard/dashboard-cards-registry";
|
||||
import {
|
||||
getSettingsComponent,
|
||||
listSettingsComponents,
|
||||
} from "@/settings/settings-components";
|
||||
import { getSlotContributions, listActions } from "@/shell/action-registry";
|
||||
import { listPaletteGroups, loadPaletteGroup } from "@/shell/palette-registry";
|
||||
import {
|
||||
listKeybindingActions,
|
||||
listKeybindingDefaults,
|
||||
} from "@/shell/keybinding-registry";
|
||||
import {
|
||||
getLoginMethodUI,
|
||||
getSecondFactorUI,
|
||||
listLoginMethodUIs,
|
||||
listSecondFactorUIs,
|
||||
} from "./auth-registry";
|
||||
import { ActionSlot, ComponentSlot } from "@/shell/ActionSlot";
|
||||
import type { Host, Tab } from "@/types/ui-types";
|
||||
import { createPluginApp } from "./app";
|
||||
import { installPluginHostBridge, setPluginApiForTesting } from "./bridge";
|
||||
import { setRemoteServerUrlForTesting } from "./desktop";
|
||||
import { setPluginSummaries, setFrontendState } from "./plugin-store";
|
||||
import {
|
||||
notifyShellReady,
|
||||
resetShellBridge,
|
||||
setShellCallbacks,
|
||||
setShellHosts,
|
||||
setShellLayoutProvider,
|
||||
} from "./shell-bridge";
|
||||
import { PluginViewPlaceholder } from "./PluginViewPlaceholder";
|
||||
import { resolveLayoutTabTarget } from "@/shell/shell-layout";
|
||||
import { getExtension, listExtensions } from "./extension-registry";
|
||||
import type { WorkspaceTabSnapshot } from "@/types/ui-types";
|
||||
|
||||
function recordingShell(calls: ShellCall[]): TabShellCallbacks {
|
||||
const record =
|
||||
(method: string) =>
|
||||
(...args: unknown[]) => {
|
||||
calls.push({ method, args });
|
||||
};
|
||||
return {
|
||||
openTab: record("openTab"),
|
||||
openSingletonTab: record("openSingletonTab"),
|
||||
connectHost: record("connectHost"),
|
||||
closeTab: record("closeTab"),
|
||||
renameTab: record("renameTab"),
|
||||
openRailView: record("openRailView"),
|
||||
closeRailView: record("closeRailView"),
|
||||
openHostEditor: record("openHostEditor"),
|
||||
saveQuickConnect: async (...args) => {
|
||||
calls.push({ method: "saveQuickConnect", args });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function wrap(element: ReactElement): HTMLElement {
|
||||
return render(
|
||||
<ThemeProvider defaultTheme="dark" storageKey="termix-test-theme">
|
||||
{element}
|
||||
</ThemeProvider>,
|
||||
).container;
|
||||
}
|
||||
|
||||
function missing(kind: string, id: string | number): never {
|
||||
throw new Error(`renderWithApp: nothing registered ${kind} "${id}"`);
|
||||
}
|
||||
|
||||
export async function renderPlugin(
|
||||
plugin: FrontendPluginModule,
|
||||
options: RenderWithAppOptions = {},
|
||||
): Promise<RenderedPluginApp> {
|
||||
const pluginId = options.pluginId ?? options.manifest?.id ?? "test-plugin";
|
||||
const manifest = {
|
||||
id: pluginId,
|
||||
name: pluginId,
|
||||
version: "1.0.0",
|
||||
description: "",
|
||||
author: { name: "test" },
|
||||
license: "MIT",
|
||||
category: "Productivity",
|
||||
engine: { termix: ">=2.9.0", api: "1" },
|
||||
capabilities: [],
|
||||
...options.manifest,
|
||||
} as PluginManifest;
|
||||
|
||||
installPluginHostBridge();
|
||||
resetShellBridge();
|
||||
setPermissionsForTesting(options.permissions ?? [], options.isAdmin);
|
||||
const hosts = (options.hosts ?? []) as unknown as Host[];
|
||||
setShellHosts(hosts);
|
||||
const shellCalls: ShellCall[] = [];
|
||||
const shell = recordingShell(shellCalls);
|
||||
setShellCallbacks(shell);
|
||||
|
||||
// Stands in for AppShell's layout: applying one runs the shell's own
|
||||
// restore rules and records which tabs it would open.
|
||||
let layout = options.layout ?? null;
|
||||
const opened: Array<{ type: string; hostId?: number; label: string }> = [];
|
||||
setShellLayoutProvider({
|
||||
getLayout: () => layout,
|
||||
applyLayout: async (next, applyOptions) => {
|
||||
shellCalls.push({ method: "applyLayout", args: [next, applyOptions] });
|
||||
layout = next;
|
||||
opened.length = 0;
|
||||
const skipped: string[] = [];
|
||||
const tabs = (next.tabs ?? []) as WorkspaceTabSnapshot[];
|
||||
for (const snapshot of tabs) {
|
||||
const target = resolveLayoutTabTarget(snapshot, hosts);
|
||||
if (target.kind === "skip") {
|
||||
skipped.push(snapshot.hostNameSnapshot || snapshot.label);
|
||||
continue;
|
||||
}
|
||||
opened.push({
|
||||
type: snapshot.type,
|
||||
hostId:
|
||||
"host" in target && target.host
|
||||
? Number(target.host.id)
|
||||
: undefined,
|
||||
label: snapshot.customLabel ?? snapshot.label,
|
||||
});
|
||||
}
|
||||
return { skipped };
|
||||
},
|
||||
});
|
||||
|
||||
const summary: PluginSummary = {
|
||||
id: pluginId,
|
||||
name: manifest.name,
|
||||
version: manifest.version,
|
||||
enabled: true,
|
||||
state: "active",
|
||||
contributes: (manifest.contributes ?? null) as PluginSummary["contributes"],
|
||||
frontend: true,
|
||||
};
|
||||
setPluginSummaries([summary]);
|
||||
|
||||
if (options.locales) {
|
||||
i18n.addResourceBundle(
|
||||
"en",
|
||||
pluginId,
|
||||
options.locales as Record<string, unknown>,
|
||||
true,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
setPluginApiForTesting(
|
||||
pluginId,
|
||||
(options.api as Parameters<typeof setPluginApiForTesting>[1]) ?? null,
|
||||
);
|
||||
setRemoteServerUrlForTesting(options.remoteServerUrl ?? null);
|
||||
const handle = createPluginApp(pluginId, manifest, summary.contributes, {
|
||||
guest: options.guest,
|
||||
});
|
||||
await plugin.activate(handle.app);
|
||||
setFrontendState(pluginId, "active");
|
||||
if (options.ready) notifyShellReady();
|
||||
|
||||
const mine = <T extends { pluginId?: string }>(items: T[]) =>
|
||||
items.filter((item) => item.pluginId === pluginId);
|
||||
|
||||
const tabRecord = (type: string, host?: Host): Tab => ({
|
||||
id: `${type}-test`,
|
||||
instanceId: `${type}-test`,
|
||||
type,
|
||||
label: type,
|
||||
host,
|
||||
openedAt: 0,
|
||||
});
|
||||
|
||||
return {
|
||||
app: handle.app,
|
||||
shellCalls,
|
||||
registered: {
|
||||
railItems: () =>
|
||||
mine(listRegisteredRailItems()).map((item) => ({
|
||||
id: item.id,
|
||||
hidden: item.hidden,
|
||||
permission: item.permission,
|
||||
})),
|
||||
tabs: () => mine(listTabTypes()).map((def) => def.id),
|
||||
panels: () => mine(listPanels()).map((panel) => panel.id),
|
||||
hostActions: () =>
|
||||
mine(listHostActions()).map((action) => ({
|
||||
id: action.id,
|
||||
tabType: action.tabType,
|
||||
})),
|
||||
hostActionsFor: (host) =>
|
||||
mine(
|
||||
hostActionsFor(listHostActions(), host as Host),
|
||||
) as unknown as HostActionContribution[],
|
||||
hostProtocols: () =>
|
||||
mine(listHostProtocols()).map((protocol) => protocol.id),
|
||||
hostEditorSections: () =>
|
||||
mine(hostEditorSectionList()).map((section) => section.id),
|
||||
dashboardCards: () =>
|
||||
mine(registeredDashboardCardList()).map((card) => card.id),
|
||||
extensions: (pointId) =>
|
||||
mine(listExtensions(pointId)).map((extension) => extension.id),
|
||||
settingsComponents: () =>
|
||||
listSettingsComponents()
|
||||
.filter((key) => key.startsWith(`${pluginId}:`))
|
||||
.map((key) => key.slice(pluginId.length + 1)),
|
||||
slot: (slotId) =>
|
||||
mine(getSlotContributions(slotId)).map(
|
||||
(contribution) => contribution.actionId,
|
||||
),
|
||||
actions: () => mine(listActions()).map((action) => action.id),
|
||||
loginMethods: () => mine(listLoginMethodUIs()).map((method) => method.id),
|
||||
secondFactors: () =>
|
||||
mine(listSecondFactorUIs()).map((factor) => factor.id),
|
||||
paletteGroups: () => mine(listPaletteGroups()).map((group) => group.id),
|
||||
keybindingActions: () =>
|
||||
mine(listKeybindingActions()).map((action) => action.id),
|
||||
keybindingDefaults: () =>
|
||||
mine(listKeybindingDefaults()).map((binding) => binding.id),
|
||||
},
|
||||
|
||||
async loadPaletteGroup(id) {
|
||||
const group =
|
||||
listPaletteGroups().find((entry) => entry.id === id) ??
|
||||
missing("a palette group", id);
|
||||
return (await loadPaletteGroup(group)) as never;
|
||||
},
|
||||
|
||||
renderTab(type, props = {}) {
|
||||
const def = getTabType(type) ?? missing("a tab", type);
|
||||
const Component = def.component;
|
||||
const host = props.host as Host | undefined;
|
||||
return wrap(
|
||||
<Component
|
||||
tab={tabRecord(type, host)}
|
||||
host={host}
|
||||
label={type}
|
||||
isVisible
|
||||
isFocusedPane
|
||||
inSplit={false}
|
||||
handleRef={null}
|
||||
shell={shell}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
openedTabs: () => opened.map((tab) => ({ ...tab })),
|
||||
|
||||
renderOpenedTab(index) {
|
||||
const tab = opened[index] ?? missing("an opened tab at index", index);
|
||||
const def = getTabType(tab.type);
|
||||
if (!def) {
|
||||
// What tabUtils renders for a tab no running plugin registered.
|
||||
return wrap(<PluginViewPlaceholder kind="tab" viewId={tab.type} />);
|
||||
}
|
||||
const Component = def.component;
|
||||
return wrap(
|
||||
<Component
|
||||
tab={tabRecord(tab.type)}
|
||||
label={tab.label}
|
||||
isVisible
|
||||
isFocusedPane
|
||||
inSplit={false}
|
||||
handleRef={null}
|
||||
shell={shell}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderPanel(id, props = {}) {
|
||||
const panel = getPanel(id) ?? missing("a panel", id);
|
||||
const Component = panel.component;
|
||||
return wrap(
|
||||
<Component
|
||||
active
|
||||
shell={shell}
|
||||
setEditing={() => {}}
|
||||
placement="left"
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderExtension(pointId, id, component = "view", props = {}) {
|
||||
const extension = getExtension(pointId, id);
|
||||
const Component =
|
||||
extension?.pluginId === pluginId
|
||||
? extension.components?.[component]
|
||||
: undefined;
|
||||
if (!Component) missing(`an extension "${component}" component`, id);
|
||||
return wrap(<Component {...props} />);
|
||||
},
|
||||
|
||||
renderDashboardCard(id) {
|
||||
const card = getRegisteredDashboardCard(id) ?? missing("a card", id);
|
||||
const Component = card.component;
|
||||
return wrap(<Component isVisible shell={shell} />);
|
||||
},
|
||||
|
||||
renderHostEditorSection(id, props = {}) {
|
||||
const section =
|
||||
getHostEditorSection(id) ?? missing("a host editor section", id);
|
||||
const Component = section.component;
|
||||
return wrap(
|
||||
<Component
|
||||
form={{}}
|
||||
setField={() => {}}
|
||||
updateForm={() => {}}
|
||||
protocols={{}}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderSettingsComponent(componentId, props = {}) {
|
||||
const Component =
|
||||
getSettingsComponent(pluginId, componentId) ??
|
||||
missing("a settings component", componentId);
|
||||
return wrap(
|
||||
<Component
|
||||
pluginId={pluginId}
|
||||
values={{}}
|
||||
setValue={() => {}}
|
||||
running
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderLoginMethod(id, props = {}) {
|
||||
const method = getLoginMethodUI(id) ?? missing("a login method", id);
|
||||
const Component = method.component;
|
||||
return wrap(
|
||||
<Component
|
||||
methodId={id}
|
||||
instances={[]}
|
||||
rememberMe={false}
|
||||
disabled={false}
|
||||
submit={async () => {}}
|
||||
startRedirect={async () => {}}
|
||||
complete={async () => {}}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderSecondFactor(id, props = {}) {
|
||||
const factor = getSecondFactorUI(id) ?? missing("a second factor", id);
|
||||
const Component = factor.component;
|
||||
return wrap(
|
||||
<Component
|
||||
factorId={id}
|
||||
rememberMe={false}
|
||||
disabled={false}
|
||||
verify={async () => {}}
|
||||
challenge={async () => null}
|
||||
cancel={() => {}}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
},
|
||||
|
||||
renderEnrollment(id) {
|
||||
const entry = getSecondFactorUI(id) ?? getLoginMethodUI(id);
|
||||
const Component =
|
||||
entry?.enrollment ?? missing("an enrolment section", id);
|
||||
return wrap(<Component />);
|
||||
},
|
||||
|
||||
renderSlot(slotId, props = {}) {
|
||||
return wrap(
|
||||
<>
|
||||
<ActionSlot slotId={slotId} />
|
||||
<ComponentSlot slotId={slotId} props={props} />
|
||||
</>,
|
||||
);
|
||||
},
|
||||
|
||||
async deactivate() {
|
||||
try {
|
||||
await plugin.deactivate?.();
|
||||
} finally {
|
||||
handle.dispose();
|
||||
setFrontendState(pluginId, "inactive");
|
||||
setPluginApiForTesting(pluginId, null);
|
||||
setRemoteServerUrlForTesting(null);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { getPluginStoreState, type PluginRecord } from "./plugin-store";
|
||||
|
||||
/**
|
||||
* Who owns a tab type, rail view or dashboard card.
|
||||
*
|
||||
* Read from the manifests in GET /plugins rather than from what registered,
|
||||
* because a disabled plugin never runs its frontend and so never registers
|
||||
* anything, yet a saved tab or card of its still has to say whose it is.
|
||||
*/
|
||||
export type ViewKind = "tab" | "panel" | "card";
|
||||
|
||||
export type ViewStatus =
|
||||
/** Registered by a running plugin. */
|
||||
| "ready"
|
||||
/** Owner is enabled but its frontend has not finished loading. */
|
||||
| "loading"
|
||||
/** Owner is installed but switched off. */
|
||||
| "disabled"
|
||||
/** Owner's frontend or backend failed, or a hard dependency is missing. */
|
||||
| "failed"
|
||||
/** Nobody we know of declares this view. */
|
||||
| "missing";
|
||||
|
||||
function declares(record: PluginRecord, kind: ViewKind, id: string): boolean {
|
||||
const contributes = record.summary.contributes;
|
||||
if (!contributes) return false;
|
||||
if (kind === "tab") return !!contributes.tabs?.some((tab) => tab.id === id);
|
||||
if (kind === "panel") {
|
||||
return (
|
||||
!!contributes.panels?.some((panel) => panel.id === id) ||
|
||||
!!contributes.tabs?.some((tab) => tab.id === id)
|
||||
);
|
||||
}
|
||||
return !!contributes.dashboardCards?.some((card) => card.id === id);
|
||||
}
|
||||
|
||||
export function viewOwner(
|
||||
kind: ViewKind,
|
||||
id: string,
|
||||
): PluginRecord | undefined {
|
||||
for (const record of getPluginStoreState().records.values()) {
|
||||
if (declares(record, kind, id)) return record;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Whether a manifest declares the id, i.e. the plugin may register it. */
|
||||
export function manifestDeclares(
|
||||
contributes: PluginRecord["summary"]["contributes"],
|
||||
kind: ViewKind,
|
||||
id: string,
|
||||
): boolean {
|
||||
if (!contributes) return false;
|
||||
return declares(
|
||||
{ summary: { contributes } as PluginRecord["summary"], frontend: "none" },
|
||||
kind,
|
||||
id,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Status of a view that is NOT currently registered. Callers check their
|
||||
* registry first; this explains why it is absent.
|
||||
*/
|
||||
export function unregisteredViewStatus(
|
||||
kind: ViewKind,
|
||||
id: string,
|
||||
): { status: Exclude<ViewStatus, "ready">; owner?: PluginRecord } {
|
||||
const owner = viewOwner(kind, id);
|
||||
if (!owner) {
|
||||
return { status: getPluginStoreState().loaded ? "missing" : "loading" };
|
||||
}
|
||||
const serverState = owner.summary.state;
|
||||
if (!owner.summary.enabled) return { status: "disabled", owner };
|
||||
if (
|
||||
owner.frontend === "failed" ||
|
||||
owner.frontend === "blocked" ||
|
||||
serverState === "failed" ||
|
||||
serverState === "blocked"
|
||||
) {
|
||||
return { status: "failed", owner };
|
||||
}
|
||||
// Running, yet it never registered this view: it declared more than it
|
||||
// ships. Nothing will arrive, so do not spin.
|
||||
if (owner.frontend === "active" || !owner.summary.frontend) {
|
||||
return { status: "missing", owner };
|
||||
}
|
||||
return { status: "loading", owner };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Plugin sources in this monorepo, for the Vite dev server.
|
||||
*
|
||||
* Empty everywhere except `vite dev`, where the termix-plugin-host Vite plugin
|
||||
* replaces this module with import.meta.glob calls over plugins/<id>/, so
|
||||
* plugin frontends load through Vite with HMR instead of from their built
|
||||
* bundles. A production build keeps it empty: plugins are separate bundles
|
||||
* served from /plugin-assets, never part of the shell's own build.
|
||||
*/
|
||||
|
||||
type Loader = () => Promise<unknown>;
|
||||
|
||||
/** plugin id -> its src/frontend/index.tsx */
|
||||
export const workspaceFrontends: Record<string, Loader> = {};
|
||||
|
||||
/** plugin id -> locale file ("en", "de_DE") -> JSON */
|
||||
export const workspaceLocales: Record<string, Record<string, Loader>> = {};
|
||||
Reference in new issue
Block a user