mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 14:45: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,32 @@
|
||||
export interface SnippetExecutionResult {
|
||||
success: boolean;
|
||||
output: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export { resolveSnippetContent as resolveSnippetCommand } from "../shared/variables.js";
|
||||
export type { SnippetHostContext as SnippetHostVars } from "../shared/variables.js";
|
||||
|
||||
export function getSnippetExecutionTimeoutMs(
|
||||
value = process.env.SNIPPET_EXECUTION_TIMEOUT_SECONDS,
|
||||
): number | undefined {
|
||||
if (value === undefined || value.trim() === "") return undefined;
|
||||
|
||||
const seconds = Number(value);
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) return undefined;
|
||||
|
||||
return seconds * 1000;
|
||||
}
|
||||
|
||||
export function createSnippetExecutionResult(
|
||||
exitCode: number | null,
|
||||
output: string,
|
||||
errorOutput: string,
|
||||
): SnippetExecutionResult {
|
||||
const success = exitCode === 0 || (exitCode === null && !errorOutput);
|
||||
return {
|
||||
success,
|
||||
output,
|
||||
...(errorOutput ? { error: errorOutput } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import {
|
||||
PLUGIN_ID,
|
||||
readQuickActions,
|
||||
readStartupSnippetId,
|
||||
} from "../shared/host-settings.js";
|
||||
|
||||
/**
|
||||
* Registered as "snippets.hostImportNormalizer": a 2.8 or early 2.9 export
|
||||
* carried quick actions as a host field and the startup snippet inside
|
||||
* terminalConfig. An export that already carries this plugin's
|
||||
* pluginSettings has had them written by core.
|
||||
*/
|
||||
export function hostImportNormalizer(
|
||||
raw: Record<string, unknown>,
|
||||
): Record<string, unknown> | null {
|
||||
const carried = (raw.pluginSettings as Record<string, unknown> | undefined)?.[
|
||||
PLUGIN_ID
|
||||
];
|
||||
if (
|
||||
carried &&
|
||||
typeof carried === "object" &&
|
||||
Object.keys(carried).length > 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const values: Record<string, unknown> = {};
|
||||
const quickActions = readQuickActions(raw.quickActions);
|
||||
if (quickActions.length > 0) values.quickActions = quickActions;
|
||||
|
||||
let terminalConfig = raw.terminalConfig;
|
||||
if (typeof terminalConfig === "string") {
|
||||
try {
|
||||
terminalConfig = JSON.parse(terminalConfig);
|
||||
} catch {
|
||||
terminalConfig = null;
|
||||
}
|
||||
}
|
||||
const startup = readStartupSnippetId(
|
||||
(terminalConfig as { startupSnippetId?: unknown } | null)?.startupSnippetId,
|
||||
);
|
||||
if (startup !== null) values.startupSnippetId = startup;
|
||||
|
||||
return Object.keys(values).length > 0 ? values : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registered as "snippets.hostPayloadLegacy": quickActions and
|
||||
* terminalConfig.startupSnippetId in their 2.8 shape, for clients that
|
||||
* still read them (Termix-Mobile). Remove once the mobile app reads
|
||||
* pluginSettings.snippets.
|
||||
*/
|
||||
export function hostPayloadLegacy(
|
||||
values: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {
|
||||
quickActions: readQuickActions(values.quickActions),
|
||||
};
|
||||
const startup = readStartupSnippetId(values.startupSnippetId);
|
||||
if (startup !== null) out.terminalConfig = { startupSnippetId: startup };
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What hostSettingsSync needs from the repository. */
|
||||
export interface SnippetSyncLookup {
|
||||
findSyncIdById: (id: number) => Promise<string | null>;
|
||||
findIdBySyncId: (syncId: string) => Promise<number | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registered as "snippets.hostSettingsSync": both host settings hold local
|
||||
* snippet ids, so remote sync carries the snippets' sync ids instead, which
|
||||
* are the same on both sides.
|
||||
*/
|
||||
export function createHostSettingsSync(lookup: SnippetSyncLookup) {
|
||||
const toSyncId = async (id: number) => lookup.findSyncIdById(id);
|
||||
const toId = async (value: unknown) =>
|
||||
typeof value === "string" && value ? lookup.findIdBySyncId(value) : null;
|
||||
|
||||
return {
|
||||
exportValue: async (key: string, value: unknown) => {
|
||||
if (key === "startupSnippetId") {
|
||||
const id = readStartupSnippetId(value);
|
||||
return id === null ? null : await toSyncId(id);
|
||||
}
|
||||
if (key === "quickActions") {
|
||||
const actions = readQuickActions(value);
|
||||
const out = [];
|
||||
for (const action of actions) {
|
||||
const syncId = await toSyncId(action.snippetId);
|
||||
if (syncId) out.push({ name: action.name, snippetId: syncId });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
importValue: async (key: string, value: unknown) => {
|
||||
if (key === "startupSnippetId") return await toId(value);
|
||||
if (key === "quickActions") {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const out = [];
|
||||
for (const entry of value) {
|
||||
const row = (entry ?? {}) as { name?: unknown; snippetId?: unknown };
|
||||
const id = await toId(row.snippetId);
|
||||
if (id !== null) {
|
||||
out.push({
|
||||
name: typeof row.name === "string" ? row.name : "",
|
||||
snippetId: id,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import type { Router } from "express";
|
||||
import type { PluginContext } from "@termix/plugin-sdk/backend";
|
||||
import { snippetAccess, snippetFolders, snippets } from "./tables.js";
|
||||
import { createSnippetRepository } from "./repository.js";
|
||||
import { registerSnippetRoutes } from "./routes.js";
|
||||
import {
|
||||
extractSnippetInputs,
|
||||
resolveSnippetContent,
|
||||
} from "../shared/variables.js";
|
||||
import {
|
||||
createHostSettingsSync,
|
||||
hostImportNormalizer,
|
||||
hostPayloadLegacy,
|
||||
} from "./host-import.js";
|
||||
|
||||
/** What other plugins get from ctx.services.get("snippets.access", {userId}). */
|
||||
export interface SnippetsService {
|
||||
/** The calling user's own snippets (not shared ones), full content included. */
|
||||
list: () => Promise<
|
||||
Array<{
|
||||
id: number;
|
||||
name: string;
|
||||
content: string;
|
||||
description: string | null;
|
||||
isNote: boolean;
|
||||
folder: string | null;
|
||||
}>
|
||||
>;
|
||||
/** A snippet the calling user owns or was shared with them. */
|
||||
get: (id: number) => Promise<{
|
||||
id: number;
|
||||
name: string;
|
||||
content: string;
|
||||
isNote: boolean;
|
||||
} | null>;
|
||||
resolveCommand: (
|
||||
id: number,
|
||||
vars: { ip?: string; username?: string; port?: number; name?: string },
|
||||
inputValues?: Record<string, string>,
|
||||
) => Promise<string | null>;
|
||||
/** Creates a snippet owned by the calling user. */
|
||||
create: (input: {
|
||||
name: string;
|
||||
content: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
}) => Promise<{ id: number; name: string }>;
|
||||
/** Updates a snippet the calling user owns. Throws if not found. */
|
||||
update: (
|
||||
id: number,
|
||||
changes: {
|
||||
name?: string;
|
||||
content?: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
},
|
||||
) => Promise<void>;
|
||||
/** Deletes a snippet the calling user owns. Returns whether one was deleted. */
|
||||
remove: (id: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export async function activate(ctx: PluginContext) {
|
||||
const snippetsTable = await ctx.db.define(snippets);
|
||||
const foldersTable = await ctx.db.define(snippetFolders);
|
||||
const accessTable = await ctx.db.define(snippetAccess);
|
||||
|
||||
const repo = createSnippetRepository(
|
||||
ctx.db,
|
||||
snippetsTable,
|
||||
foldersTable,
|
||||
accessTable,
|
||||
);
|
||||
|
||||
registerSnippetRoutes(ctx.http.router<Router>(), repo, ctx);
|
||||
|
||||
ctx.sync.registerEntity({
|
||||
type: "snippetFolders",
|
||||
table: foldersTable,
|
||||
order: 40,
|
||||
});
|
||||
ctx.sync.registerEntity({
|
||||
type: "snippets",
|
||||
table: snippetsTable,
|
||||
order: 60,
|
||||
});
|
||||
|
||||
// Host settings that name a snippet by its local id, and the 2.8 host
|
||||
// fields they came from. Keybindings name one through the runSnippet
|
||||
// declaration in the manifest, which core translates over sync.
|
||||
ctx.registry.provide("snippets.hostImportNormalizer", hostImportNormalizer);
|
||||
ctx.registry.provide("snippets.hostPayloadLegacy", hostPayloadLegacy);
|
||||
ctx.registry.provide(
|
||||
"snippets.hostSettingsSync",
|
||||
createHostSettingsSync(repo),
|
||||
);
|
||||
|
||||
// $HOST and $INPUT_n handling for commands other plugins run (fleets). A
|
||||
// pure function, so it goes through the registry rather than a service
|
||||
// gated on snippets.view.
|
||||
ctx.registry.provide("snippets.variables", {
|
||||
resolve: resolveSnippetContent,
|
||||
extractInputs: extractSnippetInputs,
|
||||
});
|
||||
|
||||
// The user row survives a password-reset data wipe, so it never triggers
|
||||
// our refUser() cascade; this topic is core's way of telling us to drop
|
||||
// our copy of that user's data too.
|
||||
ctx.events.on("user.data_wiped", (payload) => {
|
||||
const userId = (payload as { userId?: string } | null)?.userId;
|
||||
if (userId) void repo.deleteByUserId(userId);
|
||||
});
|
||||
|
||||
async function findAccessible(userId: string, id: number) {
|
||||
const owned = await repo.findOwnedById(userId, id);
|
||||
if (owned) return owned;
|
||||
const roleIds = await repo.listUserRoleIds(userId);
|
||||
return repo.findAccessibleSharedSnippet(id, userId, roleIds);
|
||||
}
|
||||
|
||||
// The service is gated on snippets.view; a write also needs the same
|
||||
// permission its route requires, so a caller cannot write through here
|
||||
// what the user could not write in the panel.
|
||||
async function requirePermission(permission: string): Promise<void> {
|
||||
if (!(await ctx.rbac.has(permission))) {
|
||||
throw new Error(`Missing permission snippets.${permission}`);
|
||||
}
|
||||
}
|
||||
|
||||
const service: SnippetsService = {
|
||||
list: async () => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) return [];
|
||||
const owned = await repo.listOwnedSnippets(userId);
|
||||
return owned.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
content: s.content,
|
||||
description: s.description,
|
||||
isNote: s.isNote,
|
||||
folder: s.folder,
|
||||
}));
|
||||
},
|
||||
get: async (id) => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) return null;
|
||||
const snippet = await findAccessible(userId, id);
|
||||
if (!snippet) return null;
|
||||
return {
|
||||
id: snippet.id,
|
||||
name: snippet.name,
|
||||
content: snippet.content,
|
||||
isNote: snippet.isNote,
|
||||
};
|
||||
},
|
||||
resolveCommand: async (id, vars, inputValues = {}) => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) return null;
|
||||
const snippet = await findAccessible(userId, id);
|
||||
if (!snippet) return null;
|
||||
return resolveSnippetContent(snippet.content, vars, inputValues);
|
||||
},
|
||||
create: async (input) => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) throw new Error("snippets.access.create needs an actor");
|
||||
await requirePermission("create");
|
||||
const created = await repo.createSnippet(userId, input);
|
||||
return { id: created.id, name: created.name };
|
||||
},
|
||||
update: async (id, changes) => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) throw new Error("snippets.access.update needs an actor");
|
||||
await requirePermission("edit");
|
||||
const result = await repo.updateSnippet(userId, id, changes);
|
||||
if (!result) throw new Error("Snippet not found");
|
||||
},
|
||||
remove: async (id) => {
|
||||
const userId = ctx.currentActor();
|
||||
if (!userId) throw new Error("snippets.access.remove needs an actor");
|
||||
await requirePermission("delete");
|
||||
const existing = await repo.deleteSnippet(userId, id);
|
||||
return !!existing;
|
||||
},
|
||||
};
|
||||
ctx.services.provide("snippets.access", service);
|
||||
|
||||
ctx.log.info("Snippets routes mounted at /plugin-api/snippets");
|
||||
}
|
||||
|
||||
export async function deactivate() {
|
||||
// Everything above was registered through ctx and is disposed by core.
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { SnippetReorderUpdate } from "./repository.js";
|
||||
|
||||
type SnippetReorderRequestBody = {
|
||||
snippets?: unknown;
|
||||
updates?: unknown;
|
||||
};
|
||||
|
||||
export function extractSnippetReorderUpdates(
|
||||
body: unknown,
|
||||
): SnippetReorderUpdate[] | null {
|
||||
if (!body || typeof body !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = body as SnippetReorderRequestBody;
|
||||
// Keep accepting the legacy `updates` key so older clients do not break
|
||||
// while the web and desktop helpers converge on `snippets`.
|
||||
const snippetsUpdates = Array.isArray(payload.snippets)
|
||||
? payload.snippets
|
||||
: Array.isArray(payload.updates)
|
||||
? payload.updates
|
||||
: null;
|
||||
|
||||
if (!snippetsUpdates) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return snippetsUpdates as SnippetReorderUpdate[];
|
||||
}
|
||||
@@ -0,0 +1,917 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
desc,
|
||||
eq,
|
||||
gte,
|
||||
inArray,
|
||||
isNull,
|
||||
like,
|
||||
or,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import type { PluginDatabase } from "@termix/plugin-sdk/backend";
|
||||
|
||||
export interface SnippetRecord {
|
||||
id: number;
|
||||
userId: string;
|
||||
name: string;
|
||||
content: string;
|
||||
description: string | null;
|
||||
folder: string | null;
|
||||
order: number;
|
||||
syncId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
hostFilter: string | null;
|
||||
isNote: boolean;
|
||||
}
|
||||
|
||||
export interface SnippetFolderRecord {
|
||||
id: number;
|
||||
userId: string;
|
||||
name: string;
|
||||
color: string | null;
|
||||
icon: string | null;
|
||||
syncId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface RenameSnippetFolderResult {
|
||||
status: "renamed" | "missing" | "conflict";
|
||||
}
|
||||
|
||||
export interface SnippetReorderUpdate {
|
||||
id: number;
|
||||
order: number;
|
||||
folder?: string;
|
||||
}
|
||||
|
||||
export interface NewSnippetInput {
|
||||
name: string;
|
||||
content: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
order?: number | null;
|
||||
hostFilter?: unknown;
|
||||
isNote?: boolean;
|
||||
}
|
||||
|
||||
export interface SnippetUpdateInput {
|
||||
name?: string;
|
||||
content?: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
order?: number;
|
||||
hostFilter?: unknown;
|
||||
isNote?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateSnippetResult {
|
||||
existing: SnippetRecord;
|
||||
updated: SnippetRecord;
|
||||
}
|
||||
|
||||
export interface SnippetBulkImportResult {
|
||||
snippetsImported: number;
|
||||
snippetsSkipped: number;
|
||||
snippetsUpdated: number;
|
||||
foldersImported: number;
|
||||
foldersSkipped: number;
|
||||
failed: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
interface BulkImportSnippetInput {
|
||||
name?: unknown;
|
||||
content?: unknown;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
order?: unknown;
|
||||
hostFilter?: string | null;
|
||||
}
|
||||
|
||||
interface BulkImportFolderInput {
|
||||
name?: unknown;
|
||||
color?: string | null;
|
||||
icon?: string | null;
|
||||
}
|
||||
|
||||
export interface RbacAccessListItem {
|
||||
id: number;
|
||||
targetType: "user" | "role";
|
||||
userId: string | null;
|
||||
roleId: number | null;
|
||||
username: string | null;
|
||||
roleName: string | null;
|
||||
roleDisplayName: string | null;
|
||||
grantedBy: string;
|
||||
grantedByUsername: string | null;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export type SnippetAccessTarget =
|
||||
| { targetType: "user"; targetUserId: string }
|
||||
| { targetType: "role"; targetRoleId: number };
|
||||
|
||||
export type UpsertSnippetAccessInput = SnippetAccessTarget & {
|
||||
snippetId: number;
|
||||
grantedBy: string;
|
||||
expiresAt: string | null;
|
||||
};
|
||||
|
||||
export interface RbacSharedSnippet {
|
||||
id: number;
|
||||
name: string;
|
||||
content: string;
|
||||
description: string | null;
|
||||
folder: string | null;
|
||||
ownerUsername: string;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
export interface RbacVisibleSharedSnippet extends RbacSharedSnippet {
|
||||
userId: string;
|
||||
order: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
isNote: boolean;
|
||||
}
|
||||
|
||||
export interface RbacAccessibleSnippet extends RbacVisibleSharedSnippet {
|
||||
hostFilter: string | null;
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
// The tables come from ctx.db.define/ctx.db.refs, which the SDK hands back
|
||||
// untyped, and the drizzle handle is the server's own. Typed at this module's
|
||||
// edge instead.
|
||||
type Table = any;
|
||||
type Drizzle = any;
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function toAccessListItem(
|
||||
row: Omit<RbacAccessListItem, "targetType">,
|
||||
): RbacAccessListItem {
|
||||
return { ...row, targetType: row.userId ? "user" : "role" };
|
||||
}
|
||||
|
||||
export type SnippetRepository = ReturnType<typeof createSnippetRepository>;
|
||||
|
||||
/**
|
||||
* Snippet, folder and sharing storage. Written without RETURNING so it runs
|
||||
* the same on all three engines: an insert or update is read back by id/sync
|
||||
* id rather than relying on `.returning()`.
|
||||
*/
|
||||
export function createSnippetRepository(
|
||||
db: PluginDatabase,
|
||||
snippets: Table,
|
||||
folders: Table,
|
||||
access: Table,
|
||||
) {
|
||||
const client = () => db.client<Drizzle>();
|
||||
const refs = () =>
|
||||
db.refs<{ users: Table; roles: Table; userRoles: Table }>();
|
||||
|
||||
async function findOwnedById(
|
||||
userId: string,
|
||||
snippetId: number,
|
||||
): Promise<SnippetRecord | null> {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async function findFolderByName(
|
||||
userId: string,
|
||||
name: string,
|
||||
): Promise<SnippetFolderRecord | null> {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(and(eq(folders.userId, userId), eq(folders.name, name)))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async function maxOrderForFolder(
|
||||
userId: string,
|
||||
folder: string | null,
|
||||
): Promise<number> {
|
||||
const drizzle = await client();
|
||||
const result = await drizzle
|
||||
.select({ maxOrder: sql<number>`MAX(${snippets.order})` })
|
||||
.from(snippets)
|
||||
.where(
|
||||
and(
|
||||
eq(snippets.userId, userId),
|
||||
folder
|
||||
? eq(snippets.folder, folder)
|
||||
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
|
||||
),
|
||||
);
|
||||
return result[0]?.maxOrder ?? -1;
|
||||
}
|
||||
|
||||
async function nextOrderForFolder(
|
||||
userId: string,
|
||||
folder: string,
|
||||
): Promise<number> {
|
||||
return (await maxOrderForFolder(userId, folder || null)) + 1;
|
||||
}
|
||||
|
||||
async function findByNameAndFolder(
|
||||
userId: string,
|
||||
name: string,
|
||||
folder: string | null,
|
||||
): Promise<SnippetRecord | null> {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(
|
||||
and(
|
||||
eq(snippets.userId, userId),
|
||||
eq(snippets.name, name),
|
||||
folder
|
||||
? eq(snippets.folder, folder)
|
||||
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
function userOrRoleAccessFilter(userId: string, roleIds: number[]) {
|
||||
if (roleIds.length === 0) return eq(access.userId, userId);
|
||||
return or(eq(access.userId, userId), inArray(access.roleId, roleIds));
|
||||
}
|
||||
|
||||
async function findSnippetAccess(
|
||||
snippetId: number,
|
||||
target: SnippetAccessTarget,
|
||||
) {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(access)
|
||||
.where(
|
||||
and(
|
||||
eq(access.snippetId, snippetId),
|
||||
target.targetType === "user"
|
||||
? eq(access.userId, target.targetUserId)
|
||||
: eq(access.roleId, target.targetRoleId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
return {
|
||||
findOwnedById,
|
||||
|
||||
async listFolders(userId: string): Promise<SnippetFolderRecord[]> {
|
||||
const drizzle = await client();
|
||||
return drizzle
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(eq(folders.userId, userId))
|
||||
.orderBy(asc(folders.name));
|
||||
},
|
||||
|
||||
async listSnippetsForExport(userId: string): Promise<SnippetRecord[]> {
|
||||
const drizzle = await client();
|
||||
return drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(eq(snippets.userId, userId))
|
||||
.orderBy(sql`coalesce(${snippets.folder}, '')`, asc(snippets.order));
|
||||
},
|
||||
|
||||
async listFoldersForExport(userId: string): Promise<SnippetFolderRecord[]> {
|
||||
const drizzle = await client();
|
||||
return drizzle
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(eq(folders.userId, userId))
|
||||
.orderBy(asc(folders.name));
|
||||
},
|
||||
|
||||
async listOwnedSnippetsInFolder(
|
||||
userId: string,
|
||||
folder: string,
|
||||
): Promise<SnippetRecord[]> {
|
||||
const drizzle = await client();
|
||||
return drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(
|
||||
and(
|
||||
eq(snippets.userId, userId),
|
||||
or(
|
||||
eq(snippets.folder, folder),
|
||||
like(snippets.folder, `${folder} / %`),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
async listOwnedSnippets(userId: string): Promise<SnippetRecord[]> {
|
||||
const drizzle = await client();
|
||||
return drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(eq(snippets.userId, userId))
|
||||
.orderBy(
|
||||
sql`CASE WHEN ${snippets.folder} IS NULL OR ${snippets.folder} = '' THEN 0 ELSE 1 END`,
|
||||
asc(snippets.folder),
|
||||
asc(snippets.order),
|
||||
sql`${snippets.updatedAt} DESC`,
|
||||
);
|
||||
},
|
||||
|
||||
async reorderSnippets(
|
||||
userId: string,
|
||||
updates: SnippetReorderUpdate[],
|
||||
): Promise<void> {
|
||||
const drizzle = await client();
|
||||
for (const update of updates) {
|
||||
const { id, order, folder } = update;
|
||||
if (!id || order === undefined) continue;
|
||||
|
||||
const updateFields: Partial<{ order: number; folder: string | null }> =
|
||||
{
|
||||
order,
|
||||
};
|
||||
if (folder !== undefined) updateFields.folder = folder?.trim() || null;
|
||||
|
||||
await drizzle
|
||||
.update(snippets)
|
||||
.set(updateFields)
|
||||
.where(and(eq(snippets.id, id), eq(snippets.userId, userId)));
|
||||
}
|
||||
await db.persist();
|
||||
},
|
||||
|
||||
async createSnippet(
|
||||
userId: string,
|
||||
input: NewSnippetInput,
|
||||
): Promise<SnippetRecord> {
|
||||
const folderValue = input.folder?.trim() || "";
|
||||
const order =
|
||||
input.order === undefined || input.order === null
|
||||
? await nextOrderForFolder(userId, folderValue)
|
||||
: input.order;
|
||||
|
||||
const syncId = randomUUID();
|
||||
const drizzle = await client();
|
||||
await drizzle.insert(snippets).values({
|
||||
syncId,
|
||||
userId,
|
||||
name: input.name.trim(),
|
||||
content: input.content.trim(),
|
||||
description: input.description?.trim() || null,
|
||||
folder: input.folder?.trim() || null,
|
||||
order,
|
||||
hostFilter: input.hostFilter ? JSON.stringify(input.hostFilter) : null,
|
||||
isNote: input.isNote ?? false,
|
||||
});
|
||||
await db.persist();
|
||||
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(eq(snippets.syncId, syncId))
|
||||
.limit(1);
|
||||
return rows[0];
|
||||
},
|
||||
|
||||
async updateSnippet(
|
||||
userId: string,
|
||||
snippetId: number,
|
||||
input: SnippetUpdateInput,
|
||||
): Promise<UpdateSnippetResult | null> {
|
||||
const existing = await findOwnedById(userId, snippetId);
|
||||
if (!existing) return null;
|
||||
|
||||
const updateFields: Record<string, unknown> = {
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
};
|
||||
if (input.name !== undefined) updateFields.name = input.name.trim();
|
||||
if (input.content !== undefined)
|
||||
updateFields.content = input.content.trim();
|
||||
if (input.description !== undefined)
|
||||
updateFields.description = input.description?.trim() || null;
|
||||
if (input.folder !== undefined)
|
||||
updateFields.folder = input.folder?.trim() || null;
|
||||
if (input.order !== undefined) updateFields.order = input.order;
|
||||
if (input.hostFilter !== undefined)
|
||||
updateFields.hostFilter = input.hostFilter
|
||||
? JSON.stringify(input.hostFilter)
|
||||
: null;
|
||||
if (input.isNote !== undefined) updateFields.isNote = input.isNote;
|
||||
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.update(snippets)
|
||||
.set(updateFields)
|
||||
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)));
|
||||
await db.persist();
|
||||
|
||||
const updated = await findOwnedById(userId, snippetId);
|
||||
return { existing, updated: updated as SnippetRecord };
|
||||
},
|
||||
|
||||
async deleteSnippet(
|
||||
userId: string,
|
||||
snippetId: number,
|
||||
): Promise<SnippetRecord | null> {
|
||||
const existing = await findOwnedById(userId, snippetId);
|
||||
if (!existing) return null;
|
||||
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.delete(snippets)
|
||||
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)));
|
||||
await db.persist();
|
||||
return existing;
|
||||
},
|
||||
|
||||
async bulkImport(
|
||||
userId: string,
|
||||
snippetsToImport: unknown[] | undefined,
|
||||
foldersToImport: unknown[] | undefined,
|
||||
overwrite: boolean,
|
||||
): Promise<SnippetBulkImportResult> {
|
||||
const results: SnippetBulkImportResult = {
|
||||
snippetsImported: 0,
|
||||
snippetsSkipped: 0,
|
||||
snippetsUpdated: 0,
|
||||
foldersImported: 0,
|
||||
foldersSkipped: 0,
|
||||
failed: 0,
|
||||
errors: [],
|
||||
};
|
||||
|
||||
const drizzle = await client();
|
||||
let changed = false;
|
||||
|
||||
if (Array.isArray(foldersToImport)) {
|
||||
for (const rawFolder of foldersToImport) {
|
||||
const folder = rawFolder as BulkImportFolderInput;
|
||||
if (!isNonEmptyString(folder.name)) {
|
||||
results.failed++;
|
||||
results.errors.push(`Folder missing name`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = await findFolderByName(userId, folder.name);
|
||||
if (existing) {
|
||||
results.foldersSkipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await drizzle.insert(folders).values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: folder.name.trim(),
|
||||
color: folder.color?.trim() || null,
|
||||
icon: folder.icon?.trim() || null,
|
||||
});
|
||||
changed = true;
|
||||
results.foldersImported++;
|
||||
}
|
||||
}
|
||||
|
||||
if (Array.isArray(snippetsToImport)) {
|
||||
for (let i = 0; i < snippetsToImport.length; i++) {
|
||||
const snippet = snippetsToImport[i] as BulkImportSnippetInput;
|
||||
|
||||
if (
|
||||
!isNonEmptyString(snippet.name) ||
|
||||
!isNonEmptyString(snippet.content)
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Snippet ${i + 1}: name and content are required`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const folderVal = snippet.folder?.trim() || null;
|
||||
const existing = await findByNameAndFolder(
|
||||
userId,
|
||||
snippet.name.trim(),
|
||||
folderVal,
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
if (!overwrite) {
|
||||
results.snippetsSkipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await drizzle
|
||||
.update(snippets)
|
||||
.set({
|
||||
content: snippet.content.trim(),
|
||||
description: snippet.description?.trim() || null,
|
||||
folder: folderVal,
|
||||
order:
|
||||
typeof snippet.order === "number"
|
||||
? snippet.order
|
||||
: existing.order,
|
||||
hostFilter: snippet.hostFilter || null,
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
})
|
||||
.where(
|
||||
and(eq(snippets.id, existing.id), eq(snippets.userId, userId)),
|
||||
);
|
||||
changed = true;
|
||||
results.snippetsUpdated++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const maxOrder = await maxOrderForFolder(userId, folderVal);
|
||||
await drizzle.insert(snippets).values({
|
||||
syncId: randomUUID(),
|
||||
userId,
|
||||
name: snippet.name.trim(),
|
||||
content: snippet.content.trim(),
|
||||
description: snippet.description?.trim() || null,
|
||||
folder: folderVal,
|
||||
order:
|
||||
typeof snippet.order === "number" ? snippet.order : maxOrder + 1,
|
||||
hostFilter: snippet.hostFilter || null,
|
||||
});
|
||||
changed = true;
|
||||
results.snippetsImported++;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) await db.persist();
|
||||
return results;
|
||||
},
|
||||
|
||||
async createFolder(
|
||||
userId: string,
|
||||
name: string,
|
||||
color: string | null | undefined,
|
||||
icon: string | null | undefined,
|
||||
): Promise<SnippetFolderRecord | null> {
|
||||
const existing = await findFolderByName(userId, name);
|
||||
if (existing) return null;
|
||||
|
||||
const syncId = randomUUID();
|
||||
const drizzle = await client();
|
||||
await drizzle.insert(folders).values({
|
||||
syncId,
|
||||
userId,
|
||||
name: name.trim(),
|
||||
color: color?.trim() || null,
|
||||
icon: icon?.trim() || null,
|
||||
});
|
||||
await db.persist();
|
||||
|
||||
const rows = await drizzle
|
||||
.select()
|
||||
.from(folders)
|
||||
.where(eq(folders.syncId, syncId))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
},
|
||||
|
||||
async updateFolderMetadata(
|
||||
userId: string,
|
||||
name: string,
|
||||
color: string | null | undefined,
|
||||
icon: string | null | undefined,
|
||||
): Promise<SnippetFolderRecord | null> {
|
||||
const existing = await findFolderByName(userId, name);
|
||||
if (!existing) return null;
|
||||
|
||||
const updateFields: Record<string, unknown> = {
|
||||
updatedAt: sql`CURRENT_TIMESTAMP`,
|
||||
};
|
||||
if (color !== undefined) updateFields.color = color?.trim() || null;
|
||||
if (icon !== undefined) updateFields.icon = icon?.trim() || null;
|
||||
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.update(folders)
|
||||
.set(updateFields)
|
||||
.where(and(eq(folders.userId, userId), eq(folders.name, name)));
|
||||
await db.persist();
|
||||
|
||||
return findFolderByName(userId, name);
|
||||
},
|
||||
|
||||
async renameFolder(
|
||||
userId: string,
|
||||
oldName: string,
|
||||
newName: string,
|
||||
): Promise<RenameSnippetFolderResult> {
|
||||
const existing = await findFolderByName(userId, oldName);
|
||||
if (!existing) return { status: "missing" };
|
||||
|
||||
const nameExists = await findFolderByName(userId, newName);
|
||||
if (nameExists) return { status: "conflict" };
|
||||
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.update(folders)
|
||||
.set({ name: newName, updatedAt: sql`CURRENT_TIMESTAMP` })
|
||||
.where(and(eq(folders.userId, userId), eq(folders.name, oldName)));
|
||||
|
||||
await drizzle
|
||||
.update(snippets)
|
||||
.set({ folder: newName })
|
||||
.where(and(eq(snippets.userId, userId), eq(snippets.folder, oldName)));
|
||||
|
||||
await db.persist();
|
||||
return { status: "renamed" };
|
||||
},
|
||||
|
||||
async deleteFolder(
|
||||
userId: string,
|
||||
name: string,
|
||||
): Promise<{ syncId: string | null } | null> {
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.update(snippets)
|
||||
.set({ folder: null })
|
||||
.where(and(eq(snippets.userId, userId), eq(snippets.folder, name)));
|
||||
|
||||
const existing = await findFolderByName(userId, name);
|
||||
if (!existing) {
|
||||
await db.persist();
|
||||
return null;
|
||||
}
|
||||
|
||||
await drizzle
|
||||
.delete(folders)
|
||||
.where(and(eq(folders.userId, userId), eq(folders.name, name)));
|
||||
await db.persist();
|
||||
return { syncId: existing.syncId };
|
||||
},
|
||||
|
||||
/** Wipes a user's snippets and folders, for the password-reset data-wipe flow. */
|
||||
async deleteByUserId(userId: string): Promise<void> {
|
||||
const drizzle = await client();
|
||||
await drizzle.delete(snippets).where(eq(snippets.userId, userId));
|
||||
await drizzle.delete(folders).where(eq(folders.userId, userId));
|
||||
await db.persist();
|
||||
},
|
||||
|
||||
// Sharing (moved from core's RbacAccessRepository)
|
||||
|
||||
async listSnippetAccess(snippetId: number): Promise<RbacAccessListItem[]> {
|
||||
const drizzle = await client();
|
||||
const { users, roles } = await refs();
|
||||
const rows = await drizzle
|
||||
.select({
|
||||
id: access.id,
|
||||
userId: access.userId,
|
||||
roleId: access.roleId,
|
||||
username: users.username,
|
||||
roleName: roles.name,
|
||||
roleDisplayName: roles.displayName,
|
||||
grantedBy: access.grantedBy,
|
||||
grantedByUsername: sql<
|
||||
string | null
|
||||
>`(SELECT username FROM users WHERE id = ${access.grantedBy})`,
|
||||
permissionLevel: access.permissionLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
createdAt: access.createdAt,
|
||||
})
|
||||
.from(access)
|
||||
.leftJoin(users, eq(access.userId, users.id))
|
||||
.leftJoin(roles, eq(access.roleId, roles.id))
|
||||
.where(eq(access.snippetId, snippetId))
|
||||
.orderBy(desc(access.createdAt));
|
||||
|
||||
return rows.map(toAccessListItem);
|
||||
},
|
||||
|
||||
async upsertSnippetAccess(
|
||||
input: UpsertSnippetAccessInput,
|
||||
): Promise<{ id: number; created: boolean }> {
|
||||
const existing = await findSnippetAccess(input.snippetId, input);
|
||||
const drizzle = await client();
|
||||
|
||||
if (existing) {
|
||||
await drizzle
|
||||
.update(access)
|
||||
.set({ expiresAt: input.expiresAt })
|
||||
.where(eq(access.id, existing.id));
|
||||
await db.persist();
|
||||
return { id: existing.id, created: false };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
await drizzle.insert(access).values({
|
||||
snippetId: input.snippetId,
|
||||
userId: input.targetType === "user" ? input.targetUserId : null,
|
||||
roleId: input.targetType === "role" ? input.targetRoleId : null,
|
||||
grantedBy: input.grantedBy,
|
||||
permissionLevel: "view",
|
||||
expiresAt: input.expiresAt,
|
||||
createdAt: now,
|
||||
});
|
||||
await db.persist();
|
||||
|
||||
const created = await findSnippetAccess(input.snippetId, input);
|
||||
return { id: created!.id, created: true };
|
||||
},
|
||||
|
||||
async revokeSnippetAccess(
|
||||
accessId: number,
|
||||
snippetId: number,
|
||||
): Promise<void> {
|
||||
const drizzle = await client();
|
||||
await drizzle
|
||||
.delete(access)
|
||||
.where(and(eq(access.id, accessId), eq(access.snippetId, snippetId)));
|
||||
await db.persist();
|
||||
},
|
||||
|
||||
async listSharedSnippets(
|
||||
userId: string,
|
||||
roleIds: number[],
|
||||
now = new Date().toISOString(),
|
||||
): Promise<RbacSharedSnippet[]> {
|
||||
const drizzle = await client();
|
||||
const { users } = await refs();
|
||||
|
||||
const directShared = await drizzle
|
||||
.select({
|
||||
id: snippets.id,
|
||||
name: snippets.name,
|
||||
content: snippets.content,
|
||||
description: snippets.description,
|
||||
folder: snippets.folder,
|
||||
ownerUsername: users.username,
|
||||
permissionLevel: access.permissionLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
})
|
||||
.from(access)
|
||||
.innerJoin(snippets, eq(access.snippetId, snippets.id))
|
||||
.innerJoin(users, eq(snippets.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
eq(access.userId, userId),
|
||||
or(isNull(access.expiresAt), gte(access.expiresAt, now)),
|
||||
),
|
||||
);
|
||||
|
||||
if (roleIds.length === 0) return directShared;
|
||||
|
||||
const directIds = new Set(directShared.map((s: { id: number }) => s.id));
|
||||
const roleShared = await drizzle
|
||||
.select({
|
||||
id: snippets.id,
|
||||
name: snippets.name,
|
||||
content: snippets.content,
|
||||
description: snippets.description,
|
||||
folder: snippets.folder,
|
||||
ownerUsername: users.username,
|
||||
permissionLevel: access.permissionLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
})
|
||||
.from(access)
|
||||
.innerJoin(snippets, eq(access.snippetId, snippets.id))
|
||||
.innerJoin(users, eq(snippets.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
or(isNull(access.expiresAt), gte(access.expiresAt, now)),
|
||||
inArray(access.roleId, roleIds),
|
||||
),
|
||||
);
|
||||
|
||||
return [
|
||||
...directShared,
|
||||
...roleShared.filter((s: { id: number }) => !directIds.has(s.id)),
|
||||
];
|
||||
},
|
||||
|
||||
async listVisibleSharedSnippets(
|
||||
userId: string,
|
||||
roleIds: number[],
|
||||
now = new Date().toISOString(),
|
||||
): Promise<RbacVisibleSharedSnippet[]> {
|
||||
const drizzle = await client();
|
||||
const { users } = await refs();
|
||||
return drizzle
|
||||
.select({
|
||||
id: snippets.id,
|
||||
userId: snippets.userId,
|
||||
name: snippets.name,
|
||||
content: snippets.content,
|
||||
description: snippets.description,
|
||||
folder: snippets.folder,
|
||||
order: snippets.order,
|
||||
createdAt: snippets.createdAt,
|
||||
updatedAt: snippets.updatedAt,
|
||||
isNote: snippets.isNote,
|
||||
ownerUsername: users.username,
|
||||
permissionLevel: access.permissionLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
})
|
||||
.from(access)
|
||||
.innerJoin(snippets, eq(access.snippetId, snippets.id))
|
||||
.innerJoin(users, eq(snippets.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
userOrRoleAccessFilter(userId, roleIds),
|
||||
or(isNull(access.expiresAt), gte(access.expiresAt, now)),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
async findAccessibleSharedSnippet(
|
||||
snippetId: number,
|
||||
userId: string,
|
||||
roleIds: number[],
|
||||
now = new Date().toISOString(),
|
||||
): Promise<RbacAccessibleSnippet | null> {
|
||||
const drizzle = await client();
|
||||
const { users } = await refs();
|
||||
const rows = await drizzle
|
||||
.select({
|
||||
id: snippets.id,
|
||||
userId: snippets.userId,
|
||||
name: snippets.name,
|
||||
content: snippets.content,
|
||||
description: snippets.description,
|
||||
folder: snippets.folder,
|
||||
order: snippets.order,
|
||||
createdAt: snippets.createdAt,
|
||||
updatedAt: snippets.updatedAt,
|
||||
hostFilter: snippets.hostFilter,
|
||||
isNote: snippets.isNote,
|
||||
ownerUsername: users.username,
|
||||
permissionLevel: access.permissionLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
})
|
||||
.from(access)
|
||||
.innerJoin(snippets, eq(access.snippetId, snippets.id))
|
||||
.innerJoin(users, eq(snippets.userId, users.id))
|
||||
.where(
|
||||
and(
|
||||
eq(access.snippetId, snippetId),
|
||||
userOrRoleAccessFilter(userId, roleIds),
|
||||
or(isNull(access.expiresAt), gte(access.expiresAt, now)),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return rows[0] ?? null;
|
||||
},
|
||||
|
||||
/** A snippet's sync id, for a host setting that names it over sync. */
|
||||
async findSyncIdById(snippetId: number): Promise<string | null> {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select({ syncId: snippets.syncId })
|
||||
.from(snippets)
|
||||
.where(eq(snippets.id, snippetId))
|
||||
.limit(1);
|
||||
return (rows[0]?.syncId as string | null | undefined) ?? null;
|
||||
},
|
||||
|
||||
async findIdBySyncId(syncId: string): Promise<number | null> {
|
||||
const drizzle = await client();
|
||||
const rows = await drizzle
|
||||
.select({ id: snippets.id })
|
||||
.from(snippets)
|
||||
.where(eq(snippets.syncId, syncId))
|
||||
.limit(1);
|
||||
return (rows[0]?.id as number | undefined) ?? null;
|
||||
},
|
||||
|
||||
/** A user's role ids, for the sharing filters above. */
|
||||
async listUserRoleIds(userId: string): Promise<number[]> {
|
||||
const drizzle = await client();
|
||||
const { userRoles } = await refs();
|
||||
const rows = await drizzle
|
||||
.select({ roleId: userRoles.roleId })
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId));
|
||||
return rows.map((r: { roleId: number }) => r.roleId);
|
||||
},
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
adoptLegacyTable,
|
||||
boolean,
|
||||
defineTable,
|
||||
id,
|
||||
integer,
|
||||
refUser,
|
||||
text,
|
||||
timestamp,
|
||||
varchar,
|
||||
} from "@termix/plugin-sdk/db";
|
||||
|
||||
export const snippets = adoptLegacyTable(
|
||||
"snippets",
|
||||
defineTable(
|
||||
"snippets",
|
||||
{
|
||||
id: id(),
|
||||
userId: refUser(),
|
||||
name: text().notNull(),
|
||||
content: text().notNull(),
|
||||
description: text(),
|
||||
folder: text(),
|
||||
order: integer().notNull().default(0),
|
||||
syncId: varchar().unique(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
hostFilter: text(),
|
||||
isNote: boolean().notNull().default(false),
|
||||
},
|
||||
{ indexes: [{ name: "idx_snippets_user_id", columns: ["userId"] }] },
|
||||
),
|
||||
);
|
||||
|
||||
export const snippetFolders = adoptLegacyTable(
|
||||
"snippet_folders",
|
||||
defineTable("snippet_folders", {
|
||||
id: id(),
|
||||
userId: refUser(),
|
||||
name: text().notNull(),
|
||||
color: text(),
|
||||
icon: text(),
|
||||
syncId: varchar().unique(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
updatedAt: timestamp().notNull().defaultNow(),
|
||||
}),
|
||||
);
|
||||
|
||||
export const snippetAccess = adoptLegacyTable(
|
||||
"snippet_access",
|
||||
defineTable(
|
||||
"snippet_access",
|
||||
{
|
||||
id: id(),
|
||||
snippetId: integer().notNull(),
|
||||
userId: varchar(),
|
||||
roleId: integer(),
|
||||
grantedBy: refUser(),
|
||||
permissionLevel: text().notNull().default("view"),
|
||||
expiresAt: timestamp(),
|
||||
createdAt: timestamp().notNull().defaultNow(),
|
||||
},
|
||||
{
|
||||
indexes: [
|
||||
{ name: "idx_snippet_access_user_id", columns: ["userId"] },
|
||||
{ name: "idx_snippet_access_snippet_id", columns: ["snippetId"] },
|
||||
{ name: "idx_snippet_access_role_id", columns: ["roleId"] },
|
||||
],
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export const tables = [snippets, snippetFolders, snippetAccess];
|
||||
@@ -0,0 +1,237 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Pencil, Plus, RefreshCw, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
usePluginApi,
|
||||
useTranslation,
|
||||
type PluginApiClient,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { Button, Input, useConfirmation } from "@termix/plugin-sdk/ui";
|
||||
|
||||
// Core's admin routes act on another user's data when this header names them.
|
||||
export const ADMIN_TARGET_USER_HEADER = "X-Admin-Target-User";
|
||||
|
||||
export function adminOptions(targetUserId: string) {
|
||||
return { headers: { [ADMIN_TARGET_USER_HEADER]: targetUserId } };
|
||||
}
|
||||
|
||||
interface ManagedSnippet {
|
||||
id: number;
|
||||
name: string;
|
||||
content: string;
|
||||
folder?: string | null;
|
||||
}
|
||||
|
||||
export function mapSnippets(res: unknown): ManagedSnippet[] {
|
||||
const list = Array.isArray(res)
|
||||
? res
|
||||
: ((res as { snippets?: unknown[] })?.snippets ?? []);
|
||||
return (list as Record<string, unknown>[]).map((s) => ({
|
||||
id: Number(s.id),
|
||||
name: String(s.name ?? ""),
|
||||
content: String(s.content ?? ""),
|
||||
folder: (s.folder as string | null) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown, fallback: string): string {
|
||||
return (
|
||||
(error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error || fallback
|
||||
);
|
||||
}
|
||||
|
||||
async function load(api: PluginApiClient, userId: string) {
|
||||
return mapSnippets((await api.get("/", adminOptions(userId))).data);
|
||||
}
|
||||
|
||||
/** The Snippets tab of the admin "manage user" panel. */
|
||||
export function AdminUserSnippets({
|
||||
user,
|
||||
}: {
|
||||
user: { id: string; username: string };
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const { confirmWithToast } = useConfirmation();
|
||||
const [snippets, setSnippets] = useState<ManagedSnippet[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editing, setEditing] = useState<ManagedSnippet | "new" | null>(null);
|
||||
const [form, setForm] = useState({ name: "", content: "", folder: "" });
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const reload = useCallback(() => {
|
||||
setLoading(true);
|
||||
load(api, user.id)
|
||||
.then(setSnippets)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, [api, user.id]);
|
||||
|
||||
useEffect(() => {
|
||||
reload();
|
||||
}, [reload]);
|
||||
|
||||
async function save() {
|
||||
if (!form.name.trim() || !form.content.trim()) {
|
||||
toast.error(t("admin.requiredFields"));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
name: form.name.trim(),
|
||||
content: form.content,
|
||||
folder: form.folder.trim() || null,
|
||||
};
|
||||
if (editing && editing !== "new") {
|
||||
await api.put(`/${editing.id}`, payload, adminOptions(user.id));
|
||||
} else {
|
||||
await api.post("/", payload, adminOptions(user.id));
|
||||
}
|
||||
setEditing(null);
|
||||
reload();
|
||||
toast.success(t("admin.saved"));
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error, t("admin.saveFailed")));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function remove(snippet: ManagedSnippet) {
|
||||
confirmWithToast(
|
||||
t("admin.deleteConfirm", { name: snippet.name, username: user.username }),
|
||||
async () => {
|
||||
try {
|
||||
await api.delete(`/${snippet.id}`, adminOptions(user.id));
|
||||
setSnippets((prev) => prev.filter((s) => s.id !== snippet.id));
|
||||
toast.success(t("admin.deleted"));
|
||||
} catch (error) {
|
||||
toast.error(errorMessage(error, t("admin.deleteFailed")));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center justify-between py-2 border-b border-border">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{t("admin.count", { count: snippets.length })}
|
||||
</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 text-muted-foreground hover:text-foreground"
|
||||
onClick={reload}
|
||||
>
|
||||
<RefreshCw className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
onClick={() => {
|
||||
setForm({ name: "", content: "", folder: "" });
|
||||
setEditing("new");
|
||||
}}
|
||||
>
|
||||
<Plus className="size-3" />
|
||||
{t("admin.add")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{editing && (
|
||||
<div className="flex flex-col gap-2.5 py-3 border-b border-border">
|
||||
<Input
|
||||
className="h-8 text-xs"
|
||||
placeholder={t("admin.namePlaceholder")}
|
||||
value={form.name}
|
||||
onChange={(e) => setForm((p) => ({ ...p, name: e.target.value }))}
|
||||
/>
|
||||
<textarea
|
||||
rows={4}
|
||||
placeholder={t("admin.contentPlaceholder")}
|
||||
value={form.content}
|
||||
onChange={(e) =>
|
||||
setForm((p) => ({ ...p, content: e.target.value }))
|
||||
}
|
||||
className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
|
||||
/>
|
||||
<Input
|
||||
className="h-8 text-xs"
|
||||
placeholder={t("admin.folderPlaceholder")}
|
||||
value={form.folder}
|
||||
onChange={(e) => setForm((p) => ({ ...p, folder: e.target.value }))}
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 text-[10px]"
|
||||
onClick={() => setEditing(null)}
|
||||
>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
disabled={saving}
|
||||
onClick={save}
|
||||
>
|
||||
{saving ? t("admin.saving") : t("admin.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!loading && snippets.length === 0 && !editing && (
|
||||
<span className="text-xs text-muted-foreground py-3">
|
||||
{t("admin.empty")}
|
||||
</span>
|
||||
)}
|
||||
{snippets.map((snippet) => (
|
||||
<div
|
||||
key={snippet.id}
|
||||
className="flex items-center justify-between py-2.5 border-b border-border last:border-0"
|
||||
>
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="text-xs font-semibold truncate max-w-[180px]">
|
||||
{snippet.name}
|
||||
</span>
|
||||
<span className="text-[10px] font-mono text-muted-foreground truncate max-w-[220px]">
|
||||
{snippet.content}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-0.5 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setForm({
|
||||
name: snippet.name,
|
||||
content: snippet.content,
|
||||
folder: snippet.folder ?? "",
|
||||
});
|
||||
setEditing(snippet);
|
||||
}}
|
||||
>
|
||||
<Pencil className="size-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 text-muted-foreground hover:text-destructive"
|
||||
onClick={() => remove(snippet)}
|
||||
>
|
||||
<Trash2 className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { Loader2, Server } from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
|
||||
export interface HostExecutionResult {
|
||||
hostId: number;
|
||||
hostLabel: string;
|
||||
/** Null while the command is still running on this host. */
|
||||
success: boolean | null;
|
||||
output: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function ExecutionResultsDialog({
|
||||
snippetName,
|
||||
results,
|
||||
onClose,
|
||||
}: {
|
||||
snippetName: string;
|
||||
results: HostExecutionResult[];
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg font-bold">
|
||||
{t("executionResultTitle", { name: snippetName })}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground">
|
||||
{t("executionResultDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col border border-border max-h-96 overflow-y-auto">
|
||||
{results.map((result) => (
|
||||
<div
|
||||
key={result.hostId}
|
||||
className="flex flex-col gap-1.5 p-2.5 border-b border-border/40 last:border-b-0"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="size-3 shrink-0 text-muted-foreground" />
|
||||
<span className="text-xs font-semibold truncate flex-1">
|
||||
{result.hostLabel}
|
||||
</span>
|
||||
{result.success === null ? (
|
||||
<Loader2 className="size-3.5 animate-spin text-muted-foreground" />
|
||||
) : (
|
||||
<span
|
||||
className={`text-[9px] px-1 py-px border uppercase tracking-wider shrink-0 ${
|
||||
result.success
|
||||
? "border-green-500/30 bg-green-500/10 text-green-500"
|
||||
: "border-destructive/30 bg-destructive/10 text-destructive"
|
||||
}`}
|
||||
>
|
||||
{t(result.success ? "executionSuccess" : "executionFailed")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(result.output || result.error) && (
|
||||
<pre className="text-[11px] bg-muted/30 p-2 overflow-x-auto whitespace-pre-wrap font-mono text-muted-foreground max-h-40">
|
||||
{result.error || result.output}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("close")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { Plus, Play, Trash2, Zap } from "lucide-react";
|
||||
import {
|
||||
useTranslation,
|
||||
type HostEditorSectionProps,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
Button,
|
||||
HostDefaultBadge,
|
||||
HostDefaultField,
|
||||
Input,
|
||||
SectionCard,
|
||||
Select2,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { PLUGIN_ID, readStartupSnippetId } from "../shared/host-settings.js";
|
||||
import { useSnippetOptions } from "./use-snippet-options";
|
||||
|
||||
type PluginSettingsBag = Record<string, Record<string, unknown>>;
|
||||
|
||||
/** A quick action row while it is being edited: the snippet may be unset. */
|
||||
interface QuickActionRow {
|
||||
name: string;
|
||||
snippetId: number | null;
|
||||
}
|
||||
|
||||
function readRows(value: unknown): QuickActionRow[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((entry) => {
|
||||
const row = (entry ?? {}) as { name?: unknown; snippetId?: unknown };
|
||||
const id = Number(row.snippetId);
|
||||
return {
|
||||
name: typeof row.name === "string" ? row.name : "",
|
||||
snippetId: Number.isInteger(id) && id > 0 ? id : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The host editor's Snippets tab: the snippet a terminal runs when it
|
||||
* connects, and the quick action buttons Host Metrics shows for the host.
|
||||
* Both are this plugin's host settings, saved with the host.
|
||||
*/
|
||||
export function HostSnippetsSection({
|
||||
form,
|
||||
updateForm,
|
||||
adminTargetUserId,
|
||||
}: HostEditorSectionProps) {
|
||||
const { t } = useTranslation();
|
||||
const { options } = useSnippetOptions(adminTargetUserId);
|
||||
const own =
|
||||
(form.pluginSettings as PluginSettingsBag | undefined)?.[PLUGIN_ID] ?? {};
|
||||
const startupSnippetId = readStartupSnippetId(own.startupSnippetId);
|
||||
const quickActions = readRows(own.quickActions);
|
||||
|
||||
const write = (values: Record<string, unknown>) =>
|
||||
updateForm((current) => {
|
||||
const all =
|
||||
(current.pluginSettings as PluginSettingsBag | undefined) ?? {};
|
||||
return {
|
||||
...current,
|
||||
pluginSettings: {
|
||||
...all,
|
||||
[PLUGIN_ID]: { ...(all[PLUGIN_ID] ?? {}), ...values },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const setQuickActions = (rows: QuickActionRow[]) =>
|
||||
write({ quickActions: rows });
|
||||
|
||||
return (
|
||||
<>
|
||||
<HostDefaultField settingKey="startupSnippetId">
|
||||
<SectionCard
|
||||
title={t("host.startupTitle")}
|
||||
icon={<Play className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-1.5 py-3">
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{t("host.startupDescription")}
|
||||
<HostDefaultBadge settingKey="startupSnippetId" />
|
||||
</p>
|
||||
<Select2
|
||||
aria-label={t("host.startupTitle")}
|
||||
value={startupSnippetId ?? ""}
|
||||
onChange={(e) =>
|
||||
write({
|
||||
startupSnippetId: e.target.value
|
||||
? Number(e.target.value)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
<option value="">{t("host.none")}</option>
|
||||
{options.map((snippet) => (
|
||||
<option key={snippet.id} value={snippet.id}>
|
||||
{snippet.name}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
</div>
|
||||
</SectionCard>
|
||||
</HostDefaultField>
|
||||
<HostDefaultField settingKey="quickActions">
|
||||
<SectionCard
|
||||
title={t("host.quickActionsTitle")}
|
||||
icon={<Zap className="size-3.5" />}
|
||||
action={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
|
||||
onClick={() =>
|
||||
setQuickActions([
|
||||
...quickActions,
|
||||
{ name: "", snippetId: null },
|
||||
])
|
||||
}
|
||||
>
|
||||
<Plus className="size-3 mr-1" /> {t("host.addQuickAction")}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-3 py-3">
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
{t("host.quickActionsDescription")}
|
||||
<HostDefaultBadge settingKey="quickActions" />
|
||||
</p>
|
||||
{quickActions.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center py-4 text-muted-foreground/40 gap-1.5">
|
||||
<Zap className="size-6" />
|
||||
<span className="text-xs">{t("host.noQuickActions")}</span>
|
||||
</div>
|
||||
)}
|
||||
{quickActions.map((row, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center gap-2 p-2 bg-muted/20 border border-border group"
|
||||
>
|
||||
<Input
|
||||
className="h-7 text-xs flex-1"
|
||||
placeholder={t("host.buttonLabel")}
|
||||
value={row.name}
|
||||
onChange={(e) => {
|
||||
const next = [...quickActions];
|
||||
next[index] = { ...row, name: e.target.value };
|
||||
setQuickActions(next);
|
||||
}}
|
||||
/>
|
||||
<Select2
|
||||
aria-label={t("host.selectSnippet")}
|
||||
className="h-7 text-xs flex-1 border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
|
||||
value={row.snippetId ?? ""}
|
||||
onChange={(e) => {
|
||||
const next = [...quickActions];
|
||||
next[index] = {
|
||||
...row,
|
||||
snippetId: e.target.value ? Number(e.target.value) : null,
|
||||
};
|
||||
setQuickActions(next);
|
||||
}}
|
||||
>
|
||||
<option value="">{t("host.selectSnippet")}</option>
|
||||
{options.map((snippet) => (
|
||||
<option key={snippet.id} value={snippet.id}>
|
||||
{snippet.name}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("host.removeQuickAction")}
|
||||
className="text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
onClick={() =>
|
||||
setQuickActions(quickActions.filter((_, i) => i !== index))
|
||||
}
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</SectionCard>
|
||||
</HostDefaultField>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { RefreshCw } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
usePermission,
|
||||
usePluginApi,
|
||||
useTranslation,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { Button, Separator } from "@termix/plugin-sdk/ui";
|
||||
import {
|
||||
readQuickActions,
|
||||
snippetHostSettings,
|
||||
type QuickAction,
|
||||
} from "../shared/host-settings.js";
|
||||
import { hasSnippetInputs } from "../shared/variables.js";
|
||||
import { askForInputs, shouldConfirmExecution } from "./prompt-store";
|
||||
import { createSnippetsApi } from "./snippets-api";
|
||||
import { errorMessage } from "./types";
|
||||
|
||||
interface ToolbarHost {
|
||||
id?: number | string;
|
||||
name?: string;
|
||||
ip?: string;
|
||||
username?: string;
|
||||
port?: number;
|
||||
pluginSettings?: Record<string, Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The host's quick actions as buttons in the Host Metrics toolbar (the
|
||||
* host-metrics.toolbar slot). Each runs its snippet on the host over a fresh
|
||||
* SSH connection and reports the result in a toast.
|
||||
*/
|
||||
export function QuickActionButtons(props: Record<string, unknown>) {
|
||||
const host = props.host as ToolbarHost | undefined;
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const client = useMemo(() => createSnippetsApi(api), [api]);
|
||||
const canView = usePermission("view");
|
||||
const [running, setRunning] = useState<Set<number>>(new Set());
|
||||
const actions = readQuickActions(snippetHostSettings(host).quickActions);
|
||||
const hostId = Number(host?.id);
|
||||
|
||||
if (!canView || actions.length === 0 || !Number.isInteger(hostId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const setBusy = (snippetId: number, busy: boolean) =>
|
||||
setRunning((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (busy) next.add(snippetId);
|
||||
else next.delete(snippetId);
|
||||
return next;
|
||||
});
|
||||
|
||||
async function execute(
|
||||
action: QuickAction,
|
||||
inputValues: Record<string, string>,
|
||||
) {
|
||||
const toastId = `quick-action-${hostId}-${action.snippetId}`;
|
||||
setBusy(action.snippetId, true);
|
||||
toast.loading(t("quickActions.running", { name: action.name }), {
|
||||
id: toastId,
|
||||
});
|
||||
try {
|
||||
const result = await client.execute(
|
||||
action.snippetId,
|
||||
hostId,
|
||||
Object.keys(inputValues).length > 0 ? inputValues : undefined,
|
||||
);
|
||||
if (result.success) {
|
||||
toast.success(t("quickActions.succeeded", { name: action.name }), {
|
||||
id: toastId,
|
||||
description: result.output?.substring(0, 200),
|
||||
duration: 5000,
|
||||
});
|
||||
} else {
|
||||
toast.error(t("quickActions.failed", { name: action.name }), {
|
||||
id: toastId,
|
||||
description: result.error || result.output,
|
||||
duration: 5000,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(t("quickActions.error", { name: action.name }), {
|
||||
id: toastId,
|
||||
description: errorMessage(error, t("executionFailed")),
|
||||
duration: 5000,
|
||||
});
|
||||
} finally {
|
||||
setBusy(action.snippetId, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function run(action: QuickAction) {
|
||||
let inputValues: Record<string, string> = {};
|
||||
const snippet = await client.get(action.snippetId).catch(() => null);
|
||||
if (snippet && hasSnippetInputs(snippet.content)) {
|
||||
const values = await askForInputs(
|
||||
{ name: action.name || snippet.name, content: snippet.content },
|
||||
host
|
||||
? {
|
||||
ip: host.ip,
|
||||
username: host.username,
|
||||
port: host.port,
|
||||
name: host.name,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
if (!values) return;
|
||||
inputValues = values;
|
||||
}
|
||||
const go = () => void execute(action, inputValues);
|
||||
if (!shouldConfirmExecution()) {
|
||||
go();
|
||||
return;
|
||||
}
|
||||
toast(t("confirmRunMessage", { name: action.name }), {
|
||||
action: { label: t("confirmRunButton"), onClick: go },
|
||||
duration: 6000,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mr-3 flex flex-wrap gap-2">
|
||||
{actions.map((action, index) => {
|
||||
const busy = running.has(action.snippetId);
|
||||
return (
|
||||
<Button
|
||||
key={index}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 text-xs font-semibold"
|
||||
disabled={busy}
|
||||
onClick={() => void run(action)}
|
||||
>
|
||||
{busy && <RefreshCw className="mr-1 size-3 animate-spin" />}
|
||||
{action.name}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Separator orientation="vertical" className="mx-3 h-8" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useHosts, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { ArrowLeft, Check, FileText, Search, Server, Zap } from "lucide-react";
|
||||
import { Button, Input, SectionCard, Select2 } from "@termix/plugin-sdk/ui";
|
||||
import { parseHostFilter, type Snippet, type SnippetFolder } from "./types";
|
||||
|
||||
export interface SnippetFormValues {
|
||||
name: string;
|
||||
content: string;
|
||||
description: string;
|
||||
folder: string;
|
||||
isNote: boolean;
|
||||
hostIds: number[];
|
||||
}
|
||||
|
||||
const labelClass =
|
||||
"text-[10px] font-bold uppercase tracking-widest text-muted-foreground";
|
||||
|
||||
export function SnippetEditor({
|
||||
snippet,
|
||||
defaultFolder,
|
||||
folders,
|
||||
onBack,
|
||||
onSave,
|
||||
}: {
|
||||
/** The snippet being edited, or null to create one. */
|
||||
snippet: Snippet | null;
|
||||
defaultFolder?: string;
|
||||
folders: SnippetFolder[];
|
||||
onBack: () => void;
|
||||
onSave: (values: SnippetFormValues) => Promise<boolean>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [values, setValues] = useState<SnippetFormValues>(() => ({
|
||||
name: snippet?.name ?? "",
|
||||
content: snippet?.content ?? "",
|
||||
description: snippet?.description ?? "",
|
||||
folder: snippet?.folder ?? defaultFolder ?? "",
|
||||
isNote: snippet?.isNote ?? false,
|
||||
hostIds: parseHostFilter(snippet?.hostFilter),
|
||||
}));
|
||||
const { hosts } = useHosts();
|
||||
const [hostSearch, setHostSearch] = useState("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const set = <K extends keyof SnippetFormValues>(
|
||||
key: K,
|
||||
value: SnippetFormValues[K],
|
||||
) => setValues((prev) => ({ ...prev, [key]: value }));
|
||||
|
||||
const canSave = !!values.name.trim() && !!values.content.trim() && !saving;
|
||||
// A snippet can point at a folder that has no metadata row yet.
|
||||
const folderNames = Array.from(
|
||||
new Set([
|
||||
...folders.map((f) => f.name),
|
||||
...(values.folder ? [values.folder] : []),
|
||||
]),
|
||||
).sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const hostQuery = hostSearch.trim().toLowerCase();
|
||||
const visibleHosts = useMemo(
|
||||
() =>
|
||||
hosts
|
||||
.filter(
|
||||
(host) =>
|
||||
!hostQuery ||
|
||||
host.name.toLowerCase().includes(hostQuery) ||
|
||||
host.ip.toLowerCase().includes(hostQuery),
|
||||
)
|
||||
.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[hosts, hostQuery],
|
||||
);
|
||||
|
||||
function toggleHost(id: number) {
|
||||
set(
|
||||
"hostIds",
|
||||
values.hostIds.includes(id)
|
||||
? values.hostIds.filter((h) => h !== id)
|
||||
: [...values.hostIds, id],
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!canSave) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave(values);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="flex items-center gap-2 px-3 py-2 shrink-0 text-xs text-muted-foreground hover:text-foreground hover:bg-muted/40 transition-colors border-b border-border"
|
||||
>
|
||||
<ArrowLeft className="size-3.5 shrink-0" />
|
||||
<span>{t("backToSnippets")}</span>
|
||||
{snippet && (
|
||||
<span
|
||||
className="ml-auto font-semibold text-foreground truncate max-w-[200px]"
|
||||
title={snippet.name}
|
||||
>
|
||||
{snippet.name}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-3 flex flex-col gap-3">
|
||||
<SectionCard
|
||||
title={t(snippet ? "editSnippetTitle" : "createSnippetTitle")}
|
||||
icon={<FileText className="size-3.5" />}
|
||||
>
|
||||
<div className="flex flex-col gap-4 py-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className={labelClass}>
|
||||
{t("nameLabel")} <span className="text-accent-brand">*</span>
|
||||
</label>
|
||||
<Input
|
||||
autoFocus
|
||||
value={values.name}
|
||||
placeholder={t("namePlaceholder")}
|
||||
onChange={(e) => set("name", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className={labelClass}>{t("descriptionLabel")}</label>
|
||||
<Input
|
||||
value={values.description}
|
||||
placeholder={t("descriptionPlaceholder")}
|
||||
onChange={(e) => set("description", e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className={labelClass}>{t("folderLabel")}</label>
|
||||
<Select2
|
||||
value={values.folder}
|
||||
onChange={(e) => set("folder", e.target.value)}
|
||||
>
|
||||
<option value="">{t("noFolder")}</option>
|
||||
{folderNames.map((name) => (
|
||||
<option key={name} value={name}>
|
||||
{name}
|
||||
</option>
|
||||
))}
|
||||
</Select2>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className={labelClass}>{t("typeLabel")}</label>
|
||||
<div className="flex items-stretch border border-border">
|
||||
{[false, true].map((isNote) => (
|
||||
<button
|
||||
key={String(isNote)}
|
||||
type="button"
|
||||
onClick={() => set("isNote", isNote)}
|
||||
className={`flex-1 h-8 text-xs transition-colors ${isNote ? "border-l border-border" : ""} ${
|
||||
values.isNote === isNote
|
||||
? "bg-accent-brand/10 text-accent-brand"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-muted/40"
|
||||
}`}
|
||||
>
|
||||
{t(isNote ? "typeNote" : "typeCommand")}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{t(values.isNote ? "typeNoteHint" : "typeCommandHint")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className={labelClass}>
|
||||
{t(values.isNote ? "noteLabel" : "commandLabel")}{" "}
|
||||
<span className="text-accent-brand">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={values.content}
|
||||
placeholder={t(
|
||||
values.isNote ? "notePlaceholder" : "commandPlaceholder",
|
||||
)}
|
||||
onChange={(e) => set("content", e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
void handleSave();
|
||||
}
|
||||
}}
|
||||
className="w-full min-h-36 px-3 py-2 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-y outline-none focus:ring-1 focus:ring-ring font-mono"
|
||||
/>
|
||||
<span className="text-[10px] text-muted-foreground/70 font-mono">
|
||||
{t("variablesHint")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</SectionCard>
|
||||
|
||||
{!values.isNote && (
|
||||
<SectionCard
|
||||
title={t("targetHostsLabel")}
|
||||
icon={<Zap className="size-3.5" />}
|
||||
action={
|
||||
values.hostIds.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => set("hostIds", [])}
|
||||
className="text-[10px] text-accent-brand hover:underline"
|
||||
>
|
||||
{t("clearTargetHosts")}
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2 py-3">
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{t("targetHostsHint")}
|
||||
</span>
|
||||
{hosts.length === 0 ? (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{t("noHostsAvailable")}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-col border border-border">
|
||||
<div className="flex items-center gap-2 px-2.5 h-7 border-b border-border bg-muted/40">
|
||||
<Search className="size-3 text-muted-foreground/60 shrink-0" />
|
||||
<input
|
||||
value={hostSearch}
|
||||
onChange={(e) => setHostSearch(e.target.value)}
|
||||
placeholder={t("searchHosts")}
|
||||
className="flex-1 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50 min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col max-h-48 overflow-y-auto">
|
||||
{visibleHosts.map((host) => {
|
||||
const id = Number(host.id);
|
||||
const selected = values.hostIds.includes(id);
|
||||
return (
|
||||
<button
|
||||
key={host.id}
|
||||
type="button"
|
||||
onClick={() => toggleHost(id)}
|
||||
className={`flex items-center gap-2 px-2.5 py-1.5 text-left border-b border-border/40 last:border-b-0 transition-colors ${
|
||||
selected
|
||||
? "bg-accent-brand/[0.07]"
|
||||
: "hover:bg-muted/40"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`size-3.5 border-2 flex items-center justify-center shrink-0 transition-colors ${selected ? "border-accent-brand bg-accent-brand" : "border-border bg-background"}`}
|
||||
>
|
||||
{selected && (
|
||||
<Check className="size-2 text-background" />
|
||||
)}
|
||||
</span>
|
||||
<Server className="size-3 shrink-0 text-muted-foreground/60" />
|
||||
<span className="text-xs font-medium truncate flex-1">
|
||||
{host.name || host.ip}
|
||||
</span>
|
||||
<span className="text-[11px] text-muted-foreground/60 font-mono truncate shrink-0 max-w-[45%]">
|
||||
{host.ip}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</SectionCard>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="ghost" onClick={onBack} disabled={saving}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand px-6"
|
||||
disabled={!canSave}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{t(snippet ? "saveSnippetButton" : "createSnippetButton")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
FOLDER_COLORS,
|
||||
Input,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { FolderIcon } from "./folder-icons";
|
||||
import { FOLDER_ICONS, type FolderIconId, type SnippetFolder } from "./types";
|
||||
|
||||
export interface FolderFormValues {
|
||||
name: string;
|
||||
color: string;
|
||||
icon: FolderIconId;
|
||||
}
|
||||
|
||||
export function SnippetFolderDialog({
|
||||
folder,
|
||||
onClose,
|
||||
onSave,
|
||||
}: {
|
||||
/** The folder being edited, or null to create one. */
|
||||
folder: SnippetFolder | null;
|
||||
onClose: () => void;
|
||||
onSave: (values: FolderFormValues) => Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [name, setName] = useState(folder?.name ?? "");
|
||||
const [color, setColor] = useState<string>(folder?.color ?? FOLDER_COLORS[0]);
|
||||
const [icon, setIcon] = useState<FolderIconId>(
|
||||
(folder?.icon as FolderIconId) ?? "folder",
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const isEdit = folder !== null;
|
||||
|
||||
async function handleSave() {
|
||||
if (!name.trim()) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await onSave({ name: name.trim(), color, icon });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg font-bold">
|
||||
{t(isEdit ? "editFolderTitle" : "createFolderTitle")}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground">
|
||||
{t(isEdit ? "editFolderDescription" : "createFolderDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4 mt-1">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("folderNameLabel")}
|
||||
</label>
|
||||
<Input
|
||||
autoFocus
|
||||
value={name}
|
||||
placeholder={t("folderNamePlaceholder")}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") void handleSave();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("folderColorLabel")}
|
||||
</label>
|
||||
<div className="grid grid-cols-8 gap-1.5">
|
||||
{FOLDER_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
title={c}
|
||||
onClick={() => setColor(c)}
|
||||
className={`h-7 transition-all ${color === c ? "ring-2 ring-offset-2 ring-offset-background ring-foreground/50" : "opacity-75 hover:opacity-100"}`}
|
||||
style={{ backgroundColor: c }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
|
||||
{t("folderIconLabel")}
|
||||
</label>
|
||||
<div className="grid grid-cols-5 gap-1.5">
|
||||
{FOLDER_ICONS.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
title={id}
|
||||
onClick={() => setIcon(id)}
|
||||
className={`flex items-center justify-center h-9 border transition-colors ${
|
||||
icon === id
|
||||
? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand"
|
||||
: "border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
<FolderIcon icon={id} className="size-4" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 px-2.5 py-2 border border-border bg-muted/20">
|
||||
<FolderIcon icon={icon} className="size-4" style={{ color }} />
|
||||
<span className="text-[13px] font-bold tracking-tight truncate">
|
||||
{name.trim() || t("folderNamePlaceholder")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
disabled={saving || !name.trim()}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{t(isEdit ? "saveFolderButton" : "createFolderButton")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect } from "react";
|
||||
import { useSettings } from "@termix/plugin-sdk/frontend";
|
||||
import { SnippetVariablesDialog } from "./SnippetVariablesDialog";
|
||||
import { readSnippetSettings } from "./settings";
|
||||
import { setConfirmExecution, usePendingPrompt } from "./prompt-store";
|
||||
|
||||
/**
|
||||
* Always mounted at the shell's root (the shell.overlay slot), so a snippet
|
||||
* started from the command palette, a keybinding or a host button can ask
|
||||
* for its inputs after whatever started it has closed.
|
||||
*/
|
||||
export function SnippetOverlay() {
|
||||
const settings = useSettings("user");
|
||||
const prompt = usePendingPrompt();
|
||||
const confirmExecution = readSnippetSettings(
|
||||
settings.values,
|
||||
).confirmExecution;
|
||||
|
||||
useEffect(() => {
|
||||
setConfirmExecution(confirmExecution);
|
||||
}, [confirmExecution]);
|
||||
|
||||
if (!prompt) return null;
|
||||
return (
|
||||
<SnippetVariablesDialog
|
||||
snippet={prompt.snippet}
|
||||
host={prompt.host}
|
||||
onCancel={() => prompt.settle(null)}
|
||||
onConfirm={(_resolved, values) => prompt.settle(values)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
useTranslation,
|
||||
type SettingsState,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { ArrowLeft, Rows3, SquareStack } from "lucide-react";
|
||||
import { FakeSwitch, SectionCard, SettingRow } from "@termix/plugin-sdk/ui";
|
||||
import { readSnippetSettings, type SnippetDisplaySettings } from "./settings";
|
||||
|
||||
export function SnippetSettings({
|
||||
settings,
|
||||
onBack,
|
||||
}: {
|
||||
settings: SettingsState;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const current = readSnippetSettings(settings.values);
|
||||
|
||||
const save = (patch: Partial<SnippetDisplaySettings>) =>
|
||||
void settings.save({ ...settings.values, ...patch });
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="flex items-center gap-2 px-3 py-2 shrink-0 text-xs text-muted-foreground hover:text-foreground hover:bg-muted/40 transition-colors border-b border-border"
|
||||
>
|
||||
<ArrowLeft className="size-3.5 shrink-0" />
|
||||
<span>{t("backToSnippets")}</span>
|
||||
<span className="ml-auto font-semibold text-foreground">
|
||||
{t("settingsTitle")}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-3 flex flex-col gap-3">
|
||||
<SectionCard
|
||||
title={t("settingsDisplayTitle")}
|
||||
icon={<Rows3 className="size-3.5" />}
|
||||
>
|
||||
<SettingRow
|
||||
label={t("settings.foldersCollapsed.label")}
|
||||
description={t("settings.foldersCollapsed.description")}
|
||||
>
|
||||
<FakeSwitch
|
||||
checked={current.foldersCollapsed}
|
||||
onChange={(v) => save({ foldersCollapsed: v })}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
label={t("settings.showCommands.label")}
|
||||
description={t("settings.showCommands.description")}
|
||||
>
|
||||
<FakeSwitch
|
||||
checked={current.showCommands}
|
||||
onChange={(v) => save({ showCommands: v })}
|
||||
/>
|
||||
</SettingRow>
|
||||
</SectionCard>
|
||||
|
||||
<SectionCard
|
||||
title={t("settingsBehaviorTitle")}
|
||||
icon={<SquareStack className="size-3.5" />}
|
||||
>
|
||||
<SettingRow
|
||||
label={t("settings.confirmExecution.label")}
|
||||
description={t("settings.confirmExecution.description")}
|
||||
>
|
||||
<FakeSwitch
|
||||
checked={current.confirmExecution}
|
||||
onChange={(v) => save({ confirmExecution: v })}
|
||||
/>
|
||||
</SettingRow>
|
||||
</SectionCard>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Check,
|
||||
ListChecks,
|
||||
Search,
|
||||
Share2,
|
||||
Shield,
|
||||
User,
|
||||
Users,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
Input,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import type {
|
||||
ShareableRole,
|
||||
ShareableUser,
|
||||
SnippetShareInput,
|
||||
SnippetsApi,
|
||||
} from "./snippets-api";
|
||||
import { errorMessage, type Snippet, type SnippetAccessEntry } from "./types";
|
||||
|
||||
export type ShareTarget =
|
||||
{ kind: "snippet"; snippet: Snippet } | { kind: "folder"; name: string };
|
||||
|
||||
const EXPIRY_HOURS = [0, 1, 24, 168, 720] as const;
|
||||
|
||||
const DOCS_URL = "https://docs.termix.site/features/authentication/rbac";
|
||||
|
||||
export function SnippetShareView({
|
||||
target,
|
||||
client,
|
||||
onBack,
|
||||
}: {
|
||||
target: ShareTarget;
|
||||
client: SnippetsApi;
|
||||
onBack: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [users, setUsers] = useState<ShareableUser[]>([]);
|
||||
const [roles, setRoles] = useState<ShareableRole[]>([]);
|
||||
const [access, setAccess] = useState<SnippetAccessEntry[]>([]);
|
||||
const [tab, setTab] = useState<"user" | "role">("user");
|
||||
const [search, setSearch] = useState("");
|
||||
const [selectedUsers, setSelectedUsers] = useState<Set<string>>(new Set());
|
||||
const [selectedRoles, setSelectedRoles] = useState<Set<number>>(new Set());
|
||||
const [expiryHours, setExpiryHours] = useState<number>(0);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [folderSummary, setFolderSummary] = useState<number | null>(null);
|
||||
|
||||
const snippetId = target.kind === "snippet" ? target.snippet.id : null;
|
||||
const selectedCount = selectedUsers.size + selectedRoles.size;
|
||||
|
||||
const loadAccess = useCallback(async () => {
|
||||
if (snippetId === null) return;
|
||||
const list = await client.getAccess(snippetId);
|
||||
setAccess(Array.isArray(list) ? list : []);
|
||||
}, [client, snippetId]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
Promise.all([
|
||||
client.shareTargetUsers(),
|
||||
client.shareTargetRoles(),
|
||||
loadAccess(),
|
||||
])
|
||||
.then(([usersRes, rolesRes]) => {
|
||||
if (cancelled) return;
|
||||
setUsers(usersRes.users ?? []);
|
||||
setRoles(rolesRes.roles ?? []);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLoadError(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [client, loadAccess]);
|
||||
|
||||
const query = search.trim().toLowerCase();
|
||||
const filteredUsers = useMemo(
|
||||
() => users.filter((u) => u.username.toLowerCase().includes(query)),
|
||||
[users, query],
|
||||
);
|
||||
const filteredRoles = useMemo(
|
||||
() =>
|
||||
roles.filter((r) =>
|
||||
(r.displayName || r.name).toLowerCase().includes(query),
|
||||
),
|
||||
[roles, query],
|
||||
);
|
||||
|
||||
function toggle<T>(set: Set<T>, value: T): Set<T> {
|
||||
const next = new Set(set);
|
||||
if (next.has(value)) next.delete(value);
|
||||
else next.add(value);
|
||||
return next;
|
||||
}
|
||||
|
||||
async function handleShare() {
|
||||
if (selectedCount === 0) return;
|
||||
const expiresAt =
|
||||
expiryHours > 0
|
||||
? new Date(Date.now() + expiryHours * 3600_000).toISOString()
|
||||
: null;
|
||||
const bodies: SnippetShareInput[] = [
|
||||
...[...selectedUsers].map((id) => ({
|
||||
targetType: "user" as const,
|
||||
targetUserId: id,
|
||||
expiresAt,
|
||||
})),
|
||||
...[...selectedRoles].map((id) => ({
|
||||
targetType: "role" as const,
|
||||
targetRoleId: id,
|
||||
expiresAt,
|
||||
})),
|
||||
];
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
if (target.kind === "snippet") {
|
||||
for (const body of bodies) await client.share(target.snippet.id, body);
|
||||
await loadAccess();
|
||||
} else {
|
||||
let shared = 0;
|
||||
for (const body of bodies) {
|
||||
const result = await client.shareFolder(target.name, body);
|
||||
shared = Math.max(shared, result.snippetsShared ?? 0);
|
||||
}
|
||||
setFolderSummary(shared);
|
||||
}
|
||||
toast.success(t("shareSuccess", { count: selectedCount }));
|
||||
setSelectedUsers(new Set());
|
||||
setSelectedRoles(new Set());
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("shareFailed")));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevoke(entry: SnippetAccessEntry) {
|
||||
if (snippetId === null) return;
|
||||
try {
|
||||
await client.revokeAccess(snippetId, entry.id);
|
||||
setAccess((prev) => prev.filter((a) => a.id !== entry.id));
|
||||
toast.success(t("revokeSuccess"));
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("revokeFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
const rowClass = (selected: boolean) =>
|
||||
`flex items-center gap-2 px-2.5 py-1.5 text-xs text-left border-b border-border/50 last:border-0 transition-colors shrink-0 ${selected ? "bg-accent-brand/10 text-accent-brand" : "hover:bg-muted/40"}`;
|
||||
|
||||
const checkbox = (selected: boolean) => (
|
||||
<div
|
||||
className={`size-3.5 border flex items-center justify-center shrink-0 transition-colors ${selected ? "border-accent-brand bg-accent-brand" : "border-border bg-background"}`}
|
||||
>
|
||||
{selected && <Check className="size-2.5 text-background" />}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="flex items-center gap-2 px-3 py-2 shrink-0 border-b border-border text-xs text-muted-foreground hover:text-foreground transition-colors w-full text-left"
|
||||
>
|
||||
<ArrowLeft className="size-3.5 shrink-0" />
|
||||
<span className="truncate">
|
||||
{target.kind === "snippet"
|
||||
? t("shareSnippetTitle", { name: target.snippet.name })
|
||||
: t("shareFolderTitle", { name: target.name })}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{loadError && (
|
||||
<div className="flex items-start gap-2 px-3 py-2 shrink-0 border-b border-destructive/30 bg-destructive/5 text-xs text-destructive">
|
||||
<Shield className="size-3.5 shrink-0 mt-0.5" />
|
||||
<div>{t("shareLoadFailed")}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-2 p-3 shrink-0 border-b border-border">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
<Users className="size-3.5" />
|
||||
{t("shareWith")}
|
||||
</div>
|
||||
<a
|
||||
href={DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-[10px] text-accent-brand hover:underline shrink-0"
|
||||
>
|
||||
{t("docsLink")}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1.5">
|
||||
{(["user", "role"] as const).map((key) => {
|
||||
const count =
|
||||
key === "user" ? selectedUsers.size : selectedRoles.size;
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setTab(key)}
|
||||
className={`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${tab === key ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
|
||||
>
|
||||
{key === "user" ? (
|
||||
<User className="size-3 shrink-0" />
|
||||
) : (
|
||||
<Shield className="size-3 shrink-0" />
|
||||
)}
|
||||
{t(key === "user" ? "usersTab" : "rolesTab")}
|
||||
{count > 0 && <span>({count})</span>}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground/50" />
|
||||
<Input
|
||||
placeholder={t("shareSearchPlaceholder")}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col border border-border h-28 overflow-y-auto">
|
||||
{tab === "user" &&
|
||||
(filteredUsers.length === 0 ? (
|
||||
<div className="px-3 py-4 text-xs text-muted-foreground/50 text-center">
|
||||
{t("shareNoMatches")}
|
||||
</div>
|
||||
) : (
|
||||
filteredUsers.map((user) => {
|
||||
const selected = selectedUsers.has(user.id);
|
||||
return (
|
||||
<button
|
||||
key={user.id}
|
||||
onClick={() =>
|
||||
setSelectedUsers((prev) => toggle(prev, user.id))
|
||||
}
|
||||
className={rowClass(selected)}
|
||||
>
|
||||
{checkbox(selected)}
|
||||
<User className="size-3 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">{user.username}</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
))}
|
||||
{tab === "role" &&
|
||||
(filteredRoles.length === 0 ? (
|
||||
<div className="px-3 py-4 text-xs text-muted-foreground/50 text-center">
|
||||
{t("shareNoMatches")}
|
||||
</div>
|
||||
) : (
|
||||
filteredRoles.map((role) => {
|
||||
const selected = selectedRoles.has(role.id);
|
||||
return (
|
||||
<button
|
||||
key={role.id}
|
||||
onClick={() =>
|
||||
setSelectedRoles((prev) => toggle(prev, role.id))
|
||||
}
|
||||
className={rowClass(selected)}
|
||||
>
|
||||
{checkbox(selected)}
|
||||
<Shield className="size-3 text-muted-foreground shrink-0" />
|
||||
<span className="truncate">
|
||||
{role.displayName || role.name}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="flex flex-col gap-1 flex-1 min-w-0">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground text-left">
|
||||
{t("shareExpiry")}
|
||||
</span>
|
||||
<span className="h-8 flex items-center px-2.5 text-xs border border-border hover:bg-muted/40 transition-colors whitespace-nowrap">
|
||||
{t(`shareExpiryOptions.h${expiryHours}`)}
|
||||
</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="text-xs">
|
||||
{EXPIRY_HOURS.map((hours) => (
|
||||
<DropdownMenuItem
|
||||
key={hours}
|
||||
onClick={() => setExpiryHours(hours)}
|
||||
>
|
||||
{expiryHours === hours ? (
|
||||
<Check className="size-3 mr-1.5" />
|
||||
) : (
|
||||
<span className="size-3 mr-1.5" />
|
||||
)}
|
||||
{t(`shareExpiryOptions.h${hours}`)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-8 shrink-0 border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
disabled={selectedCount === 0 || submitting}
|
||||
onClick={() => void handleShare()}
|
||||
>
|
||||
<Share2 className="size-3.5 mr-1.5" />
|
||||
{selectedCount > 0
|
||||
? t("shareWithCount", { count: selectedCount })
|
||||
: t("shareButton")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{target.kind === "folder" && (
|
||||
<p className="text-[11px] text-muted-foreground leading-snug">
|
||||
{t("shareFolderHint")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{target.kind === "folder" && folderSummary !== null && (
|
||||
<div className="flex items-center gap-1.5 px-3 py-2 shrink-0 text-xs text-muted-foreground">
|
||||
<ListChecks className="size-3.5 shrink-0" />
|
||||
{t("shareFolderSummary", { count: folderSummary })}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{target.kind === "snippet" && (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<div className="flex items-center gap-1.5 px-3 py-2 shrink-0 border-b border-border text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
<ListChecks className="size-3.5" />
|
||||
{t("currentAccess")}
|
||||
{access.length > 0 && (
|
||||
<span className="text-muted-foreground/40">
|
||||
({access.length})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{access.length === 0 && (
|
||||
<div className="px-3 py-6 text-xs text-muted-foreground/50 text-center">
|
||||
{t("notSharedYet")}
|
||||
</div>
|
||||
)}
|
||||
{access.map((entry) => {
|
||||
const expired =
|
||||
entry.expiresAt && new Date(entry.expiresAt) < new Date();
|
||||
return (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="flex flex-col gap-1 px-3 py-2 border-b border-border/60 last:border-0 text-xs"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{entry.targetType === "user" ? (
|
||||
<User className="size-3 text-muted-foreground shrink-0" />
|
||||
) : (
|
||||
<Shield className="size-3 text-muted-foreground shrink-0" />
|
||||
)}
|
||||
<span className="font-semibold truncate">
|
||||
{entry.username ??
|
||||
entry.roleDisplayName ??
|
||||
entry.roleName ??
|
||||
entry.userId ??
|
||||
entry.roleId}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 text-[10px] px-2 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => void handleRevoke(entry)}
|
||||
>
|
||||
{t("revokeAccess")}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-[10px] text-muted-foreground pl-4">
|
||||
<span>
|
||||
{t("grantedBy")}:{" "}
|
||||
<span className="text-foreground/70">
|
||||
{entry.grantedByUsername ?? "?"}
|
||||
</span>
|
||||
</span>
|
||||
<span className={expired ? "text-destructive" : ""}>
|
||||
{t("shareExpiry")}:{" "}
|
||||
{expired ? (
|
||||
<span className="inline-flex items-center gap-0.5 text-destructive">
|
||||
<X className="size-3" />
|
||||
{t("expired")}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-foreground/70">
|
||||
{entry.expiresAt
|
||||
? new Date(entry.expiresAt).toLocaleString()
|
||||
: t("shareExpiryOptions.h0")}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
import { useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
ChevronRight,
|
||||
ClipboardPaste,
|
||||
Copy,
|
||||
FolderInput,
|
||||
GripVertical,
|
||||
MoreHorizontal,
|
||||
Pencil,
|
||||
Play,
|
||||
Plus,
|
||||
Share2,
|
||||
StickyNote,
|
||||
Terminal,
|
||||
Trash2,
|
||||
Users,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { FolderIcon } from "./folder-icons";
|
||||
import type { Snippet, SnippetFolder } from "./types";
|
||||
|
||||
const trayButtonClass =
|
||||
"flex items-center justify-center size-[22.75px] text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors";
|
||||
|
||||
export type DropPosition = "above" | "below";
|
||||
|
||||
export function SnippetRow({
|
||||
snippet,
|
||||
stripeIndex,
|
||||
showCommand,
|
||||
folderNames,
|
||||
targetHostNames,
|
||||
canEdit,
|
||||
canDelete,
|
||||
canShare,
|
||||
draggable,
|
||||
dragActive,
|
||||
isDragging,
|
||||
dropIndicator,
|
||||
onRun,
|
||||
onCopy,
|
||||
onEdit,
|
||||
onShare,
|
||||
onMove,
|
||||
onDelete,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
onDragOverRow,
|
||||
onDropRow,
|
||||
}: {
|
||||
snippet: Snippet;
|
||||
stripeIndex: number;
|
||||
showCommand: boolean;
|
||||
folderNames: string[];
|
||||
/** Hosts a command snippet runs on directly, instead of the active terminal. */
|
||||
targetHostNames: string[];
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
canShare: boolean;
|
||||
draggable: boolean;
|
||||
/** True while any snippet is being dragged, so this row is a drop target. */
|
||||
dragActive: boolean;
|
||||
isDragging: boolean;
|
||||
dropIndicator: DropPosition | null;
|
||||
onRun: () => void;
|
||||
onCopy: () => void;
|
||||
onEdit: () => void;
|
||||
onShare: () => void;
|
||||
onMove: (folder: string | null) => void;
|
||||
onDelete: () => void;
|
||||
onDragStart: () => void;
|
||||
onDragEnd: () => void;
|
||||
onDragOverRow: (position: DropPosition) => void;
|
||||
onDropRow: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const owned = !snippet.isShared;
|
||||
const editable = canEdit && owned;
|
||||
const deletable = canDelete && owned;
|
||||
const shareable = canShare && owned;
|
||||
const hasTargets = !snippet.isNote && targetHostNames.length > 0;
|
||||
const TypeIcon = snippet.isNote ? StickyNote : Terminal;
|
||||
const RunIcon = hasTargets ? Zap : snippet.isNote ? ClipboardPaste : Play;
|
||||
const runLabel = t(
|
||||
hasTargets ? "runOnTargets" : snippet.isNote ? "pasteToTerminal" : "run",
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
draggable={draggable}
|
||||
onDragStart={(e) => {
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
onDragStart();
|
||||
}}
|
||||
onDragEnd={onDragEnd}
|
||||
onDragOver={(e) => {
|
||||
if (!dragActive) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
onDragOverRow(
|
||||
e.clientY < rect.top + rect.height / 2 ? "above" : "below",
|
||||
);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (!dragActive) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onDropRow();
|
||||
}}
|
||||
onDoubleClick={onRun}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
setMenuOpen(true);
|
||||
}}
|
||||
title={t("doubleClickToRun")}
|
||||
className={`group relative flex items-stretch select-none border-b border-border/40 transition-colors hover:bg-muted/50 ${
|
||||
draggable ? "cursor-grab active:cursor-grabbing" : ""
|
||||
} ${
|
||||
menuOpen ? "bg-muted/50" : stripeIndex % 2 === 1 ? "bg-muted/15" : ""
|
||||
} ${isDragging ? "opacity-40" : ""}`}
|
||||
>
|
||||
{dropIndicator && (
|
||||
<div
|
||||
className={`absolute left-0 right-0 h-0.5 bg-accent-brand z-10 pointer-events-none ${dropIndicator === "above" ? "-top-px" : "-bottom-px"}`}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className={`w-[3px] shrink-0 ${snippet.isNote ? "bg-muted-foreground/30" : "bg-accent-brand/60"}`}
|
||||
/>
|
||||
{draggable && (
|
||||
<div className="flex items-center justify-center w-3.5 shrink-0 -mr-1.5 text-muted-foreground/30 group-hover:text-muted-foreground/70 transition-colors">
|
||||
<GripVertical className="size-3" />
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col flex-1 min-w-0 pl-[8.75px] pr-[7px] py-[7px] gap-[3.5px]">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<TypeIcon className="size-3 shrink-0 text-muted-foreground/60" />
|
||||
<span className="text-[13px] font-semibold truncate text-foreground leading-none tracking-tight">
|
||||
{snippet.name}
|
||||
</span>
|
||||
{snippet.isNote && (
|
||||
<span className="text-[9px] px-1 py-px border border-border bg-muted/40 text-muted-foreground shrink-0 leading-none uppercase tracking-wider">
|
||||
{t("typeNote")}
|
||||
</span>
|
||||
)}
|
||||
{snippet.isShared && (
|
||||
<span className="flex items-center gap-0.5 text-[9px] px-1 py-px border border-accent-brand/30 bg-accent-brand/10 text-accent-brand shrink-0 leading-none uppercase tracking-wider">
|
||||
<Users className="size-2.5" />
|
||||
{t("sharedBadge")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{snippet.description && (
|
||||
<span className="text-[11px] text-muted-foreground/80 truncate leading-tight">
|
||||
{snippet.description}
|
||||
</span>
|
||||
)}
|
||||
{showCommand && (
|
||||
<span className="text-[11px] text-muted-foreground/60 truncate leading-tight font-mono">
|
||||
{snippet.content.split("\n")[0]}
|
||||
</span>
|
||||
)}
|
||||
{hasTargets && (
|
||||
<div className="flex items-center gap-1 min-w-0 overflow-hidden">
|
||||
<Zap className="size-2.5 shrink-0 text-accent-brand/70" />
|
||||
{targetHostNames.slice(0, 3).map((name) => (
|
||||
<span
|
||||
key={name}
|
||||
className="text-[9px] px-1.5 py-[1px] bg-accent-brand/10 text-accent-brand shrink-0 leading-[1.4] truncate max-w-28"
|
||||
>
|
||||
{name}
|
||||
</span>
|
||||
))}
|
||||
{targetHostNames.length > 3 && (
|
||||
<span className="text-[9px] text-muted-foreground/50 shrink-0">
|
||||
+{targetHostNames.length - 3}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`absolute right-1.5 top-1.5 items-center border border-border bg-background shadow-sm ${
|
||||
menuOpen ? "flex" : "hidden group-hover:flex pointer-coarse:flex"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
title={runLabel}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onRun();
|
||||
}}
|
||||
className={`${trayButtonClass} text-accent-brand/80 hover:text-accent-brand`}
|
||||
>
|
||||
<RunIcon className="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
title={t("copyToClipboard")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onCopy();
|
||||
}}
|
||||
className={trayButtonClass}
|
||||
>
|
||||
<Copy className="size-3.5" />
|
||||
</button>
|
||||
{editable && (
|
||||
<button
|
||||
title={t("editSnippetTitle")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEdit();
|
||||
}}
|
||||
className={trayButtonClass}
|
||||
>
|
||||
<Pencil className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
{shareable && (
|
||||
<button
|
||||
title={t("shareSnippet")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onShare();
|
||||
}}
|
||||
className={trayButtonClass}
|
||||
>
|
||||
<Share2 className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
title={t("moreOptions")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className={trayButtonClass}
|
||||
>
|
||||
<MoreHorizontal className="size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="text-xs min-w-44">
|
||||
<DropdownMenuItem onClick={onRun}>
|
||||
<RunIcon className="size-3.5 mr-2" />
|
||||
{runLabel}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={onCopy}>
|
||||
<Copy className="size-3.5 mr-2" />
|
||||
{t("copyToClipboard")}
|
||||
</DropdownMenuItem>
|
||||
{editable && (
|
||||
<DropdownMenuItem onClick={onEdit}>
|
||||
<Pencil className="size-3.5 mr-2" />
|
||||
{t("editSnippetTitle")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{shareable && (
|
||||
<DropdownMenuItem onClick={onShare}>
|
||||
<Share2 className="size-3.5 mr-2" />
|
||||
{t("shareSnippet")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{editable && (
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<FolderInput className="size-3.5 mr-2" />
|
||||
{t("moveToFolder")}
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent className="text-xs max-w-72">
|
||||
<DropdownMenuItem
|
||||
disabled={!snippet.folder}
|
||||
onClick={() => onMove(null)}
|
||||
>
|
||||
{t("noFolder")}
|
||||
</DropdownMenuItem>
|
||||
{folderNames.map((name) => (
|
||||
<DropdownMenuItem
|
||||
key={name}
|
||||
disabled={snippet.folder === name}
|
||||
onClick={() => onMove(name)}
|
||||
>
|
||||
<span className="truncate">{name}</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
)}
|
||||
{deletable && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-3.5 mr-2" />
|
||||
{t("deleteSnippet")}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SnippetFolderRow({
|
||||
name,
|
||||
folder,
|
||||
count,
|
||||
open,
|
||||
stripeIndex,
|
||||
canCreate,
|
||||
canEdit,
|
||||
canDelete,
|
||||
canShare,
|
||||
acceptsDrop,
|
||||
onToggle,
|
||||
onAddSnippet,
|
||||
onEdit,
|
||||
onShare,
|
||||
onDelete,
|
||||
onDropSnippet,
|
||||
children,
|
||||
}: {
|
||||
name: string;
|
||||
/** Null for a folder that only exists as a name on its snippets. */
|
||||
folder: SnippetFolder | null;
|
||||
count: number;
|
||||
open: boolean;
|
||||
stripeIndex: number;
|
||||
canCreate: boolean;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
canShare: boolean;
|
||||
/** True while a snippet is being dragged that could move into this folder. */
|
||||
acceptsDrop: boolean;
|
||||
onToggle: () => void;
|
||||
onAddSnippet: () => void;
|
||||
onEdit: () => void;
|
||||
onShare: () => void;
|
||||
onDelete: () => void;
|
||||
onDropSnippet: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const hasActions = canCreate || canEdit || canDelete || canShare;
|
||||
|
||||
return (
|
||||
<div className="border-b border-border/40">
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={onToggle}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
onToggle();
|
||||
}
|
||||
}}
|
||||
onDragOver={(e) => {
|
||||
if (!acceptsDrop) return;
|
||||
e.preventDefault();
|
||||
setDragOver(true);
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
if (e.currentTarget === e.target) setDragOver(false);
|
||||
}}
|
||||
onDrop={(e) => {
|
||||
if (!acceptsDrop) return;
|
||||
e.preventDefault();
|
||||
setDragOver(false);
|
||||
onDropSnippet();
|
||||
}}
|
||||
className={`group/folder flex items-center gap-2 w-full pl-2.5 pr-2 py-1.5 cursor-pointer select-none transition-colors ${
|
||||
open ? "bg-muted/40" : "hover:bg-muted/30"
|
||||
} ${stripeIndex % 2 === 1 && !open ? "bg-muted/[0.08]" : ""} ${
|
||||
dragOver && acceptsDrop
|
||||
? "ring-1 ring-inset ring-accent-brand bg-accent-brand/10"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<ChevronRight
|
||||
className={`size-3.5 shrink-0 text-muted-foreground/60 transition-transform ${open ? "rotate-90" : ""}`}
|
||||
/>
|
||||
<FolderIcon
|
||||
icon={folder?.icon}
|
||||
className={`size-4 shrink-0 ${folder?.color ? "" : open ? "text-accent-brand" : "text-muted-foreground/70"}`}
|
||||
style={folder?.color ? { color: folder.color } : undefined}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-bold text-foreground tracking-tight">
|
||||
{name}
|
||||
</span>
|
||||
<span className="text-[10px] tabular-nums shrink-0 px-1.5 py-[1px] bg-muted/70 text-muted-foreground/70">
|
||||
{count}
|
||||
</span>
|
||||
{hasActions && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
title={t("folderActions")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="flex items-center justify-center size-5 shrink-0 text-muted-foreground/60 hover:text-foreground hover:bg-muted opacity-0 group-hover/folder:opacity-100 focus:opacity-100 pointer-coarse:opacity-100 data-[state=open]:opacity-100 transition-opacity"
|
||||
>
|
||||
<MoreHorizontal className="size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="text-xs min-w-40">
|
||||
{canCreate && (
|
||||
<DropdownMenuItem onClick={onAddSnippet}>
|
||||
<Plus className="size-3.5 mr-2" />
|
||||
{t("addSnippetHere")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canEdit && (
|
||||
<DropdownMenuItem onClick={onEdit}>
|
||||
<Pencil className="size-3.5 mr-2" />
|
||||
{t("editFolderTitle")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canShare && count > 0 && (
|
||||
<DropdownMenuItem onClick={onShare}>
|
||||
<Share2 className="size-3.5 mr-2" />
|
||||
{t("shareFolder")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={onDelete}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2 className="size-3.5 mr-2" />
|
||||
{t("deleteFolder")}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
{open && (
|
||||
<div className="border-l border-border/50 ml-[27px] border-t border-t-border/40 [&>*:last-child]:border-b-0">
|
||||
{count === 0 ? (
|
||||
<div className="px-3 py-2 text-[11px] text-muted-foreground/60">
|
||||
{t("noSnippetsInFolder")}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import {
|
||||
extractSnippetInputs,
|
||||
resolveSnippetContent,
|
||||
type SnippetHostContext,
|
||||
} from "../shared/variables.js";
|
||||
|
||||
/** Enough of a snippet to fill in its inputs. */
|
||||
export interface VariablesDialogSnippet {
|
||||
name: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown before running a snippet that contains $INPUT_n placeholders:
|
||||
* collects a value per placeholder and previews the fully resolved command
|
||||
* (host vars and inputs) before handing the result back to the caller.
|
||||
*/
|
||||
export function SnippetVariablesDialog({
|
||||
snippet,
|
||||
host,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
}: {
|
||||
snippet: VariablesDialogSnippet;
|
||||
host: SnippetHostContext | null;
|
||||
onCancel: () => void;
|
||||
onConfirm: (
|
||||
resolvedContent: string,
|
||||
inputValues: Record<string, string>,
|
||||
) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const inputs = useMemo(
|
||||
() => extractSnippetInputs(snippet.content),
|
||||
[snippet.content],
|
||||
);
|
||||
const [values, setValues] = useState<Record<string, string>>({});
|
||||
|
||||
useEffect(() => {
|
||||
setValues({});
|
||||
}, [snippet]);
|
||||
|
||||
const preview = resolveSnippetContent(snippet.content, host, values);
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(v) => !v && onCancel()}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-lg font-bold">
|
||||
{t("variablesDialogTitle", { name: snippet.name })}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-xs text-muted-foreground">
|
||||
{t("variablesDialogDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-4 mt-1">
|
||||
{inputs.map((input) => (
|
||||
<div key={input.key} className="flex flex-col gap-1.5">
|
||||
<label className="text-xs font-semibold">{input.label}</label>
|
||||
<Input
|
||||
autoFocus={inputs[0]?.key === input.key}
|
||||
value={values[input.key] ?? ""}
|
||||
onChange={(e) =>
|
||||
setValues((prev) => ({
|
||||
...prev,
|
||||
[input.key]: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-xs font-semibold text-muted-foreground">
|
||||
{t("variablesPreviewLabel")}
|
||||
</label>
|
||||
<span className="text-xs text-muted-foreground font-mono px-2.5 py-2 border border-border bg-muted/20 min-w-0 break-all whitespace-pre-wrap">
|
||||
{preview}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 mt-2">
|
||||
<Button variant="ghost" onClick={onCancel}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
|
||||
onClick={() => onConfirm(preview, values)}
|
||||
>
|
||||
{t("variablesConfirmButton")}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,831 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
useHosts,
|
||||
usePermission,
|
||||
usePluginApi,
|
||||
useSettings,
|
||||
useTranslation,
|
||||
type PanelProps,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
ChevronsDownUp,
|
||||
ChevronsUpDown,
|
||||
Download,
|
||||
ExternalLink,
|
||||
FolderPlus,
|
||||
MoreHorizontal,
|
||||
Plus,
|
||||
Search,
|
||||
SlidersHorizontal,
|
||||
Upload,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Button,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
copyToClipboard,
|
||||
useConfirmation,
|
||||
} from "@termix/plugin-sdk/ui";
|
||||
import { createSnippetsApi } from "./snippets-api";
|
||||
import { useSnippetRunner, type TargetHost } from "./use-snippet-runner";
|
||||
import {
|
||||
TargetTerminals,
|
||||
toRunTargets,
|
||||
useOpenTerminals,
|
||||
} from "./TargetTerminals";
|
||||
import { SnippetShareView, type ShareTarget } from "./SnippetShareView";
|
||||
import { SnippetEditor, type SnippetFormValues } from "./SnippetEditor";
|
||||
import { SnippetSettings } from "./SnippetSettings";
|
||||
import { readSnippetSettings } from "./settings";
|
||||
import {
|
||||
SnippetFolderDialog,
|
||||
type FolderFormValues,
|
||||
} from "./SnippetFolderDialog";
|
||||
import { SnippetFolderRow, SnippetRow, type DropPosition } from "./SnippetTree";
|
||||
import {
|
||||
errorMessage,
|
||||
parseHostFilter,
|
||||
type Snippet,
|
||||
type SnippetFolder,
|
||||
} from "./types";
|
||||
|
||||
const DOCS_URL = "https://docs.termix.site/features/terminal/snippets";
|
||||
|
||||
type View =
|
||||
| { kind: "list" }
|
||||
| { kind: "edit"; snippet: Snippet | null; folder?: string }
|
||||
| { kind: "settings" }
|
||||
| { kind: "share"; target: ShareTarget };
|
||||
|
||||
interface FolderGroup {
|
||||
name: string;
|
||||
folder: SnippetFolder | null;
|
||||
snippets: Snippet[];
|
||||
}
|
||||
|
||||
function matchesQuery(snippet: Snippet, query: string): boolean {
|
||||
return (
|
||||
snippet.name.toLowerCase().includes(query) ||
|
||||
(snippet.description ?? "").toLowerCase().includes(query) ||
|
||||
snippet.content.toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
export function SnippetsPanel({ active: _active }: PanelProps) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const client = useMemo(() => createSnippetsApi(api), [api]);
|
||||
const canView = usePermission("view");
|
||||
const canCreate = usePermission("create");
|
||||
const canEdit = usePermission("edit");
|
||||
const canDelete = usePermission("delete");
|
||||
const canShare = usePermission("share");
|
||||
const settings = useSettings("user");
|
||||
const display = readSnippetSettings(settings.values);
|
||||
const {
|
||||
runSnippet,
|
||||
runOnActive,
|
||||
runOnHosts,
|
||||
dialog: runnerDialog,
|
||||
} = useSnippetRunner(display.confirmExecution);
|
||||
const openTerminals = useOpenTerminals();
|
||||
const [selectedTerminals, setSelectedTerminals] = useState<Set<string>>(
|
||||
() => new Set(),
|
||||
);
|
||||
useEffect(() => {
|
||||
setSelectedTerminals((prev) => {
|
||||
const open = new Set(openTerminals.map((terminal) => terminal.id));
|
||||
const next = new Set([...prev].filter((id) => open.has(id)));
|
||||
return next.size === prev.size ? prev : next;
|
||||
});
|
||||
}, [openTerminals]);
|
||||
const { hosts } = useHosts();
|
||||
const { confirmWithToast } = useConfirmation();
|
||||
|
||||
const [snippets, setSnippets] = useState<Snippet[]>([]);
|
||||
const [folders, setFolders] = useState<SnippetFolder[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
const [view, setView] = useState<View>({ kind: "list" });
|
||||
// Folders the user opened or closed by hand; the rest follow the setting.
|
||||
const [folderOverrides, setFolderOverrides] = useState<Map<string, boolean>>(
|
||||
new Map(),
|
||||
);
|
||||
const [folderDialog, setFolderDialog] = useState<{
|
||||
folder: SnippetFolder | null;
|
||||
/** The name being edited, set even when the folder has no metadata row. */
|
||||
editName: string | null;
|
||||
} | null>(null);
|
||||
const [dragged, setDragged] = useState<Snippet | null>(null);
|
||||
const [dropTarget, setDropTarget] = useState<{
|
||||
id: number;
|
||||
position: DropPosition;
|
||||
} | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const importOverwriteRef = useRef(false);
|
||||
|
||||
const hostsById = useMemo(
|
||||
() => new Map(hosts.map((host) => [Number(host.id), host])),
|
||||
[hosts],
|
||||
);
|
||||
|
||||
function targetHostsOf(snippet: Snippet): TargetHost[] {
|
||||
if (snippet.isNote) return [];
|
||||
return parseHostFilter(snippet.hostFilter).flatMap((id) => {
|
||||
const host = hostsById.get(id);
|
||||
return host
|
||||
? [
|
||||
{
|
||||
id,
|
||||
name: host.name,
|
||||
ip: host.ip,
|
||||
username: host.username,
|
||||
port: host.port,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!canView) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const [snippetList, folderList] = await Promise.all([
|
||||
client.list(),
|
||||
client.listFolders(),
|
||||
]);
|
||||
setSnippets(Array.isArray(snippetList) ? snippetList : []);
|
||||
setFolders(Array.isArray(folderList) ? folderList : []);
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("loadFailed")));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [canView, client, t]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const query = search.trim().toLowerCase();
|
||||
|
||||
const { groups, rootSnippets } = useMemo(() => {
|
||||
const byFolder = new Map<string, FolderGroup>();
|
||||
for (const folder of folders) {
|
||||
byFolder.set(folder.name, {
|
||||
name: folder.name,
|
||||
folder,
|
||||
snippets: [],
|
||||
});
|
||||
}
|
||||
const root: Snippet[] = [];
|
||||
for (const snippet of snippets) {
|
||||
if (query && !matchesQuery(snippet, query)) continue;
|
||||
if (!snippet.folder) {
|
||||
root.push(snippet);
|
||||
continue;
|
||||
}
|
||||
const group = byFolder.get(snippet.folder) ?? {
|
||||
name: snippet.folder,
|
||||
folder: null,
|
||||
snippets: [],
|
||||
};
|
||||
group.snippets.push(snippet);
|
||||
byFolder.set(snippet.folder, group);
|
||||
}
|
||||
const sorted = Array.from(byFolder.values())
|
||||
.filter((group) => !query || group.snippets.length > 0)
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
return { groups: sorted, rootSnippets: root };
|
||||
}, [folders, snippets, query]);
|
||||
|
||||
const folderNames = useMemo(
|
||||
() =>
|
||||
Array.from(
|
||||
new Set([
|
||||
...folders.map((f) => f.name),
|
||||
...snippets.flatMap((s) => (s.folder ? [s.folder] : [])),
|
||||
]),
|
||||
).sort((a, b) => a.localeCompare(b)),
|
||||
[folders, snippets],
|
||||
);
|
||||
|
||||
function isOpen(name: string): boolean {
|
||||
if (query) return true;
|
||||
return folderOverrides.get(name) ?? !display.foldersCollapsed;
|
||||
}
|
||||
|
||||
function toggleFolder(name: string) {
|
||||
setFolderOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
next.set(name, !isOpen(name));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function setAllFolders(open: boolean) {
|
||||
setFolderOverrides(new Map(folderNames.map((name) => [name, open])));
|
||||
}
|
||||
|
||||
async function handleSaveSnippet(values: SnippetFormValues) {
|
||||
if (view.kind !== "edit") return false;
|
||||
const body = {
|
||||
name: values.name.trim(),
|
||||
content: values.content.trim(),
|
||||
description: values.description.trim() || null,
|
||||
folder: values.folder || null,
|
||||
isNote: values.isNote,
|
||||
hostFilter:
|
||||
!values.isNote && values.hostIds.length > 0 ? values.hostIds : null,
|
||||
};
|
||||
const editing = view.snippet;
|
||||
try {
|
||||
if (editing) {
|
||||
await client.update(editing.id, body);
|
||||
toast.success(t("updateSuccess"));
|
||||
} else {
|
||||
await client.create(body);
|
||||
toast.success(t("createSuccess"));
|
||||
}
|
||||
if (body.folder) {
|
||||
setFolderOverrides((prev) => new Map(prev).set(body.folder!, true));
|
||||
}
|
||||
setView({ kind: "list" });
|
||||
await load();
|
||||
return true;
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
errorMessage(err, t(editing ? "updateFailed" : "createFailed")),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleRun(snippet: Snippet) {
|
||||
const targets = targetHostsOf(snippet);
|
||||
const terminalTargets = toRunTargets(openTerminals, selectedTerminals);
|
||||
if (targets.length > 0 && !snippet.isNote) runOnHosts(snippet, targets);
|
||||
else if (terminalTargets.length > 0) runSnippet(snippet, terminalTargets);
|
||||
else runOnActive(snippet, null);
|
||||
}
|
||||
|
||||
function endDrag() {
|
||||
setDragged(null);
|
||||
setDropTarget(null);
|
||||
}
|
||||
|
||||
// Drops the dragged snippet next to a row, taking that row's folder.
|
||||
async function handleDropOnRow(target: Snippet) {
|
||||
const source = dragged;
|
||||
const position = dropTarget?.position ?? "below";
|
||||
endDrag();
|
||||
if (!source || source.id === target.id) return;
|
||||
|
||||
const folder = target.folder ?? null;
|
||||
const group = snippets.filter(
|
||||
(s) => (s.folder ?? null) === folder && s.id !== source.id,
|
||||
);
|
||||
const index = group.findIndex((s) => s.id === target.id);
|
||||
group.splice(position === "above" ? index : index + 1, 0, {
|
||||
...source,
|
||||
folder,
|
||||
});
|
||||
await saveOrder(group, folder);
|
||||
}
|
||||
|
||||
async function handleDropOnFolder(folder: string) {
|
||||
const source = dragged;
|
||||
endDrag();
|
||||
if (!source || source.folder === folder) return;
|
||||
const group = [
|
||||
...snippets.filter((s) => s.folder === folder && s.id !== source.id),
|
||||
{ ...source, folder },
|
||||
];
|
||||
setFolderOverrides((prev) => new Map(prev).set(folder, true));
|
||||
await saveOrder(group, folder);
|
||||
}
|
||||
|
||||
async function saveOrder(group: Snippet[], folder: string | null) {
|
||||
const ordered = group.map((s, order) => ({ ...s, order }));
|
||||
const byId = new Map(ordered.map((s) => [s.id, s]));
|
||||
setSnippets((prev) => {
|
||||
const rest = prev.filter((s) => !byId.has(s.id));
|
||||
return [...rest, ...ordered];
|
||||
});
|
||||
try {
|
||||
await client.reorder(
|
||||
ordered.map((s) => ({
|
||||
id: s.id,
|
||||
order: s.order,
|
||||
folder: folder ?? "",
|
||||
})),
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("reorderFailed")));
|
||||
await load();
|
||||
}
|
||||
}
|
||||
|
||||
function handleDeleteSnippet(snippet: Snippet) {
|
||||
void confirmWithToast(
|
||||
t("deleteSnippetConfirm", { name: snippet.name }),
|
||||
async () => {
|
||||
try {
|
||||
await client.remove(snippet.id);
|
||||
toast.success(t("deleteSuccess"));
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("deleteFailed")));
|
||||
}
|
||||
},
|
||||
t("delete"),
|
||||
t("cancel"),
|
||||
);
|
||||
}
|
||||
|
||||
async function handleMoveSnippet(snippet: Snippet, folder: string | null) {
|
||||
try {
|
||||
await client.update(snippet.id, { folder });
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("updateFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopy(snippet: Snippet) {
|
||||
const ok = await copyToClipboard(snippet.content);
|
||||
if (ok) toast.success(t("copySuccess"));
|
||||
else toast.error(t("copyFailed"));
|
||||
}
|
||||
|
||||
async function handleSaveFolder(values: FolderFormValues) {
|
||||
const editName = folderDialog?.editName ?? null;
|
||||
try {
|
||||
if (editName === null) {
|
||||
await client.createFolder(values);
|
||||
toast.success(t("folderCreateSuccess"));
|
||||
} else {
|
||||
// A folder named only on its snippets gets a metadata row first.
|
||||
if (!folderDialog?.folder) {
|
||||
await client.createFolder({ name: editName });
|
||||
}
|
||||
if (values.name !== editName) {
|
||||
await client.renameFolder(editName, values.name);
|
||||
setFolderOverrides((prev) => {
|
||||
const next = new Map(prev);
|
||||
const wasOpen = next.get(editName);
|
||||
next.delete(editName);
|
||||
if (wasOpen !== undefined) next.set(values.name, wasOpen);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
await client.updateFolderMetadata(values.name, {
|
||||
color: values.color,
|
||||
icon: values.icon,
|
||||
});
|
||||
toast.success(t("folderEditSuccess"));
|
||||
}
|
||||
setFolderDialog(null);
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(
|
||||
errorMessage(
|
||||
err,
|
||||
t(editName === null ? "folderCreateFailed" : "folderEditFailed"),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function handleDeleteFolder(name: string) {
|
||||
void confirmWithToast(
|
||||
t("deleteFolderConfirm", { name }),
|
||||
async () => {
|
||||
try {
|
||||
await client.deleteFolder(name);
|
||||
toast.success(t("folderDeleteSuccess"));
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("folderDeleteFailed")));
|
||||
}
|
||||
},
|
||||
t("delete"),
|
||||
t("cancel"),
|
||||
);
|
||||
}
|
||||
|
||||
async function handleExport() {
|
||||
try {
|
||||
const data = await client.export();
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], {
|
||||
type: "application/json",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "termix-snippets.json";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
toast.success(t("exportSuccess"));
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("exportFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
async function handleImport(file: File) {
|
||||
let parsed: { snippets?: unknown; folders?: unknown };
|
||||
try {
|
||||
parsed = JSON.parse(await file.text());
|
||||
} catch {
|
||||
toast.error(t("importInvalidFile"));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== "object" ||
|
||||
(!Array.isArray(parsed.snippets) && !Array.isArray(parsed.folders))
|
||||
) {
|
||||
toast.error(t("importInvalidFile"));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = (await client.bulkImport({
|
||||
snippets: Array.isArray(parsed.snippets) ? parsed.snippets : [],
|
||||
folders: Array.isArray(parsed.folders) ? parsed.folders : [],
|
||||
overwrite: importOverwriteRef.current,
|
||||
})) as {
|
||||
snippetsImported?: number;
|
||||
snippetsUpdated?: number;
|
||||
snippetsSkipped?: number;
|
||||
};
|
||||
toast.success(
|
||||
t("importSuccess", {
|
||||
imported: result.snippetsImported ?? 0,
|
||||
updated: result.snippetsUpdated ?? 0,
|
||||
skipped: result.snippetsSkipped ?? 0,
|
||||
}),
|
||||
);
|
||||
await load();
|
||||
} catch (err) {
|
||||
toast.error(errorMessage(err, t("importFailed")));
|
||||
}
|
||||
}
|
||||
|
||||
function startImport(overwrite: boolean) {
|
||||
importOverwriteRef.current = overwrite;
|
||||
fileInputRef.current?.click();
|
||||
}
|
||||
|
||||
if (!canView) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (view.kind === "edit") {
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<SnippetEditor
|
||||
snippet={view.snippet}
|
||||
defaultFolder={view.folder}
|
||||
folders={folders}
|
||||
onBack={() => setView({ kind: "list" })}
|
||||
onSave={handleSaveSnippet}
|
||||
/>
|
||||
{runnerDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (view.kind === "share") {
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<SnippetShareView
|
||||
target={view.target}
|
||||
client={client}
|
||||
onBack={() => setView({ kind: "list" })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (view.kind === "settings") {
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<SnippetSettings
|
||||
settings={settings}
|
||||
onBack={() => setView({ kind: "list" })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
let stripe = 0;
|
||||
const renderSnippet = (snippet: Snippet) => (
|
||||
<SnippetRow
|
||||
key={snippet.id}
|
||||
snippet={snippet}
|
||||
stripeIndex={stripe++}
|
||||
showCommand={display.showCommands}
|
||||
folderNames={folderNames}
|
||||
targetHostNames={targetHostsOf(snippet).map(
|
||||
(host) => host.name || host.ip || String(host.id),
|
||||
)}
|
||||
canEdit={canEdit}
|
||||
canDelete={canDelete}
|
||||
canShare={canShare}
|
||||
draggable={canEdit && !snippet.isShared && !query}
|
||||
dragActive={dragged !== null}
|
||||
isDragging={dragged?.id === snippet.id}
|
||||
dropIndicator={
|
||||
dropTarget?.id === snippet.id && dragged?.id !== snippet.id
|
||||
? dropTarget.position
|
||||
: null
|
||||
}
|
||||
onRun={() => handleRun(snippet)}
|
||||
onCopy={() => void handleCopy(snippet)}
|
||||
onEdit={() => setView({ kind: "edit", snippet })}
|
||||
onShare={() =>
|
||||
setView({ kind: "share", target: { kind: "snippet", snippet } })
|
||||
}
|
||||
onMove={(folder) => void handleMoveSnippet(snippet, folder)}
|
||||
onDelete={() => handleDeleteSnippet(snippet)}
|
||||
onDragStart={() => setDragged(snippet)}
|
||||
onDragEnd={endDrag}
|
||||
onDragOverRow={(position) =>
|
||||
setDropTarget((prev) =>
|
||||
prev?.id === snippet.id && prev.position === position
|
||||
? prev
|
||||
: { id: snippet.id, position },
|
||||
)
|
||||
}
|
||||
onDropRow={() => void handleDropOnRow(snippet)}
|
||||
/>
|
||||
);
|
||||
|
||||
const isEmpty = groups.length === 0 && rootSnippets.length === 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<div className="flex flex-col px-2 py-1.5 shrink-0 border-b border-border/60 gap-1.5">
|
||||
<div className="flex items-center gap-2 px-2.5 h-7 bg-muted/60 border border-border/60">
|
||||
<Search className="size-3 text-muted-foreground/60 shrink-0" />
|
||||
<input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t("searchPlaceholder")}
|
||||
className="flex-1 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50 text-foreground min-w-0"
|
||||
/>
|
||||
{search && (
|
||||
<button
|
||||
onClick={() => setSearch("")}
|
||||
title={t("clearSearch")}
|
||||
className="text-muted-foreground/60 hover:text-muted-foreground transition-colors"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TargetTerminals
|
||||
terminals={openTerminals}
|
||||
selected={selectedTerminals}
|
||||
onChange={setSelectedTerminals}
|
||||
/>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (file) void handleImport(file);
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-1.5 overflow-x-auto overflow-y-hidden toolbar-scrollbar">
|
||||
<div className="flex items-center border border-border shrink-0">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-foreground"
|
||||
title={t("importExport")}
|
||||
>
|
||||
<Upload className="size-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="text-xs">
|
||||
{canCreate && (
|
||||
<>
|
||||
<DropdownMenuItem onClick={() => startImport(false)}>
|
||||
<Upload className="size-3.5 mr-2" />
|
||||
{t("importSkipExisting")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => startImport(true)}>
|
||||
<Upload className="size-3.5 mr-2" />
|
||||
{t("importOverwrite")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => void handleExport()}
|
||||
disabled={snippets.length === 0}
|
||||
>
|
||||
<Download className="size-3.5 mr-2" />
|
||||
{t("exportSnippets")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<div className="w-px self-stretch bg-border" />
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 text-muted-foreground hover:text-foreground"
|
||||
title={t("moreActions")}
|
||||
>
|
||||
<MoreHorizontal className="size-3.5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="text-xs min-w-44">
|
||||
{canCreate && (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
setFolderDialog({ folder: null, editName: null })
|
||||
}
|
||||
>
|
||||
<FolderPlus className="size-3.5 mr-2" />
|
||||
{t("newFolder")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => setAllFolders(true)}>
|
||||
<ChevronsUpDown className="size-3.5 mr-2" />
|
||||
{t("expandAll")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setAllFolders(false)}>
|
||||
<ChevronsDownUp className="size-3.5 mr-2" />
|
||||
{t("collapseAll")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<div className="w-px self-stretch bg-border" />
|
||||
<a
|
||||
href={DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
title={t("docsLink")}
|
||||
className="flex items-center justify-center size-7 text-muted-foreground hover:text-foreground shrink-0 transition-colors"
|
||||
>
|
||||
<ExternalLink className="size-3.5" />
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex items-center border border-border shrink-0">
|
||||
<button
|
||||
onClick={() => setView({ kind: "settings" })}
|
||||
title={t("settingsTitle")}
|
||||
className="flex items-center justify-center size-7 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors shrink-0"
|
||||
>
|
||||
<SlidersHorizontal className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<div className="flex items-center border border-accent-brand/30 ml-auto shrink-0">
|
||||
<button
|
||||
onClick={() => setView({ kind: "edit", snippet: null })}
|
||||
title={t("newSnippet")}
|
||||
className="flex items-center justify-center gap-1 h-7 px-2 text-[10px] font-medium text-accent-brand hover:bg-accent-brand/10 transition-colors"
|
||||
>
|
||||
<Plus className="size-3 shrink-0" />
|
||||
<span className="hidden min-[280px]:inline">
|
||||
{t("newSnippet")}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto">
|
||||
{loading ? (
|
||||
<div className="p-4 text-xs text-muted-foreground">
|
||||
{t("loading")}
|
||||
</div>
|
||||
) : isEmpty ? (
|
||||
<div className="flex flex-col items-center gap-1 px-4 py-8 text-center">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{t(query ? "noSearchResults" : "emptyTitle")}
|
||||
</span>
|
||||
{!query && (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{t("emptyDescription")}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{groups.map((group, index) => {
|
||||
const open = isOpen(group.name);
|
||||
return (
|
||||
<SnippetFolderRow
|
||||
key={group.name}
|
||||
name={group.name}
|
||||
folder={group.folder}
|
||||
count={group.snippets.length}
|
||||
open={open}
|
||||
stripeIndex={index}
|
||||
canCreate={canCreate}
|
||||
canEdit={canEdit}
|
||||
canDelete={canDelete}
|
||||
canShare={canShare}
|
||||
acceptsDrop={
|
||||
dragged !== null && dragged.folder !== group.name
|
||||
}
|
||||
onToggle={() => toggleFolder(group.name)}
|
||||
onAddSnippet={() =>
|
||||
setView({
|
||||
kind: "edit",
|
||||
snippet: null,
|
||||
folder: group.name,
|
||||
})
|
||||
}
|
||||
onEdit={() =>
|
||||
setFolderDialog({
|
||||
folder: group.folder,
|
||||
editName: group.name,
|
||||
})
|
||||
}
|
||||
onShare={() =>
|
||||
setView({
|
||||
kind: "share",
|
||||
target: { kind: "folder", name: group.name },
|
||||
})
|
||||
}
|
||||
onDelete={() => handleDeleteFolder(group.name)}
|
||||
onDropSnippet={() => void handleDropOnFolder(group.name)}
|
||||
>
|
||||
{open && group.snippets.map(renderSnippet)}
|
||||
</SnippetFolderRow>
|
||||
);
|
||||
})}
|
||||
{rootSnippets.map(renderSnippet)}
|
||||
{dragged?.folder && (
|
||||
<div
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
const source = dragged;
|
||||
endDrag();
|
||||
void saveOrder(
|
||||
[
|
||||
...snippets.filter((s) => !s.folder),
|
||||
{ ...source, folder: null },
|
||||
],
|
||||
null,
|
||||
);
|
||||
}}
|
||||
className="m-2 px-3 py-3 text-center text-[11px] text-muted-foreground border border-dashed border-border"
|
||||
>
|
||||
{t("dropToRemoveFromFolder")}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{folderDialog && (
|
||||
<SnippetFolderDialog
|
||||
folder={
|
||||
folderDialog.folder ??
|
||||
(folderDialog.editName
|
||||
? ({
|
||||
name: folderDialog.editName,
|
||||
color: null,
|
||||
icon: null,
|
||||
} as SnippetFolder)
|
||||
: null)
|
||||
}
|
||||
onClose={() => setFolderDialog(null)}
|
||||
onSave={handleSaveFolder}
|
||||
/>
|
||||
)}
|
||||
{runnerDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Terminal } from "lucide-react";
|
||||
import { invokeAction, useTranslation } from "@termix/plugin-sdk/frontend";
|
||||
import type { RunTarget } from "./use-snippet-runner";
|
||||
|
||||
export interface OpenTerminal {
|
||||
id: string;
|
||||
label?: string;
|
||||
hostName?: string;
|
||||
ip?: string;
|
||||
username?: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
const POLL_MS = 1500;
|
||||
|
||||
/** The open terminal sessions, refreshed while the panel is on screen. */
|
||||
export function useOpenTerminals(): OpenTerminal[] {
|
||||
const [terminals, setTerminals] = useState<OpenTerminal[]>([]);
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = () => {
|
||||
void invokeAction("terminal.listSessions")
|
||||
.then((result) => {
|
||||
if (cancelled) return;
|
||||
const next = Array.isArray(result) ? (result as OpenTerminal[]) : [];
|
||||
setTerminals((prev) =>
|
||||
prev.length === next.length &&
|
||||
prev.every(
|
||||
(item, i) =>
|
||||
item.id === next[i].id && item.label === next[i].label,
|
||||
)
|
||||
? prev
|
||||
: next,
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setTerminals([]);
|
||||
});
|
||||
};
|
||||
load();
|
||||
const timer = setInterval(load, POLL_MS);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, []);
|
||||
return terminals;
|
||||
}
|
||||
|
||||
export function toRunTargets(
|
||||
terminals: OpenTerminal[],
|
||||
selected: Set<string>,
|
||||
): RunTarget[] {
|
||||
return terminals
|
||||
.filter((terminal) => selected.has(terminal.id))
|
||||
.map((terminal) => ({
|
||||
sessionId: terminal.id,
|
||||
host: {
|
||||
name: terminal.hostName,
|
||||
ip: terminal.ip,
|
||||
username: terminal.username,
|
||||
port: terminal.port,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
/** Pick terminals to run in; with none picked a snippet runs in the active one. */
|
||||
export function TargetTerminals({
|
||||
terminals,
|
||||
selected,
|
||||
onChange,
|
||||
}: {
|
||||
terminals: OpenTerminal[];
|
||||
selected: Set<string>;
|
||||
onChange: (next: Set<string>) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (terminals.length < 2) return null;
|
||||
|
||||
const toggle = (id: string) => {
|
||||
const next = new Set(selected);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center justify-between px-0.5">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
{t("targetTerminals")}{" "}
|
||||
<span className="font-normal normal-case tracking-normal text-muted-foreground/60">
|
||||
({t("targetTerminalsHint")})
|
||||
</span>
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(new Set(terminals.map((item) => item.id)))}
|
||||
className="text-[10px] text-accent-brand hover:text-accent-brand/70"
|
||||
>
|
||||
{t("selectAll")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(new Set())}
|
||||
className="text-[10px] text-accent-brand hover:text-accent-brand/70"
|
||||
>
|
||||
{t("selectNone")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5 max-h-32 overflow-y-auto thin-scrollbar">
|
||||
{terminals.map((terminal) => {
|
||||
const isSelected = selected.has(terminal.id);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={terminal.id}
|
||||
aria-pressed={isSelected}
|
||||
onClick={() => toggle(terminal.id)}
|
||||
className={`flex items-center gap-2 px-2 py-1 border text-left transition-colors ${
|
||||
isSelected
|
||||
? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand"
|
||||
: "border-border text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`size-3 border-2 flex items-center justify-center shrink-0 ${
|
||||
isSelected
|
||||
? "border-accent-brand bg-accent-brand"
|
||||
: "border-border/60"
|
||||
}`}
|
||||
>
|
||||
{isSelected && <span className="size-1.5 bg-background" />}
|
||||
</span>
|
||||
<Terminal className="size-3 shrink-0 opacity-60" />
|
||||
<span className="text-xs truncate flex-1">
|
||||
{terminal.label || terminal.hostName || terminal.id}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import {
|
||||
Box,
|
||||
Cloud,
|
||||
Copy,
|
||||
Cpu,
|
||||
Database,
|
||||
Folder,
|
||||
Globe,
|
||||
Network,
|
||||
Server,
|
||||
Settings,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import type { FolderIconId } from "./types";
|
||||
|
||||
const ICONS: Record<FolderIconId, LucideIcon> = {
|
||||
folder: Folder,
|
||||
server: Server,
|
||||
cloud: Cloud,
|
||||
database: Database,
|
||||
box: Box,
|
||||
network: Network,
|
||||
copy: Copy,
|
||||
settings: Settings,
|
||||
cpu: Cpu,
|
||||
globe: Globe,
|
||||
};
|
||||
|
||||
export function FolderIcon({
|
||||
icon,
|
||||
className,
|
||||
style,
|
||||
}: {
|
||||
icon: string | null | undefined;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}) {
|
||||
const Icon = ICONS[(icon ?? "folder") as FolderIconId] ?? Folder;
|
||||
return <Icon className={className} style={style} />;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { Clipboard, Play } from "lucide-react";
|
||||
import type {
|
||||
PaletteItem,
|
||||
PanelProps,
|
||||
PluginHostRecord,
|
||||
TermixApp,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import type { Snippet } from "./types";
|
||||
import { SnippetsPanel } from "./SnippetsPanel";
|
||||
import { createSnippetsApi } from "./snippets-api";
|
||||
import {
|
||||
extractSnippetInputs,
|
||||
resolveSnippetContent,
|
||||
type SnippetHostContext,
|
||||
} from "../shared/variables.js";
|
||||
import {
|
||||
readStartupSnippetId,
|
||||
snippetHostSettings,
|
||||
} from "../shared/host-settings.js";
|
||||
import { AdminUserSnippets } from "./AdminUserSnippets";
|
||||
import { SnippetOverlay } from "./SnippetOverlay";
|
||||
import { HostSnippetsSection } from "./HostSnippetsSection";
|
||||
import { QuickActionButtons } from "./QuickActionButtons";
|
||||
import { resetPrompts } from "./prompt-store";
|
||||
import { fetchSnippet, runInSession } from "./run-flows";
|
||||
import {
|
||||
RUN_SNIPPET_ACTION,
|
||||
RunSnippetEditor,
|
||||
RunSnippetSummary,
|
||||
runSnippetBinding,
|
||||
validateRunSnippet,
|
||||
} from "./keybinding";
|
||||
|
||||
function hostContext(host: unknown): SnippetHostContext | null {
|
||||
if (!host || typeof host !== "object") return null;
|
||||
const record = host as Record<string, unknown>;
|
||||
return {
|
||||
ip: typeof record.ip === "string" ? record.ip : undefined,
|
||||
username: typeof record.username === "string" ? record.username : undefined,
|
||||
port:
|
||||
typeof record.port === "number" || typeof record.port === "string"
|
||||
? record.port
|
||||
: undefined,
|
||||
name: typeof record.name === "string" ? record.name : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function activate(app: TermixApp): void {
|
||||
app.onDispose(resetPrompts);
|
||||
|
||||
app.registerRailItem({
|
||||
id: "snippets",
|
||||
icon: Play,
|
||||
titleKey: "nav.snippets",
|
||||
permission: "view",
|
||||
// The most approachable power feature, so Simple keeps it.
|
||||
simplePreset: true,
|
||||
});
|
||||
|
||||
app.registerPanel("snippets", (props: PanelProps) => (
|
||||
<SnippetsPanel {...props} />
|
||||
));
|
||||
|
||||
app.registerPaletteEntry({
|
||||
id: "snippets.run",
|
||||
titleKey: "nav.snippets",
|
||||
scope: "global",
|
||||
icon: Play,
|
||||
run: async (shell) => {
|
||||
shell.openRailView("snippets");
|
||||
},
|
||||
});
|
||||
|
||||
// Every snippet in the command palette, run in the terminal the user is
|
||||
// working in.
|
||||
app.registerPaletteGroup({
|
||||
id: "snippets",
|
||||
titleKey: "nav.snippets",
|
||||
order: 10,
|
||||
load: async (): Promise<PaletteItem[]> => {
|
||||
if (!(await app.hasPermission("view"))) return [];
|
||||
const snippets: Snippet[] = await createSnippetsApi(app.api)
|
||||
.list()
|
||||
.catch(() => []);
|
||||
return snippets.map((snippet) => ({
|
||||
id: String(snippet.id),
|
||||
title: snippet.name,
|
||||
description: snippet.content,
|
||||
icon: snippet.isNote ? Clipboard : Play,
|
||||
keywords: [snippet.description ?? ""],
|
||||
needsTarget: true,
|
||||
hint: app.t(snippet.isNote ? "paletteHintPaste" : "paletteHintRun"),
|
||||
run: ({ targetTab }) => {
|
||||
if (!targetTab) return;
|
||||
void runInSession(
|
||||
app,
|
||||
snippet,
|
||||
{ sessionId: targetTab.id },
|
||||
hostContext(targetTab.host),
|
||||
{ announce: true },
|
||||
);
|
||||
},
|
||||
}));
|
||||
},
|
||||
});
|
||||
|
||||
// Keeps the input dialog and the confirm setting alive at the shell root.
|
||||
app.registerSlotContribution("shell.overlay", {
|
||||
actionId: "snippets.overlay",
|
||||
titleKey: "nav.snippets",
|
||||
kind: "component",
|
||||
component: SnippetOverlay as never,
|
||||
});
|
||||
|
||||
app.registerKeybindingAction({
|
||||
id: RUN_SNIPPET_ACTION,
|
||||
titleKey: "keybindings.runSnippet",
|
||||
editor: RunSnippetEditor,
|
||||
summary: RunSnippetSummary,
|
||||
validate: validateRunSnippet,
|
||||
run: (action, context) => runSnippetBinding(app, action, context),
|
||||
});
|
||||
|
||||
app.registerHostEditorSection({
|
||||
id: "snippets",
|
||||
group: "ssh",
|
||||
titleKey: "host.tabTitle",
|
||||
icon: Play,
|
||||
order: 15,
|
||||
defaults: true,
|
||||
component: HostSnippetsSection,
|
||||
});
|
||||
|
||||
// Host Metrics shows a host's quick actions as toolbar buttons.
|
||||
app.registerSlotContribution("host-metrics.toolbar", {
|
||||
actionId: "snippets.quickActions",
|
||||
titleKey: "host.quickActionsTitle",
|
||||
kind: "component",
|
||||
component: QuickActionButtons,
|
||||
});
|
||||
|
||||
app.registerSlotContribution("onboarding.features", {
|
||||
actionId: "snippets.feature",
|
||||
titleKey: "onboarding.feature_snippets",
|
||||
descriptionKey: "onboarding.feature_snippets_desc",
|
||||
icon: Play,
|
||||
});
|
||||
|
||||
// The admin "manage user" panel's Snippets tab.
|
||||
app.registerSlotContribution("admin.userTabs", {
|
||||
actionId: "snippets.adminUserTab",
|
||||
titleKey: "admin.tabTitle",
|
||||
kind: "component",
|
||||
component: AdminUserSnippets as never,
|
||||
order: 10,
|
||||
});
|
||||
|
||||
// The command a terminal types when it connects to a host: the host's
|
||||
// startup snippet with its variables filled in, or null.
|
||||
app.registerAction("snippets.startupCommand", (async (
|
||||
host: PluginHostRecord | null,
|
||||
vars?: SnippetHostContext,
|
||||
) => {
|
||||
const id = readStartupSnippetId(snippetHostSettings(host).startupSnippetId);
|
||||
if (id === null) return null;
|
||||
const snippet = await fetchSnippet(app, id);
|
||||
if (!snippet) return null;
|
||||
return resolveSnippetContent(snippet.content, vars ?? hostContext(host));
|
||||
}) as never);
|
||||
|
||||
// For pickers in other plugins (the AI assistant's @-mentions): id and name.
|
||||
app.registerAction("snippets.list", (async () => {
|
||||
const snippets = await createSnippetsApi(app.api)
|
||||
.list()
|
||||
.catch(() => []);
|
||||
return snippets.map((snippet) => ({ id: snippet.id, name: snippet.name }));
|
||||
}) as never);
|
||||
|
||||
// Variable handling for commands other plugins run (fleets' run box).
|
||||
app.registerAction("snippets.extractInputs", ((content: string) =>
|
||||
extractSnippetInputs(typeof content === "string" ? content : "")) as never);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import {
|
||||
useTranslation,
|
||||
type KeybindingAction,
|
||||
type KeybindingActionEditorProps,
|
||||
type KeybindingRunContext,
|
||||
type TermixApp,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { fetchSnippet, runInSession } from "./run-flows";
|
||||
import { useSnippetOptions } from "./use-snippet-options";
|
||||
|
||||
/** Stored as action.type; kept from 2.8 so saved bindings keep working. */
|
||||
export const RUN_SNIPPET_ACTION = "runSnippet";
|
||||
|
||||
function snippetIdOf(action: KeybindingAction): string {
|
||||
return typeof action.snippetId === "string" ? action.snippetId : "";
|
||||
}
|
||||
|
||||
/** Picks the snippet a "Run snippet" binding runs. */
|
||||
export function RunSnippetEditor({
|
||||
action,
|
||||
onChange,
|
||||
}: KeybindingActionEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { options } = useSnippetOptions();
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<label className="text-xs font-semibold">
|
||||
{t("keybindings.snippetLabel")}
|
||||
</label>
|
||||
<select
|
||||
aria-label={t("keybindings.snippetLabel")}
|
||||
value={snippetIdOf(action)}
|
||||
onChange={(e) =>
|
||||
onChange({
|
||||
type: RUN_SNIPPET_ACTION,
|
||||
snippetId: e.target.value || undefined,
|
||||
appendEnter: true,
|
||||
})
|
||||
}
|
||||
className="h-8 border border-border bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring"
|
||||
>
|
||||
<option value="">{t("keybindings.selectSnippet")}</option>
|
||||
{options.map((snippet) => (
|
||||
<option key={snippet.id} value={String(snippet.id)}>
|
||||
{snippet.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The bound snippet's name in the binding list, or a warning once it is gone. */
|
||||
export function RunSnippetSummary({ action }: KeybindingActionEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { options, loaded } = useSnippetOptions();
|
||||
if (!loaded) return null;
|
||||
const snippet = options.find((s) => String(s.id) === snippetIdOf(action));
|
||||
if (snippet) return <span>({snippet.name})</span>;
|
||||
return (
|
||||
<span className="text-destructive">
|
||||
({t("keybindings.snippetMissing")})
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function validateRunSnippet(action: KeybindingAction): string | null {
|
||||
return /^\d+$/.test(snippetIdOf(action))
|
||||
? null
|
||||
: "keybindings.snippetRequired";
|
||||
}
|
||||
|
||||
/** Runs a bound snippet in the terminal the key was pressed in. */
|
||||
export function runSnippetBinding(
|
||||
app: Pick<TermixApp, "api" | "t">,
|
||||
action: KeybindingAction,
|
||||
context: KeybindingRunContext,
|
||||
): void {
|
||||
void fetchSnippet(app, Number(snippetIdOf(action))).then((snippet) => {
|
||||
if (!snippet) return;
|
||||
void runInSession(
|
||||
app,
|
||||
{ ...snippet, isNote: false },
|
||||
{ sessionId: context.sessionId, send: context.send },
|
||||
context.host ?? null,
|
||||
{ pressEnter: action.appendEnter !== false },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import type { SnippetHostContext } from "../shared/variables.js";
|
||||
|
||||
export interface PendingPrompt {
|
||||
snippet: { name: string; content: string };
|
||||
host: SnippetHostContext | null;
|
||||
settle: (values: Record<string, string> | null) => void;
|
||||
}
|
||||
|
||||
let pending: PendingPrompt | null = null;
|
||||
let confirmExecution = false;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function notify(): void {
|
||||
for (const listener of [...listeners]) listener();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for a snippet's $INPUT_n values through the dialog the overlay draws.
|
||||
* Resolves null when the user cancels. A second request cancels the first.
|
||||
*/
|
||||
export function askForInputs(
|
||||
snippet: { name: string; content: string },
|
||||
host: SnippetHostContext | null,
|
||||
): Promise<Record<string, string> | null> {
|
||||
pending?.settle(null);
|
||||
return new Promise((resolve) => {
|
||||
const prompt: PendingPrompt = {
|
||||
snippet,
|
||||
host,
|
||||
settle: (values) => {
|
||||
if (pending === prompt) {
|
||||
pending = null;
|
||||
notify();
|
||||
}
|
||||
resolve(values);
|
||||
},
|
||||
};
|
||||
pending = prompt;
|
||||
notify();
|
||||
});
|
||||
}
|
||||
|
||||
export function usePendingPrompt(): PendingPrompt | null {
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => pending,
|
||||
() => pending,
|
||||
);
|
||||
}
|
||||
|
||||
/** Kept current by the overlay from the user's confirmExecution setting. */
|
||||
export function setConfirmExecution(value: boolean): void {
|
||||
confirmExecution = value;
|
||||
}
|
||||
|
||||
export function shouldConfirmExecution(): boolean {
|
||||
return confirmExecution;
|
||||
}
|
||||
|
||||
/** Cancels anything waiting, for deactivate. */
|
||||
export function resetPrompts(): void {
|
||||
pending?.settle(null);
|
||||
pending = null;
|
||||
confirmExecution = false;
|
||||
notify();
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { toast } from "sonner";
|
||||
import { invokeAction, type TermixApp } from "@termix/plugin-sdk/frontend";
|
||||
import {
|
||||
hasSnippetInputs,
|
||||
resolveSnippetContent,
|
||||
type SnippetHostContext,
|
||||
} from "../shared/variables.js";
|
||||
import { askForInputs, shouldConfirmExecution } from "./prompt-store";
|
||||
import { createSnippetsApi } from "./snippets-api";
|
||||
|
||||
export interface RunnableSnippet {
|
||||
id: number;
|
||||
name: string;
|
||||
content: string;
|
||||
isNote?: boolean;
|
||||
}
|
||||
|
||||
/** Where a run sends its text: a session by id, or a raw writer. */
|
||||
export interface RunTarget {
|
||||
sessionId?: string;
|
||||
send?: (data: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The snippet with its variables filled in, asking for $INPUT_n values when
|
||||
* it has any. Null when the user cancels.
|
||||
*/
|
||||
export async function resolveForRun(
|
||||
snippet: { name: string; content: string },
|
||||
host: SnippetHostContext | null,
|
||||
): Promise<string | null> {
|
||||
if (!hasSnippetInputs(snippet.content)) {
|
||||
return resolveSnippetContent(snippet.content, host);
|
||||
}
|
||||
const values = await askForInputs(snippet, host);
|
||||
if (!values) return null;
|
||||
return resolveSnippetContent(snippet.content, host, values);
|
||||
}
|
||||
|
||||
/** Runs `execute` now, or after the user confirms when they asked to. */
|
||||
export function confirmThenRun(
|
||||
app: Pick<TermixApp, "t">,
|
||||
name: string,
|
||||
execute: () => void,
|
||||
): void {
|
||||
if (!shouldConfirmExecution()) {
|
||||
execute();
|
||||
return;
|
||||
}
|
||||
toast(app.t("confirmRunMessage", { name }), {
|
||||
action: { label: app.t("confirmRunButton"), onClick: execute },
|
||||
duration: 6000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Types a snippet into a terminal session: resolves its variables, asks for
|
||||
* inputs and confirmation as the user's settings say, then sends it. A note
|
||||
* is pasted without running.
|
||||
*/
|
||||
export async function runInSession(
|
||||
app: Pick<TermixApp, "t">,
|
||||
snippet: RunnableSnippet,
|
||||
target: RunTarget,
|
||||
host: SnippetHostContext | null,
|
||||
options: { pressEnter?: boolean; announce?: boolean } = {},
|
||||
): Promise<void> {
|
||||
const content = await resolveForRun(snippet, host);
|
||||
if (content === null) return;
|
||||
const run = !snippet.isNote && options.pressEnter !== false;
|
||||
const send = async () => {
|
||||
let sent = true;
|
||||
if (target.send) {
|
||||
target.send(content + (run ? "\r" : ""));
|
||||
} else if (target.sessionId) {
|
||||
sent =
|
||||
(await invokeAction(
|
||||
"terminal.sendToSession",
|
||||
target.sessionId,
|
||||
content,
|
||||
{
|
||||
run,
|
||||
},
|
||||
)) === true;
|
||||
} else {
|
||||
sent = false;
|
||||
}
|
||||
if (!options.announce) return;
|
||||
if (!sent) {
|
||||
toast.error(app.t("noTerminalTabsOpen"));
|
||||
return;
|
||||
}
|
||||
toast.success(
|
||||
app.t(snippet.isNote ? "pasteSuccess" : "runSuccess", {
|
||||
name: snippet.name,
|
||||
count: 1,
|
||||
}),
|
||||
);
|
||||
};
|
||||
if (snippet.isNote) void send();
|
||||
else confirmThenRun(app, snippet.name, () => void send());
|
||||
}
|
||||
|
||||
/** One snippet by id, or null when it is gone or unreadable. */
|
||||
export async function fetchSnippet(
|
||||
app: Pick<TermixApp, "api">,
|
||||
id: number,
|
||||
): Promise<RunnableSnippet | null> {
|
||||
if (!Number.isInteger(id) || id <= 0) return null;
|
||||
const snippet = await createSnippetsApi(app.api)
|
||||
.get(id)
|
||||
.catch(() => null);
|
||||
return snippet
|
||||
? {
|
||||
id: snippet.id,
|
||||
name: snippet.name,
|
||||
content: snippet.content,
|
||||
isNote: snippet.isNote,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export interface SnippetDisplaySettings {
|
||||
foldersCollapsed: boolean;
|
||||
showCommands: boolean;
|
||||
confirmExecution: boolean;
|
||||
}
|
||||
|
||||
export function readSnippetSettings(
|
||||
values: Record<string, unknown>,
|
||||
): SnippetDisplaySettings {
|
||||
return {
|
||||
foldersCollapsed: values.foldersCollapsed !== false,
|
||||
showCommands: values.showCommands !== false,
|
||||
confirmExecution: values.confirmExecution === true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { PluginApiClient } from "@termix/plugin-sdk/frontend";
|
||||
import type { Snippet, SnippetAccessEntry, SnippetFolder } from "./types";
|
||||
|
||||
export interface NewSnippetInput {
|
||||
name: string;
|
||||
content: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
order?: number | null;
|
||||
hostFilter?: unknown;
|
||||
isNote?: boolean;
|
||||
}
|
||||
|
||||
export interface SnippetUpdateInput {
|
||||
name?: string;
|
||||
content?: string;
|
||||
description?: string | null;
|
||||
folder?: string | null;
|
||||
order?: number;
|
||||
hostFilter?: unknown;
|
||||
isNote?: boolean;
|
||||
}
|
||||
|
||||
export interface SnippetReorderUpdate {
|
||||
id: number;
|
||||
order: number;
|
||||
folder?: string;
|
||||
}
|
||||
|
||||
export interface SnippetExecutionResult {
|
||||
success: boolean;
|
||||
output: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ShareableUser {
|
||||
id: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface ShareableRole {
|
||||
id: number;
|
||||
name: string;
|
||||
displayName: string | null;
|
||||
}
|
||||
|
||||
export interface SnippetShareInput {
|
||||
targetType: "user" | "role";
|
||||
targetUserId?: string;
|
||||
targetRoleId?: number;
|
||||
expiresAt?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The snippets routes, through the plugin's own client. Paths are relative
|
||||
* to /plugin-api/snippets/, which the client already points at.
|
||||
*/
|
||||
export function createSnippetsApi(api: PluginApiClient) {
|
||||
const data = async <T>(request: Promise<{ data: T }>) => (await request).data;
|
||||
|
||||
return {
|
||||
list: () => data(api.get<Snippet[]>("/")),
|
||||
get: (id: number) => data(api.get<Snippet>(`/${id}`)),
|
||||
create: (body: NewSnippetInput) => data(api.post<Snippet>("/", body)),
|
||||
update: (id: number, body: SnippetUpdateInput) =>
|
||||
data(api.put<Snippet>(`/${id}`, body)),
|
||||
remove: (id: number) => data(api.delete<{ success: boolean }>(`/${id}`)),
|
||||
execute: (
|
||||
snippetId: number,
|
||||
hostId: number,
|
||||
inputValues?: Record<string, string>,
|
||||
) =>
|
||||
data(
|
||||
api.post<SnippetExecutionResult>("/execute", {
|
||||
snippetId,
|
||||
hostId,
|
||||
inputValues,
|
||||
}),
|
||||
),
|
||||
reorder: (updates: SnippetReorderUpdate[]) =>
|
||||
data(api.put<{ success: boolean }>("/reorder", { snippets: updates })),
|
||||
export: () =>
|
||||
data(api.get<{ snippets: unknown[]; folders: unknown[] }>("/export")),
|
||||
bulkImport: (body: {
|
||||
snippets?: unknown[];
|
||||
folders?: unknown[];
|
||||
overwrite?: boolean;
|
||||
}) => data(api.post<{ success: boolean }>("/bulk-import", body)),
|
||||
|
||||
listFolders: () => data(api.get<SnippetFolder[]>("/folders")),
|
||||
createFolder: (body: {
|
||||
name: string;
|
||||
color?: string | null;
|
||||
icon?: string | null;
|
||||
}) => data(api.post<SnippetFolder>("/folders", body)),
|
||||
updateFolderMetadata: (
|
||||
name: string,
|
||||
body: { color?: string | null; icon?: string | null },
|
||||
) =>
|
||||
data(
|
||||
api.put<SnippetFolder>(
|
||||
`/folders/${encodeURIComponent(name)}/metadata`,
|
||||
body,
|
||||
),
|
||||
),
|
||||
renameFolder: (oldName: string, newName: string) =>
|
||||
data(
|
||||
api.put<{ success: boolean }>("/folders/rename", { oldName, newName }),
|
||||
),
|
||||
deleteFolder: (name: string) =>
|
||||
data(
|
||||
api.delete<{ success: boolean }>(
|
||||
`/folders/${encodeURIComponent(name)}`,
|
||||
),
|
||||
),
|
||||
|
||||
share: (snippetId: number, body: SnippetShareInput) =>
|
||||
data(api.post<{ success: boolean }>(`/${snippetId}/share`, body)),
|
||||
shareFolder: (folder: string, body: SnippetShareInput) =>
|
||||
data(
|
||||
api.put<{ success: boolean; snippetsShared: number }>("/folder/share", {
|
||||
folder,
|
||||
...body,
|
||||
}),
|
||||
),
|
||||
getAccess: (snippetId: number) =>
|
||||
data(api.get<SnippetAccessEntry[]>(`/${snippetId}/access`)),
|
||||
revokeAccess: (snippetId: number, accessId: number) =>
|
||||
data(
|
||||
api.delete<{ success: boolean }>(`/${snippetId}/access/${accessId}`),
|
||||
),
|
||||
shareTargetUsers: () =>
|
||||
data(api.get<{ users: ShareableUser[] }>("/share-targets/users")),
|
||||
shareTargetRoles: () =>
|
||||
data(api.get<{ roles: ShareableRole[] }>("/share-targets/roles")),
|
||||
listShared: () => data(api.get<{ sharedSnippets: Snippet[] }>("/shared")),
|
||||
};
|
||||
}
|
||||
|
||||
export type SnippetsApi = ReturnType<typeof createSnippetsApi>;
|
||||
@@ -0,0 +1,84 @@
|
||||
export const FOLDER_ICONS = [
|
||||
"folder",
|
||||
"server",
|
||||
"cloud",
|
||||
"database",
|
||||
"box",
|
||||
"network",
|
||||
"copy",
|
||||
"settings",
|
||||
"cpu",
|
||||
"globe",
|
||||
] as const;
|
||||
export type FolderIconId = (typeof FOLDER_ICONS)[number];
|
||||
|
||||
export interface Snippet {
|
||||
id: number;
|
||||
userId: string;
|
||||
name: string;
|
||||
content: string;
|
||||
description: string | null;
|
||||
folder: string | null;
|
||||
order: number;
|
||||
hostFilter: string | null;
|
||||
isNote: boolean;
|
||||
isShared?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SnippetFolder {
|
||||
id: number;
|
||||
userId: string;
|
||||
name: string;
|
||||
color: string | null;
|
||||
icon: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface SnippetAccessEntry {
|
||||
id: number;
|
||||
targetType: "user" | "role";
|
||||
userId: string | null;
|
||||
roleId: number | null;
|
||||
username: string | null;
|
||||
roleName: string | null;
|
||||
roleDisplayName: string | null;
|
||||
grantedBy: string;
|
||||
grantedByUsername: string | null;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** The host ids a command snippet targets, from its stored JSON filter. */
|
||||
export function parseHostFilter(raw: string | null | undefined): number[] {
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return Array.isArray(parsed)
|
||||
? parsed.filter((id): id is number => typeof id === "number")
|
||||
: [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function errorMessage(error: unknown, fallback: string): string {
|
||||
if (
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
"response" in error &&
|
||||
error.response &&
|
||||
typeof error.response === "object" &&
|
||||
"data" in error.response &&
|
||||
error.response.data &&
|
||||
typeof error.response.data === "object" &&
|
||||
"error" in error.response.data &&
|
||||
typeof error.response.data.error === "string"
|
||||
) {
|
||||
return error.response.data.error;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { usePluginApi } from "@termix/plugin-sdk/frontend";
|
||||
import { adminOptions } from "./AdminUserSnippets";
|
||||
|
||||
export interface SnippetOption {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's snippets as picker options: their own, or the target user's
|
||||
* while an admin edits that user's host. `loaded` turns true once the list
|
||||
* came back, so a picker can tell "no snippets" from "not loaded yet".
|
||||
*/
|
||||
export function useSnippetOptions(targetUserId?: string): {
|
||||
options: SnippetOption[];
|
||||
loaded: boolean;
|
||||
} {
|
||||
const api = usePluginApi();
|
||||
const [state, setState] = useState<{
|
||||
options: SnippetOption[];
|
||||
loaded: boolean;
|
||||
}>({ options: [], loaded: false });
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const request = targetUserId
|
||||
? api.get("/", adminOptions(targetUserId))
|
||||
: api.get("/");
|
||||
request
|
||||
.then((response) => {
|
||||
const raw = response.data as unknown;
|
||||
const list = Array.isArray(raw)
|
||||
? raw
|
||||
: ((raw as { snippets?: unknown[] })?.snippets ?? []);
|
||||
const options = (list as Array<{ id?: unknown; name?: unknown }>)
|
||||
.filter((row) => typeof row.id === "number")
|
||||
.map((row) => ({
|
||||
id: row.id as number,
|
||||
name: typeof row.name === "string" ? row.name : `#${row.id}`,
|
||||
}));
|
||||
if (!cancelled) setState({ options, loaded: true });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setState({ options: [], loaded: true });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [api, targetUserId]);
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
invokeAction,
|
||||
usePluginApi,
|
||||
useTranslation,
|
||||
} from "@termix/plugin-sdk/frontend";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
hasSnippetInputs,
|
||||
resolveSnippetContent,
|
||||
type SnippetHostContext,
|
||||
} from "../shared/variables.js";
|
||||
import { SnippetVariablesDialog } from "./SnippetVariablesDialog";
|
||||
import { createSnippetsApi } from "./snippets-api";
|
||||
import {
|
||||
ExecutionResultsDialog,
|
||||
type HostExecutionResult,
|
||||
} from "./ExecutionResultsDialog";
|
||||
import { errorMessage, type Snippet } from "./types";
|
||||
|
||||
export interface TargetHost {
|
||||
id: number;
|
||||
name?: string;
|
||||
ip?: string;
|
||||
username?: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
export interface RunTarget {
|
||||
sessionId: string;
|
||||
host: SnippetHostContext | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared "run this snippet against these terminal sessions" flow: resolves
|
||||
* $HOST-style vars per target, prompts once for $INPUT_n placeholders when
|
||||
* present, and gates on the confirm-before-running setting. Sends through
|
||||
* the ssh-terminal plugin's terminal.sendToActive/sendToSession actions
|
||||
* rather than touching a terminal ref directly, since core's tab state is
|
||||
* not part of the plugin surface. runOnHosts instead runs a command over a
|
||||
* fresh SSH connection to each of the snippet's target hosts.
|
||||
*/
|
||||
export function useSnippetRunner(confirmExecution = false) {
|
||||
const { t } = useTranslation();
|
||||
const api = usePluginApi();
|
||||
const client = useMemo(() => createSnippetsApi(api), [api]);
|
||||
const [execution, setExecution] = useState<{
|
||||
snippetName: string;
|
||||
results: HostExecutionResult[];
|
||||
} | null>(null);
|
||||
const [runningSnippet, setRunningSnippet] = useState<{
|
||||
snippet: Snippet;
|
||||
host: SnippetHostContext | null;
|
||||
onConfirm: (
|
||||
resolvedContent: string,
|
||||
inputValues: Record<string, string>,
|
||||
) => void;
|
||||
} | null>(null);
|
||||
|
||||
const handleConfirmRun = useCallback(
|
||||
(snippet: Snippet, execute: () => void) => {
|
||||
if (!confirmExecution) {
|
||||
execute();
|
||||
return;
|
||||
}
|
||||
toast(t("confirmRunMessage", { name: snippet.name }), {
|
||||
action: {
|
||||
label: t("confirmRunButton"),
|
||||
onClick: execute,
|
||||
},
|
||||
duration: 6000,
|
||||
});
|
||||
},
|
||||
[confirmExecution, t],
|
||||
);
|
||||
|
||||
async function sendResolvedToTarget(
|
||||
target: RunTarget,
|
||||
snippet: Snippet,
|
||||
inputValues: Record<string, string>,
|
||||
) {
|
||||
const content = resolveSnippetContent(
|
||||
snippet.content,
|
||||
target.host,
|
||||
inputValues,
|
||||
);
|
||||
const run = !snippet.isNote;
|
||||
await invokeAction("terminal.sendToSession", target.sessionId, content, {
|
||||
run,
|
||||
});
|
||||
}
|
||||
|
||||
const runSnippet = useCallback(
|
||||
(snippet: Snippet, targets: RunTarget[]) => {
|
||||
const runWithInputs = (inputValues: Record<string, string>) => {
|
||||
const doSend = () => {
|
||||
Promise.all(
|
||||
targets.map((target) =>
|
||||
sendResolvedToTarget(target, snippet, inputValues),
|
||||
),
|
||||
)
|
||||
.then(() => {
|
||||
toast.success(
|
||||
t(snippet.isNote ? "pasteSuccess" : "runSuccess", {
|
||||
name: snippet.name,
|
||||
count: targets.length,
|
||||
}),
|
||||
);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
if (snippet.isNote) doSend();
|
||||
else handleConfirmRun(snippet, doSend);
|
||||
};
|
||||
|
||||
if (hasSnippetInputs(snippet.content)) {
|
||||
setRunningSnippet({
|
||||
snippet,
|
||||
host: targets[0]?.host ?? null,
|
||||
onConfirm: (_resolvedContent, inputValues) => {
|
||||
setRunningSnippet(null);
|
||||
runWithInputs(inputValues);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
runWithInputs({});
|
||||
}
|
||||
},
|
||||
[handleConfirmRun, t],
|
||||
);
|
||||
|
||||
const runOnActive = useCallback(
|
||||
(snippet: Snippet, host: SnippetHostContext | null) => {
|
||||
const runWithInputs = (inputValues: Record<string, string>) => {
|
||||
const doSend = () => {
|
||||
const content = resolveSnippetContent(
|
||||
snippet.content,
|
||||
host,
|
||||
inputValues,
|
||||
);
|
||||
void invokeAction("terminal.sendToActive", content, {
|
||||
run: !snippet.isNote,
|
||||
}).then((sent) => {
|
||||
if (sent === false) {
|
||||
toast.error(t("noTerminalTabsOpen"));
|
||||
return;
|
||||
}
|
||||
toast.success(
|
||||
t(snippet.isNote ? "pasteSuccess" : "runSuccess", {
|
||||
name: snippet.name,
|
||||
count: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
};
|
||||
if (snippet.isNote) doSend();
|
||||
else handleConfirmRun(snippet, doSend);
|
||||
};
|
||||
|
||||
if (hasSnippetInputs(snippet.content)) {
|
||||
setRunningSnippet({
|
||||
snippet,
|
||||
host,
|
||||
onConfirm: (_resolvedContent, inputValues) => {
|
||||
setRunningSnippet(null);
|
||||
runWithInputs(inputValues);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
runWithInputs({});
|
||||
}
|
||||
},
|
||||
[handleConfirmRun, t],
|
||||
);
|
||||
|
||||
const runOnHosts = useCallback(
|
||||
(snippet: Snippet, hosts: TargetHost[]) => {
|
||||
if (hosts.length === 0) return;
|
||||
const execute = (inputValues: Record<string, string>) => {
|
||||
const label = (host: TargetHost) =>
|
||||
host.name || host.ip || String(host.id);
|
||||
setExecution({
|
||||
snippetName: snippet.name,
|
||||
results: hosts.map((host) => ({
|
||||
hostId: host.id,
|
||||
hostLabel: label(host),
|
||||
success: null,
|
||||
output: "",
|
||||
})),
|
||||
});
|
||||
const update = (result: HostExecutionResult) =>
|
||||
setExecution((prev) =>
|
||||
prev
|
||||
? {
|
||||
...prev,
|
||||
results: prev.results.map((r) =>
|
||||
r.hostId === result.hostId ? result : r,
|
||||
),
|
||||
}
|
||||
: prev,
|
||||
);
|
||||
const inputs =
|
||||
Object.keys(inputValues).length > 0 ? inputValues : undefined;
|
||||
void Promise.all(
|
||||
hosts.map(async (host) => {
|
||||
try {
|
||||
const result = await client.execute(snippet.id, host.id, inputs);
|
||||
update({ hostId: host.id, hostLabel: label(host), ...result });
|
||||
return result.success;
|
||||
} catch (err) {
|
||||
update({
|
||||
hostId: host.id,
|
||||
hostLabel: label(host),
|
||||
success: false,
|
||||
output: "",
|
||||
error: errorMessage(err, t("executionFailed")),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
).then((outcomes) => {
|
||||
if (outcomes.every(Boolean)) {
|
||||
toast.success(
|
||||
t("directRunSuccess", {
|
||||
name: snippet.name,
|
||||
count: hosts.length,
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
toast.error(t("directRunPartialFail", { name: snippet.name }));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const runWithInputs = (inputValues: Record<string, string>) =>
|
||||
handleConfirmRun(snippet, () => execute(inputValues));
|
||||
|
||||
if (hasSnippetInputs(snippet.content)) {
|
||||
const first = hosts[0];
|
||||
setRunningSnippet({
|
||||
snippet,
|
||||
host: {
|
||||
ip: first.ip,
|
||||
username: first.username,
|
||||
port: first.port,
|
||||
name: first.name,
|
||||
},
|
||||
onConfirm: (_resolvedContent, inputValues) => {
|
||||
setRunningSnippet(null);
|
||||
runWithInputs(inputValues);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
runWithInputs({});
|
||||
}
|
||||
},
|
||||
[client, handleConfirmRun, t],
|
||||
);
|
||||
|
||||
const variablesDialog = runningSnippet ? (
|
||||
<SnippetVariablesDialog
|
||||
snippet={runningSnippet.snippet}
|
||||
host={runningSnippet.host}
|
||||
onCancel={() => setRunningSnippet(null)}
|
||||
onConfirm={runningSnippet.onConfirm}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
const dialog = (
|
||||
<>
|
||||
{variablesDialog}
|
||||
{execution && (
|
||||
<ExecutionResultsDialog
|
||||
snippetName={execution.snippetName}
|
||||
results={execution.results}
|
||||
onClose={() => setExecution(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
return { runSnippet, runOnActive, runOnHosts, handleConfirmRun, dialog };
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* The snippets plugin's host settings: the startup snippet a terminal runs
|
||||
* when it connects, and the quick action buttons Host Metrics shows.
|
||||
*/
|
||||
|
||||
export const PLUGIN_ID = "snippets";
|
||||
|
||||
export interface QuickAction {
|
||||
name: string;
|
||||
snippetId: number;
|
||||
}
|
||||
|
||||
function snippetId(value: unknown): number | null {
|
||||
const id = typeof value === "string" ? Number(value) : value;
|
||||
return typeof id === "number" && Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/** Quick actions in their stored shape, dropping any without a snippet. */
|
||||
export function readQuickActions(value: unknown): QuickAction[] {
|
||||
let list = value;
|
||||
if (typeof list === "string") {
|
||||
try {
|
||||
list = JSON.parse(list);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list.flatMap((entry): QuickAction[] => {
|
||||
if (!entry || typeof entry !== "object") return [];
|
||||
const id = snippetId((entry as { snippetId?: unknown }).snippetId);
|
||||
if (id === null) return [];
|
||||
const name = (entry as { name?: unknown }).name;
|
||||
return [{ name: typeof name === "string" ? name : "", snippetId: id }];
|
||||
});
|
||||
}
|
||||
|
||||
export function readStartupSnippetId(value: unknown): number | null {
|
||||
return snippetId(value);
|
||||
}
|
||||
|
||||
/** This plugin's slice of a host record's pluginSettings. */
|
||||
export function snippetHostSettings(host: unknown): Record<string, unknown> {
|
||||
const all = (host as { pluginSettings?: Record<string, unknown> } | null)
|
||||
?.pluginSettings;
|
||||
const own = all?.[PLUGIN_ID];
|
||||
return own && typeof own === "object" ? (own as Record<string, unknown>) : {};
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* $HOST, $USER, $PORT, $NAME and $INPUT_n in a command. The one copy: the
|
||||
* frontend, the backend and other plugins (fleets, through the
|
||||
* "snippets.variables" registry entry and action) all use this.
|
||||
*/
|
||||
|
||||
export interface SnippetInput {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface SnippetHostContext {
|
||||
ip?: string;
|
||||
username?: string;
|
||||
port?: number | string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
const INPUT_PATTERN =
|
||||
/\$\{INPUT_(\d+)(?::([^}$]+))?\}|\$INPUT_(\d+)(?![a-zA-Z0-9_])/g;
|
||||
|
||||
export function extractSnippetInputs(content: string): SnippetInput[] {
|
||||
const seen = new Map<string, SnippetInput>();
|
||||
let match: RegExpExecArray | null;
|
||||
INPUT_PATTERN.lastIndex = 0;
|
||||
while ((match = INPUT_PATTERN.exec(content)) !== null) {
|
||||
const digits = match[1] ?? match[3];
|
||||
const key = `INPUT_${digits}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.set(key, { key, label: match[2]?.trim() || `Input ${digits}` });
|
||||
}
|
||||
}
|
||||
return Array.from(seen.values());
|
||||
}
|
||||
|
||||
export function hasSnippetInputs(content: string): boolean {
|
||||
INPUT_PATTERN.lastIndex = 0;
|
||||
return INPUT_PATTERN.test(content);
|
||||
}
|
||||
|
||||
function replaceVar(
|
||||
content: string,
|
||||
name: string,
|
||||
value: string | undefined,
|
||||
): string {
|
||||
if (value === undefined) return content;
|
||||
const pattern = new RegExp(`\\$\\{?${name}\\}?`, "g");
|
||||
return content.replace(pattern, value);
|
||||
}
|
||||
|
||||
export function resolveSnippetContent(
|
||||
content: string,
|
||||
host: SnippetHostContext | null,
|
||||
inputValues: Record<string, string> = {},
|
||||
): string {
|
||||
let resolved = content;
|
||||
|
||||
resolved = replaceVar(resolved, "HOST", host?.ip);
|
||||
resolved = replaceVar(resolved, "USER", host?.username);
|
||||
resolved = replaceVar(
|
||||
resolved,
|
||||
"PORT",
|
||||
host?.port !== undefined ? String(host.port) : undefined,
|
||||
);
|
||||
resolved = replaceVar(resolved, "NAME", host?.name);
|
||||
|
||||
resolved = resolved.replace(
|
||||
INPUT_PATTERN,
|
||||
(
|
||||
fullMatch,
|
||||
braceDigits: string | undefined,
|
||||
_label,
|
||||
plainDigits: string | undefined,
|
||||
) => {
|
||||
const key = `INPUT_${braceDigits ?? plainDigits}`;
|
||||
return key in inputValues ? inputValues[key] : fullMatch;
|
||||
},
|
||||
);
|
||||
|
||||
return resolved;
|
||||
}
|
||||
Reference in new issue
Block a user