mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 14:15: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,406 @@
|
||||
/**
|
||||
* The Docker panel's interactive connect.
|
||||
*
|
||||
* Core's pipeline does the handshake; this only bridges its prompt channel to
|
||||
* HTTP. A connect that needs a person (a TOTP code, a browser sign-in, a
|
||||
* password the host does not store) answers the request that is waiting with
|
||||
* what to ask, and the next request (connect-totp, connect-browser-sign-in) carries
|
||||
* the answer back and waits for whatever comes after it: the session, another
|
||||
* prompt, or an error.
|
||||
*/
|
||||
|
||||
import type { Client } from "ssh2";
|
||||
import type {
|
||||
PluginContext,
|
||||
PluginSshHost,
|
||||
PluginSshPromptRequest,
|
||||
} from "@termix/plugin-sdk/backend";
|
||||
import type { ContainerRuntime } from "./container-runtime.js";
|
||||
import type { DockerSessions } from "./sessions.js";
|
||||
import {
|
||||
connectionLog,
|
||||
getErrorMessage,
|
||||
type ConnectionLogLine,
|
||||
type DockerLogger,
|
||||
} from "./helpers.js";
|
||||
|
||||
/** What one HTTP request answers with. */
|
||||
export interface ConnectStep {
|
||||
status: number;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const TOTP_WAIT_MS = 3 * 60 * 1000;
|
||||
const BROWSER_SIGN_IN_WAIT_MS = 5 * 60 * 1000;
|
||||
const STEP_WAIT_MS = 90 * 1000;
|
||||
// Covers the longest a person may take on a prompt, plus the handshake.
|
||||
const CONNECT_TIMEOUT_MS = BROWSER_SIGN_IN_WAIT_MS + 30 * 1000;
|
||||
|
||||
const PASSWORD_PROMPT = /password/i;
|
||||
|
||||
/** Hands each step to whichever request is waiting for one. */
|
||||
export class PendingConnect {
|
||||
constructor(
|
||||
readonly userId: string,
|
||||
readonly hostId: number,
|
||||
) {}
|
||||
|
||||
expiresAt = Date.now() + TOTP_WAIT_MS;
|
||||
/** What the open prompt expects, or null when nothing is being asked. */
|
||||
awaiting: "totp" | "browser" | null = null;
|
||||
abandoned = false;
|
||||
private waiter: ((step: ConnectStep) => void) | null = null;
|
||||
private queued: ConnectStep | null = null;
|
||||
private answer: ((value: string | null) => void) | null = null;
|
||||
|
||||
emit(step: ConnectStep): void {
|
||||
if (this.waiter) {
|
||||
const waiter = this.waiter;
|
||||
this.waiter = null;
|
||||
waiter(step);
|
||||
} else {
|
||||
this.queued = step;
|
||||
}
|
||||
}
|
||||
|
||||
next(timeoutMs = STEP_WAIT_MS): Promise<ConnectStep> {
|
||||
if (this.queued) {
|
||||
const step = this.queued;
|
||||
this.queued = null;
|
||||
return Promise.resolve(step);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
if (this.waiter !== settle) return;
|
||||
this.waiter = null;
|
||||
this.cancel();
|
||||
resolve({
|
||||
status: 408,
|
||||
body: { error: "Connection timed out. Please reconnect." },
|
||||
});
|
||||
}, timeoutMs);
|
||||
const settle = (step: ConnectStep) => {
|
||||
clearTimeout(timer);
|
||||
resolve(step);
|
||||
};
|
||||
this.waiter = settle;
|
||||
});
|
||||
}
|
||||
|
||||
ask(kind: "totp" | "browser", waitMs: number): Promise<string | null> {
|
||||
this.awaiting = kind;
|
||||
this.expiresAt = Date.now() + waitMs;
|
||||
return new Promise((resolve) => {
|
||||
this.answer = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
respond(value: string | null): void {
|
||||
const answer = this.answer;
|
||||
this.answer = null;
|
||||
this.awaiting = null;
|
||||
answer?.(value);
|
||||
}
|
||||
|
||||
/** Nobody will read the result: give up the prompt and drop the client. */
|
||||
cancel(): void {
|
||||
this.abandoned = true;
|
||||
this.respond(null);
|
||||
}
|
||||
}
|
||||
|
||||
function classifyConnectError(
|
||||
message: string,
|
||||
logs: ConnectionLogLine[],
|
||||
): { hostKeyChanged: boolean; authFailed: boolean } {
|
||||
if (message.includes("ENOTFOUND") || message.includes("getaddrinfo")) {
|
||||
logs.push(
|
||||
connectionLog("error", "dns", `DNS resolution failed: ${message}`),
|
||||
);
|
||||
} else if (
|
||||
message.includes("ECONNREFUSED") ||
|
||||
message.includes("ETIMEDOUT")
|
||||
) {
|
||||
logs.push(
|
||||
connectionLog("error", "tcp", `TCP connection failed: ${message}`),
|
||||
);
|
||||
} else if (message.includes("verification failed")) {
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"error",
|
||||
"handshake",
|
||||
"SSH host key has changed. For security, please open a Terminal connection to this host first to verify and accept the new key fingerprint.",
|
||||
),
|
||||
);
|
||||
return { hostKeyChanged: true, authFailed: false };
|
||||
} else if (
|
||||
message.includes("handshake") ||
|
||||
message.includes("key exchange")
|
||||
) {
|
||||
logs.push(
|
||||
connectionLog("error", "handshake", `SSH handshake failed: ${message}`),
|
||||
);
|
||||
} else if (/authentication/i.test(message)) {
|
||||
logs.push(
|
||||
connectionLog("error", "auth", `Authentication failed: ${message}`),
|
||||
);
|
||||
return { hostKeyChanged: false, authFailed: true };
|
||||
} else {
|
||||
logs.push(
|
||||
connectionLog("error", "error", `SSH connection failed: ${message}`),
|
||||
);
|
||||
}
|
||||
return { hostKeyChanged: false, authFailed: false };
|
||||
}
|
||||
|
||||
export interface StartConnectInput {
|
||||
sessionId: string;
|
||||
userId: string;
|
||||
host: PluginSshHost;
|
||||
runtime: ContainerRuntime;
|
||||
logs: ConnectionLogLine[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a connect and returns the first step for the request that asked.
|
||||
* The pending entry lives in `sessions` until the connect settles, so the
|
||||
* answer routes can find it.
|
||||
*/
|
||||
export async function startConnect(
|
||||
ctx: PluginContext,
|
||||
sessions: DockerSessions,
|
||||
log: DockerLogger,
|
||||
input: StartConnectInput,
|
||||
): Promise<ConnectStep> {
|
||||
const { sessionId, userId, host, runtime, logs } = input;
|
||||
const hostId = host.id;
|
||||
const authType = (host.authType as string) || "none";
|
||||
const credentialless = !ctx.ssh.requiresSecret(authType);
|
||||
|
||||
const pending = new PendingConnect(userId, hostId);
|
||||
sessions.setPending(sessionId, pending);
|
||||
|
||||
const parkTotp = (prompt: string, extra: Record<string, unknown>) => {
|
||||
logs.push(connectionLog("info", "docker_auth", "Verification required"));
|
||||
const answer = pending.ask("totp", TOTP_WAIT_MS);
|
||||
pending.emit({
|
||||
status: 200,
|
||||
body: {
|
||||
requires_totp: true,
|
||||
sessionId,
|
||||
prompt,
|
||||
connectionLogs: logs,
|
||||
...extra,
|
||||
},
|
||||
});
|
||||
return answer;
|
||||
};
|
||||
|
||||
const ask = async (
|
||||
request: PluginSshPromptRequest,
|
||||
): Promise<string | null> => {
|
||||
if (pending.abandoned) return null;
|
||||
switch (request.kind) {
|
||||
case "totp":
|
||||
return parkTotp(request.prompt, request.retry ? { retry: true } : {});
|
||||
case "browser": {
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"info",
|
||||
"docker_auth",
|
||||
`${request.label} sign-in required`,
|
||||
),
|
||||
);
|
||||
const answer = pending.ask("browser", BROWSER_SIGN_IN_WAIT_MS);
|
||||
pending.emit({
|
||||
status: 200,
|
||||
body: {
|
||||
requires_browser_sign_in: true,
|
||||
sessionId,
|
||||
label: request.label,
|
||||
url: request.url,
|
||||
code: request.code,
|
||||
connectionLogs: logs,
|
||||
},
|
||||
});
|
||||
return answer;
|
||||
}
|
||||
case "input": {
|
||||
const isPassword = PASSWORD_PROMPT.test(request.prompt);
|
||||
if (isPassword && credentialless) {
|
||||
pending.abandoned = true;
|
||||
pending.emit({
|
||||
status: 200,
|
||||
body: { status: "auth_required", reason: "no_keyboard" },
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (!isPassword && !request.isPush) return "";
|
||||
return parkTotp(request.prompt, isPassword ? { isPassword: true } : {});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
logs.push(connectionLog("info", "dns", `Resolving DNS for ${host.ip}`));
|
||||
logs.push(
|
||||
connectionLog("info", "tcp", `Connecting to ${host.ip}:${host.port}`),
|
||||
);
|
||||
logs.push(connectionLog("info", "handshake", "Initiating SSH handshake"));
|
||||
|
||||
ctx.ssh
|
||||
.connect<Client>(host, {
|
||||
purpose: "docker",
|
||||
profile: "session",
|
||||
timeoutMs: CONNECT_TIMEOUT_MS,
|
||||
prompt: { ask },
|
||||
})
|
||||
.then(
|
||||
(connection) => {
|
||||
sessions.clearPending(sessionId);
|
||||
ctx.hosts.status.reportLogin(hostId, { ok: true });
|
||||
if (pending.abandoned) {
|
||||
connection.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
const session = {
|
||||
id: sessionId,
|
||||
client: connection.client,
|
||||
dispose: connection.dispose,
|
||||
hostId,
|
||||
userId,
|
||||
runtime,
|
||||
isWindows: false,
|
||||
lastActive: Date.now(),
|
||||
activeOperations: 0,
|
||||
};
|
||||
sessions.add(session);
|
||||
|
||||
connection.client.exec("ver", (err, stream) => {
|
||||
if (err || !stream) return;
|
||||
let output = "";
|
||||
stream.on("data", (d: Buffer) => {
|
||||
output += d.toString();
|
||||
});
|
||||
stream.on("close", () => {
|
||||
if (output.toLowerCase().includes("windows")) {
|
||||
session.isWindows = true;
|
||||
}
|
||||
});
|
||||
stream.stderr.on("data", () => {});
|
||||
});
|
||||
|
||||
void ctx.audit.record({
|
||||
action: "docker_connect",
|
||||
resourceType: "host",
|
||||
resourceId: String(hostId),
|
||||
resourceName: (host.name as string) || undefined,
|
||||
success: true,
|
||||
});
|
||||
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"success",
|
||||
"connected",
|
||||
"SSH connection established successfully",
|
||||
),
|
||||
);
|
||||
pending.emit({
|
||||
status: 200,
|
||||
body: { success: true, status: "success", connectionLogs: logs },
|
||||
});
|
||||
},
|
||||
(error: unknown) => {
|
||||
sessions.clearPending(sessionId);
|
||||
const message = getErrorMessage(error, "SSH connection failed");
|
||||
if (pending.abandoned) return;
|
||||
|
||||
const outcome = (error as { outcome?: Record<string, unknown> })
|
||||
.outcome;
|
||||
if (outcome?.status === "interaction-required") {
|
||||
logs.push(connectionLog("error", "docker_auth", message));
|
||||
pending.emit({
|
||||
status: 401,
|
||||
body: {
|
||||
error: message,
|
||||
requiresAuthInteraction: outcome.interaction,
|
||||
...(typeof outcome.flag === "string"
|
||||
? { [outcome.flag]: true }
|
||||
: {}),
|
||||
connectionLogs: logs,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (outcome?.status === "error") {
|
||||
logs.push(connectionLog("error", "docker_auth", message));
|
||||
pending.emit({
|
||||
status: 400,
|
||||
body: { error: message, connectionLogs: logs },
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { hostKeyChanged, authFailed } = classifyConnectError(
|
||||
message,
|
||||
logs,
|
||||
);
|
||||
if (hostKeyChanged || authFailed) {
|
||||
ctx.hosts.status.reportLogin(hostId, { ok: false, hostKeyChanged });
|
||||
}
|
||||
log.error("Docker SSH connection failed", {
|
||||
hostId,
|
||||
userId,
|
||||
error: message,
|
||||
});
|
||||
|
||||
if (credentialless && authFailed) {
|
||||
pending.emit({
|
||||
status: 200,
|
||||
body: {
|
||||
status: "auth_required",
|
||||
reason: "no_keyboard",
|
||||
connectionLogs: logs,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
pending.emit({
|
||||
status: 500,
|
||||
body: { success: false, message, connectionLogs: logs },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return pending.next();
|
||||
}
|
||||
|
||||
/** Carries a person's answer to a parked connect and waits for what's next. */
|
||||
export async function answerConnect(
|
||||
sessions: DockerSessions,
|
||||
sessionId: string,
|
||||
userId: string,
|
||||
kind: "totp" | "browser",
|
||||
value: string,
|
||||
): Promise<ConnectStep> {
|
||||
const pending = sessions.getPending(sessionId);
|
||||
if (!(pending instanceof PendingConnect) || pending.userId !== userId) {
|
||||
return {
|
||||
status: 404,
|
||||
body: { error: "Authentication session expired. Please reconnect." },
|
||||
};
|
||||
}
|
||||
if (pending.awaiting !== kind) {
|
||||
return {
|
||||
status: 400,
|
||||
body: {
|
||||
error:
|
||||
kind === "browser"
|
||||
? "Session is not waiting for a browser sign-in"
|
||||
: "Session is not waiting for a code",
|
||||
},
|
||||
};
|
||||
}
|
||||
pending.respond(value);
|
||||
return pending.next();
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import { AsyncResource } from "node:async_hooks";
|
||||
import { StringDecoder } from "node:string_decoder";
|
||||
import type { Client, ClientChannel } from "ssh2";
|
||||
import { WebSocket, type RawData } from "ws";
|
||||
import type {
|
||||
PluginContext,
|
||||
PluginWebSocketConnection,
|
||||
} from "@termix/plugin-sdk/backend";
|
||||
import {
|
||||
containerCommand,
|
||||
type ContainerRuntime,
|
||||
} from "./container-runtime.js";
|
||||
import { readDockerHostSettings } from "./host-settings.js";
|
||||
import {
|
||||
CONTAINER_ID_RE,
|
||||
HOST_ADDRESS_MISMATCH_MESSAGE,
|
||||
HOST_NOT_ON_THIS_SERVER_MESSAGE,
|
||||
asObject,
|
||||
asString,
|
||||
getErrorMessage,
|
||||
hostAddressMismatch,
|
||||
parseWsMessage,
|
||||
toTerminalDimension,
|
||||
type DockerLogger,
|
||||
} from "./helpers.js";
|
||||
|
||||
const SHELLS = ["bash", "sh", "ash", "zsh"];
|
||||
const PING_MS = 30_000;
|
||||
|
||||
interface ConsoleSession {
|
||||
client: Client;
|
||||
dispose: () => void;
|
||||
stream: ClientChannel | null;
|
||||
hostId: number;
|
||||
containerId: string;
|
||||
runtime: ContainerRuntime;
|
||||
}
|
||||
|
||||
function shellExists(
|
||||
client: Client,
|
||||
runtime: ContainerRuntime,
|
||||
containerId: string,
|
||||
shell: string,
|
||||
): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
client.exec(
|
||||
containerCommand(runtime, `exec ${containerId} which ${shell}`),
|
||||
(err, stream) => {
|
||||
if (err) return resolve(false);
|
||||
let output = "";
|
||||
stream.on("data", (data: Buffer) => {
|
||||
output += data.toString();
|
||||
});
|
||||
stream.on("close", (code: number) =>
|
||||
resolve(code === 0 && output.trim().length > 0),
|
||||
);
|
||||
stream.stderr.on("data", () => {});
|
||||
stream.stderr.on("error", () => {});
|
||||
stream.on("error", () => resolve(false));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function pickShell(
|
||||
client: Client,
|
||||
runtime: ContainerRuntime,
|
||||
containerId: string,
|
||||
requested: string | undefined,
|
||||
): Promise<string> {
|
||||
if (requested && (await shellExists(client, runtime, containerId, requested)))
|
||||
return requested;
|
||||
for (const shell of ["bash", "sh", "ash"]) {
|
||||
if (await shellExists(client, runtime, containerId, shell)) return shell;
|
||||
}
|
||||
return "sh";
|
||||
}
|
||||
|
||||
/**
|
||||
* The container console at /plugin-ws/docker/console.
|
||||
*
|
||||
* Public with optionalAuth: core still resolves the caller's token, and the
|
||||
* handler refuses a socket without a user or without docker.use. Every live
|
||||
* console is closed when the plugin deactivates.
|
||||
*/
|
||||
export function registerConsole(ctx: PluginContext, log: DockerLogger): void {
|
||||
const live = new Set<() => void>();
|
||||
ctx.disposables.add(() => {
|
||||
for (const end of [...live]) end();
|
||||
live.clear();
|
||||
});
|
||||
|
||||
const onConnection = async (connection: PluginWebSocketConnection) => {
|
||||
const ws = connection.socket as WebSocket;
|
||||
const userId = connection.userId;
|
||||
if (!userId || !(await ctx.rbac.hasFor(userId, "use"))) {
|
||||
ws.close(1008, "Authentication required");
|
||||
return;
|
||||
}
|
||||
|
||||
let session: ConsoleSession | null = null;
|
||||
const send = (message: Record<string, unknown>) => {
|
||||
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
|
||||
};
|
||||
|
||||
const endSession = () => {
|
||||
if (!session) return;
|
||||
const current = session;
|
||||
session = null;
|
||||
current.stream?.end();
|
||||
current.dispose();
|
||||
};
|
||||
|
||||
const pingTimer = setInterval(() => {
|
||||
if (ws.readyState === WebSocket.OPEN) ws.ping();
|
||||
}, PING_MS);
|
||||
|
||||
const cleanup = () => {
|
||||
clearInterval(pingTimer);
|
||||
endSession();
|
||||
live.delete(shutdown);
|
||||
};
|
||||
const shutdown = () => {
|
||||
cleanup();
|
||||
try {
|
||||
ws.close(1001, "Docker plugin disabled");
|
||||
} catch {
|
||||
// already closed
|
||||
}
|
||||
};
|
||||
live.add(shutdown);
|
||||
|
||||
const connect = async (data: unknown) => {
|
||||
if (!connection.isDataUnlocked()) {
|
||||
send({
|
||||
type: "error",
|
||||
message: "Session expired - please log in again",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const payload = asObject(data);
|
||||
const hostConfig = asObject(payload.hostConfig);
|
||||
const hostId = Number(hostConfig.id);
|
||||
const syncId =
|
||||
typeof hostConfig.syncId === "string" ? hostConfig.syncId : null;
|
||||
const containerId = asString(payload.containerId);
|
||||
const shell = asString(payload.shell) || undefined;
|
||||
const cols = toTerminalDimension(payload.cols) || 80;
|
||||
const rows = toTerminalDimension(payload.rows) || 24;
|
||||
|
||||
if (!hostId || !containerId) {
|
||||
send({
|
||||
type: "error",
|
||||
message: "Host configuration and container ID are required",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!CONTAINER_ID_RE.test(containerId)) {
|
||||
send({ type: "error", message: "Invalid container ID" });
|
||||
return;
|
||||
}
|
||||
if (shell && !SHELLS.includes(shell)) {
|
||||
send({ type: "error", message: "Invalid shell" });
|
||||
return;
|
||||
}
|
||||
|
||||
endSession();
|
||||
|
||||
try {
|
||||
// syncId names the host on both sides of a sync pair; the numeric
|
||||
// id only names it in the database the client is displaying.
|
||||
const host = await ctx.ssh.resolveHost(hostId, { syncId });
|
||||
if (!host) {
|
||||
send({
|
||||
type: "error",
|
||||
message: syncId
|
||||
? HOST_NOT_ON_THIS_SERVER_MESSAGE
|
||||
: "Host not found",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!syncId && hostAddressMismatch(hostConfig.ip, host.ip)) {
|
||||
log.error("Refusing Docker console: host id resolves elsewhere", {
|
||||
hostId,
|
||||
userId,
|
||||
});
|
||||
send({ type: "error", message: HOST_ADDRESS_MISMATCH_MESSAGE });
|
||||
return;
|
||||
}
|
||||
|
||||
const settings = await readDockerHostSettings(ctx, host.id);
|
||||
if (!settings.enabled) {
|
||||
send({
|
||||
type: "error",
|
||||
message:
|
||||
"Docker is not enabled for this host. Enable it in Host Settings.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { client, dispose } = await ctx.ssh.connect<Client>(host, {
|
||||
purpose: "docker-console",
|
||||
profile: "stream",
|
||||
timeoutMs: 65_000,
|
||||
});
|
||||
if (ws.readyState !== WebSocket.OPEN) {
|
||||
dispose();
|
||||
return;
|
||||
}
|
||||
const current: ConsoleSession = {
|
||||
client,
|
||||
dispose,
|
||||
stream: null,
|
||||
hostId: host.id,
|
||||
containerId,
|
||||
runtime: settings.runtime,
|
||||
};
|
||||
session = current;
|
||||
|
||||
const shellToUse = await pickShell(
|
||||
client,
|
||||
settings.runtime,
|
||||
containerId,
|
||||
shell,
|
||||
);
|
||||
if (session !== current) return;
|
||||
|
||||
client.exec(
|
||||
containerCommand(
|
||||
settings.runtime,
|
||||
`exec -it ${containerId} /bin/${shellToUse}`,
|
||||
),
|
||||
{ pty: { term: "xterm-256color", cols, rows } },
|
||||
(err, stream) => {
|
||||
if (err) {
|
||||
send({
|
||||
type: "error",
|
||||
message: `Failed to start console: ${err.message}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (session !== current) {
|
||||
stream.end();
|
||||
return;
|
||||
}
|
||||
current.stream = stream;
|
||||
|
||||
// Buffers split multi-byte UTF-8 sequences across chunks.
|
||||
const decoder = new StringDecoder("utf-8");
|
||||
stream.on("data", (chunk: Buffer) => {
|
||||
const text = decoder.write(chunk);
|
||||
if (text) send({ type: "output", data: text });
|
||||
});
|
||||
stream.stderr.on("data", () => {});
|
||||
stream.stderr.on("error", () => {});
|
||||
stream.on("error", (streamErr: Error) => {
|
||||
send({
|
||||
type: "error",
|
||||
message: `Console error: ${streamErr.message}`,
|
||||
});
|
||||
});
|
||||
stream.on("close", () => {
|
||||
send({ type: "disconnected", message: "Console session ended" });
|
||||
if (session === current) endSession();
|
||||
});
|
||||
|
||||
send({
|
||||
type: "connected",
|
||||
data: {
|
||||
shell: shellToUse,
|
||||
requestedShell: shell,
|
||||
shellChanged: !!shell && shell !== shellToUse,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
log.error("Failed to connect to container", error, {
|
||||
hostId,
|
||||
containerId,
|
||||
});
|
||||
send({
|
||||
type: "error",
|
||||
message: getErrorMessage(error, "Failed to connect to container"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
ws.on(
|
||||
"message",
|
||||
AsyncResource.bind(async (raw: RawData) => {
|
||||
let type: string;
|
||||
let data: unknown;
|
||||
try {
|
||||
({ type, data } = parseWsMessage(raw));
|
||||
} catch (error) {
|
||||
send({ type: "error", message: getErrorMessage(error) });
|
||||
return;
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case "connect":
|
||||
await connect(data);
|
||||
break;
|
||||
case "input": {
|
||||
const input = asString(data);
|
||||
if (input) session?.stream?.write(input);
|
||||
break;
|
||||
}
|
||||
case "resize": {
|
||||
const size = asObject(data);
|
||||
const cols = toTerminalDimension(size.cols);
|
||||
const rows = toTerminalDimension(size.rows);
|
||||
if (cols && rows)
|
||||
session?.stream?.setWindow(rows, cols, rows, cols);
|
||||
break;
|
||||
}
|
||||
case "disconnect":
|
||||
if (session) {
|
||||
endSession();
|
||||
send({
|
||||
type: "disconnected",
|
||||
message: "Disconnected from container",
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "ping":
|
||||
send({ type: "pong" });
|
||||
break;
|
||||
default:
|
||||
log.warn("Unknown docker console message", { type });
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
ws.on("close", cleanup);
|
||||
ws.on("error", (error: Error) => {
|
||||
log.error("Docker console socket error", error);
|
||||
cleanup();
|
||||
});
|
||||
};
|
||||
|
||||
ctx.ws.route("/console", onConnection, { public: true, optionalAuth: true });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export type ContainerRuntime = "docker" | "podman";
|
||||
|
||||
export function normalizeContainerRuntime(value: unknown): ContainerRuntime {
|
||||
return value === "podman" ? "podman" : "docker";
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-interactive SSH shells don't source ~/.zprofile or ~/.bash_profile,
|
||||
* so PATH additions from installers like Homebrew or OrbStack are missing.
|
||||
* Extend PATH with their common install locations before invoking the CLI.
|
||||
*/
|
||||
const EXTRA_PATH_DIRS =
|
||||
'/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:"$HOME/.orbstack/bin"';
|
||||
|
||||
export function containerCommand(
|
||||
runtime: ContainerRuntime | undefined,
|
||||
args: string,
|
||||
): string {
|
||||
return `PATH="${EXTRA_PATH_DIRS}:$PATH" ${normalizeContainerRuntime(runtime)} ${args}`;
|
||||
}
|
||||
|
||||
export function getRuntimeLabel(runtime: ContainerRuntime): string {
|
||||
return runtime === "podman" ? "Podman" : "Docker";
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Container state snapshots and the events two of them imply, for the
|
||||
* docker.events service.
|
||||
*
|
||||
* Events come from diffing successive `ps -a` snapshots, so the poll interval
|
||||
* is the resolution: a container that stops and starts between two polls is
|
||||
* not reported. That is the tradeoff for not holding a `docker events` stream
|
||||
* open against every watched host.
|
||||
*/
|
||||
|
||||
export interface ContainerState {
|
||||
/** Docker's own state word: running, exited, restarting, ... */
|
||||
state: string;
|
||||
/** Health from the status text, when the image declares a healthcheck. */
|
||||
unhealthy: boolean;
|
||||
}
|
||||
|
||||
export type DockerEventName = "exited" | "started" | "unhealthy" | "restarting";
|
||||
|
||||
export const PS_STATE_FORMAT = `'{"name":"{{.Names}}","state":"{{.State}}","status":"{{.Status}}"}'`;
|
||||
|
||||
/** Parses `ps -a --format PS_STATE_FORMAT` output, one JSON object per line. */
|
||||
export function parseContainerStates(
|
||||
output: string,
|
||||
): Map<string, ContainerState> {
|
||||
const states = new Map<string, ContainerState>();
|
||||
|
||||
for (const line of output.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) continue;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as {
|
||||
name?: string;
|
||||
state?: string;
|
||||
status?: string;
|
||||
};
|
||||
if (!parsed.name) continue;
|
||||
|
||||
states.set(parsed.name, {
|
||||
state: (parsed.state ?? "").toLowerCase(),
|
||||
unhealthy: /\(unhealthy\)/i.test(parsed.status ?? ""),
|
||||
});
|
||||
} catch {
|
||||
// A partial line is not worth failing the whole poll over.
|
||||
}
|
||||
}
|
||||
|
||||
return states;
|
||||
}
|
||||
|
||||
/**
|
||||
* The events a pair of snapshots implies. A container missing from the
|
||||
* previous snapshot counts as newly seen rather than started, so the first
|
||||
* poll after a restart does not replay every running container.
|
||||
*/
|
||||
export function diffContainerStates(
|
||||
previous: Map<string, ContainerState>,
|
||||
current: Map<string, ContainerState>,
|
||||
): Array<{ container: string; event: DockerEventName }> {
|
||||
const events: Array<{ container: string; event: DockerEventName }> = [];
|
||||
|
||||
for (const [name, now] of current) {
|
||||
const before = previous.get(name);
|
||||
if (!before) continue;
|
||||
|
||||
if (before.state !== now.state) {
|
||||
if (now.state === "exited")
|
||||
events.push({ container: name, event: "exited" });
|
||||
else if (now.state === "running")
|
||||
events.push({ container: name, event: "started" });
|
||||
else if (now.state === "restarting")
|
||||
events.push({ container: name, event: "restarting" });
|
||||
}
|
||||
|
||||
// Health is independent of state: a container can go unhealthy while it
|
||||
// stays up, which is exactly the case worth alerting on.
|
||||
if (!before.unhealthy && now.unhealthy) {
|
||||
events.push({ container: name, event: "unhealthy" });
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { RawData } from "ws";
|
||||
import type { PluginLogger } from "@termix/plugin-sdk/backend";
|
||||
|
||||
export function getErrorMessage(
|
||||
error: unknown,
|
||||
fallback = "Unknown error",
|
||||
): string {
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
|
||||
export type Meta = Record<string, unknown>;
|
||||
|
||||
export interface DockerLogger {
|
||||
info: (message: string, meta?: Meta) => void;
|
||||
warn: (message: string, meta?: Meta) => void;
|
||||
/** An error, or structured context, or both. */
|
||||
error: (message: string, errorOrMeta?: unknown, meta?: Meta) => void;
|
||||
}
|
||||
|
||||
function withMeta(message: string, meta?: Meta): string {
|
||||
if (!meta || Object.keys(meta).length === 0) return message;
|
||||
try {
|
||||
return `${message} ${JSON.stringify(meta)}`;
|
||||
} catch {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
/** ctx.log with the structured context the old core logger carried. */
|
||||
export function createLogger(log: PluginLogger): DockerLogger {
|
||||
return {
|
||||
info: (message, meta) => log.info(withMeta(message, meta)),
|
||||
warn: (message, meta) => log.warn(withMeta(message, meta)),
|
||||
error: (message, errorOrMeta, meta) => {
|
||||
if (errorOrMeta instanceof Error) {
|
||||
log.error(withMeta(message, meta), errorOrMeta);
|
||||
return;
|
||||
}
|
||||
log.error(
|
||||
withMeta(message, {
|
||||
...((errorOrMeta as Meta | undefined) ?? {}),
|
||||
...meta,
|
||||
}),
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type LogLevel = "info" | "success" | "warning" | "error";
|
||||
|
||||
/** One line of the connection log the panel shows while connecting. */
|
||||
export interface ConnectionLogLine {
|
||||
type: LogLevel;
|
||||
stage: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function connectionLog(
|
||||
type: LogLevel,
|
||||
stage: string,
|
||||
message: string,
|
||||
): ConnectionLogLine {
|
||||
return { type, stage, message };
|
||||
}
|
||||
|
||||
export const CONTAINER_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
||||
export const DOCKER_TIMESTAMP_RE = /^[0-9T:.Z+-]+$/;
|
||||
|
||||
// Cap on a single decoded text frame. Control messages are tiny, and console
|
||||
// input is bounded by what a user can type or paste.
|
||||
export const MAX_WS_MESSAGE_BYTES = 1024 * 1024;
|
||||
|
||||
function rawByteLength(raw: RawData): number {
|
||||
if (Buffer.isBuffer(raw)) return raw.length;
|
||||
if (Array.isArray(raw))
|
||||
return raw.reduce((sum, part) => sum + part.length, 0);
|
||||
if (raw instanceof ArrayBuffer) return raw.byteLength;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Parses a frame into `{ type, data }`, throwing on anything else. */
|
||||
export function parseWsMessage(raw: RawData): { type: string; data: unknown } {
|
||||
if (rawByteLength(raw) > MAX_WS_MESSAGE_BYTES) {
|
||||
throw new Error("Message too large");
|
||||
}
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(raw.toString());
|
||||
} catch {
|
||||
throw new Error("Invalid JSON");
|
||||
}
|
||||
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
||||
throw new Error("Message must be a JSON object");
|
||||
}
|
||||
const { type, data } = parsed as { type?: unknown; data?: unknown };
|
||||
if (typeof type !== "string") {
|
||||
throw new Error("Message type must be a string");
|
||||
}
|
||||
return { type, data };
|
||||
}
|
||||
|
||||
export function asObject(data: unknown): Record<string, unknown> {
|
||||
return data !== null && typeof data === "object" && !Array.isArray(data)
|
||||
? (data as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
export function asString(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
/** A sane integer width or height, or 0 when the value is unusable. */
|
||||
export function toTerminalDimension(value: unknown): number {
|
||||
const n = typeof value === "number" ? value : Number(value);
|
||||
if (!Number.isFinite(n)) return 0;
|
||||
const rounded = Math.floor(n);
|
||||
if (rounded < 1) return 0;
|
||||
return Math.min(rounded, 10000);
|
||||
}
|
||||
|
||||
function normalizeHostAddress(value: unknown): string {
|
||||
if (typeof value !== "string") return "";
|
||||
return value
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a numeric host id resolved to a different machine than the client
|
||||
* meant. Ids from the desktop app and a sync server drift apart, and the
|
||||
* resolved row supplies the credentials, so a mismatch must be refused.
|
||||
*/
|
||||
export function hostAddressMismatch(
|
||||
clientAddress: unknown,
|
||||
resolvedAddress: unknown,
|
||||
): boolean {
|
||||
const resolved = normalizeHostAddress(resolvedAddress);
|
||||
if (!resolved) return false;
|
||||
return resolved !== normalizeHostAddress(clientAddress);
|
||||
}
|
||||
|
||||
export const HOST_ADDRESS_MISMATCH_MESSAGE =
|
||||
"Host mismatch: this server resolved the selected host to a different machine, so the connection was refused. " +
|
||||
"The host ids on this device and on the sync server have drifted apart. " +
|
||||
'Set the connection origin to "This device" for this host, or re-run a full sync, then try again.';
|
||||
|
||||
export const HOST_NOT_ON_THIS_SERVER_MESSAGE =
|
||||
"This host does not exist on the sync server, so the connection was refused. " +
|
||||
'Run a sync so the server knows about it, or set the connection origin to "This device" for this host.';
|
||||
|
||||
export function newSessionId(prefix: string): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import {
|
||||
normalizeContainerRuntime,
|
||||
type ContainerRuntime,
|
||||
} from "./container-runtime.js";
|
||||
|
||||
export const PLUGIN_ID = "docker";
|
||||
|
||||
export interface DockerHostSettings {
|
||||
enabled: boolean;
|
||||
runtime: ContainerRuntime;
|
||||
}
|
||||
|
||||
export async function readDockerHostSettings(
|
||||
ctx: PluginContext,
|
||||
hostId: number,
|
||||
): Promise<DockerHostSettings> {
|
||||
const values = await ctx.settings.getAll("host", hostId);
|
||||
return {
|
||||
enabled: values.enableDocker === true,
|
||||
runtime: normalizeContainerRuntime(values.containerRuntime),
|
||||
};
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
let parsed = value;
|
||||
if (typeof value === "string") {
|
||||
try {
|
||||
parsed = JSON.parse(value);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function asBool(value: unknown): boolean | undefined {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (value === 1 || value === "1" || value === "true") return true;
|
||||
if (value === 0 || value === "0" || value === "false") return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The docker host settings in an imported or created host row: the nested
|
||||
* `pluginSettings.docker` of a Termix export first, then the flat
|
||||
* `enableDocker` and `dockerConfig.runtime` hosts had before 2.9.0 (older
|
||||
* exports, proxmox guests marked as Docker hosts).
|
||||
*/
|
||||
export function normalizeImportedHost(
|
||||
raw: Record<string, unknown>,
|
||||
): Record<string, unknown> | null {
|
||||
const nested = asObject(asObject(raw.pluginSettings)?.[PLUGIN_ID]) ?? {};
|
||||
const out: Record<string, unknown> = {};
|
||||
|
||||
const enabled = asBool(
|
||||
nested.enableDocker !== undefined ? nested.enableDocker : raw.enableDocker,
|
||||
);
|
||||
if (enabled !== undefined) out.enableDocker = enabled;
|
||||
|
||||
const runtime =
|
||||
nested.containerRuntime ?? asObject(raw.dockerConfig)?.runtime;
|
||||
if (runtime === "docker" || runtime === "podman") {
|
||||
out.containerRuntime = runtime;
|
||||
}
|
||||
|
||||
return Object.keys(out).length > 0 ? out : null;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Router } from "express";
|
||||
import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import { createLogger } from "./helpers.js";
|
||||
import { createDockerSessions } from "./sessions.js";
|
||||
import { registerRoutes } from "./routes.js";
|
||||
import { registerConsole } from "./console.js";
|
||||
import { registerServices } from "./services.js";
|
||||
import { normalizeImportedHost } from "./host-settings.js";
|
||||
|
||||
export type {
|
||||
DockerContainerAction,
|
||||
DockerContainerSummary,
|
||||
DockerEvent,
|
||||
DockerEventsV1,
|
||||
DockerServiceV1,
|
||||
} from "./services.js";
|
||||
|
||||
export async function activate(ctx: PluginContext) {
|
||||
const log = createLogger(ctx.log);
|
||||
const sessions = createDockerSessions(ctx.schedule, log);
|
||||
ctx.disposables.add(() => sessions.closeAll());
|
||||
|
||||
registerRoutes(ctx.http.router<Router>(), { ctx, sessions, log });
|
||||
registerConsole(ctx, log);
|
||||
registerServices(ctx, log);
|
||||
ctx.registry.provide("docker.hostImportNormalizer", normalizeImportedHost);
|
||||
|
||||
ctx.log.info(
|
||||
"Docker mounted at /plugin-api/docker and /plugin-ws/docker/console",
|
||||
);
|
||||
}
|
||||
|
||||
export async function deactivate() {}
|
||||
@@ -0,0 +1,998 @@
|
||||
import type { Request, Response, Router } from "express";
|
||||
import type { PluginContext, PluginSshHost } from "@termix/plugin-sdk/backend";
|
||||
import { answerConnect, startConnect } from "./connect.js";
|
||||
import { containerCommand, getRuntimeLabel } from "./container-runtime.js";
|
||||
import { readDockerHostSettings } from "./host-settings.js";
|
||||
import type { DockerSession, DockerSessions } from "./sessions.js";
|
||||
import {
|
||||
CONTAINER_ID_RE,
|
||||
DOCKER_TIMESTAMP_RE,
|
||||
connectionLog,
|
||||
getErrorMessage,
|
||||
type ConnectionLogLine,
|
||||
type DockerLogger,
|
||||
} from "./helpers.js";
|
||||
|
||||
const CONTAINER_ACTIONS = [
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
"pause",
|
||||
"unpause",
|
||||
] as const;
|
||||
type ContainerAction = (typeof CONTAINER_ACTIONS)[number];
|
||||
|
||||
const LIST_FORMAT_UNIX = `'{"id":"{{.ID}}","name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","state":"{{.State}}","ports":"{{.Ports}}","created":"{{.CreatedAt}}"}' `;
|
||||
const LIST_FORMAT_WINDOWS = `"{\\"id\\":\\"{{.ID}}\\",\\"name\\":\\"{{.Names}}\\",\\"image\\":\\"{{.Image}}\\",\\"status\\":\\"{{.Status}}\\",\\"state\\":\\"{{.State}}\\",\\"ports\\":\\"{{.Ports}}\\",\\"created\\":\\"{{.CreatedAt}}\\"}"`;
|
||||
const STATS_FORMAT_UNIX = `'{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}' `;
|
||||
const STATS_FORMAT_WINDOWS = `"{\\"cpu\\":\\"{{.CPUPerc}}\\",\\"memory\\":\\"{{.MemUsage}}\\",\\"memoryPercent\\":\\"{{.MemPerc}}\\",\\"netIO\\":\\"{{.NetIO}}\\",\\"blockIO\\":\\"{{.BlockIO}}\\",\\"pids\\":\\"{{.PIDs}}\\"}"`;
|
||||
|
||||
export function listFormat(isWindows: boolean): string {
|
||||
return isWindows ? LIST_FORMAT_WINDOWS : LIST_FORMAT_UNIX;
|
||||
}
|
||||
|
||||
/** Parses `ps --format listFormat()` output, skipping lines that are not JSON. */
|
||||
export function parseContainerList(output: string): Record<string, unknown>[] {
|
||||
return output
|
||||
.split("\n")
|
||||
.filter((line) => line.trim())
|
||||
.flatMap((line) => {
|
||||
try {
|
||||
return [JSON.parse(line) as Record<string, unknown>];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function notFound(error: unknown): boolean {
|
||||
return getErrorMessage(error, "").includes("No such container");
|
||||
}
|
||||
|
||||
interface Deps {
|
||||
ctx: PluginContext;
|
||||
sessions: DockerSessions;
|
||||
log: DockerLogger;
|
||||
}
|
||||
|
||||
export function registerRoutes(router: Router, { ctx, sessions, log }: Deps) {
|
||||
router.use((_req, res, next) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
router.use(ctx.rbac.require("use") as never);
|
||||
|
||||
router.param("containerId", (_req, res, next, value) => {
|
||||
if (!CONTAINER_ID_RE.test(value)) {
|
||||
res.status(400).json({ error: "Invalid container ID" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
const userOf = (res: Response): string | null => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) {
|
||||
res.status(401).json({ error: "Authentication required" });
|
||||
return null;
|
||||
}
|
||||
return userId;
|
||||
};
|
||||
|
||||
/** The caller's live session for the path's sessionId, or an error reply. */
|
||||
const sessionOf = (req: Request, res: Response): DockerSession | null => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return null;
|
||||
const sessionId = String(req.params.sessionId ?? "");
|
||||
if (sessions.getPending(sessionId)) {
|
||||
res.status(400).json({
|
||||
error: "Connection pending authentication",
|
||||
code: "AUTH_PENDING",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const session = sessions.get(sessionId, userId);
|
||||
if (!session) {
|
||||
res.status(400).json({ error: "SSH session not found or not connected" });
|
||||
return null;
|
||||
}
|
||||
return session;
|
||||
};
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/connect:
|
||||
* post:
|
||||
* summary: Establish SSH session for Docker
|
||||
* description: Opens an SSH session to a host for Docker operations. When the host asks for a code, a browser sign-in or a password, the reply says so and the session waits for connect-totp or connect-browser-sign-in.
|
||||
* tags:
|
||||
* - Docker
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - sessionId
|
||||
* - hostId
|
||||
* properties:
|
||||
* sessionId:
|
||||
* type: string
|
||||
* hostId:
|
||||
* type: integer
|
||||
* userProvidedPassword:
|
||||
* type: string
|
||||
* userProvidedSshKey:
|
||||
* type: string
|
||||
* userProvidedKeyPassword:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Connected, or a prompt the user has to answer.
|
||||
* 400:
|
||||
* description: Missing sessionId or hostId.
|
||||
* 403:
|
||||
* description: Docker is not enabled for this host, or the user lacks docker.use.
|
||||
* 404:
|
||||
* description: Host not found.
|
||||
* 500:
|
||||
* description: SSH connection failed.
|
||||
*/
|
||||
router.post("/ssh/connect", async (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const {
|
||||
sessionId,
|
||||
hostId,
|
||||
userProvidedPassword,
|
||||
userProvidedSshKey,
|
||||
userProvidedKeyPassword,
|
||||
} = (req.body ?? {}) as Record<string, unknown>;
|
||||
const logs: ConnectionLogLine[] = [];
|
||||
|
||||
if (typeof sessionId !== "string" || !sessionId || !hostId) {
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"error",
|
||||
"docker_connecting",
|
||||
"Missing connection parameters",
|
||||
),
|
||||
);
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Missing sessionId or hostId", connectionLogs: logs });
|
||||
}
|
||||
const numericHostId = Number(hostId);
|
||||
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"info",
|
||||
"docker_connecting",
|
||||
"Initiating Docker SSH connection",
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
const host = await ctx.ssh.resolveHost(numericHostId);
|
||||
if (!host) {
|
||||
logs.push(
|
||||
connectionLog("error", "docker_connecting", "Host not found"),
|
||||
);
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "Host not found", connectionLogs: logs });
|
||||
}
|
||||
|
||||
const settings = await readDockerHostSettings(ctx, numericHostId);
|
||||
if (!settings.enabled) {
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"error",
|
||||
"docker_connecting",
|
||||
"Docker is not enabled for this host",
|
||||
),
|
||||
);
|
||||
return res.status(403).json({
|
||||
error:
|
||||
"Docker is not enabled for this host. Enable it in Host Settings.",
|
||||
code: "DOCKER_DISABLED",
|
||||
connectionLogs: logs,
|
||||
});
|
||||
}
|
||||
|
||||
sessions.close(sessionId);
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"info",
|
||||
"docker_auth",
|
||||
"Resolving authentication credentials",
|
||||
),
|
||||
);
|
||||
|
||||
const target: PluginSshHost = {
|
||||
...host,
|
||||
id: numericHostId,
|
||||
port: host.port || 22,
|
||||
};
|
||||
if (typeof userProvidedPassword === "string" && userProvidedPassword) {
|
||||
target.password = userProvidedPassword;
|
||||
target.authType = "password";
|
||||
}
|
||||
if (typeof userProvidedSshKey === "string" && userProvidedSshKey) {
|
||||
target.key = userProvidedSshKey;
|
||||
target.authType = "key";
|
||||
}
|
||||
if (
|
||||
typeof userProvidedKeyPassword === "string" &&
|
||||
userProvidedKeyPassword
|
||||
) {
|
||||
target.keyPassword = userProvidedKeyPassword;
|
||||
}
|
||||
|
||||
const step = await startConnect(ctx, sessions, log, {
|
||||
sessionId,
|
||||
userId,
|
||||
host: target,
|
||||
runtime: settings.runtime,
|
||||
logs,
|
||||
});
|
||||
return res.status(step.status).json(step.body);
|
||||
} catch (error) {
|
||||
log.error("Docker SSH connection error", error, {
|
||||
hostId: numericHostId,
|
||||
userId,
|
||||
});
|
||||
logs.push(
|
||||
connectionLog(
|
||||
"error",
|
||||
"docker_connecting",
|
||||
`Connection error: ${getErrorMessage(error)}`,
|
||||
),
|
||||
);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: getErrorMessage(error),
|
||||
connectionLogs: logs,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/connect-totp:
|
||||
* post:
|
||||
* summary: Answer a verification prompt
|
||||
* description: Sends the code (or password) the host asked for and waits for the next step of the connect.
|
||||
* tags:
|
||||
* - Docker
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - sessionId
|
||||
* - totpCode
|
||||
* properties:
|
||||
* sessionId:
|
||||
* type: string
|
||||
* totpCode:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Connected, or another prompt.
|
||||
* 400:
|
||||
* description: Session ID and code required, or the session is not waiting for a code.
|
||||
* 404:
|
||||
* description: The connect expired.
|
||||
* 408:
|
||||
* description: The host did not answer in time.
|
||||
*/
|
||||
router.post("/ssh/connect-totp", async (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const { sessionId, totpCode } = (req.body ?? {}) as Record<string, unknown>;
|
||||
if (typeof sessionId !== "string" || typeof totpCode !== "string") {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Session ID and TOTP code required" });
|
||||
}
|
||||
const step = await answerConnect(
|
||||
sessions,
|
||||
sessionId,
|
||||
userId,
|
||||
"totp",
|
||||
totpCode.trim(),
|
||||
);
|
||||
return res.status(step.status).json(step.body);
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/connect-browser-sign-in:
|
||||
* post:
|
||||
* summary: Continue after a browser sign-in
|
||||
* description: Continues a connect after the user finished signing in in the browser (an SSH gateway's approval, for example).
|
||||
* tags:
|
||||
* - Docker
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required:
|
||||
* - sessionId
|
||||
* properties:
|
||||
* sessionId:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Connected, or another prompt.
|
||||
* 400:
|
||||
* description: Session ID required, or the session is not waiting for a browser sign-in.
|
||||
* 404:
|
||||
* description: The connect expired.
|
||||
* 408:
|
||||
* description: The host did not answer in time.
|
||||
*/
|
||||
router.post("/ssh/connect-browser-sign-in", async (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const { sessionId } = (req.body ?? {}) as Record<string, unknown>;
|
||||
if (typeof sessionId !== "string" || !sessionId) {
|
||||
return res.status(400).json({ error: "Session ID required" });
|
||||
}
|
||||
const step = await answerConnect(
|
||||
sessions,
|
||||
sessionId,
|
||||
userId,
|
||||
"browser",
|
||||
"",
|
||||
);
|
||||
return res.status(step.status).json(step.body);
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/disconnect:
|
||||
* post:
|
||||
* summary: Disconnect SSH session
|
||||
* description: Closes the caller's Docker SSH session.
|
||||
* tags:
|
||||
* - Docker
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* sessionId:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: SSH session disconnected.
|
||||
* 400:
|
||||
* description: Session ID is required.
|
||||
*/
|
||||
router.post("/ssh/disconnect", (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const { sessionId } = (req.body ?? {}) as Record<string, unknown>;
|
||||
if (typeof sessionId !== "string" || !sessionId) {
|
||||
return res.status(400).json({ error: "Session ID is required" });
|
||||
}
|
||||
const pending = sessions.getPending(sessionId);
|
||||
if (sessions.get(sessionId, userId) || pending?.userId === userId) {
|
||||
sessions.close(sessionId);
|
||||
}
|
||||
return res.json({ success: true, message: "SSH session disconnected" });
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/keepalive:
|
||||
* post:
|
||||
* summary: Keep SSH session alive
|
||||
* description: Resets the idle timeout of the caller's Docker SSH session.
|
||||
* tags:
|
||||
* - Docker
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* sessionId:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Session keepalive successful.
|
||||
* 400:
|
||||
* description: Session ID is required or session not found.
|
||||
*/
|
||||
router.post("/ssh/keepalive", (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const { sessionId } = (req.body ?? {}) as Record<string, unknown>;
|
||||
if (typeof sessionId !== "string" || !sessionId) {
|
||||
return res.status(400).json({ error: "Session ID is required" });
|
||||
}
|
||||
const session = sessions.get(sessionId, userId);
|
||||
if (!session) {
|
||||
return res.status(400).json({
|
||||
error: "SSH session not found or not connected",
|
||||
connected: false,
|
||||
});
|
||||
}
|
||||
sessions.touch(session);
|
||||
return res.json({
|
||||
success: true,
|
||||
connected: true,
|
||||
lastActive: session.lastActive,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/ssh/status:
|
||||
* get:
|
||||
* summary: Check SSH session status
|
||||
* description: Whether the caller's Docker SSH session is connected.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Session status.
|
||||
* 400:
|
||||
* description: Session ID is required.
|
||||
*/
|
||||
router.get("/ssh/status", (req, res) => {
|
||||
const userId = userOf(res);
|
||||
if (!userId) return;
|
||||
const sessionId = req.query.sessionId;
|
||||
if (typeof sessionId !== "string" || !sessionId) {
|
||||
return res.status(400).json({ error: "Session ID is required" });
|
||||
}
|
||||
return res.json({
|
||||
success: true,
|
||||
connected: !!sessions.get(sessionId, userId),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/validate/{sessionId}:
|
||||
* get:
|
||||
* summary: Validate Docker availability
|
||||
* description: Checks that the container runtime is installed and its daemon answers.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Docker availability status.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
*/
|
||||
router.get("/validate/:sessionId", async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const runtime = session.runtime;
|
||||
const label = getRuntimeLabel(runtime);
|
||||
|
||||
await sessions.run(session, async () => {
|
||||
let version = "unknown";
|
||||
try {
|
||||
const output = await sessions.exec(
|
||||
session,
|
||||
containerCommand(runtime, "--version"),
|
||||
);
|
||||
version =
|
||||
output.match(/(?:Docker|podman) version ([^\s,]+)/i)?.[1] ??
|
||||
"unknown";
|
||||
} catch {
|
||||
res.json({
|
||||
available: false,
|
||||
error: `${label} is not installed on this host.`,
|
||||
code: "NOT_INSTALLED",
|
||||
runtime,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sessions.exec(session, containerCommand(runtime, "ps"));
|
||||
res.json({ available: true, version, runtime });
|
||||
} catch (error) {
|
||||
const message = getErrorMessage(error, "");
|
||||
if (message.includes("Cannot connect to the Docker daemon")) {
|
||||
res.json({
|
||||
available: false,
|
||||
error: `${label} daemon is not running or accessible`,
|
||||
code: "DAEMON_NOT_RUNNING",
|
||||
runtime,
|
||||
});
|
||||
} else if (message.includes("permission denied")) {
|
||||
res.json({
|
||||
available: false,
|
||||
error: `Permission denied accessing ${label}`,
|
||||
code: "PERMISSION_DENIED",
|
||||
runtime,
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
available: false,
|
||||
error: message,
|
||||
code: "DOCKER_ERROR",
|
||||
runtime,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}:
|
||||
* get:
|
||||
* summary: List all containers
|
||||
* description: Lists the containers on the session's host.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: query
|
||||
* name: all
|
||||
* schema:
|
||||
* type: boolean
|
||||
* responses:
|
||||
* 200:
|
||||
* description: A list of containers.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
* 500:
|
||||
* description: Failed to list containers.
|
||||
*/
|
||||
router.get("/containers/:sessionId", async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const all = req.query.all !== "false";
|
||||
try {
|
||||
const output = await sessions.run(session, () =>
|
||||
sessions.exec(
|
||||
session,
|
||||
containerCommand(
|
||||
session.runtime,
|
||||
`ps ${all ? "-a " : ""}--format ${listFormat(session.isWindows)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
res.json(parseContainerList(output));
|
||||
} catch (error) {
|
||||
log.error("Failed to list Docker containers", error, {
|
||||
hostId: session.hostId,
|
||||
});
|
||||
res.status(500).json({
|
||||
error: getErrorMessage(error, "Failed to list containers"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}/{containerId}:
|
||||
* get:
|
||||
* summary: Get container details
|
||||
* description: The container's inspect output.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: containerId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Container details.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
* 404:
|
||||
* description: Container not found.
|
||||
* 500:
|
||||
* description: Failed to get container details.
|
||||
*/
|
||||
router.get("/containers/:sessionId/:containerId", async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const { containerId } = req.params;
|
||||
try {
|
||||
const output = await sessions.run(session, () =>
|
||||
sessions.exec(
|
||||
session,
|
||||
containerCommand(session.runtime, `inspect ${containerId}`),
|
||||
),
|
||||
);
|
||||
const details = JSON.parse(output) as unknown[];
|
||||
if (details?.length > 0) {
|
||||
res.json(details[0]);
|
||||
} else {
|
||||
res
|
||||
.status(404)
|
||||
.json({ error: "Container not found", code: "CONTAINER_NOT_FOUND" });
|
||||
}
|
||||
} catch (error) {
|
||||
if (notFound(error)) {
|
||||
return res
|
||||
.status(404)
|
||||
.json({ error: "Container not found", code: "CONTAINER_NOT_FOUND" });
|
||||
}
|
||||
log.error("Failed to get container details", error, {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
});
|
||||
res.status(500).json({
|
||||
error: getErrorMessage(error, "Failed to get container details"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}/{containerId}/{action}:
|
||||
* post:
|
||||
* summary: Start, stop, restart, pause or unpause a container
|
||||
* description: Runs the container action on the session's host.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: containerId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: action
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* enum: [start, stop, restart, pause, unpause]
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The action ran.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
* 404:
|
||||
* description: Container not found, or an unknown action.
|
||||
* 500:
|
||||
* description: The action failed.
|
||||
*/
|
||||
router.post(
|
||||
"/containers/:sessionId/:containerId/:action",
|
||||
async (req, res) => {
|
||||
const action = req.params.action as ContainerAction;
|
||||
if (!CONTAINER_ACTIONS.includes(action)) {
|
||||
return res.status(404).json({ error: "Unknown container action" });
|
||||
}
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const { containerId } = req.params;
|
||||
try {
|
||||
log.info("Docker container operation", {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
action,
|
||||
});
|
||||
await sessions.run(session, () =>
|
||||
sessions.exec(
|
||||
session,
|
||||
containerCommand(session.runtime, `${action} ${containerId}`),
|
||||
),
|
||||
);
|
||||
res.json({ success: true, message: `Container ${action} succeeded` });
|
||||
} catch (error) {
|
||||
if (notFound(error)) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: "Container not found",
|
||||
code: "CONTAINER_NOT_FOUND",
|
||||
});
|
||||
}
|
||||
log.error(`Failed to ${action} container`, error, {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
});
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, `Failed to ${action} container`),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}/{containerId}/remove:
|
||||
* delete:
|
||||
* summary: Remove container
|
||||
* description: Removes a container, optionally by force.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: containerId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: query
|
||||
* name: force
|
||||
* schema:
|
||||
* type: boolean
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Container removed.
|
||||
* 400:
|
||||
* description: Session not found, or the container is running and force was not set.
|
||||
* 404:
|
||||
* description: Container not found.
|
||||
* 500:
|
||||
* description: Failed to remove container.
|
||||
*/
|
||||
router.delete(
|
||||
"/containers/:sessionId/:containerId/remove",
|
||||
async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const { containerId } = req.params;
|
||||
const force = req.query.force === "true";
|
||||
try {
|
||||
log.info("Docker container operation", {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
action: "remove",
|
||||
});
|
||||
await sessions.run(session, () =>
|
||||
sessions.exec(
|
||||
session,
|
||||
containerCommand(
|
||||
session.runtime,
|
||||
`rm ${force ? "-f " : ""}${containerId}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
res.json({ success: true, message: "Container removed successfully" });
|
||||
} catch (error) {
|
||||
if (notFound(error)) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: "Container not found",
|
||||
code: "CONTAINER_NOT_FOUND",
|
||||
});
|
||||
}
|
||||
if (
|
||||
getErrorMessage(error, "").includes(
|
||||
"cannot remove a running container",
|
||||
)
|
||||
) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error:
|
||||
"Cannot remove a running container. Stop it first or use force.",
|
||||
code: "CONTAINER_RUNNING",
|
||||
});
|
||||
}
|
||||
log.error("Failed to remove container", error, {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
});
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, "Failed to remove container"),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}/{containerId}/logs:
|
||||
* get:
|
||||
* summary: Get container logs
|
||||
* description: The container's log output.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: containerId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: query
|
||||
* name: tail
|
||||
* schema:
|
||||
* type: integer
|
||||
* - in: query
|
||||
* name: timestamps
|
||||
* schema:
|
||||
* type: boolean
|
||||
* - in: query
|
||||
* name: since
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: query
|
||||
* name: until
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Container logs.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
* 404:
|
||||
* description: Container not found.
|
||||
* 500:
|
||||
* description: Failed to get container logs.
|
||||
*/
|
||||
router.get("/containers/:sessionId/:containerId/logs", async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const { containerId } = req.params;
|
||||
const tail = req.query.tail ? parseInt(String(req.query.tail), 10) : 100;
|
||||
const since = typeof req.query.since === "string" ? req.query.since : "";
|
||||
const until = typeof req.query.until === "string" ? req.query.until : "";
|
||||
|
||||
let command = containerCommand(session.runtime, `logs ${containerId}`);
|
||||
if (tail && tail > 0) command += ` --tail ${Math.floor(tail)}`;
|
||||
if (req.query.timestamps === "true") command += " --timestamps";
|
||||
if (since && DOCKER_TIMESTAMP_RE.test(since))
|
||||
command += ` --since ${since}`;
|
||||
if (until && DOCKER_TIMESTAMP_RE.test(until))
|
||||
command += ` --until ${until}`;
|
||||
command += " 2>&1";
|
||||
|
||||
try {
|
||||
const logs = await sessions.run(session, () =>
|
||||
sessions.exec(session, command),
|
||||
);
|
||||
res.json({ success: true, logs });
|
||||
} catch (error) {
|
||||
if (notFound(error)) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: "Container not found",
|
||||
code: "CONTAINER_NOT_FOUND",
|
||||
});
|
||||
}
|
||||
log.error("Failed to get container logs", error, {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
});
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, "Failed to get container logs"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/docker/containers/{sessionId}/{containerId}/stats:
|
||||
* get:
|
||||
* summary: Get container stats
|
||||
* description: One sample of the container's CPU, memory, network and block IO.
|
||||
* tags:
|
||||
* - Docker
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: sessionId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* - in: path
|
||||
* name: containerId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Container stats.
|
||||
* 400:
|
||||
* description: SSH session not found or not connected.
|
||||
* 404:
|
||||
* description: Container not found.
|
||||
* 500:
|
||||
* description: Failed to get container stats.
|
||||
*/
|
||||
router.get("/containers/:sessionId/:containerId/stats", async (req, res) => {
|
||||
const session = sessionOf(req, res);
|
||||
if (!session) return;
|
||||
const { containerId } = req.params;
|
||||
const format = session.isWindows ? STATS_FORMAT_WINDOWS : STATS_FORMAT_UNIX;
|
||||
try {
|
||||
const output = await sessions.run(session, () =>
|
||||
sessions.exec(
|
||||
session,
|
||||
containerCommand(
|
||||
session.runtime,
|
||||
`stats ${containerId} --no-stream --format ${format}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const raw = JSON.parse(output.trim()) as Record<string, string>;
|
||||
const split = (value: string | undefined) => {
|
||||
const [first, second] = (value ?? "").split(" / ");
|
||||
return [first?.trim() || "0B", second?.trim() || "0B"];
|
||||
};
|
||||
const [memoryUsed, memoryLimit] = split(raw.memory);
|
||||
const [netInput, netOutput] = split(raw.netIO);
|
||||
const [blockRead, blockWrite] = split(raw.blockIO);
|
||||
res.json({
|
||||
cpu: raw.cpu,
|
||||
memoryUsed,
|
||||
memoryLimit,
|
||||
memoryPercent: raw.memoryPercent,
|
||||
netInput,
|
||||
netOutput,
|
||||
blockRead,
|
||||
blockWrite,
|
||||
pids: raw.pids,
|
||||
});
|
||||
} catch (error) {
|
||||
if (notFound(error)) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: "Container not found",
|
||||
code: "CONTAINER_NOT_FOUND",
|
||||
});
|
||||
}
|
||||
log.error("Failed to get container stats", error, {
|
||||
hostId: session.hostId,
|
||||
containerId,
|
||||
});
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: getErrorMessage(error, "Failed to get container stats"),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import type { Client } from "ssh2";
|
||||
import type { PluginContext, PluginSshHost } from "@termix/plugin-sdk/backend";
|
||||
import { containerCommand } from "./container-runtime.js";
|
||||
import {
|
||||
PS_STATE_FORMAT,
|
||||
diffContainerStates,
|
||||
parseContainerStates,
|
||||
type ContainerState,
|
||||
type DockerEventName,
|
||||
} from "./container-state.js";
|
||||
import { readDockerHostSettings } from "./host-settings.js";
|
||||
import { execOnClient } from "./sessions.js";
|
||||
import { listFormat, parseContainerList } from "./routes.js";
|
||||
import {
|
||||
CONTAINER_ID_RE,
|
||||
getErrorMessage,
|
||||
type DockerLogger,
|
||||
} from "./helpers.js";
|
||||
|
||||
export const POOL = "docker";
|
||||
const TICK_MS = 15_000;
|
||||
const POLL_INTERVAL_MS = 60_000;
|
||||
const HOST_CACHE_MS = 5 * 60_000;
|
||||
|
||||
export interface DockerContainerSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
image: string;
|
||||
status: string;
|
||||
state: string;
|
||||
ports: string;
|
||||
created: string;
|
||||
}
|
||||
|
||||
export type DockerContainerAction =
|
||||
"start" | "stop" | "restart" | "pause" | "unpause" | "remove";
|
||||
|
||||
const ACTIONS: DockerContainerAction[] = [
|
||||
"start",
|
||||
"stop",
|
||||
"restart",
|
||||
"pause",
|
||||
"unpause",
|
||||
"remove",
|
||||
];
|
||||
|
||||
/** The "docker.containers" service, version 1. Runs as the caller's user. */
|
||||
export interface DockerServiceV1 {
|
||||
listContainers: (
|
||||
hostId: number,
|
||||
options?: { all?: boolean },
|
||||
) => Promise<DockerContainerSummary[]>;
|
||||
action: (
|
||||
hostId: number,
|
||||
container: string,
|
||||
action: DockerContainerAction,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface DockerEvent {
|
||||
hostId: number;
|
||||
container: string;
|
||||
event: DockerEventName;
|
||||
}
|
||||
|
||||
/** The "docker.events" service, version 1. Runs as the caller's user. */
|
||||
export interface DockerEventsV1 {
|
||||
/**
|
||||
* Calls `listener` for container state changes on a host, polled about
|
||||
* once a minute as the subscribing user. Subscribing the same listener
|
||||
* again is a no-op, so a consumer can re-subscribe on a timer and pick up
|
||||
* a restarted docker plugin. Resolves to an unsubscribe function.
|
||||
*/
|
||||
subscribe: (
|
||||
hostId: number,
|
||||
listener: (event: DockerEvent) => void,
|
||||
) => Promise<() => void>;
|
||||
}
|
||||
|
||||
function actorOf(ctx: PluginContext): string {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) throw new Error("The docker service needs a calling user");
|
||||
return userId;
|
||||
}
|
||||
|
||||
export function registerServices(ctx: PluginContext, log: DockerLogger): void {
|
||||
const runOnHost = async <T>(
|
||||
hostId: number,
|
||||
command: (runtime: "docker" | "podman") => string,
|
||||
handle: (output: string) => T,
|
||||
): Promise<T> => {
|
||||
const { runtime } = await readDockerHostSettings(ctx, hostId);
|
||||
const output = await ctx.ssh.withConnection<string, Client>(
|
||||
hostId,
|
||||
{ pool: POOL, purpose: "docker", profile: "session" },
|
||||
(client) => execOnClient(client, command(runtime)),
|
||||
);
|
||||
return handle(output);
|
||||
};
|
||||
|
||||
ctx.services.provide<DockerServiceV1>("docker.containers", {
|
||||
listContainers: async (hostId, options) => {
|
||||
actorOf(ctx);
|
||||
const all = options?.all !== false;
|
||||
return runOnHost(
|
||||
hostId,
|
||||
(runtime) =>
|
||||
containerCommand(
|
||||
runtime,
|
||||
`ps ${all ? "-a " : ""}--format ${listFormat(false)}`,
|
||||
),
|
||||
(output) =>
|
||||
parseContainerList(output) as unknown as DockerContainerSummary[],
|
||||
);
|
||||
},
|
||||
action: async (hostId, container, action) => {
|
||||
actorOf(ctx);
|
||||
if (!CONTAINER_ID_RE.test(container)) {
|
||||
throw new Error("Invalid container name");
|
||||
}
|
||||
if (!ACTIONS.includes(action)) {
|
||||
throw new Error(`Unknown container action: ${action}`);
|
||||
}
|
||||
const args =
|
||||
action === "remove" ? `rm ${container}` : `${action} ${container}`;
|
||||
await runOnHost(
|
||||
hostId,
|
||||
(runtime) => containerCommand(runtime, args),
|
||||
() => undefined,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
interface Watch {
|
||||
userId: string;
|
||||
hostId: number;
|
||||
listeners: Set<(event: DockerEvent) => void>;
|
||||
snapshot?: Map<string, ContainerState>;
|
||||
host?: { value: PluginSshHost; at: number };
|
||||
lastPolledAt: number;
|
||||
failing: boolean;
|
||||
}
|
||||
const watches = new Map<string, Watch>();
|
||||
ctx.disposables.add(() => watches.clear());
|
||||
|
||||
const hostFor = async (watch: Watch): Promise<PluginSshHost | null> => {
|
||||
if (watch.host && Date.now() - watch.host.at < HOST_CACHE_MS) {
|
||||
return watch.host.value;
|
||||
}
|
||||
const host = await ctx.asUser(watch.userId, () =>
|
||||
ctx.ssh.resolveHost(watch.hostId),
|
||||
);
|
||||
watch.host = host ? { value: host, at: Date.now() } : undefined;
|
||||
return host;
|
||||
};
|
||||
|
||||
const pollOne = async (watch: Watch) => {
|
||||
try {
|
||||
const host = await hostFor(watch);
|
||||
if (!host) throw new Error("Host not found");
|
||||
const { runtime } = await readDockerHostSettings(ctx, watch.hostId);
|
||||
const output = await ctx.ssh.withConnection<string, Client>(
|
||||
host,
|
||||
{ pool: POOL, purpose: "docker", profile: "session" },
|
||||
(client) =>
|
||||
execOnClient(
|
||||
client,
|
||||
containerCommand(runtime, `ps -a --format ${PS_STATE_FORMAT}`),
|
||||
),
|
||||
);
|
||||
const current = parseContainerStates(output);
|
||||
const previous = watch.snapshot;
|
||||
watch.snapshot = current;
|
||||
watch.failing = false;
|
||||
if (!previous) return;
|
||||
for (const { container, event } of diffContainerStates(
|
||||
previous,
|
||||
current,
|
||||
)) {
|
||||
for (const listener of [...watch.listeners]) {
|
||||
try {
|
||||
listener({ hostId: watch.hostId, container, event });
|
||||
} catch (error) {
|
||||
log.warn("Docker event listener failed", {
|
||||
hostId: watch.hostId,
|
||||
error: getErrorMessage(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Docker missing, the host down or the owner's data locked. A later
|
||||
// success is a first observation again rather than a diff.
|
||||
watch.snapshot = undefined;
|
||||
watch.host = undefined;
|
||||
if (!watch.failing) {
|
||||
log.warn("Docker event poll failed", {
|
||||
hostId: watch.hostId,
|
||||
error: getErrorMessage(error),
|
||||
});
|
||||
}
|
||||
watch.failing = true;
|
||||
}
|
||||
};
|
||||
|
||||
ctx.schedule.every(TICK_MS, async () => {
|
||||
const now = Date.now();
|
||||
for (const watch of [...watches.values()]) {
|
||||
if (now - watch.lastPolledAt < POLL_INTERVAL_MS) continue;
|
||||
watch.lastPolledAt = now;
|
||||
await pollOne(watch);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.events.on("host.updated", (payload) => {
|
||||
const { hostId } = payload as { hostId?: number };
|
||||
if (!hostId) return;
|
||||
ctx.ssh.dropPooled(POOL, hostId);
|
||||
for (const watch of watches.values()) {
|
||||
if (watch.hostId === hostId) watch.host = undefined;
|
||||
}
|
||||
});
|
||||
ctx.events.on("host.deleted", (payload) => {
|
||||
const { hostId } = payload as { hostId?: number };
|
||||
if (!hostId) return;
|
||||
for (const [key, watch] of watches) {
|
||||
if (watch.hostId === hostId) watches.delete(key);
|
||||
}
|
||||
});
|
||||
|
||||
ctx.services.provide<DockerEventsV1>("docker.events", {
|
||||
subscribe: async (hostId, listener) => {
|
||||
const userId = actorOf(ctx);
|
||||
const key = `${userId}:${hostId}`;
|
||||
let watch = watches.get(key);
|
||||
if (!watch) {
|
||||
watch = {
|
||||
userId,
|
||||
hostId,
|
||||
listeners: new Set(),
|
||||
lastPolledAt: 0,
|
||||
failing: false,
|
||||
};
|
||||
watches.set(key, watch);
|
||||
}
|
||||
watch.listeners.add(listener);
|
||||
const current = watch;
|
||||
return () => {
|
||||
current.listeners.delete(listener);
|
||||
if (current.listeners.size === 0 && watches.get(key) === current) {
|
||||
watches.delete(key);
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import type { Client } from "ssh2";
|
||||
import type { PluginSchedule } from "@termix/plugin-sdk/backend";
|
||||
import type { ContainerRuntime } from "./container-runtime.js";
|
||||
import type { DockerLogger } from "./helpers.js";
|
||||
|
||||
const SESSION_IDLE_MS = 60 * 60 * 1000;
|
||||
const PENDING_SWEEP_MS = 60 * 1000;
|
||||
|
||||
/** A live SSH connection behind the Docker panel, owned by one user. */
|
||||
export interface DockerSession {
|
||||
id: string;
|
||||
client: Client;
|
||||
dispose: () => void;
|
||||
hostId: number;
|
||||
userId: string;
|
||||
runtime: ContainerRuntime;
|
||||
isWindows: boolean;
|
||||
lastActive: number;
|
||||
activeOperations: number;
|
||||
cancelIdle?: () => void;
|
||||
}
|
||||
|
||||
/** A connect still waiting on a person (TOTP, a browser sign-in). */
|
||||
export interface PendingEntry {
|
||||
userId: string;
|
||||
hostId: number;
|
||||
expiresAt: number;
|
||||
/** Gives up: answers the open prompt with nothing. */
|
||||
cancel: () => void;
|
||||
}
|
||||
|
||||
export interface DockerSessions {
|
||||
add: (session: DockerSession) => void;
|
||||
/** The session when `userId` owns it. */
|
||||
get: (id: string, userId: string) => DockerSession | undefined;
|
||||
close: (id: string) => void;
|
||||
touch: (session: DockerSession) => void;
|
||||
/** Runs `fn` with the session marked busy, so idle cleanup waits. */
|
||||
run: <T>(session: DockerSession, fn: () => Promise<T>) => Promise<T>;
|
||||
exec: (session: DockerSession, command: string) => Promise<string>;
|
||||
setPending: (id: string, entry: PendingEntry) => void;
|
||||
getPending: (id: string) => PendingEntry | undefined;
|
||||
clearPending: (id: string) => void;
|
||||
closeAll: () => void;
|
||||
}
|
||||
|
||||
/** Runs one command and resolves stdout, rejecting on a non-zero exit. */
|
||||
export function execOnClient(client: Client, command: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
client.exec(command, (err, stream) => {
|
||||
if (err) return reject(err);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
stream.on("close", (code: number) => {
|
||||
if (code !== 0 && code !== null && code !== undefined) {
|
||||
reject(new Error(stderr || `Command exited with code ${code}`));
|
||||
} else {
|
||||
resolve(stdout);
|
||||
}
|
||||
});
|
||||
stream.on("data", (data: Buffer) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
stream.stderr.on("data", (data: Buffer) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
stream.on("error", (streamErr: Error) => reject(streamErr));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function createDockerSessions(
|
||||
schedule: PluginSchedule,
|
||||
log: DockerLogger,
|
||||
): DockerSessions {
|
||||
const sessions = new Map<string, DockerSession>();
|
||||
const pending = new Map<string, PendingEntry>();
|
||||
|
||||
const end = (session: DockerSession) => {
|
||||
session.cancelIdle?.();
|
||||
sessions.delete(session.id);
|
||||
session.dispose();
|
||||
};
|
||||
|
||||
const scheduleIdle = (session: DockerSession) => {
|
||||
session.cancelIdle?.();
|
||||
session.cancelIdle = schedule.after(SESSION_IDLE_MS, () => {
|
||||
if (sessions.get(session.id) !== session) return;
|
||||
if (session.activeOperations > 0) {
|
||||
scheduleIdle(session);
|
||||
return;
|
||||
}
|
||||
end(session);
|
||||
});
|
||||
};
|
||||
|
||||
schedule.every(PENDING_SWEEP_MS, () => {
|
||||
const now = Date.now();
|
||||
for (const [id, entry] of pending) {
|
||||
if (now < entry.expiresAt) continue;
|
||||
pending.delete(id);
|
||||
entry.cancel();
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
add: (session) => {
|
||||
const existing = sessions.get(session.id);
|
||||
if (existing) end(existing);
|
||||
sessions.set(session.id, session);
|
||||
session.client.once("close", () => {
|
||||
if (sessions.get(session.id) === session) {
|
||||
session.cancelIdle?.();
|
||||
sessions.delete(session.id);
|
||||
}
|
||||
});
|
||||
scheduleIdle(session);
|
||||
},
|
||||
|
||||
get: (id, userId) => {
|
||||
const session = sessions.get(id);
|
||||
return session && session.userId === userId ? session : undefined;
|
||||
},
|
||||
|
||||
close: (id) => {
|
||||
const session = sessions.get(id);
|
||||
if (session) end(session);
|
||||
const entry = pending.get(id);
|
||||
if (entry) {
|
||||
pending.delete(id);
|
||||
entry.cancel();
|
||||
}
|
||||
},
|
||||
|
||||
touch: (session) => {
|
||||
session.lastActive = Date.now();
|
||||
scheduleIdle(session);
|
||||
},
|
||||
|
||||
run: async (session, fn) => {
|
||||
session.lastActive = Date.now();
|
||||
session.activeOperations++;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
session.activeOperations--;
|
||||
}
|
||||
},
|
||||
|
||||
exec: async (session, command) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
return await execOnClient(session.client, command);
|
||||
} catch (error) {
|
||||
log.warn("Docker command failed", {
|
||||
hostId: session.hostId,
|
||||
command: command.split(" ")[2],
|
||||
durationMs: Date.now() - started,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
setPending: (id, entry) => {
|
||||
const existing = pending.get(id);
|
||||
if (existing) existing.cancel();
|
||||
pending.set(id, entry);
|
||||
},
|
||||
|
||||
getPending: (id) => pending.get(id),
|
||||
|
||||
clearPending: (id) => {
|
||||
pending.delete(id);
|
||||
},
|
||||
|
||||
closeAll: () => {
|
||||
for (const session of [...sessions.values()]) end(session);
|
||||
for (const entry of pending.values()) entry.cancel();
|
||||
pending.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { ConnectionScreen, FullScreenAppWrapper } from "@termix/plugin-sdk/ui";
|
||||
import React from "react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { DockerManager } from "./DockerManager.tsx";
|
||||
import { toDockerHost, type DockerHostSource } from "./types";
|
||||
|
||||
interface DockerAppProps {
|
||||
hostId?: string;
|
||||
}
|
||||
|
||||
const DockerApp: React.FC<DockerAppProps> = ({ hostId }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<FullScreenAppWrapper hostId={hostId}>
|
||||
{(hostConfig, phase) => {
|
||||
if (phase === "loading") {
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<ConnectionScreen
|
||||
status="connecting"
|
||||
message={t("hosts.loadingHost")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!hostConfig) {
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<ConnectionScreen
|
||||
status="disconnected"
|
||||
message={t("hosts.hostNotFound")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DockerManager
|
||||
host={toDockerHost(hostConfig as unknown as DockerHostSource)}
|
||||
title={hostConfig.name || `${hostConfig.username}@${hostConfig.ip}`}
|
||||
isVisible={true}
|
||||
isTopbarOpen={false}
|
||||
embedded={true}
|
||||
onClose={() => {}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
</FullScreenAppWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
export default DockerApp;
|
||||
@@ -0,0 +1,714 @@
|
||||
/* eslint-disable react-hooks/exhaustive-deps */
|
||||
import React from "react";
|
||||
import {
|
||||
AlertCircle,
|
||||
Box,
|
||||
ExternalLink,
|
||||
Grid3X3,
|
||||
List as ListIcon,
|
||||
RefreshCw,
|
||||
Search,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useConnectionRetry,
|
||||
useHost,
|
||||
useTranslation,
|
||||
logActivity,
|
||||
usePluginUiPreferences,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Button,
|
||||
Card,
|
||||
ConnectionLogProvider,
|
||||
ConnectionScreen,
|
||||
Input,
|
||||
SSHAuthDialog,
|
||||
Select2,
|
||||
Separator,
|
||||
TOTPDialog,
|
||||
BrowserSignInDialog,
|
||||
useAdaptivePolling,
|
||||
useConnectionLog,
|
||||
useTabsSafe,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { DockerApiError, useDockerApi, type ConnectResult } from "./docker-api";
|
||||
import {
|
||||
dockerEnabled,
|
||||
hostTitle,
|
||||
toDockerHost,
|
||||
type DockerContainer,
|
||||
type DockerHost,
|
||||
type DockerValidation,
|
||||
} from "./types";
|
||||
import { ContainerList } from "./components/ContainerList.tsx";
|
||||
import { ContainerTable } from "./components/ContainerTable.tsx";
|
||||
import { ContainerDetail } from "./components/ContainerDetail.tsx";
|
||||
|
||||
interface DockerManagerProps {
|
||||
host?: DockerHost;
|
||||
title?: string;
|
||||
isVisible?: boolean;
|
||||
isTopbarOpen?: boolean;
|
||||
embedded?: boolean;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
interface PromptState {
|
||||
kind: "totp" | "browser";
|
||||
sessionId: string;
|
||||
prompt?: string;
|
||||
isPassword?: boolean;
|
||||
url?: string;
|
||||
code?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
function newSessionId(): string {
|
||||
return `docker-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
||||
}
|
||||
|
||||
function DockerManagerInner({
|
||||
host,
|
||||
title,
|
||||
isVisible = true,
|
||||
isTopbarOpen = true,
|
||||
embedded = false,
|
||||
onClose,
|
||||
}: DockerManagerProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const docker = useDockerApi();
|
||||
const { addLog, setLogs, clearLogs } = useConnectionLog();
|
||||
const { currentTab, removeTab } = useTabsSafe();
|
||||
const { values: dockerPrefs, set: setDockerPref } = usePluginUiPreferences<{
|
||||
viewMode: "list" | "detail";
|
||||
containerLayout: "card" | "table";
|
||||
}>();
|
||||
|
||||
// The shell's host list keeps the host current after an edit; a
|
||||
// standalone window has no shell, so it keeps the host it was given.
|
||||
const liveRecord = useHost(host?.id);
|
||||
const currentHost = React.useMemo(
|
||||
() => (liveRecord ? toDockerHost(liveRecord) : host),
|
||||
[liveRecord, host],
|
||||
);
|
||||
const enabled = dockerEnabled(currentHost);
|
||||
|
||||
const [sessionId, setSessionId] = React.useState<string | null>(null);
|
||||
const [containers, setContainers] = React.useState<DockerContainer[]>([]);
|
||||
const containersSignatureRef = React.useRef("");
|
||||
const [selectedContainer, setSelectedContainer] = React.useState<
|
||||
string | null
|
||||
>(null);
|
||||
const [detailInitialTab, setDetailInitialTab] = React.useState<
|
||||
"logs" | "stats" | "console"
|
||||
>("logs");
|
||||
const [containerLayout, setContainerLayout] = React.useState<
|
||||
"card" | "table"
|
||||
>(dockerPrefs.containerLayout);
|
||||
|
||||
const handleSetContainerLayout = React.useCallback(
|
||||
(layout: "card" | "table") => {
|
||||
setContainerLayout(layout);
|
||||
setDockerPref("containerLayout", layout);
|
||||
},
|
||||
[setDockerPref],
|
||||
);
|
||||
const [isConnecting, setIsConnecting] = React.useState(false);
|
||||
const [dockerValidation, setDockerValidation] =
|
||||
React.useState<DockerValidation | null>(null);
|
||||
const [isValidating, setIsValidating] = React.useState(false);
|
||||
// Initial view follows the interface preset; switching it afterwards is a
|
||||
// per-session choice.
|
||||
const [viewMode, setViewMode] = React.useState<"list" | "detail">(
|
||||
dockerPrefs.viewMode,
|
||||
);
|
||||
const [isLoadingContainers, setIsLoadingContainers] = React.useState(false);
|
||||
const [hasLoadedContainersOnce, setHasLoadedContainersOnce] =
|
||||
React.useState(false);
|
||||
const [prompt, setPrompt] = React.useState<PromptState | null>(null);
|
||||
const [showAuthDialog, setShowAuthDialog] = React.useState(false);
|
||||
const [authReason, setAuthReason] = React.useState<
|
||||
"no_keyboard" | "auth_failed" | "timeout"
|
||||
>("no_keyboard");
|
||||
const [search, setSearch] = React.useState("");
|
||||
const [statusFilter, setStatusFilter] = React.useState("all");
|
||||
const [retryCount, setRetryCount] = React.useState(0);
|
||||
|
||||
const activityLoggedRef = React.useRef(false);
|
||||
|
||||
const logDockerActivity = () => {
|
||||
if (!currentHost?.id || activityLoggedRef.current) return;
|
||||
activityLoggedRef.current = true;
|
||||
logActivity("docker", currentHost.id, hostTitle(currentHost)).catch(() => {
|
||||
activityLoggedRef.current = false;
|
||||
});
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
setContainers([]);
|
||||
setSelectedContainer(null);
|
||||
setSessionId(null);
|
||||
setDockerValidation(null);
|
||||
setViewMode("list");
|
||||
}, [host?.id]);
|
||||
|
||||
const retryRef = React.useRef<ReturnType<typeof useConnectionRetry> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const validate = async (sid: string, clearAfter: boolean) => {
|
||||
setSessionId(sid);
|
||||
setIsValidating(true);
|
||||
try {
|
||||
const validation = await docker.validate(sid);
|
||||
setDockerValidation(validation);
|
||||
if (!validation.available) {
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "validation",
|
||||
message: validation.error || t("docker.error"),
|
||||
details: validation.code
|
||||
? `Error code: ${validation.code}`
|
||||
: undefined,
|
||||
});
|
||||
retryRef.current?.markFailed();
|
||||
} else {
|
||||
logDockerActivity();
|
||||
if (clearAfter) setTimeout(() => clearLogs(), 1000);
|
||||
retryRef.current?.markConnected();
|
||||
}
|
||||
} finally {
|
||||
setIsValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** Acts on one step of a connect, whichever request it answered. */
|
||||
const applyConnectResult = async (
|
||||
sid: string,
|
||||
result: ConnectResult,
|
||||
clearAfter: boolean,
|
||||
) => {
|
||||
if (result.connectionLogs) setLogs(result.connectionLogs);
|
||||
|
||||
if (result.requires_browser_sign_in) {
|
||||
setPrompt({
|
||||
kind: "browser",
|
||||
sessionId: sid,
|
||||
url: result.url || "",
|
||||
code: result.code || "",
|
||||
label: result.label || "",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (result.requires_totp) {
|
||||
if (result.retry) {
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "auth",
|
||||
message: t("docker.totpVerificationFailed"),
|
||||
});
|
||||
}
|
||||
setPrompt({
|
||||
kind: "totp",
|
||||
sessionId: sid,
|
||||
prompt: result.prompt || t("docker.verificationCodePrompt"),
|
||||
isPassword: result.isPassword,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (result.status === "auth_required") {
|
||||
setAuthReason(
|
||||
result.reason === "no_keyboard" ? "no_keyboard" : "auth_failed",
|
||||
);
|
||||
setShowAuthDialog(true);
|
||||
return;
|
||||
}
|
||||
setPrompt(null);
|
||||
await validate(sid, clearAfter);
|
||||
};
|
||||
|
||||
const reportFailure = (error: unknown, fallback: string) => {
|
||||
if (error instanceof DockerApiError && error.connectionLogs?.length) {
|
||||
setLogs(error.connectionLogs);
|
||||
} else {
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "connection",
|
||||
message: error instanceof Error ? error.message : fallback,
|
||||
});
|
||||
}
|
||||
retryRef.current?.markFailed();
|
||||
};
|
||||
|
||||
const connect = async (credentials?: {
|
||||
userProvidedPassword?: string;
|
||||
userProvidedSshKey?: string;
|
||||
userProvidedKeyPassword?: string;
|
||||
}) => {
|
||||
if (!currentHost?.id) return;
|
||||
const sid = newSessionId();
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
const result = await docker.connect(sid, currentHost.id, credentials);
|
||||
await applyConnectResult(sid, result, !credentials);
|
||||
} catch (error) {
|
||||
reportFailure(error, t("docker.connectionFailed"));
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const initializingRef = React.useRef(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentHost?.id || !enabled) return;
|
||||
if (initializingRef.current || sessionId) return;
|
||||
initializingRef.current = true;
|
||||
clearLogs();
|
||||
void connect();
|
||||
|
||||
return () => {
|
||||
initializingRef.current = false;
|
||||
};
|
||||
}, [currentHost?.id, enabled, retryCount]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
return () => {
|
||||
docker.disconnect(sessionId).catch(() => {});
|
||||
};
|
||||
}, [sessionId]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!sessionId || !isVisible) return;
|
||||
const keepalive = setInterval(
|
||||
() => {
|
||||
docker.keepalive(sessionId).catch(() => {});
|
||||
},
|
||||
10 * 60 * 1000,
|
||||
);
|
||||
return () => clearInterval(keepalive);
|
||||
}, [sessionId, isVisible]);
|
||||
|
||||
const refreshContainers = React.useCallback(async () => {
|
||||
if (!sessionId) return;
|
||||
try {
|
||||
setContainers(await docker.listContainers(sessionId, true));
|
||||
} catch {
|
||||
// the next poll tries again
|
||||
}
|
||||
}, [sessionId, docker]);
|
||||
|
||||
React.useEffect(() => {
|
||||
setHasLoadedContainersOnce(false);
|
||||
}, [sessionId]);
|
||||
|
||||
useAdaptivePolling(
|
||||
async () => {
|
||||
if (!sessionId) return;
|
||||
setIsLoadingContainers((loading) =>
|
||||
hasLoadedContainersOnce ? loading : true,
|
||||
);
|
||||
const data = await docker.listContainers(sessionId, true);
|
||||
const signature = JSON.stringify(data);
|
||||
const changed = signature !== containersSignatureRef.current;
|
||||
containersSignatureRef.current = signature;
|
||||
setContainers(data);
|
||||
setIsLoadingContainers(false);
|
||||
setHasLoadedContainersOnce(true);
|
||||
return changed;
|
||||
},
|
||||
{
|
||||
minIntervalMs: 5000,
|
||||
maxIntervalMs: 30000,
|
||||
stablePollsPerStep: 3,
|
||||
},
|
||||
!!sessionId && isVisible && !!dockerValidation?.available,
|
||||
{
|
||||
onError: () => {
|
||||
setIsLoadingContainers(false);
|
||||
setHasLoadedContainersOnce(true);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const handleBack = React.useCallback(() => {
|
||||
setViewMode("list");
|
||||
setSelectedContainer(null);
|
||||
}, []);
|
||||
|
||||
const closeTab = () => {
|
||||
if (currentTab !== null) removeTab(currentTab);
|
||||
};
|
||||
|
||||
const handleTotpSubmit = async (code: string) => {
|
||||
if (!prompt || prompt.kind !== "totp" || !code) return;
|
||||
const sid = prompt.sessionId;
|
||||
setPrompt(null);
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
await applyConnectResult(sid, await docker.answerTotp(sid, code), false);
|
||||
} catch (error) {
|
||||
reportFailure(error, t("docker.totpVerificationFailed"));
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBrowserSignInContinue = async () => {
|
||||
if (!prompt || prompt.kind !== "browser") return;
|
||||
const sid = prompt.sessionId;
|
||||
setPrompt(null);
|
||||
setIsConnecting(true);
|
||||
try {
|
||||
await applyConnectResult(
|
||||
sid,
|
||||
await docker.continueBrowserSignIn(sid),
|
||||
false,
|
||||
);
|
||||
} catch (error) {
|
||||
reportFailure(error, t("docker.browserSignInFailed"));
|
||||
} finally {
|
||||
setIsConnecting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePromptCancel = () => {
|
||||
const sid = prompt?.sessionId;
|
||||
setPrompt(null);
|
||||
setIsConnecting(false);
|
||||
if (sid) docker.disconnect(sid).catch(() => {});
|
||||
closeTab();
|
||||
};
|
||||
|
||||
const handleBrowserSignInOpenUrl = () => {
|
||||
if (prompt?.url) window.open(prompt.url, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
const handleAuthSubmit = async (credentials: {
|
||||
password?: string;
|
||||
sshKey?: string;
|
||||
keyPassword?: string;
|
||||
}) => {
|
||||
setShowAuthDialog(false);
|
||||
await connect({
|
||||
userProvidedPassword: credentials.password,
|
||||
userProvidedSshKey: credentials.sshKey,
|
||||
userProvidedKeyPassword: credentials.keyPassword,
|
||||
});
|
||||
};
|
||||
|
||||
const handleAuthCancel = () => {
|
||||
setShowAuthDialog(false);
|
||||
setIsConnecting(false);
|
||||
onClose?.();
|
||||
};
|
||||
|
||||
const handleRetry = () => {
|
||||
initializingRef.current = false;
|
||||
setSessionId(null);
|
||||
setDockerValidation(null);
|
||||
clearLogs();
|
||||
setRetryCount((c) => c + 1);
|
||||
};
|
||||
|
||||
const dockerConnectRetry = useConnectionRetry({
|
||||
connect: () => {
|
||||
handleRetry();
|
||||
},
|
||||
enabled: enabled && !prompt && !showAuthDialog,
|
||||
autoStart: false,
|
||||
});
|
||||
retryRef.current = dockerConnectRetry;
|
||||
|
||||
const topMarginPx = isTopbarOpen ? 74 : 16;
|
||||
const leftMarginPx = 8;
|
||||
const bottomMarginPx = 8;
|
||||
|
||||
const wrapperStyle: React.CSSProperties = embedded
|
||||
? { opacity: isVisible ? 1 : 0, height: "100%", width: "100%" }
|
||||
: {
|
||||
opacity: isVisible ? 1 : 0,
|
||||
marginLeft: leftMarginPx,
|
||||
marginRight: 17,
|
||||
marginTop: topMarginPx,
|
||||
marginBottom: bottomMarginPx,
|
||||
height: `calc(100vh - ${topMarginPx + bottomMarginPx}px)`,
|
||||
};
|
||||
|
||||
const containerClass = embedded
|
||||
? "h-full w-full text-foreground overflow-hidden bg-transparent"
|
||||
: "bg-canvas text-foreground border-2 border-edge overflow-hidden";
|
||||
|
||||
if (!enabled) {
|
||||
return (
|
||||
<div style={wrapperStyle} className={`${containerClass} relative`}>
|
||||
<div className="h-full w-full flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<div className="flex-1 overflow-y-auto px-3 py-3 flex flex-col gap-3">
|
||||
<Card className="flex-row items-center justify-between px-3 py-3 shrink-0 gap-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 border border-border bg-muted flex items-center justify-center shrink-0">
|
||||
<Box className="size-5 text-accent-brand" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{title}</h1>
|
||||
<span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
|
||||
{t("docker.manager")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{t("docker.notEnabled")}</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const dialogs = (
|
||||
<>
|
||||
<TOTPDialog
|
||||
isOpen={prompt?.kind === "totp"}
|
||||
prompt={prompt?.prompt ?? ""}
|
||||
mode={prompt?.isPassword ? "password" : "totp"}
|
||||
onSubmit={handleTotpSubmit}
|
||||
onCancel={handlePromptCancel}
|
||||
/>
|
||||
<BrowserSignInDialog
|
||||
isOpen={prompt?.kind === "browser"}
|
||||
label={prompt?.label ?? ""}
|
||||
url={prompt?.url ?? ""}
|
||||
code={prompt?.code ?? ""}
|
||||
onContinue={handleBrowserSignInContinue}
|
||||
onCancel={handlePromptCancel}
|
||||
onOpenUrl={handleBrowserSignInOpenUrl}
|
||||
/>
|
||||
{currentHost && (
|
||||
<SSHAuthDialog
|
||||
isOpen={showAuthDialog}
|
||||
reason={authReason}
|
||||
onSubmit={handleAuthSubmit}
|
||||
onCancel={handleAuthCancel}
|
||||
hostInfo={{
|
||||
ip: currentHost.ip,
|
||||
port: currentHost.port,
|
||||
username: currentHost.username ?? "",
|
||||
name: currentHost.name,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
if (isConnecting || isValidating) {
|
||||
return (
|
||||
<div style={wrapperStyle} className={`${containerClass} relative`}>
|
||||
<ConnectionScreen
|
||||
status={dockerConnectRetry.status}
|
||||
message={
|
||||
isValidating ? t("docker.validating") : t("docker.connecting")
|
||||
}
|
||||
attempt={dockerConnectRetry.attempt}
|
||||
maxAttempts={dockerConnectRetry.maxAttempts}
|
||||
nextRetryInMs={dockerConnectRetry.nextRetryInMs}
|
||||
onManualRetry={dockerConnectRetry.retryNow}
|
||||
/>
|
||||
{dialogs}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (dockerValidation && !dockerValidation.available) {
|
||||
return (
|
||||
<div style={wrapperStyle} className={`${containerClass} relative`}>
|
||||
<ConnectionScreen
|
||||
status={dockerConnectRetry.status}
|
||||
message={t("docker.connectionFailed")}
|
||||
attempt={dockerConnectRetry.attempt}
|
||||
maxAttempts={dockerConnectRetry.maxAttempts}
|
||||
nextRetryInMs={dockerConnectRetry.nextRetryInMs}
|
||||
onManualRetry={dockerConnectRetry.retryNow}
|
||||
retryLabel={t("terminal.retry")}
|
||||
logPosition="top"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={wrapperStyle} className={`${containerClass} relative`}>
|
||||
<div className="h-full w-full flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
{viewMode === "detail" &&
|
||||
sessionId &&
|
||||
selectedContainer &&
|
||||
currentHost ? (
|
||||
<ContainerDetail
|
||||
sessionId={sessionId}
|
||||
containerId={selectedContainer}
|
||||
containers={containers}
|
||||
hostConfig={currentHost}
|
||||
onBack={handleBack}
|
||||
initialTab={detailInitialTab}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex-1 overflow-y-auto px-3 py-3 flex flex-col gap-3">
|
||||
<Card className="flex-row items-center justify-between px-3 py-3 shrink-0 gap-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-10 border border-border bg-muted flex items-center justify-center shrink-0">
|
||||
<Box className="size-5 text-accent-brand" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{title}</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="size-2 rounded-full bg-accent-brand" />
|
||||
<span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
|
||||
{dockerValidation?.version
|
||||
? t("docker.version", {
|
||||
runtime:
|
||||
dockerValidation.runtime === "podman"
|
||||
? "Podman"
|
||||
: "Docker",
|
||||
version: dockerValidation.version,
|
||||
})
|
||||
: t("docker.manager")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative w-56">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("docker.searchPlaceholder")}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-8 h-8"
|
||||
/>
|
||||
</div>
|
||||
<Select2
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="h-8 px-2 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
<option value="all">{t("docker.allStatuses")}</option>
|
||||
<option value="running">{t("docker.stateRunning")}</option>
|
||||
<option value="paused">{t("docker.statePaused")}</option>
|
||||
<option value="exited">{t("docker.stateExited")}</option>
|
||||
<option value="restarting">
|
||||
{t("docker.stateRestarting")}
|
||||
</option>
|
||||
</Select2>
|
||||
<Separator orientation="vertical" className="h-8 mx-1" />
|
||||
<div className="flex items-center border border-border overflow-hidden">
|
||||
<Button
|
||||
variant={containerLayout === "card" ? "secondary" : "ghost"}
|
||||
size="icon"
|
||||
onClick={() => handleSetContainerLayout("card")}
|
||||
className={`size-8 rounded-none ${containerLayout === "card" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
|
||||
title={t("docker.cardView")}
|
||||
>
|
||||
<Grid3X3 className="size-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant={
|
||||
containerLayout === "table" ? "secondary" : "ghost"
|
||||
}
|
||||
size="icon"
|
||||
onClick={() => handleSetContainerLayout("table")}
|
||||
className={`size-8 rounded-none border-l border-border ${containerLayout === "table" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
|
||||
title={t("docker.listView")}
|
||||
>
|
||||
<ListIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Separator orientation="vertical" className="h-8 mx-1" />
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={refreshContainers}
|
||||
disabled={isLoadingContainers}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`size-4 text-accent-brand ${isLoadingContainers ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</Button>
|
||||
<a
|
||||
href="https://docs.termix.site/features/networking/docker"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center justify-center size-9 text-muted-foreground hover:text-foreground transition-colors"
|
||||
title={t("hosts.docsLink")}
|
||||
>
|
||||
<ExternalLink className="size-4" />
|
||||
</a>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{sessionId ? (
|
||||
!hasLoadedContainersOnce ? (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-40 py-20">
|
||||
<RefreshCw className="size-8 animate-spin mb-4" />
|
||||
<span className="text-sm font-semibold">
|
||||
{t("docker.loadingContainers")}
|
||||
</span>
|
||||
</div>
|
||||
) : containerLayout === "table" ? (
|
||||
<ContainerTable
|
||||
containers={containers}
|
||||
sessionId={sessionId}
|
||||
onSelectContainer={(id, tab) => {
|
||||
setSelectedContainer(id);
|
||||
setDetailInitialTab(tab ?? "logs");
|
||||
setViewMode("detail");
|
||||
}}
|
||||
selectedContainerId={selectedContainer}
|
||||
onRefresh={refreshContainers}
|
||||
search={search}
|
||||
statusFilter={statusFilter}
|
||||
/>
|
||||
) : (
|
||||
<ContainerList
|
||||
containers={containers}
|
||||
sessionId={sessionId}
|
||||
onSelectContainer={(id) => {
|
||||
setSelectedContainer(id);
|
||||
setDetailInitialTab("logs");
|
||||
setViewMode("detail");
|
||||
}}
|
||||
selectedContainerId={selectedContainer}
|
||||
onRefresh={refreshContainers}
|
||||
search={search}
|
||||
statusFilter={statusFilter}
|
||||
/>
|
||||
)
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{dialogs}
|
||||
<ConnectionScreen
|
||||
status={dockerConnectRetry.status}
|
||||
message={t("docker.connecting")}
|
||||
attempt={dockerConnectRetry.attempt}
|
||||
maxAttempts={dockerConnectRetry.maxAttempts}
|
||||
nextRetryInMs={dockerConnectRetry.nextRetryInMs}
|
||||
onManualRetry={dockerConnectRetry.retryNow}
|
||||
retryLabel={t("terminal.retry")}
|
||||
logPosition="top"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DockerManager(props: DockerManagerProps): React.ReactElement {
|
||||
return (
|
||||
<ConnectionLogProvider>
|
||||
<DockerManagerInner {...props} />
|
||||
</ConnectionLogProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { Box } from "lucide-react";
|
||||
import { useHost, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { WidgetTitle } from "@termix/plugin-sdk/ui";
|
||||
import { DockerWidgetEditForm } from "./DockerWidgetEditForm";
|
||||
import { DockerManager } from "./DockerManager";
|
||||
import {
|
||||
GRID_SIZE,
|
||||
type DockerWidgetConfig,
|
||||
type WidgetComponentProps,
|
||||
type WidgetDefinition,
|
||||
} from "./homepage";
|
||||
import { dockerEnabled, hostTitle, toDockerHost } from "./types";
|
||||
|
||||
function DockerWidget({
|
||||
widget,
|
||||
config,
|
||||
}: WidgetComponentProps<DockerWidgetConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const record = useHost(config.hostId || undefined);
|
||||
|
||||
if (!config.hostId || !record || !dockerEnabled(record)) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center w-full h-full gap-2 text-muted-foreground/60">
|
||||
<Box size={20} />
|
||||
<span className="text-xs">{t("common.noHostConfigured")}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const host = toDockerHost(record);
|
||||
return (
|
||||
<div className="flex flex-col w-full h-full overflow-hidden">
|
||||
<WidgetTitle title={widget.title} icon={<Box size={11} />} />
|
||||
<div
|
||||
className="flex-1 overflow-hidden"
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DockerManager
|
||||
host={host}
|
||||
title={hostTitle(host)}
|
||||
isVisible={true}
|
||||
isTopbarOpen={false}
|
||||
embedded={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Registered by the plugin while it runs. */
|
||||
export const dockerWidget: WidgetDefinition<DockerWidgetConfig> = {
|
||||
id: "docker_widget",
|
||||
name: "Docker Manager",
|
||||
description: "Embedded Docker container manager for a configured host",
|
||||
category: "system",
|
||||
icon: <Box size={14} />,
|
||||
defaultConfig: { hostId: 0 },
|
||||
defaultSize: { w: GRID_SIZE * 20, h: GRID_SIZE * 14 },
|
||||
minSize: { w: GRID_SIZE * 10, h: GRID_SIZE * 8 },
|
||||
components: { view: DockerWidget, editForm: DockerWidgetEditForm },
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useHosts, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { Select2 } from "@termix/plugin-sdk/ui";
|
||||
import type { DockerWidgetConfig, WidgetEditFormProps } from "./homepage";
|
||||
import { dockerEnabled } from "./types";
|
||||
|
||||
export function DockerWidgetEditForm({
|
||||
config,
|
||||
onChange,
|
||||
}: WidgetEditFormProps<DockerWidgetConfig>) {
|
||||
const { t } = useTranslation();
|
||||
const { hosts } = useHosts();
|
||||
const options = hosts.filter(
|
||||
(host) => host.enableSsh !== false && dockerEnabled(host),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs font-medium text-muted-foreground">
|
||||
{t("common.host")}
|
||||
</label>
|
||||
<Select2
|
||||
value={config.hostId || ""}
|
||||
onChange={(e) =>
|
||||
onChange({ ...config, hostId: Number(e.target.value) })
|
||||
}
|
||||
className="h-8 text-xs border border-border bg-background px-2"
|
||||
>
|
||||
<option value="">{t("common.selectHost")}</option>
|
||||
{options.map((host) => (
|
||||
<option key={host.id} value={host.id}>
|
||||
{host.name || host.ip}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
import { getErrorMessage } from "../error-message";
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
ConnectionLogProvider,
|
||||
ConnectionScreen,
|
||||
RobustClipboardProvider,
|
||||
Select2,
|
||||
copyToClipboard,
|
||||
isElectron,
|
||||
pluginWsUrl,
|
||||
readFromClipboard,
|
||||
resolveConnectionOrigin,
|
||||
useAppTheme as useTheme,
|
||||
useConnectionLog,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import type { DockerHost } from "../types";
|
||||
import { useConsoleLook, type ConsoleLook } from "./console-look";
|
||||
import React from "react";
|
||||
import { useXTerm } from "react-xtermjs";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { ClipboardAddon } from "@xterm/addon-clipboard";
|
||||
import { WebLinksAddon } from "@xterm/addon-web-links";
|
||||
import { Terminal as TerminalIcon, Power, PowerOff } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useTranslation,
|
||||
useConnectionRetry,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
function applyConsoleLook(
|
||||
terminal: NonNullable<ReturnType<typeof useXTerm>["instance"]>,
|
||||
look: ConsoleLook,
|
||||
): void {
|
||||
terminal.options.cursorBlink = look.cursorBlink;
|
||||
terminal.options.cursorStyle = look.cursorStyle;
|
||||
terminal.options.fontSize = look.fontSize;
|
||||
terminal.options.fontFamily = look.fontFamily;
|
||||
terminal.options.scrollback = look.scrollback;
|
||||
terminal.options.letterSpacing = look.letterSpacing;
|
||||
terminal.options.lineHeight = look.lineHeight;
|
||||
terminal.options.theme = { ...look.colors };
|
||||
}
|
||||
|
||||
interface ConsoleTerminalProps {
|
||||
containerId: string;
|
||||
containerName: string;
|
||||
containerState: string;
|
||||
hostConfig: DockerHost;
|
||||
}
|
||||
|
||||
export function ConsoleTerminal(
|
||||
props: ConsoleTerminalProps,
|
||||
): React.ReactElement {
|
||||
return (
|
||||
<ConnectionLogProvider>
|
||||
<ConsoleTerminalInner {...props} />
|
||||
</ConnectionLogProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ConsoleTerminalInner({
|
||||
containerId,
|
||||
containerName,
|
||||
containerState,
|
||||
hostConfig,
|
||||
}: ConsoleTerminalProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { theme: appTheme } = useTheme();
|
||||
const { instance: terminal, ref: xtermRef } = useXTerm();
|
||||
const { addLog, clearLogs } = useConnectionLog();
|
||||
|
||||
// The SSH terminal's look on this host, or plain colors while it is off.
|
||||
const look = useConsoleLook(
|
||||
hostConfig as unknown as Parameters<typeof useConsoleLook>[0],
|
||||
appTheme,
|
||||
);
|
||||
const themeColors = look.colors;
|
||||
const lookRef = React.useRef<ConsoleLook>(look);
|
||||
lookRef.current = look;
|
||||
|
||||
const [isConnected, setIsConnected] = React.useState(false);
|
||||
const [isConnecting, setIsConnecting] = React.useState(false);
|
||||
const [selectedShell, setSelectedShell] = React.useState<string>("bash");
|
||||
const wsRef = React.useRef<WebSocket | null>(null);
|
||||
const fitAddonRef = React.useRef<FitAddon | null>(null);
|
||||
const pingIntervalRef = React.useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!terminal) return;
|
||||
|
||||
const fitAddon = new FitAddon();
|
||||
const clipboardProvider = new RobustClipboardProvider();
|
||||
const clipboardAddon = new ClipboardAddon(undefined, clipboardProvider);
|
||||
const webLinksAddon = new WebLinksAddon();
|
||||
|
||||
fitAddonRef.current = fitAddon;
|
||||
|
||||
terminal.loadAddon(fitAddon);
|
||||
terminal.loadAddon(clipboardAddon);
|
||||
terminal.loadAddon(webLinksAddon);
|
||||
|
||||
applyConsoleLook(terminal, lookRef.current);
|
||||
|
||||
const readTextFromClipboard = async (): Promise<string> => {
|
||||
return readFromClipboard();
|
||||
};
|
||||
|
||||
const writeTextToClipboard = async (text: string): Promise<void> => {
|
||||
await copyToClipboard(text);
|
||||
};
|
||||
|
||||
terminal.attachCustomKeyEventHandler((e: KeyboardEvent): boolean => {
|
||||
if (e.type !== "keydown") return true;
|
||||
|
||||
if (
|
||||
((e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey) ||
|
||||
(e.metaKey && !e.shiftKey && !e.ctrlKey && !e.altKey)) &&
|
||||
e.key.toLowerCase() === "v"
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
readTextFromClipboard()
|
||||
.then((text) => {
|
||||
if (text) terminal.paste(text);
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error(t("terminal.clipboardReadFailed"));
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
e.ctrlKey &&
|
||||
!e.shiftKey &&
|
||||
!e.altKey &&
|
||||
!e.metaKey &&
|
||||
e.key.toLowerCase() === "c" &&
|
||||
terminal.hasSelection()
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const selection = terminal.getSelection();
|
||||
if (selection) {
|
||||
writeTextToClipboard(selection).catch(() => {
|
||||
toast.error(t("terminal.clipboardWriteFailed"));
|
||||
});
|
||||
terminal.clearSelection();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
e.ctrlKey &&
|
||||
!e.shiftKey &&
|
||||
!e.altKey &&
|
||||
!e.metaKey &&
|
||||
e.key === "Insert" &&
|
||||
terminal.hasSelection()
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const selection = terminal.getSelection();
|
||||
if (selection) {
|
||||
writeTextToClipboard(selection).catch(() => {
|
||||
toast.error(t("terminal.clipboardWriteFailed"));
|
||||
});
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
e.shiftKey &&
|
||||
!e.ctrlKey &&
|
||||
!e.altKey &&
|
||||
!e.metaKey &&
|
||||
e.key === "Insert"
|
||||
) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
readTextFromClipboard()
|
||||
.then((text) => {
|
||||
if (text) terminal.paste(text);
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error(t("terminal.clipboardReadFailed"));
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
fitAddon.fit();
|
||||
}, 100);
|
||||
|
||||
const resizeHandler = () => {
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit();
|
||||
|
||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
const { rows, cols } = terminal;
|
||||
wsRef.current.send(
|
||||
JSON.stringify({
|
||||
type: "resize",
|
||||
data: { rows, cols },
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("resize", resizeHandler);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", resizeHandler);
|
||||
clipboardProvider.dispose();
|
||||
|
||||
if (wsRef.current) {
|
||||
try {
|
||||
wsRef.current.send(JSON.stringify({ type: "disconnect" }));
|
||||
} catch {
|
||||
// Best-effort disconnect during cleanup.
|
||||
}
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
|
||||
terminal.dispose();
|
||||
};
|
||||
}, [terminal, t]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!terminal) return;
|
||||
applyConsoleLook(terminal, look);
|
||||
fitAddonRef.current?.fit();
|
||||
}, [terminal, look]);
|
||||
|
||||
const disconnect = React.useCallback(() => {
|
||||
if (wsRef.current) {
|
||||
try {
|
||||
wsRef.current.send(JSON.stringify({ type: "disconnect" }));
|
||||
} catch {
|
||||
// Best-effort disconnect.
|
||||
}
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
setIsConnected(false);
|
||||
retryRef.current.reset();
|
||||
clearLogs();
|
||||
if (terminal) {
|
||||
try {
|
||||
terminal.clear();
|
||||
} catch {
|
||||
// Terminal clear can fail after disposal.
|
||||
}
|
||||
}
|
||||
}, [terminal, clearLogs]);
|
||||
|
||||
const connect = React.useCallback(async () => {
|
||||
if (!terminal || containerState !== "running") {
|
||||
toast.error(t("docker.containerMustBeRunning"));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsConnecting(true);
|
||||
addLog({
|
||||
type: "info",
|
||||
stage: "docker_connecting",
|
||||
message: t("docker.connectingTo", { containerName }),
|
||||
});
|
||||
|
||||
try {
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit();
|
||||
}
|
||||
|
||||
const isElectronApp = isElectron();
|
||||
|
||||
const origin = isElectronApp
|
||||
? await resolveConnectionOrigin({
|
||||
connectionOrigin: hostConfig.connectionOrigin,
|
||||
})
|
||||
: "local";
|
||||
|
||||
const resolvedUrl = await pluginWsUrl("docker", "/console", { origin });
|
||||
if (!resolvedUrl) {
|
||||
setIsConnecting(false);
|
||||
toast.error(t("errors.remoteServerRequired"));
|
||||
return;
|
||||
}
|
||||
|
||||
const ws = new WebSocket(resolvedUrl.url, resolvedUrl.protocols);
|
||||
|
||||
ws.onopen = () => {
|
||||
const cols = terminal.cols || 80;
|
||||
const rows = terminal.rows || 24;
|
||||
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "connect",
|
||||
data: {
|
||||
hostConfig: {
|
||||
id: hostConfig.id,
|
||||
syncId: hostConfig.syncId ?? null,
|
||||
ip: hostConfig.ip,
|
||||
},
|
||||
containerId,
|
||||
shell: selectedShell,
|
||||
cols,
|
||||
rows,
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
|
||||
switch (msg.type) {
|
||||
case "output":
|
||||
terminal.write(msg.data);
|
||||
break;
|
||||
|
||||
case "connected":
|
||||
setIsConnected(true);
|
||||
setIsConnecting(false);
|
||||
retryRef.current.markConnected();
|
||||
|
||||
if (msg.data?.shellChanged) {
|
||||
toast.warning(
|
||||
`Shell "${msg.data.requestedShell}" not available. Using "${msg.data.shell}" instead.`,
|
||||
);
|
||||
} else {
|
||||
toast.success(t("docker.connectedTo", { containerName }));
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit();
|
||||
}
|
||||
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "resize",
|
||||
data: { rows: terminal.rows, cols: terminal.cols },
|
||||
}),
|
||||
);
|
||||
}
|
||||
}, 100);
|
||||
break;
|
||||
|
||||
case "disconnected":
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
retryRef.current.reset();
|
||||
terminal.write(
|
||||
`\r\n\x1b[1;33m${msg.message || t("docker.disconnected")}\x1b[0m\r\n`,
|
||||
);
|
||||
if (wsRef.current) {
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
break;
|
||||
|
||||
case "error":
|
||||
setIsConnecting(false);
|
||||
toast.error(msg.message || t("docker.consoleError"));
|
||||
terminal.write(
|
||||
`\r\n\x1b[1;31m${t("docker.errorMessage", { message: msg.message })}\x1b[0m\r\n`,
|
||||
);
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "error",
|
||||
message: msg.message || t("docker.consoleError"),
|
||||
});
|
||||
retryRef.current.markFailed();
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to parse WebSocket message:", error);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onerror = (error) => {
|
||||
console.error("WebSocket error:", error);
|
||||
setIsConnecting(false);
|
||||
setIsConnected(false);
|
||||
toast.error(t("docker.failedToConnect"));
|
||||
addLog({
|
||||
type: "error",
|
||||
stage: "error",
|
||||
message: t("docker.failedToConnect"),
|
||||
});
|
||||
retryRef.current.markFailed();
|
||||
};
|
||||
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current);
|
||||
}
|
||||
pingIntervalRef.current = setInterval(() => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: "ping" }));
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
ws.onclose = () => {
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current);
|
||||
pingIntervalRef.current = null;
|
||||
}
|
||||
setIsConnected(false);
|
||||
setIsConnecting(false);
|
||||
if (wsRef.current === ws) {
|
||||
wsRef.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
wsRef.current = ws;
|
||||
|
||||
terminal.onData((data) => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "input",
|
||||
data,
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
setIsConnecting(false);
|
||||
const message = `Failed to connect: ${getErrorMessage(error)}`;
|
||||
toast.error(message);
|
||||
addLog({ type: "error", stage: "error", message });
|
||||
retryRef.current.markFailed();
|
||||
}
|
||||
}, [
|
||||
terminal,
|
||||
containerState,
|
||||
hostConfig,
|
||||
containerId,
|
||||
selectedShell,
|
||||
containerName,
|
||||
t,
|
||||
addLog,
|
||||
]);
|
||||
|
||||
const retry = useConnectionRetry({
|
||||
connect,
|
||||
autoStart: false,
|
||||
});
|
||||
const retryRef = React.useRef(retry);
|
||||
retryRef.current = retry;
|
||||
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
if (pingIntervalRef.current) {
|
||||
clearInterval(pingIntervalRef.current);
|
||||
pingIntervalRef.current = null;
|
||||
}
|
||||
if (wsRef.current) {
|
||||
try {
|
||||
wsRef.current.send(JSON.stringify({ type: "disconnect" }));
|
||||
} catch {
|
||||
// Best-effort disconnect during cleanup.
|
||||
}
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
setIsConnected(false);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (containerState !== "running") {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center space-y-2">
|
||||
<TerminalIcon className="h-12 w-12 text-muted-foreground/50 mx-auto" />
|
||||
<p className="text-muted-foreground text-lg">
|
||||
{t("docker.containerNotRunning")}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("docker.startContainerToAccess")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full gap-3">
|
||||
<Card className="py-3">
|
||||
<CardContent className="px-3">
|
||||
<div className="flex flex-col sm:flex-row gap-2 items-center sm:items-center">
|
||||
<div className="flex items-center gap-2 flex-1">
|
||||
<TerminalIcon className="h-5 w-5" />
|
||||
<span className="text-base font-medium">
|
||||
{t("docker.console")}
|
||||
</span>
|
||||
</div>
|
||||
<Select2
|
||||
value={selectedShell}
|
||||
onChange={(event) => setSelectedShell(event.target.value)}
|
||||
disabled={isConnected}
|
||||
placeholder={t("docker.selectShell")}
|
||||
className="w-[120px]"
|
||||
>
|
||||
<option value="bash">{t("docker.bash")}</option>
|
||||
<option value="sh">{t("docker.sh")}</option>
|
||||
<option value="ash">{t("docker.ash")}</option>
|
||||
</Select2>
|
||||
<div className="flex gap-2 sm:gap-2">
|
||||
{!isConnected ? (
|
||||
<Button
|
||||
onClick={connect}
|
||||
disabled={isConnecting}
|
||||
className="min-w-[120px]"
|
||||
>
|
||||
{isConnecting ? (
|
||||
<>
|
||||
<div className="h-4 w-4 mr-2 animate-spin rounded-full border-2 border-gray-400 border-t-transparent" />
|
||||
{t("docker.connecting")}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Power className="h-4 w-4 mr-2" />
|
||||
{t("docker.connect")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={disconnect}
|
||||
variant="destructive"
|
||||
className="min-w-[120px]"
|
||||
>
|
||||
<PowerOff className="h-4 w-4 mr-2" />
|
||||
{t("docker.disconnect")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="flex-1 overflow-hidden pt-1 pb-0"
|
||||
style={{ background: themeColors.background }}
|
||||
>
|
||||
<CardContent className="p-0 h-full relative">
|
||||
<div
|
||||
ref={xtermRef}
|
||||
className="h-full w-full"
|
||||
style={{ display: isConnected ? "block" : "none" }}
|
||||
/>
|
||||
|
||||
{!isConnected &&
|
||||
!isConnecting &&
|
||||
retry.status !== "error" &&
|
||||
retry.status !== "disconnected" && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="text-center space-y-2">
|
||||
<TerminalIcon className="h-12 w-12 text-muted-foreground/50 mx-auto" />
|
||||
<p className="text-muted-foreground">
|
||||
{t("docker.notConnected")}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("docker.clickToConnect")}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isConnected &&
|
||||
(isConnecting ||
|
||||
retry.status === "error" ||
|
||||
retry.status === "disconnected") && (
|
||||
<ConnectionScreen
|
||||
status={isConnecting ? "connecting" : retry.status}
|
||||
message={t("docker.connectingTo", { containerName })}
|
||||
attempt={retry.attempt}
|
||||
maxAttempts={retry.maxAttempts}
|
||||
nextRetryInMs={retry.nextRetryInMs}
|
||||
onManualRetry={() => {
|
||||
clearLogs();
|
||||
retry.retryNow();
|
||||
}}
|
||||
retryLabel={t("docker.connect")}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { getErrorMessage } from "../error-message";
|
||||
import { Button, Card, useConfirmation } from "@termix/plugin-sdk/ui";
|
||||
import type { DockerContainer } from "../types";
|
||||
import React from "react";
|
||||
import {
|
||||
Box,
|
||||
Play,
|
||||
Square,
|
||||
RotateCw,
|
||||
Pause,
|
||||
PlayCircle,
|
||||
Trash2,
|
||||
RefreshCw,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useDockerApi } from "../docker-api";
|
||||
|
||||
interface ContainerCardProps {
|
||||
container: DockerContainer;
|
||||
sessionId: string;
|
||||
onSelect?: () => void;
|
||||
isSelected?: boolean;
|
||||
onRefresh?: () => void;
|
||||
}
|
||||
|
||||
export function DockerBadge({ state }: { state: DockerContainer["state"] }) {
|
||||
let colorClass = "border-border text-muted-foreground";
|
||||
if (state === "running")
|
||||
colorClass = "border-accent-brand/40 text-accent-brand bg-accent-brand/10";
|
||||
if (state === "paused")
|
||||
colorClass = "border-yellow-500/40 text-yellow-500 bg-yellow-500/10";
|
||||
if (state === "exited")
|
||||
colorClass = "border-destructive/40 text-destructive bg-destructive/5";
|
||||
if (state === "restarting")
|
||||
colorClass = "border-blue-400/40 text-blue-400 bg-blue-400/10";
|
||||
return (
|
||||
<span
|
||||
className={`text-[10px] font-bold px-1.5 py-0.5 border uppercase tracking-wider ${colorClass}`}
|
||||
>
|
||||
{state}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContainerCard({
|
||||
container,
|
||||
sessionId,
|
||||
onSelect,
|
||||
isSelected = false,
|
||||
onRefresh,
|
||||
}: ContainerCardProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const { confirmWithToast } = useConfirmation();
|
||||
const docker = useDockerApi();
|
||||
const [isStarting, setIsStarting] = React.useState(false);
|
||||
const [isStopping, setIsStopping] = React.useState(false);
|
||||
const [isRestarting, setIsRestarting] = React.useState(false);
|
||||
const [isPausing, setIsPausing] = React.useState(false);
|
||||
const [isRemoving, setIsRemoving] = React.useState(false);
|
||||
|
||||
const isLoading =
|
||||
isStarting || isStopping || isRestarting || isPausing || isRemoving;
|
||||
|
||||
const containerName = container.name.startsWith("/")
|
||||
? container.name.slice(1)
|
||||
: container.name;
|
||||
const portsList = (container.ports ?? "")
|
||||
.split(",")
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const handleStart = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsStarting(true);
|
||||
try {
|
||||
await docker.containerAction(sessionId, container.id, "start");
|
||||
toast.success(t("docker.containerStarted", { name: containerName }));
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
t("docker.failedToStartContainer", {
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsStarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStop = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsStopping(true);
|
||||
try {
|
||||
await docker.containerAction(sessionId, container.id, "stop");
|
||||
toast.success(t("docker.containerStopped", { name: containerName }));
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
t("docker.failedToStopContainer", {
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsStopping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRestart = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsRestarting(true);
|
||||
try {
|
||||
await docker.containerAction(sessionId, container.id, "restart");
|
||||
toast.success(t("docker.containerRestarted", { name: containerName }));
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
t("docker.failedToRestartContainer", {
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRestarting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePause = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsPausing(true);
|
||||
try {
|
||||
if (container.state === "paused") {
|
||||
await docker.containerAction(sessionId, container.id, "unpause");
|
||||
toast.success(t("docker.containerUnpaused", { name: containerName }));
|
||||
} else {
|
||||
await docker.containerAction(sessionId, container.id, "pause");
|
||||
toast.success(t("docker.containerPaused", { name: containerName }));
|
||||
}
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
t("docker.failedToTogglePauseContainer", {
|
||||
action: container.state === "paused" ? "unpause" : "pause",
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsPausing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemove = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
confirmWithToast(
|
||||
t("docker.confirmRemoveContainer", { name: containerName }) +
|
||||
(container.state === "running"
|
||||
? " " + t("docker.runningContainerWarning")
|
||||
: ""),
|
||||
async () => {
|
||||
setIsRemoving(true);
|
||||
try {
|
||||
await docker.removeContainer(
|
||||
sessionId,
|
||||
container.id,
|
||||
container.state === "running",
|
||||
);
|
||||
toast.success(t("docker.containerRemoved", { name: containerName }));
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
t("docker.failedToRemoveContainer", {
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setIsRemoving(false);
|
||||
}
|
||||
},
|
||||
t("common.remove"),
|
||||
t("common.cancel"),
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
className={`flex flex-col overflow-hidden p-0 gap-0 group hover:border-accent-brand/40 transition-colors cursor-pointer ${isSelected ? "border-accent-brand/60 bg-accent-brand/5" : ""}`}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-2.5 border-b border-border bg-muted/10">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Box
|
||||
className={`size-3.5 ${container.state === "running" ? "text-accent-brand" : "text-muted-foreground"}`}
|
||||
/>
|
||||
<span className="text-sm font-bold truncate">{containerName}</span>
|
||||
</div>
|
||||
<DockerBadge state={container.state} />
|
||||
</div>
|
||||
<div className="px-4 py-3 flex flex-col gap-2">
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-widest">
|
||||
{t("docker.image")}
|
||||
</span>
|
||||
<span className="text-xs font-mono truncate text-foreground/80">
|
||||
{container.image}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5 mt-1">
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-widest">
|
||||
{t("docker.ports")}
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-1 mt-0.5">
|
||||
{portsList.length > 0 ? (
|
||||
portsList.slice(0, 3).map((p) => (
|
||||
<span
|
||||
key={p}
|
||||
className="text-[10px] font-mono px-1 border border-border bg-muted/30"
|
||||
>
|
||||
{p}
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="text-[10px] text-muted-foreground italic">
|
||||
{t("docker.noPorts")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-4 py-2 border-t border-border bg-muted/5 flex items-center justify-between opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<span className="text-[10px] text-muted-foreground italic">
|
||||
{container.id.substring(0, 12)}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
{container.state !== "running" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="text-accent-brand"
|
||||
disabled={isLoading}
|
||||
onClick={handleStart}
|
||||
>
|
||||
{isStarting ? (
|
||||
<RefreshCw className="size-3 animate-spin" />
|
||||
) : (
|
||||
<Play className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{container.state === "running" && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="text-destructive"
|
||||
disabled={isLoading}
|
||||
onClick={handleStop}
|
||||
>
|
||||
{isStopping ? (
|
||||
<RefreshCw className="size-3 animate-spin" />
|
||||
) : (
|
||||
<Square className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{(container.state === "running" || container.state === "paused") && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
disabled={isLoading}
|
||||
onClick={handlePause}
|
||||
>
|
||||
{isPausing ? (
|
||||
<RefreshCw className="size-3 animate-spin" />
|
||||
) : container.state === "paused" ? (
|
||||
<PlayCircle className="size-3" />
|
||||
) : (
|
||||
<Pause className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
disabled={isLoading || container.state === "exited"}
|
||||
onClick={handleRestart}
|
||||
>
|
||||
{isRestarting ? (
|
||||
<RefreshCw className="size-3 animate-spin" />
|
||||
) : (
|
||||
<RotateCw className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="text-destructive"
|
||||
disabled={isLoading}
|
||||
onClick={handleRemove}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Button, Card, Separator } from "@termix/plugin-sdk/ui";
|
||||
import type { DockerContainer, DockerHost } from "../types";
|
||||
import React from "react";
|
||||
import {
|
||||
Activity,
|
||||
ArrowLeft,
|
||||
Box,
|
||||
List,
|
||||
Settings,
|
||||
Terminal,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { LogViewer } from "./LogViewer.tsx";
|
||||
import { ContainerStats } from "./ContainerStats.tsx";
|
||||
import { ConsoleTerminal } from "./ConsoleTerminal.tsx";
|
||||
import { DockerBadge } from "./ContainerCard.tsx";
|
||||
|
||||
type DetailTab = "logs" | "stats" | "console";
|
||||
|
||||
interface ContainerDetailProps {
|
||||
sessionId: string;
|
||||
containerId: string;
|
||||
containers: DockerContainer[];
|
||||
hostConfig: DockerHost;
|
||||
onBack: () => void;
|
||||
initialTab?: DetailTab;
|
||||
}
|
||||
|
||||
export function ContainerDetail({
|
||||
sessionId,
|
||||
containerId,
|
||||
containers,
|
||||
hostConfig,
|
||||
onBack,
|
||||
initialTab = "logs",
|
||||
}: ContainerDetailProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = React.useState<DetailTab>(initialTab);
|
||||
|
||||
React.useEffect(() => {
|
||||
setActiveTab(initialTab);
|
||||
}, [containerId, initialTab]);
|
||||
|
||||
const container = containers.find((c) => c.id === containerId);
|
||||
const containerName = container
|
||||
? container.name.startsWith("/")
|
||||
? container.name.slice(1)
|
||||
: container.name
|
||||
: "";
|
||||
|
||||
if (!container) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="text-center flex flex-col gap-3">
|
||||
<p className="text-muted-foreground">
|
||||
{t("docker.containerNotFound")}
|
||||
</p>
|
||||
<Button onClick={onBack} variant="outline" size="sm">
|
||||
<ArrowLeft className="size-4 mr-2" />
|
||||
{t("docker.backToList")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const tabs: { id: DetailTab; label: string; icon: React.ReactNode }[] = [
|
||||
{
|
||||
id: "logs",
|
||||
label: t("docker.logs"),
|
||||
icon: <List className="size-3.5" />,
|
||||
},
|
||||
{
|
||||
id: "stats",
|
||||
label: t("docker.stats"),
|
||||
icon: <Activity className="size-3.5" />,
|
||||
},
|
||||
{
|
||||
id: "console",
|
||||
label: t("docker.consoleTab"),
|
||||
icon: <Terminal className="size-3.5" />,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-y-auto px-3 py-3 gap-3">
|
||||
<Card className="flex-row items-center justify-between px-3 py-3 shrink-0 gap-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onBack}
|
||||
className="size-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="size-4" />
|
||||
</Button>
|
||||
<div className="size-10 border border-border bg-muted flex items-center justify-center shrink-0">
|
||||
<Box className="size-5 text-accent-brand" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">{containerName}</h1>
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
{container.image}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<DockerBadge state={container.state} />
|
||||
<Separator orientation="vertical" className="h-8 mx-2" />
|
||||
<Button variant="ghost" size="icon">
|
||||
<Settings className="size-4 text-accent-brand" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div className="flex flex-col flex-1 min-h-0 gap-3">
|
||||
<div className="flex gap-1 border-b border-border shrink-0">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`flex items-center gap-2 px-4 py-2 text-sm font-semibold border-b-2 transition-colors ${
|
||||
activeTab === tab.id
|
||||
? "border-b-accent-brand text-foreground bg-accent-brand/5"
|
||||
: "border-b-transparent text-muted-foreground hover:text-foreground hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
{tab.icon}
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 flex flex-col">
|
||||
{activeTab === "logs" && (
|
||||
<LogViewer
|
||||
sessionId={sessionId}
|
||||
containerId={containerId}
|
||||
containerName={containerName}
|
||||
/>
|
||||
)}
|
||||
{activeTab === "stats" && (
|
||||
<ContainerStats
|
||||
sessionId={sessionId}
|
||||
containerId={containerId}
|
||||
containerName={containerName}
|
||||
containerState={container.state}
|
||||
/>
|
||||
)}
|
||||
{activeTab === "console" && (
|
||||
<ConsoleTerminal
|
||||
containerId={containerId}
|
||||
containerName={containerName}
|
||||
containerState={container.state}
|
||||
hostConfig={hostConfig}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { DockerContainer } from "../types";
|
||||
import React from "react";
|
||||
import { Box } from "lucide-react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { ContainerCard } from "./ContainerCard.tsx";
|
||||
|
||||
interface ContainerListProps {
|
||||
containers: DockerContainer[];
|
||||
sessionId: string;
|
||||
onSelectContainer: (containerId: string) => void;
|
||||
selectedContainerId?: string | null;
|
||||
onRefresh?: () => void;
|
||||
search?: string;
|
||||
statusFilter?: string;
|
||||
}
|
||||
|
||||
export function ContainerList({
|
||||
containers,
|
||||
sessionId,
|
||||
onSelectContainer,
|
||||
selectedContainerId = null,
|
||||
onRefresh,
|
||||
search = "",
|
||||
statusFilter = "all",
|
||||
}: ContainerListProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const filtered = React.useMemo(() => {
|
||||
return containers.filter((c) => {
|
||||
const name = c.name.startsWith("/") ? c.name.slice(1) : c.name;
|
||||
const matchesSearch =
|
||||
name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.image.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.id.toLowerCase().includes(search.toLowerCase());
|
||||
return (
|
||||
matchesSearch && (statusFilter === "all" || c.state === statusFilter)
|
||||
);
|
||||
});
|
||||
}, [containers, search, statusFilter]);
|
||||
|
||||
if (containers.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<Box className="size-16 mb-4" />
|
||||
<span className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("docker.noContainersFound")}
|
||||
</span>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("docker.noContainersFoundHint")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<Box className="size-16 mb-4" />
|
||||
<span className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("docker.noContainersMatchFilters")}
|
||||
</span>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("docker.noContainersMatchFiltersHint")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
|
||||
{filtered.map((container) => (
|
||||
<ContainerCard
|
||||
key={container.id}
|
||||
container={container}
|
||||
sessionId={sessionId}
|
||||
onSelect={() => onSelectContainer(container.id)}
|
||||
isSelected={selectedContainerId === container.id}
|
||||
onRefresh={onRefresh}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import { getErrorMessage } from "../error-message";
|
||||
import { SectionCard, useAdaptivePolling } from "@termix/plugin-sdk/ui";
|
||||
import type { DockerStats } from "../types";
|
||||
import React from "react";
|
||||
import {
|
||||
Activity,
|
||||
Cpu,
|
||||
HardDrive,
|
||||
Info,
|
||||
MemoryStick,
|
||||
Network,
|
||||
RefreshCw,
|
||||
} from "lucide-react";
|
||||
import { useDockerApi } from "../docker-api";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { DockerBadge } from "./ContainerCard.tsx";
|
||||
|
||||
interface ContainerStatsProps {
|
||||
sessionId: string;
|
||||
containerId: string;
|
||||
containerName: string;
|
||||
containerState: string;
|
||||
}
|
||||
|
||||
export function ContainerStats({
|
||||
sessionId,
|
||||
containerId,
|
||||
containerName,
|
||||
containerState,
|
||||
}: ContainerStatsProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const docker = useDockerApi();
|
||||
const [stats, setStats] = React.useState<DockerStats | null>(null);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
const statsRef = React.useRef(stats);
|
||||
statsRef.current = stats;
|
||||
|
||||
const fetchStats = React.useCallback(async () => {
|
||||
if (containerState !== "running") return false;
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await docker.stats(sessionId, containerId);
|
||||
const previous = statsRef.current;
|
||||
const changed =
|
||||
!previous ||
|
||||
Math.abs(parseFloat(data.cpu) - parseFloat(previous.cpu)) >= 1.5 ||
|
||||
Math.abs(
|
||||
parseFloat(data.memoryPercent) - parseFloat(previous.memoryPercent),
|
||||
) >= 1 ||
|
||||
data.pids !== previous.pids;
|
||||
statsRef.current = data;
|
||||
setStats(data);
|
||||
return changed;
|
||||
} catch (err) {
|
||||
setError(getErrorMessage(err, t("docker.failedToFetchStats")));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sessionId, containerId, containerState, t, docker]);
|
||||
|
||||
useAdaptivePolling(
|
||||
fetchStats,
|
||||
{
|
||||
minIntervalMs: 2_000,
|
||||
maxIntervalMs: 12_000,
|
||||
stablePollsPerStep: 2,
|
||||
maxRequestDutyCycle: 0.2,
|
||||
},
|
||||
containerState === "running",
|
||||
);
|
||||
|
||||
if (containerState !== "running") {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<Activity className="size-16 mb-4" />
|
||||
<span className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("docker.containerNotRunning")}
|
||||
</span>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("docker.startContainerToViewStats")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading && !stats) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-40 py-20">
|
||||
<RefreshCw className="size-8 animate-spin mb-4" />
|
||||
<span className="text-sm font-semibold">
|
||||
{t("docker.loadingStats")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-40 py-20">
|
||||
<Activity className="size-8 mb-4" />
|
||||
<span className="text-sm font-semibold text-destructive">
|
||||
{t("docker.errorLoadingStats")}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground mt-1">{error}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!stats) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<span className="text-sm font-semibold">
|
||||
{t("docker.noStatsAvailable")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const cpuPercent = parseFloat(stats.cpu) || 0;
|
||||
const memPercent = parseFloat(stats.memoryPercent) || 0;
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
<SectionCard
|
||||
title={t("docker.cpuUsage")}
|
||||
icon={<Cpu className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-3 py-2">
|
||||
<div className="flex items-end justify-between">
|
||||
<span className="text-3xl font-bold text-accent-brand">
|
||||
{stats.cpu}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold">
|
||||
{t("docker.current")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-muted w-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-accent-brand transition-all duration-500"
|
||||
style={{ width: `${Math.min(cpuPercent, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title={t("docker.memoryUsage")}
|
||||
icon={<MemoryStick className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-3 py-2">
|
||||
<div className="flex items-end justify-between">
|
||||
<span className="text-3xl font-bold text-accent-brand">
|
||||
{stats.memoryPercent}
|
||||
</span>
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold">
|
||||
{stats.memoryUsed} / {stats.memoryLimit}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 bg-muted w-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-accent-brand transition-all duration-500"
|
||||
style={{ width: `${Math.min(memPercent, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title={t("docker.networkIo")}
|
||||
icon={<Network className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-1 py-1">
|
||||
<div className="flex justify-between items-center py-1">
|
||||
<span className="text-xs text-muted-foreground font-semibold">
|
||||
{t("docker.input")}
|
||||
</span>
|
||||
<span className="text-sm font-mono font-bold">
|
||||
{stats.netInput}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center py-1">
|
||||
<span className="text-xs text-muted-foreground font-semibold">
|
||||
{t("docker.output")}
|
||||
</span>
|
||||
<span className="text-sm font-mono font-bold text-accent-brand">
|
||||
{stats.netOutput}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title={t("docker.blockIo")}
|
||||
icon={<HardDrive className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-1 py-1">
|
||||
<div className="flex justify-between items-center py-1">
|
||||
<span className="text-xs text-muted-foreground font-semibold">
|
||||
{t("docker.read")}
|
||||
</span>
|
||||
<span className="text-sm font-mono font-bold">
|
||||
{stats.blockRead}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center py-1">
|
||||
<span className="text-xs text-muted-foreground font-semibold">
|
||||
{t("docker.write")}
|
||||
</span>
|
||||
<span className="text-sm font-mono font-bold text-accent-brand">
|
||||
{stats.blockWrite}
|
||||
</span>
|
||||
</div>
|
||||
{stats.pids && (
|
||||
<div className="flex justify-between items-center py-1">
|
||||
<span className="text-xs text-muted-foreground font-semibold">
|
||||
{t("docker.pids")}
|
||||
</span>
|
||||
<span className="text-sm font-mono font-bold">{stats.pids}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title={t("docker.containerInformation")}
|
||||
icon={<Info className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-1.5 py-1">
|
||||
<div className="flex justify-between items-center text-xs py-1 border-b border-border/50">
|
||||
<span className="text-muted-foreground font-semibold">
|
||||
{t("docker.name")}
|
||||
</span>
|
||||
<span className="font-mono">{containerName}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center text-xs py-1 border-b border-border/50">
|
||||
<span className="text-muted-foreground font-semibold">
|
||||
{t("docker.id")}
|
||||
</span>
|
||||
<span className="font-mono">{containerId.substring(0, 12)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center text-xs py-1">
|
||||
<span className="text-muted-foreground font-semibold">
|
||||
{t("docker.state")}
|
||||
</span>
|
||||
<DockerBadge
|
||||
state={
|
||||
containerState as import("../types").DockerContainer["state"]
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import { getErrorMessage } from "../error-message";
|
||||
import { Button } from "@termix/plugin-sdk/ui";
|
||||
import type { DockerContainer } from "../types";
|
||||
import React from "react";
|
||||
import { Box, List, Play, RefreshCw, Square, Terminal } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useDockerApi } from "../docker-api";
|
||||
import { DockerBadge } from "./ContainerCard.tsx";
|
||||
|
||||
type DetailTab = "logs" | "stats" | "console";
|
||||
|
||||
interface ContainerTableProps {
|
||||
containers: DockerContainer[];
|
||||
sessionId: string;
|
||||
onSelectContainer: (containerId: string, tab?: DetailTab) => void;
|
||||
selectedContainerId?: string | null;
|
||||
onRefresh?: () => void;
|
||||
search?: string;
|
||||
statusFilter?: string;
|
||||
}
|
||||
|
||||
export function ContainerTable({
|
||||
containers,
|
||||
sessionId,
|
||||
onSelectContainer,
|
||||
selectedContainerId = null,
|
||||
onRefresh,
|
||||
search = "",
|
||||
statusFilter = "all",
|
||||
}: ContainerTableProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const docker = useDockerApi();
|
||||
const [pendingId, setPendingId] = React.useState<string | null>(null);
|
||||
|
||||
const filtered = React.useMemo(() => {
|
||||
return containers.filter((c) => {
|
||||
const name = c.name.startsWith("/") ? c.name.slice(1) : c.name;
|
||||
const matchesSearch =
|
||||
name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.image.toLowerCase().includes(search.toLowerCase()) ||
|
||||
c.id.toLowerCase().includes(search.toLowerCase());
|
||||
return (
|
||||
matchesSearch && (statusFilter === "all" || c.state === statusFilter)
|
||||
);
|
||||
});
|
||||
}, [containers, search, statusFilter]);
|
||||
|
||||
const handleToggleRun = async (
|
||||
e: React.MouseEvent,
|
||||
container: DockerContainer,
|
||||
) => {
|
||||
e.stopPropagation();
|
||||
const containerName = container.name.startsWith("/")
|
||||
? container.name.slice(1)
|
||||
: container.name;
|
||||
setPendingId(container.id);
|
||||
try {
|
||||
if (container.state === "running") {
|
||||
await docker.containerAction(sessionId, container.id, "stop");
|
||||
toast.success(t("docker.containerStopped", { name: containerName }));
|
||||
} else {
|
||||
await docker.containerAction(sessionId, container.id, "start");
|
||||
toast.success(t("docker.containerStarted", { name: containerName }));
|
||||
}
|
||||
onRefresh?.();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
container.state === "running"
|
||||
? t("docker.failedToStopContainer", { error: getErrorMessage(err) })
|
||||
: t("docker.failedToStartContainer", {
|
||||
error: getErrorMessage(err),
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
setPendingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (containers.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<Box className="size-16 mb-4" />
|
||||
<span className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("docker.noContainersFound")}
|
||||
</span>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("docker.noContainersFoundHint")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full opacity-20 py-20">
|
||||
<Box className="size-16 mb-4" />
|
||||
<span className="text-xl font-bold uppercase tracking-widest">
|
||||
{t("docker.noContainersMatchFilters")}
|
||||
</span>
|
||||
<span className="text-xs font-semibold">
|
||||
{t("docker.noContainersMatchFiltersHint")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden border border-border bg-card">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto thin-scrollbar">
|
||||
<table className="w-full border-collapse text-xs">
|
||||
<thead className="sticky top-0 z-10 bg-card">
|
||||
<tr className="border-b border-border text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
<th className="px-3 py-2 text-left font-semibold">
|
||||
{t("docker.name")}
|
||||
</th>
|
||||
<th className="px-3 py-2 text-left font-semibold">
|
||||
{t("docker.image")}
|
||||
</th>
|
||||
<th className="px-3 py-2 text-left font-semibold">
|
||||
{t("docker.state")}
|
||||
</th>
|
||||
<th className="px-3 py-2 text-left font-semibold">
|
||||
{t("docker.ports")}
|
||||
</th>
|
||||
<th className="px-3 py-2 text-left font-semibold">
|
||||
{t("docker.status")}
|
||||
</th>
|
||||
<th className="px-3 py-2 text-right font-semibold">
|
||||
{t("docker.actions")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{filtered.map((container) => {
|
||||
const containerName = container.name.startsWith("/")
|
||||
? container.name.slice(1)
|
||||
: container.name;
|
||||
const portsList = (container.ports ?? "")
|
||||
.split(",")
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean);
|
||||
const isSelected = selectedContainerId === container.id;
|
||||
const isPending = pendingId === container.id;
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={container.id}
|
||||
onClick={() => onSelectContainer(container.id, "logs")}
|
||||
className={`cursor-pointer transition-colors hover:bg-muted/40 ${
|
||||
isSelected ? "bg-accent-brand/5" : ""
|
||||
}`}
|
||||
>
|
||||
<td className="px-3 py-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Box
|
||||
className={`size-3.5 shrink-0 ${container.state === "running" ? "text-accent-brand" : "text-muted-foreground"}`}
|
||||
/>
|
||||
<span className="min-w-0 truncate font-semibold">
|
||||
{containerName}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-2 max-w-[220px]">
|
||||
<span className="block truncate font-mono text-muted-foreground">
|
||||
{container.image}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<DockerBadge state={container.state} />
|
||||
</td>
|
||||
<td className="px-3 py-2 max-w-[200px]">
|
||||
{portsList.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{portsList.slice(0, 2).map((p) => (
|
||||
<span
|
||||
key={p}
|
||||
className="text-[10px] font-mono px-1 border border-border bg-muted/30"
|
||||
>
|
||||
{p}
|
||||
</span>
|
||||
))}
|
||||
{portsList.length > 2 && (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
+{portsList.length - 2}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-[10px] text-muted-foreground italic">
|
||||
{t("docker.noPorts")}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-2 whitespace-nowrap text-muted-foreground">
|
||||
{container.status}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<div
|
||||
className="flex items-center justify-end gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
title={t("docker.logs")}
|
||||
onClick={() => onSelectContainer(container.id, "logs")}
|
||||
>
|
||||
<List className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
title={t("docker.stats")}
|
||||
onClick={() => onSelectContainer(container.id, "stats")}
|
||||
>
|
||||
<Box className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
title={t("docker.consoleTab")}
|
||||
disabled={container.state !== "running"}
|
||||
onClick={() =>
|
||||
onSelectContainer(container.id, "console")
|
||||
}
|
||||
>
|
||||
<Terminal className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className={
|
||||
container.state === "running"
|
||||
? "text-destructive"
|
||||
: "text-accent-brand"
|
||||
}
|
||||
disabled={isPending}
|
||||
title={
|
||||
container.state === "running"
|
||||
? t("docker.stop")
|
||||
: t("docker.start")
|
||||
}
|
||||
onClick={(e) => handleToggleRun(e, container)}
|
||||
>
|
||||
{isPending ? (
|
||||
<RefreshCw className="size-3 animate-spin" />
|
||||
) : container.state === "running" ? (
|
||||
<Square className="size-3" />
|
||||
) : (
|
||||
<Play className="size-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { getErrorMessage } from "../error-message";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Select2,
|
||||
Separator,
|
||||
useAdaptivePolling,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import type { DockerLogOptions } from "../types";
|
||||
import React from "react";
|
||||
import { Download, RefreshCw, Search, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { useDockerApi } from "../docker-api";
|
||||
|
||||
interface LogViewerProps {
|
||||
sessionId: string;
|
||||
containerId: string;
|
||||
containerName: string;
|
||||
}
|
||||
|
||||
function AdminToggle({
|
||||
on,
|
||||
onToggle,
|
||||
label,
|
||||
}: {
|
||||
on: boolean;
|
||||
onToggle: () => void;
|
||||
label: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold">
|
||||
{label}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center border-2 transition-colors ${on ? "bg-accent-brand border-accent-brand" : "bg-muted border-border"}`}
|
||||
>
|
||||
<span
|
||||
className={`pointer-events-none inline-block h-3 w-3 bg-background shadow-sm transition-transform ${on ? "translate-x-4" : "translate-x-0.5"}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getLogColor(line: string): string {
|
||||
if (line.includes(" WARN") || line.includes(" warn"))
|
||||
return "text-yellow-400/90";
|
||||
if (line.includes(" ERROR") || line.includes(" error"))
|
||||
return "text-destructive";
|
||||
if (line.includes(" DEBUG") || line.includes(" debug"))
|
||||
return "text-muted-foreground/60";
|
||||
return "text-foreground/90";
|
||||
}
|
||||
|
||||
export function LogViewer({
|
||||
sessionId,
|
||||
containerId,
|
||||
containerName,
|
||||
}: LogViewerProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const docker = useDockerApi();
|
||||
const [rawLogs, setRawLogs] = React.useState<string[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [isDownloading, setIsDownloading] = React.useState(false);
|
||||
const [tailLines, setTailLines] = React.useState("100");
|
||||
const [showTimestamps, setShowTimestamps] = React.useState(false);
|
||||
const [autoRefresh, setAutoRefresh] = React.useState(false);
|
||||
const [logSearch, setLogSearch] = React.useState("");
|
||||
const logsEndRef = React.useRef<HTMLDivElement>(null);
|
||||
const rawLogsRef = React.useRef(rawLogs);
|
||||
rawLogsRef.current = rawLogs;
|
||||
|
||||
const fetchLogs = React.useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const options: DockerLogOptions = {
|
||||
tail: tailLines === "all" ? undefined : parseInt(tailLines, 10),
|
||||
timestamps: showTimestamps,
|
||||
};
|
||||
const data = await docker.logs(sessionId, containerId, options);
|
||||
const next = data.logs.split("\n").filter(Boolean);
|
||||
const changed =
|
||||
next.length !== rawLogsRef.current.length ||
|
||||
next.some((line, index) => line !== rawLogsRef.current[index]);
|
||||
if (changed) {
|
||||
rawLogsRef.current = next;
|
||||
setRawLogs(next);
|
||||
}
|
||||
return changed;
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("docker.failedToFetchLogs", { error: getErrorMessage(error) }),
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sessionId, containerId, tailLines, showTimestamps, docker, t]);
|
||||
|
||||
React.useEffect(() => {
|
||||
fetchLogs();
|
||||
}, [fetchLogs]);
|
||||
|
||||
useAdaptivePolling(
|
||||
fetchLogs,
|
||||
{
|
||||
minIntervalMs: 3_000,
|
||||
maxIntervalMs: 18_000,
|
||||
stablePollsPerStep: 2,
|
||||
maxRequestDutyCycle: 0.2,
|
||||
},
|
||||
autoRefresh,
|
||||
{ runImmediately: false },
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (autoRefresh && logsEndRef.current) {
|
||||
logsEndRef.current.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
}, [rawLogs, autoRefresh]);
|
||||
|
||||
const handleDownload = async () => {
|
||||
setIsDownloading(true);
|
||||
try {
|
||||
const data = await docker.logs(sessionId, containerId, {
|
||||
timestamps: showTimestamps,
|
||||
});
|
||||
const blob = new Blob([data.logs], { type: "text/plain" });
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${containerName.replace(/[^a-z0-9]/gi, "_")}_logs.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
toast.success(t("docker.logsDownloaded"));
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("docker.failedToDownloadLogs", { error: getErrorMessage(error) }),
|
||||
);
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredLogs = logSearch
|
||||
? rawLogs.filter((l) => l.toLowerCase().includes(logSearch.toLowerCase()))
|
||||
: rawLogs;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 gap-3">
|
||||
<div className="flex items-center justify-between bg-card border border-border px-3 py-2 gap-3 flex-wrap">
|
||||
<div className="flex items-center gap-3 shrink-0 flex-wrap">
|
||||
<AdminToggle
|
||||
on={autoRefresh}
|
||||
onToggle={() => setAutoRefresh(!autoRefresh)}
|
||||
label={t("docker.autoRefresh")}
|
||||
/>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<AdminToggle
|
||||
on={showTimestamps}
|
||||
onToggle={() => setShowTimestamps(!showTimestamps)}
|
||||
label={t("docker.timestamps")}
|
||||
/>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<Select2
|
||||
value={tailLines}
|
||||
onChange={(e) => setTailLines(e.target.value)}
|
||||
className="h-7 px-2 text-[10px] bg-background border border-border text-foreground outline-none uppercase font-bold"
|
||||
>
|
||||
<option value="50">{t("docker.last50")}</option>
|
||||
<option value="100">{t("docker.last100")}</option>
|
||||
<option value="500">{t("docker.last500")}</option>
|
||||
<option value="1000">{t("docker.last1000")}</option>
|
||||
<option value="all">{t("docker.allLogs")}</option>
|
||||
</Select2>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<span className="text-[10px] text-muted-foreground uppercase font-bold tracking-widest">
|
||||
{filteredLogs.length}/{rawLogs.length} {t("docker.lines")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative flex-1 max-w-64">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("docker.filterLogs")}
|
||||
value={logSearch}
|
||||
onChange={(e) => setLogSearch(e.target.value)}
|
||||
className="pl-7 h-7 text-xs bg-background border-border rounded-none"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1.5"
|
||||
onClick={fetchLogs}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`size-3 ${isLoading ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{t("docker.refresh")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1.5"
|
||||
onClick={handleDownload}
|
||||
disabled={isDownloading}
|
||||
>
|
||||
<Download className="size-3" />
|
||||
{t("docker.download")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-xs gap-1.5"
|
||||
onClick={() => setRawLogs([])}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
{t("docker.clear")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 bg-background border border-border p-3 overflow-auto font-mono text-xs leading-relaxed scrollbar-thin min-h-0">
|
||||
{filteredLogs.length > 0 ? (
|
||||
filteredLogs.map((line, i) => {
|
||||
const tsEnd = line.indexOf(" ", 1);
|
||||
const maybeTs = tsEnd > 10 ? line.substring(0, tsEnd) : null;
|
||||
const rest = maybeTs ? line.substring(tsEnd) : line;
|
||||
return (
|
||||
<div key={i} className="whitespace-pre-wrap break-all">
|
||||
{maybeTs && (
|
||||
<span className="text-accent-brand/50">{maybeTs}</span>
|
||||
)}
|
||||
<span className={getLogColor(rest)}>{rest}</span>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<span className="text-muted-foreground italic">
|
||||
{logSearch
|
||||
? t("docker.noLogsMatching", { query: logSearch })
|
||||
: t("docker.noLogsAvailable")}
|
||||
</span>
|
||||
)}
|
||||
<div ref={logsEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
invokeAction,
|
||||
type PluginHostRecord,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
|
||||
/** What the SSH terminal's "terminal.resolveTheme" action answers. */
|
||||
export interface ConsoleLook {
|
||||
colors: Record<string, string | undefined> & {
|
||||
background: string;
|
||||
foreground: string;
|
||||
};
|
||||
fontFamily: string;
|
||||
fontSize: number;
|
||||
cursorStyle: "block" | "underline" | "bar";
|
||||
cursorBlink: boolean;
|
||||
letterSpacing: number;
|
||||
lineHeight: number;
|
||||
scrollback: number;
|
||||
}
|
||||
|
||||
/** Plain colors, for when the SSH terminal plugin is off. */
|
||||
export const FALLBACK_CONSOLE_LOOK: ConsoleLook = {
|
||||
colors: {
|
||||
background: "#0c0d0b",
|
||||
foreground: "#fafafa",
|
||||
cursor: "#fafafa",
|
||||
cursorAccent: "#0c0d0b",
|
||||
},
|
||||
fontFamily: '"SF Mono", Consolas, "Liberation Mono", monospace',
|
||||
fontSize: 14,
|
||||
cursorStyle: "bar",
|
||||
cursorBlink: true,
|
||||
letterSpacing: 0,
|
||||
lineHeight: 1,
|
||||
scrollback: 10000,
|
||||
};
|
||||
|
||||
/** The look the SSH terminal uses on this host, or plain colors without it. */
|
||||
export function useConsoleLook(
|
||||
host: PluginHostRecord | null | undefined,
|
||||
appTheme: string,
|
||||
): ConsoleLook {
|
||||
const [look, setLook] = useState<ConsoleLook>(FALLBACK_CONSOLE_LOOK);
|
||||
// The terminal's settings live with the terminal, so it resolves them from
|
||||
// the host id.
|
||||
const hostId = host?.id;
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
invokeAction("terminal.resolveTheme", { hostId, appTheme })
|
||||
.then((resolved) => {
|
||||
if (active) setLook((resolved as ConsoleLook) ?? FALLBACK_CONSOLE_LOOK);
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setLook(FALLBACK_CONSOLE_LOOK);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [hostId, appTheme]);
|
||||
|
||||
return look;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
usePluginApi,
|
||||
type PluginApiClient,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import type { ConnectionStage } from "@termix/plugin-sdk/ui";
|
||||
import type {
|
||||
DockerContainer,
|
||||
DockerLogOptions,
|
||||
DockerStats,
|
||||
DockerValidation,
|
||||
} from "./types";
|
||||
|
||||
export interface ApiConnectionLog {
|
||||
type: "info" | "success" | "warning" | "error";
|
||||
stage: ConnectionStage;
|
||||
message: string;
|
||||
details?: string;
|
||||
}
|
||||
|
||||
/** One step of a connect: connected, a prompt to answer, or auth needed. */
|
||||
export interface ConnectResult {
|
||||
success?: boolean;
|
||||
status?: string;
|
||||
reason?: string;
|
||||
message?: string;
|
||||
requires_totp?: boolean;
|
||||
prompt?: string;
|
||||
isPassword?: boolean;
|
||||
retry?: boolean;
|
||||
requires_browser_sign_in?: boolean;
|
||||
url?: string | null;
|
||||
code?: string;
|
||||
label?: string;
|
||||
connectionLogs?: ApiConnectionLog[];
|
||||
}
|
||||
|
||||
/** An API failure carrying the server's message and connection logs. */
|
||||
export class DockerApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status?: number,
|
||||
readonly connectionLogs?: ApiConnectionLog[],
|
||||
) {
|
||||
super(message);
|
||||
this.name = "DockerApiError";
|
||||
}
|
||||
}
|
||||
|
||||
function apiError(error: unknown, action: string): DockerApiError {
|
||||
const response = (
|
||||
error as {
|
||||
response?: {
|
||||
status?: number;
|
||||
data?: {
|
||||
error?: string;
|
||||
message?: string;
|
||||
connectionLogs?: ApiConnectionLog[];
|
||||
};
|
||||
};
|
||||
}
|
||||
)?.response;
|
||||
const data = response?.data;
|
||||
const message =
|
||||
data?.error ||
|
||||
data?.message ||
|
||||
(error instanceof Error ? error.message : `Failed to ${action}`);
|
||||
return new DockerApiError(message, response?.status, data?.connectionLogs);
|
||||
}
|
||||
|
||||
async function call<T>(
|
||||
action: string,
|
||||
request: () => Promise<{ data: T }>,
|
||||
): Promise<T> {
|
||||
try {
|
||||
return (await request()).data;
|
||||
} catch (error) {
|
||||
throw apiError(error, action);
|
||||
}
|
||||
}
|
||||
|
||||
export type ContainerAction =
|
||||
"start" | "stop" | "restart" | "pause" | "unpause";
|
||||
|
||||
export function createDockerApi(api: PluginApiClient) {
|
||||
return {
|
||||
connect: (
|
||||
sessionId: string,
|
||||
hostId: number,
|
||||
credentials?: {
|
||||
userProvidedPassword?: string;
|
||||
userProvidedSshKey?: string;
|
||||
userProvidedKeyPassword?: string;
|
||||
},
|
||||
) =>
|
||||
call<ConnectResult>("connect to Docker", () =>
|
||||
api.post("/ssh/connect", { sessionId, hostId, ...credentials }),
|
||||
),
|
||||
|
||||
answerTotp: (sessionId: string, totpCode: string) =>
|
||||
call<ConnectResult>("verify the code", () =>
|
||||
api.post("/ssh/connect-totp", { sessionId, totpCode }),
|
||||
),
|
||||
|
||||
continueBrowserSignIn: (sessionId: string) =>
|
||||
call<ConnectResult>("continue after a browser sign-in", () =>
|
||||
api.post("/ssh/connect-browser-sign-in", { sessionId }),
|
||||
),
|
||||
|
||||
disconnect: (sessionId: string) =>
|
||||
call("disconnect from Docker", () =>
|
||||
api.post("/ssh/disconnect", { sessionId }),
|
||||
),
|
||||
|
||||
keepalive: (sessionId: string) =>
|
||||
call("keep the Docker session alive", () =>
|
||||
api.post("/ssh/keepalive", { sessionId }),
|
||||
),
|
||||
|
||||
validate: (sessionId: string) =>
|
||||
call<DockerValidation>("validate Docker", () =>
|
||||
api.get(`/validate/${sessionId}`),
|
||||
),
|
||||
|
||||
listContainers: (sessionId: string, all = true) =>
|
||||
call<DockerContainer[]>("list containers", () =>
|
||||
api.get(`/containers/${sessionId}`, { params: { all } }),
|
||||
),
|
||||
|
||||
containerAction: (
|
||||
sessionId: string,
|
||||
containerId: string,
|
||||
action: ContainerAction,
|
||||
) =>
|
||||
call<{ success: boolean; message: string }>(
|
||||
`${action} the container`,
|
||||
() => api.post(`/containers/${sessionId}/${containerId}/${action}`),
|
||||
),
|
||||
|
||||
removeContainer: (sessionId: string, containerId: string, force = false) =>
|
||||
call<{ success: boolean; message: string }>("remove the container", () =>
|
||||
api.delete(`/containers/${sessionId}/${containerId}/remove`, {
|
||||
params: { force },
|
||||
}),
|
||||
),
|
||||
|
||||
logs: (
|
||||
sessionId: string,
|
||||
containerId: string,
|
||||
options?: DockerLogOptions,
|
||||
) =>
|
||||
call<{ logs: string }>("load container logs", () =>
|
||||
api.get(`/containers/${sessionId}/${containerId}/logs`, {
|
||||
params: options,
|
||||
}),
|
||||
),
|
||||
|
||||
stats: (sessionId: string, containerId: string) =>
|
||||
call<DockerStats>("load container stats", () =>
|
||||
api.get(`/containers/${sessionId}/${containerId}/stats`),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export type DockerApi = ReturnType<typeof createDockerApi>;
|
||||
|
||||
/** The Docker API on this plugin's own client. */
|
||||
export function useDockerApi(): DockerApi {
|
||||
const api = usePluginApi();
|
||||
return useMemo(() => createDockerApi(api), [api]);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export function getErrorMessage(
|
||||
error: unknown,
|
||||
fallback = "Unknown error",
|
||||
): string {
|
||||
return error instanceof Error ? error.message : fallback;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import type { ExtensionContribution } from "@termix/plugin-sdk/frontend";
|
||||
|
||||
/** The homepage's grid step, in pixels. */
|
||||
export const GRID_SIZE = 30;
|
||||
|
||||
export interface DockerWidgetConfig {
|
||||
hostId: number;
|
||||
}
|
||||
|
||||
/** What the homepage hands a widget; only the fields this plugin reads. */
|
||||
export interface WidgetComponentProps<C> {
|
||||
widget: { title?: string | null };
|
||||
config: C;
|
||||
}
|
||||
|
||||
export interface WidgetEditFormProps<C> {
|
||||
config: C;
|
||||
onChange: (config: C) => void;
|
||||
}
|
||||
|
||||
/** What app.registerExtension("homepage.widgets", ...) takes. */
|
||||
export interface WidgetDefinition<C> extends ExtensionContribution {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
category: "links" | "info" | "system" | "monitoring";
|
||||
icon: ReactNode;
|
||||
defaultConfig: C;
|
||||
defaultSize: { w: number; h: number };
|
||||
minSize: { w: number; h: number };
|
||||
components: {
|
||||
view: ComponentType<WidgetComponentProps<C>>;
|
||||
editForm?: ComponentType<WidgetEditFormProps<C>>;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// The terminal surfaces need xterm's own stylesheet.
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
import type { ComponentType } from "react";
|
||||
import { Box } from "lucide-react";
|
||||
import type {
|
||||
StandaloneViewProps,
|
||||
TabProps,
|
||||
TermixApp,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { DockerManager } from "./DockerManager";
|
||||
import DockerApp from "./DockerApp";
|
||||
import { dockerWidget } from "./DockerWidget";
|
||||
import { dockerEnabled, toDockerHost, type DockerHostSource } from "./types";
|
||||
|
||||
function DockerTab({ host, sshHost, label, isVisible }: TabProps) {
|
||||
const record = host ?? (sshHost as DockerHostSource | undefined);
|
||||
return (
|
||||
<DockerManager
|
||||
host={record ? toDockerHost(record) : undefined}
|
||||
title={label}
|
||||
isVisible={isVisible}
|
||||
isTopbarOpen={false}
|
||||
embedded={true}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DockerStandalone({ hostId }: StandaloneViewProps) {
|
||||
return <DockerApp hostId={hostId} />;
|
||||
}
|
||||
|
||||
export function activate(app: TermixApp): void {
|
||||
// Host actions filter synchronously, so the permission is read once here.
|
||||
let canUse = true;
|
||||
void app.hasPermission("use").then((allowed) => {
|
||||
canUse = allowed;
|
||||
});
|
||||
|
||||
app.registerTab("docker", DockerTab, {
|
||||
icon: Box,
|
||||
titleKey: "nav.docker",
|
||||
requiresHost: true,
|
||||
noHostMessageKey: "docker.noHostSelected",
|
||||
persistent: true,
|
||||
activityTypes: ["docker"],
|
||||
standalone: DockerStandalone,
|
||||
preload: () => import("./DockerManager"),
|
||||
});
|
||||
|
||||
app.registerHostAction({
|
||||
id: "docker",
|
||||
titleKey: "nav.docker",
|
||||
icon: Box,
|
||||
kind: "open",
|
||||
order: 30,
|
||||
tabType: "docker",
|
||||
copyUrlView: "docker",
|
||||
when: (host) => canUse && !!host.enableSsh && dockerEnabled(host),
|
||||
});
|
||||
|
||||
app.registerExtension("homepage.widgets", dockerWidget);
|
||||
|
||||
app.registerSlotContribution("onboarding.features", {
|
||||
actionId: "docker.feature",
|
||||
titleKey: "onboarding.feature_docker",
|
||||
descriptionKey: "onboarding.feature_docker_desc",
|
||||
icon: Box as ComponentType<{ className?: string }>,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
export interface DockerContainer {
|
||||
id: string;
|
||||
name: string;
|
||||
image: string;
|
||||
status: string;
|
||||
state:
|
||||
| "created"
|
||||
| "running"
|
||||
| "paused"
|
||||
| "restarting"
|
||||
| "removing"
|
||||
| "exited"
|
||||
| "dead";
|
||||
ports: string;
|
||||
created: string;
|
||||
command?: string;
|
||||
labels?: Record<string, string>;
|
||||
networks?: string[];
|
||||
mounts?: string[];
|
||||
}
|
||||
|
||||
export interface DockerStats {
|
||||
cpu: string;
|
||||
memoryUsed: string;
|
||||
memoryLimit: string;
|
||||
memoryPercent: string;
|
||||
netInput: string;
|
||||
netOutput: string;
|
||||
blockRead: string;
|
||||
blockWrite: string;
|
||||
pids?: string;
|
||||
}
|
||||
|
||||
export interface DockerLogOptions {
|
||||
tail?: number;
|
||||
timestamps?: boolean;
|
||||
since?: string;
|
||||
until?: string;
|
||||
follow?: boolean;
|
||||
}
|
||||
|
||||
export interface DockerValidation {
|
||||
available: boolean;
|
||||
version?: string;
|
||||
runtime?: "docker" | "podman";
|
||||
error?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
/** What the Docker views read from a host. */
|
||||
export interface DockerHost {
|
||||
id: number;
|
||||
name?: string;
|
||||
ip: string;
|
||||
port: number;
|
||||
username?: string;
|
||||
syncId?: string | null;
|
||||
connectionOrigin?: "local" | "remote" | null;
|
||||
pluginSettings?: Record<string, Record<string, unknown> | undefined>;
|
||||
}
|
||||
|
||||
/** The fields toDockerHost reads from a shell or API host. */
|
||||
export type DockerHostSource = Omit<DockerHost, "id" | "name"> & {
|
||||
id: string | number;
|
||||
name?: string | null;
|
||||
};
|
||||
|
||||
/** Any host record the shell or an API hands over, as a DockerHost. */
|
||||
export function toDockerHost(record: DockerHostSource): DockerHost {
|
||||
return {
|
||||
id: Number(record.id),
|
||||
name: record.name ?? undefined,
|
||||
ip: record.ip,
|
||||
port: record.port,
|
||||
username: record.username,
|
||||
syncId: record.syncId ?? null,
|
||||
connectionOrigin: record.connectionOrigin ?? null,
|
||||
pluginSettings: record.pluginSettings,
|
||||
};
|
||||
}
|
||||
|
||||
function dockerSettings(
|
||||
host: object | null | undefined,
|
||||
): Record<string, unknown> {
|
||||
const all = (host as { pluginSettings?: unknown } | null | undefined)
|
||||
?.pluginSettings as
|
||||
Record<string, Record<string, unknown> | undefined> | undefined;
|
||||
return all?.docker ?? {};
|
||||
}
|
||||
|
||||
export function dockerEnabled(host: object | null | undefined): boolean {
|
||||
return dockerSettings(host).enableDocker === true;
|
||||
}
|
||||
|
||||
export function hostTitle(host: DockerHost): string {
|
||||
return host.name || `${host.username ?? ""}@${host.ip}`;
|
||||
}
|
||||
Reference in new issue
Block a user