Compare commits

..
Author SHA1 Message Date
GOUKI9999 81af709d9b fix(ai): resolve lazy SDK modules from their own directory (#4507) 2026-11-28 20:38:06 +08:00
Pyroandpyroch fc21162bd7 fix(i18n): shorten Russian labels in narrow panels (#4506)
Co-authored-by: pyroch <cvdysh@gmail.com>
2026-11-28 19:54:37 +08:00
陈大猫 9d64860ba6 feat(vault): unify group details UI and add RDP/VNC group defaults (#4503) (#4505)
* feat(vault): unify group details UI and add RDP/VNC group defaults (#4503)

* fix(vault): address PR review findings for RDP/VNC group defaults

* fix(vault): preserve inherited RDP/VNC username when creating identity

* fix(vault): retain inherited desktop username when detaching standalone identity
2026-11-28 19:06:27 +08:00
Pyroandpyroch f208b46b40 fix(i18n): complete Russian translations (#4502)
Co-authored-by: pyroch <cvdysh@gmail.com>
2026-11-28 17:36:48 +08:00
陈大猫 f6d1ed2deb fix(ui): clip magnified pane fill to rounded chrome (#4499) 2026-11-28 16:38:50 +08:00
陈大猫 baa8ef5743 feat(remote-desktop): enable leak-free RDP/VNC video recording with multi-clip logs, timeline seek, and posters (#4501)
* feat(remote-desktop): enable leak-free RDP/VNC video recording with multi-clip logs, timeline seek, and posters

* test(remote-desktop): stub navigator.locks in remoteDesktopLogActions test for Node 22 CI
2026-11-28 16:24:31 +08:00
陈大猫 7a7deba65a fix(packaging): stop platform files arrays from triggering **/* fallback in app.asar (#4498) 2026-11-28 13:29:13 +08:00
Netcatty-Botandgithub-actions[bot] 2433d56d90 Update Nix release metadata for v1.1.94 (#4497)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-11-28 11:49:13 +08:00
dependabot[bot] 9ec417cbe4 ci: bump softprops/action-gh-release (#4495)
Bumps the github-actions group with 1 update: [softprops/action-gh-release](https://github.com/softprops/action-gh-release).


Updates `softprops/action-gh-release` from 2.6.2 to 3.0.4
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v2.6.2...v3.0.4)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-version: 3.0.4
  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>
2026-11-28 10:12:59 +08:00
d81ac36dbd fix(terminal): rehydrate prompt readiness and show jump targets (#4479)
* fix(mcp): rehydrate shell readiness from visible terminal context

When a worker session has a live but unrecognized prompt, read the renderer's current terminal buffer and seed prompt tracking without writing to the PTY. Restrict recovery to an unknown readiness state so busy, password, and alternate-screen sessions remain fail-closed. Apply the same preflight to foreground exec and background jobs.

* fix(tabs): show live jump targets in agent title mode

Mark prompt hostnames observed after a JumpServer menu as nested-host presentation and prefer them over the configured jump endpoint in agent mode. Manual names still win, disabled dynamic titles stay stable, and direct SSH hosts retain their configured labels.

* fix(terminal): address PR #4479 review findings on readiness rehydration and jump titles

* fix(terminal): drain worker output before readiness read and bound seed to cursor

* fix(terminal): preserve prompt trailing spaces via cursor column when seeding readiness

* fix(terminal): reconstruct logical lines via xterm isWrapped before seeding readiness

* fix(terminal): strip wide-char wrap padding and opt-in readiness context

* fix(terminal): match screen-derived prompts against raw CR+EL redraws

* fix(terminal): keep raw prompt suffix fast paths ahead of rendered fallback

* fix(terminal): restrict rendered prompt suffix fallback to redraw controls

* fix(terminal): match trimmed multiline prompt headers on CRLF-only output

* fix(terminal): handle tab-expanded prompts and coalesced JumpServer selections

* fix(terminal): discard truncated or evicted preceding wrapped lines during readiness seed

* fix(terminal): share worker prompt readiness preflight with Catty IPC exec path

---------

Co-authored-by: zjio26 <zjao2026@outlook.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-28 09:43:55 +08:00
陈大猫 8af37bae96 ci: configure Dependabot for GitHub Actions and fix stale CI unit tests (#4490) 2026-11-28 09:43:46 +08:00
陈大猫 0b5143af1d fix(mcp): exit stdio server cleanly on client disconnect to prevent orphan leaks (#4475) (#4492)
* fix(mcp): exit stdio server cleanly on client disconnect to prevent orphan leaks

* fix(mcp): harden stdio lifecycle startup EOF detection and teardown error handling

* test(mcp): keep lifecycle test exit waiter referenced and guard sync read(0) shutdown
2026-11-28 01:13:22 +08:00
陈大猫 29008d5d10 fix(rdp): support Standard RDP Security (RC4 40/56/128-bit & FIPS) and auto fallback (#4493)
* fix(rdp): support Standard RDP Security (RC4 40/56/128-bit & FIPS) and auto fallback (#4482)

* fix(rdp): harden Standard RDP channels, Fast-Path numEvents, and WASM lifecycle
2026-11-28 00:40:39 +08:00
陈大猫 066241af89 fix(rdp): do not let fullscreen toolbar wrapper steal clicks (#4486) (#4487) 2026-11-28 00:14:39 +08:00
陈大猫 0a209474d1 chore(electron): upgrade Electron 42.11.12 -> 45.5.0 with 43-45 breaking change fixes (#4491)
Upgrades Electron from EOL 42.11.12 to latest stable 45.5.0 (Chromium 156.0.8078.109,
Node 24.22.3, V8 15.6) and migrates all affected Electron 43/44/45 APIs:

- Bump electron to ^45.5.0 and node-abi override to 4.43.0 so @electron/rebuild
  rebuilds node-pty, @serialport/bindings-cpp, and sqlite3 cleanly
- Electron 44 async W3C Clipboard API:
  - Migrate electron/bridges/clipboardFiles.cjs to support async clipboard.read()
    (ClipboardItem[] with text/uri-list file paths and image/* blobs) and
    clipboard.has() alongside legacy sync test mocks, plus new unit tests
  - Await clipboard.readText/writeText/readFiles/readImage/hasImage in
    electron/main/registerBridges.cjs
  - Await clipboard.readText/writeText (handling both sync mocks and Promise
    returns safely) in electron/plugins/hostInteractionService.cjs
- Electron 45 sandboxed preload Buffer removal:
  - Replace Buffer.from with standard Uint8Array in electron/preload/stageUploadFile.cjs
- Electron 44 openAsHidden removal:
  - Remove openAsHidden from app.setLoginItemSettings in electron/autoLaunch.cjs
    and update electron/autoLaunch.test.cjs
- Electron 43 Linux dialog showHiddenFiles removal:
  - Omit showHiddenFiles from dialog.showOpenDialog properties on Linux in
    electron/main/registerBridges.cjs

Verified on Electron 45.5.0:
- npm run build & npm run pack:dir (electron-builder 26.15.2 + all patches)
- Live Electron 45.5.0: async clipboard smoke, terminal-background-rendering,
  tray-panel-layout, plugin-runtime:electron (PLUGIN_RUNTIME_SMOKE_OK),
  and 5-terminal local PTY stress/leak test (0 leaks; peak JS heap 41.28 MiB;
  131 KB sandbox_bundle.js eliminated from sandboxed renderer heap)
- Unit tests: 815/815 test:plugin-runtime + all modified bridge/preload/autoLaunch tests
2026-11-28 00:06:33 +08:00
Thibaud-Vdb e85b726451 ci: lock the actions and containers that build the release packages (#4485)
* ci: declare the read-only token in build-et-binaries.yml

The four et build jobs have no permissions block, so their token is
whatever the repository default gives. That default is read-only today
(the main run of 2026-11-26 lists Contents, Metadata and Packages as
read). Writing contents: read in the file keeps it that way if the
setting ever changes, as build.yml and test.yml already do.

The build jobs only check out the repository, restore caches, pull the
manylinux image from quay.io and upload artifacts. The release job
keeps its own block.

* ci: stop storing the job token in the build and test checkouts

actions/checkout keeps the job token in the git configuration until
the job ends, where every later step can read it. Fifteen checkouts
never use it again: the test job, the package builds, the two resolve
jobs, release, homebrew-tap, the five et jobs, and the issue-format
and spam-comments helpers. They now set persist-credentials: false.

None of these jobs runs an authenticated git command afterwards. The
release job talks to the API through GH_TOKEN and the token input of
the release action, and bump-homebrew-cask.sh clones the tap with its
own token in a temporary directory.

Two checkouts are left as they are because a later step pushes with
the stored RELEASE_TOKEN: update-nix-release in build.yml and the
star-history workflow.

* ci: pin the two Linux package build containers by digest

build-linux-x64 and build-linux-arm64 build the AppImage, deb, rpm and
pacman packages inside quay.io/almalinuxorg/almalinux:8 and
debian:bullseye. Both are tags, so the job runs whatever image the tag
names on the day of the build, and that image produces the packages a
release publishes.

Each image now carries its digest next to the dated tag that names the
same image today: 8.10-20261114 for AlmaLinux (what :8 points to) and
bullseye-20260824 for Debian (what :bullseye points to, last pushed on
2026-08-25). The glibc floors do not change (2.28 and 2.31), and the
dnf and apt steps still install current packages on top.

The cost: a newer AlmaLinux base image is a one line change here
instead of arriving by itself.

* ci: lock the workflow actions to their commits in actions.lock

Every action is referenced by a major tag, and a tag can be moved to
other code by whoever controls the action. Two of them sit on the
release path: ilammy/msvc-dev-cmd runs in the job that builds the
Windows installer, and softprops/action-gh-release receives
RELEASE_TOKEN in the job that publishes the release.

.github/workflows/actions.lock is GitHub's workflow dependency
lockfile, written by gh actions-lock. It records the commit, owner id
and repository id behind each of the eight actions the workflows use,
and the locked commit is what runs, whatever the tag says later. The
tool also narrowed each reference to the release it locked:
actions/checkout@v7 is now v7.0.1, the commit the runs on main already
used on 2026-11-26.

No bot updates actions in this repository. After this commit an action
is updated by changing its version and running gh actions-lock again,
and a new uses: line needs the same run, because every action a locked
workflow uses has to be in the lockfile.
2026-11-27 23:53:20 +08:00
陈大猫 1bcf37d777 fix(ssh): try saved password before default keys in auto auth (#4478) (#4480)
In automatic SSH auth, discovered ~/.ssh id_* keys were queued before a
saved password. Servers with a typical MaxAuthTries of 6 then disconnected
with "Too many authentication failures" before the password was ever sent.
Password-only with the same saved password succeeded.

Keep agent and any user-configured key first, then the saved password
(and MFA keyboard-interactive immediately before it), then discovered
default keys. SFTP/jump buildAuthHandler stays consistent with the
terminal startSession path. Password-only still skips default keys
(#266/#2079). Auto without a password still tries keys first.
2026-11-27 23:52:08 +08:00
陈大猫andCodex 9f52799363 fix(ui): paint 1px magnified chrome inside overflow-hidden (#4489)
Fixes #4168

Co-authored-by: Codex <codex@openai.com>
2026-11-27 23:50:28 +08:00
陈大猫 a0af73e458 fix(rdp): keep fixed-size resolution editable without mid-type clamp (#4473)
Keep fixed-resolution drafts editable with inline range hints and block host saving until both dimensions are valid.

Show the missing width and height fields for companion RDP hosts, and translate the validation hint in all vault locales.

Fixes #4472
2026-11-27 23:48:09 +08:00
陈大猫 e2b3004d4b perf(memory): Phase 3 deep business-code memory optimization (main, renderer & active terminals) (#4488)
Includes all Phase 3 rounds (1-5), Node unit test mock compatibility fixes,
and Codex review fixes (pinyin readiness subscribers & KnownHostsManager
mount retention).
2026-11-27 23:24:40 +08:00
陈大猫 681a200f3f perf(memory): implement Phase 1–2 idle, window, and terminal memory optimizations (#4476)
* perf(memory): implement Phase 1–2 idle, window, and terminal memory optimizations

- Fix kittyKeyboardBroadcast closure leak while preserving hibernated broadcast via detached top-level handler
- Replace dense KeywordHighlighter line caches with sparse packed triples and 53-bit numeric fingerprints
- Deduplicate hibernation snapshots and compress large scrollbacks via native gzip
- Eliminate cold-start terminalWorker wakes (portForwarding, transfer concurrency, empty monitor updates, cold MCP cancel, and stateless local shell/path queries)
- Auto-destroy hidden Settings and Tray windows after a configurable 20s idle grace window
- Tune Electron V8/GPU startup flags, switch V8 cache to code, and stream large app:// assets
- Split renderer entry bundle (App, NotesManager, MonitorPanels, globalAgentToolSpecs) and enable Chromium sandbox: true on all BrowserWindows via esbuild-bundled preload and IPC upload staging
- Add MRU=1 hidden WebGL context budget, dynamic main-window backgroundThrottling, bounded SSH/Fig caches, and lazy native addon loading

* fix(memory): fix CI unit test compatibility for tray spellcheck, pty mocks, and sync toolNameIndex

* fix(terminal): defer hibernate snapshot gzip until after live listeners detach

Addresses Codex P1 review finding on PR #4476:
- Add compress?: boolean option to serializeTerminalForHibernate so
  fullHibernateRuntime avoids awaiting gzip while the live output
  listener is still attached to the old xterm instance
- Compress the retained snapshot asynchronously only after live listeners
  are detached, runtime is disposed, and beginHibernatedSessionListeners
  is buffering all incoming output into hibernatePendingBufferRef
- Guard async swap with hibernateCompressionGenRef so wake/clear/new
  snapshots can never be overwritten by an earlier compression promise

* fix(terminal): preserve Kitty broadcast key-pairing sets across hibernate detach

Addresses Codex P2 review finding on PR #4476:
- Pass existing broadcastEncodedKeys, broadcastLegacySuppressedKeys, and
  broadcastWin32ShiftEnterTextKeys (plain string sets) into the detached
  hibernated broadcast handler so in-flight key-up releases are preserved
2026-11-27 23:23:01 +08:00
3bd49c7470 Update Nix release metadata for v1.1.93 (#4470)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-27 09:28:20 +08:00
Netcatty-Bot 55464713c3 Update Nix release metadata for v1.1.92 (#4467) 2026-11-27 09:22:58 +08:00
陈大猫 394621ec69 fix(mcp): classify remote_desktop_read_screen in progressive MCP catalog (#4468) (#4469) 2026-11-27 08:37:56 +08:00
陈大猫 c4bcb57e84 feat(ai): raise default maxIterations to 200 and add remote desktop tool artifact cards (#4465)
* feat(ai): raise default maxIterations to 200 and add remote desktop tool artifact cards

* chore: resync package-lock.json with npm 10 for Node 22 CI

* fix(ai): forward TooltipTrigger DOM props in RemoteDesktopArtifactCard

* style(vault): unify new-host dropdown icon badges and hide remote desktop record button
2026-11-27 00:47:59 +08:00
陈大猫 894543f93a fix: export isDiscoveredGitBash via localShell wrapper and streamline CI/CD (#4464) 2026-11-27 00:04:37 +08:00
陈大猫 c8c4b14938 feat(remote-desktop): built-in VNC & RDP support, multi-monitor/RDPDR, telemetry, and Catty Computer Use (#4463)
* feat(remote-desktop): add built-in VNC and RDP support, JumpServer RDP, AI vision, monitoring, and recordings

* fix(build): move ironrdp-web patches out of patch-package directory

* perf(remote-desktop): coalesce pointer/snip events, zero-copy VNC paint, and memoize views

* fix(remote-desktop): prevent StrictMode WS one-time token race and improve new-host protocol switch

* style(remote-desktop): align toolbar height to 36px, refine overlays, and complete zh-CN/en i18n

* fix(rdp): fallback to TLS 1.2 kRSA when Electron BoringSSL rejects Windows RDP cert KEY_USAGE_BIT_INCORRECT

* feat(remote-desktop): responsive toolbar overflow, fix RDP HiDPI scaling, add Cmd-to-Ctrl, VNC refresh, and protocol-aware keys

* feat(remote-desktop): add RDP multi-monitor/RDPDR, telemetry, AI Computer Use, VNC upgrades, and perf hardening
2026-11-26 23:46:58 +08:00
陈大猫 9e127676b6 feat(sftp): add setting for tree view folder double-click behavior (#4424) (#4460) 2026-11-26 23:46:28 +08:00
270 changed files with 21183 additions and 3656 deletions

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
timezone: "Asia/Shanghai"
open-pull-requests-limit: 5
groups:
github-actions:
patterns:
- "*"
commit-message:
prefix: "ci"
+72
View File
@@ -0,0 +1,72 @@
# This file is machine-generated by `gh actions-lock`.
# Do not edit by hand; run `gh actions-lock` to update.
# Docs: https://gh.io/actions-lockfile
version: 'v0.0.3'
workflows:
'.github/workflows/build-et-binaries.yml':
- 'actions/cache@v6.1.0'
- 'actions/checkout@v7.0.1'
- 'actions/download-artifact@v8.0.2'
- 'actions/upload-artifact@v7.0.2'
- 'ilammy/msvc-dev-cmd@v1.13.0'
'.github/workflows/build.yml':
- 'actions/cache@v6.1.0'
- 'actions/checkout@v7.0.1'
- 'actions/download-artifact@v8.0.2'
- 'actions/setup-node@v7.1.0'
- 'actions/upload-artifact@v7.0.2'
- 'ilammy/msvc-dev-cmd@v1.13.0'
- 'softprops/action-gh-release@v3.0.4'
'.github/workflows/grokbot-issue-relay.yml': []
'.github/workflows/issue-format.yml':
- 'actions/checkout@v7.0.1'
- 'actions/github-script@v9.0.0'
'.github/workflows/spam-comments.yml':
- 'actions/checkout@v7.0.1'
- 'actions/github-script@v9.0.0'
'.github/workflows/star-history.yml':
- 'actions/checkout@v7.0.1'
'.github/workflows/test.yml':
- 'actions/checkout@v7.0.1'
- 'actions/setup-node@v7.1.0'
dependencies:
'actions/cache@v6.1.0':
ref: 'v6.1.0'
commit: 'sha1-55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
owner_id: 44036562
repo_id: 215566462
'actions/checkout@v7.0.1':
ref: 'v7.0.1'
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
owner_id: 44036562
repo_id: 197814629
'actions/download-artifact@v8.0.2':
ref: 'v8.0.2'
commit: 'sha1-9000827ccba6bdab643e8b6fd33ac0654aef8333'
owner_id: 44036562
repo_id: 192626254
'actions/github-script@v9.0.0':
ref: 'v9.0.0'
commit: 'sha1-3a2844b7e9c422d3c10d287c895573f7108da1b3'
owner_id: 44036562
repo_id: 205262760
'actions/setup-node@v7.1.0':
ref: 'v7.1.0'
commit: 'sha1-949feb2413d6458794dcd2491c4babbbce0c15c1'
owner_id: 44036562
repo_id: 189476904
'actions/upload-artifact@v7.0.2':
ref: 'v7.0.2'
commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9'
owner_id: 44036562
repo_id: 192625955
'ilammy/msvc-dev-cmd@v1.13.0':
ref: 'v1.13.0'
commit: 'sha1-0b201ec74fa43914dc39ae48a89fd1d8cb592756'
owner_id: 1256587
repo_id: 212181767
'softprops/action-gh-release@v3.0.4':
ref: 'v3.0.4'
commit: 'sha1-8a0cd651e5b2365bd640854a3fa5dfc70e4875f3'
owner_id: 2242
repo_id: 204253808
+32 -19
View File
@@ -48,6 +48,9 @@ concurrency:
group: build-et-binaries-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
ET_REF: ${{ inputs.et_ref || 'et-v6.2.10' }}
@@ -59,17 +62,19 @@ jobs:
name: build-linux-x64
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore cached PR build
id: et-build-cache
if: github.event_name == 'pull_request'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: out/
key: et-pr-build-v1-${{ runner.os }}-${{ runner.arch }}-${{ env.ET_REF }}-${{ hashFiles('.github/workflows/build-et-binaries.yml', 'scripts/build-et/**') }}
- name: Restore vcpkg download cache
if: github.event_name != 'pull_request' || steps.et-build-cache.outputs.cache-hit != 'true'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: .cache/vcpkg-downloads
key: vcpkg-downloads-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-et/**') }}
@@ -102,7 +107,7 @@ jobs:
quay.io/pypa/manylinux2014_x86_64 \
bash scripts/build-et/build-linux.sh
- name: Upload artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: et-linux-x64
path: out/
@@ -112,17 +117,19 @@ jobs:
name: build-linux-arm64
runs-on: ubuntu-24.04-arm
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore cached PR build
id: et-build-cache
if: github.event_name == 'pull_request'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: out/
key: et-pr-build-v1-${{ runner.os }}-${{ runner.arch }}-${{ env.ET_REF }}-${{ hashFiles('.github/workflows/build-et-binaries.yml', 'scripts/build-et/**') }}
- name: Restore vcpkg download cache
if: github.event_name != 'pull_request' || steps.et-build-cache.outputs.cache-hit != 'true'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: .cache/vcpkg-downloads
key: vcpkg-downloads-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-et/**') }}
@@ -155,7 +162,7 @@ jobs:
quay.io/pypa/manylinux2014_aarch64 \
bash scripts/build-et/build-linux.sh
- name: Upload artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: et-linux-arm64
path: out/
@@ -168,17 +175,19 @@ jobs:
name: build-macos-universal
runs-on: macos-15
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore cached PR build
id: et-build-cache
if: github.event_name == 'pull_request'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: out/
key: et-pr-build-v1-${{ runner.os }}-${{ runner.arch }}-${{ env.ET_REF }}-${{ hashFiles('.github/workflows/build-et-binaries.yml', 'scripts/build-et/**') }}
- name: Restore vcpkg download cache
if: github.event_name != 'pull_request' || steps.et-build-cache.outputs.cache-hit != 'true'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: ${{ runner.temp }}/vcpkg-downloads
key: vcpkg-downloads-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-et/**') }}
@@ -196,7 +205,7 @@ jobs:
MACOSX_DEPLOYMENT_TARGET: "11.0"
run: bash scripts/build-et/build-macos.sh
- name: Upload artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: et-darwin-universal
path: out/
@@ -209,17 +218,19 @@ jobs:
name: build-windows-x64
runs-on: windows-latest
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore cached PR build
id: et-build-cache
if: github.event_name == 'pull_request'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: out/
key: et-pr-build-v1-${{ runner.os }}-${{ runner.arch }}-${{ env.ET_REF }}-${{ hashFiles('.github/workflows/build-et-binaries.yml', 'scripts/build-et/**') }}
- name: Restore vcpkg download cache
if: github.event_name != 'pull_request' || steps.et-build-cache.outputs.cache-hit != 'true'
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: ${{ runner.temp }}\vcpkg-downloads
key: vcpkg-downloads-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-et/**') }}
@@ -236,7 +247,7 @@ jobs:
run: choco install -y ninja
- name: Set up MSVC developer command prompt
if: github.event_name != 'pull_request' || steps.et-build-cache.outputs.cache-hit != 'true'
uses: ilammy/msvc-dev-cmd@v1
uses: ilammy/msvc-dev-cmd@v1.13.0
with:
arch: x64
- name: Build et (win32-x64)
@@ -247,7 +258,7 @@ jobs:
shell: pwsh
run: pwsh -File scripts/build-et/build-windows.ps1
- name: Upload artifact
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: et-win32-x64
path: out/
@@ -272,9 +283,11 @@ jobs:
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Download artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v8.0.2
with:
path: artifacts
- name: Stage release files
+36 -92
View File
@@ -40,10 +40,6 @@ on:
pull_request:
paths:
- ".github/workflows/build.yml"
- "components/AppLockGate.tsx"
- "components/TrayPanel.tsx"
- "index.tsx"
- "index.css"
- "build/**"
- "electron-builder.config.cjs"
- "electron/**"
@@ -81,11 +77,7 @@ on:
- "scripts/rebuildPatchedNodePty.cjs"
- "scripts/resolve-et-bin-release.cjs"
- "scripts/resolve-mosh-bin-release.cjs"
- "scripts/tray-panel-layout.live.test.cjs"
- "scripts/serial-named-pipe.live.test.cjs"
- "scripts/fixtures/serial/**"
- "scripts/verify-linux-*.sh"
- "scripts/xterm-macos-column-selection.live.test.cjs"
- "skills/**"
# A newer run for the same main push or PR cancels older in-progress work.
@@ -127,7 +119,9 @@ jobs:
mosh_bin_release: ${{ steps.resolve.outputs.mosh_bin_release }}
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Resolve bundled mosh-client release
id: resolve
@@ -154,7 +148,9 @@ jobs:
et_bin_release: ${{ steps.resolve.outputs.et_bin_release }}
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Resolve bundled et-client release
id: resolve
@@ -222,22 +218,24 @@ jobs:
fi
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
uses: actions/setup-node@v7.1.0
with:
node-version: 22
cache: npm
- name: Set up MSVC developer command prompt
if: matrix.name == 'windows'
uses: ilammy/msvc-dev-cmd@v1
uses: ilammy/msvc-dev-cmd@v1.13.0
with:
arch: x64
- name: Restore Electron download cache
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: |
~/.cache/electron
@@ -253,36 +251,6 @@ jobs:
- name: Install deps
run: npm ci
- name: Test Windows serial pipe through native Electron
if: matrix.name == 'windows'
run: npx electron scripts/serial-named-pipe.live.test.cjs
- name: Test macOS Option column selection
if: matrix.name == 'macos'
run: npm run test:xterm-macos-selection
- name: Compile ConPTY test helpers
if: matrix.name == 'windows'
shell: pwsh
run: |
$compiler = "$env:WINDIR\Microsoft.NET\Framework64\v4.0.30319\csc.exe"
if (-not (Test-Path $compiler)) { throw "csc.exe not found" }
New-Item -ItemType Directory -Force -Path "$env:RUNNER_TEMP\netcatty-mosh-conpty" | Out-Null
& $compiler /nologo /target:exe /out:"$env:RUNNER_TEMP\netcatty-mosh-conpty\ssh.exe" electron\bridges\fixtures\mosh-conpty-fake-ssh.cs
if ($LASTEXITCODE -ne 0) { throw "failed to compile fake ssh" }
& $compiler /nologo /target:exe /out:"$env:RUNNER_TEMP\netcatty-mosh-conpty\mosh-client.exe" electron\bridges\fixtures\mosh-conpty-fake-client.cs
if ($LASTEXITCODE -ne 0) { throw "failed to compile fake mosh-client" }
- name: Test Mosh handshake through ConPTY
if: matrix.name == 'windows'
shell: pwsh
env:
NETCATTY_TEST_MOSH_SSH_EXE: ${{ runner.temp }}\netcatty-mosh-conpty\ssh.exe
NETCATTY_TEST_MOSH_CLIENT_EXE: ${{ runner.temp }}\netcatty-mosh-conpty\mosh-client.exe
run: |
node --test electron/bridges/moshHandshake.test.cjs
node electron/bridges/terminalBridge.moshConpty.integration.cjs
- name: Fetch bundled mosh-client
if: env.BUNDLE_MOSH == 'true'
shell: bash
@@ -330,20 +298,8 @@ jobs:
APPLE_TEAM_ID: ${{ matrix.name == 'macos' && secrets.APPLE_TEAM_ID || '' }}
run: npm run ${{ matrix.pack_script }}
- name: Test packaged SSH cipher negotiation
run: node scripts/test-packaged-ssh-ciphers.cjs
- name: Test tray panel layout
run: npm run test:tray-panel-layout
- name: Test tray panel layout at 200% scale on Windows
if: matrix.name == 'windows'
env:
NETCATTY_TRAY_LAYOUT_SCALE: "2"
run: npm run test:tray-panel-layout
- name: Upload artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: netcatty-${{ matrix.name }}
path: |
@@ -383,7 +339,7 @@ jobs:
# The GitHub runner already retries container pulls three times. Use the
# official Quay mirror to avoid the Docker Hub endpoint that repeatedly
# timed out in package validation.
image: quay.io/almalinuxorg/almalinux:8
image: quay.io/almalinuxorg/almalinux:8.10-20261114@sha256:e85b75cd6ce05cd1e7616d4b2590077e0acc395e7ee73a9f887b17d1591b6ef3
env:
MOSH_BIN_RELEASE: ${{ needs.resolve-mosh.outputs.mosh_bin_release }}
ET_BIN_RELEASE: ${{ needs.resolve-et.outputs.et_bin_release }}
@@ -567,10 +523,12 @@ jobs:
echo "npm_config_python=/usr/bin/python3.11" >> "${GITHUB_ENV}"
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore Electron download cache
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: |
~/.cache/electron
@@ -634,9 +592,6 @@ jobs:
done
npm run pack:linux-x64
- name: Test packaged SSH cipher negotiation
run: node scripts/test-packaged-ssh-ciphers.cjs
- name: Verify packaged node-pty Linux runtime
run: bash scripts/ensure-node-pty-linux.sh verify x64
@@ -647,7 +602,7 @@ jobs:
run: bash scripts/verify-linux-rpm-artifact.sh x86_64
- name: Upload artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: netcatty-linux-x64
path: |
@@ -671,7 +626,7 @@ jobs:
&& (needs.resolve-et.result == 'success' || needs.resolve-et.result == 'skipped')
runs-on: ubuntu-24.04-arm
container:
image: debian:bullseye
image: debian:bullseye-20260824@sha256:6f519a81440354a85eb592c5f32109ab80605f6b892455983a6f618bf87fabe9
env:
MOSH_BIN_RELEASE: ${{ needs.resolve-mosh.outputs.mosh_bin_release }}
ET_BIN_RELEASE: ${{ needs.resolve-et.outputs.et_bin_release }}
@@ -723,10 +678,12 @@ jobs:
apt-get -o Acquire::Retries=4 install -y nodejs
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Restore Electron download cache
uses: actions/cache@v6
uses: actions/cache@v6.1.0
with:
path: |
~/.cache/electron
@@ -771,9 +728,6 @@ jobs:
ELECTRON_BUILDER_PUBLISH: "never"
run: npm run pack:linux-arm64
- name: Test packaged SSH cipher negotiation
run: node scripts/test-packaged-ssh-ciphers.cjs
- name: Verify packaged node-pty Linux runtime
run: bash scripts/ensure-node-pty-linux.sh verify arm64
@@ -784,7 +738,7 @@ jobs:
run: bash scripts/verify-linux-rpm-artifact.sh aarch64
- name: Upload artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: netcatty-linux-arm64
path: |
@@ -811,7 +765,9 @@ jobs:
actions: read
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Validate release tag
shell: bash
@@ -822,7 +778,7 @@ jobs:
fi
- name: Download artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v8.0.2
with:
path: artifacts
merge-multiple: true
@@ -864,20 +820,6 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Verify downloaded Linux amd64 deb artifact
run: |
deb_file="$(find artifacts -maxdepth 1 -type f -name '*-linux-amd64.deb' -print | sort | head -n 1)"
test -n "${deb_file}"
bash scripts/verify-linux-deb-artifact.sh amd64 "${deb_file}"
- name: Verify downloaded Linux arm64 deb artifact metadata
env:
VERIFY_LOAD: "0"
run: |
deb_file="$(find artifacts -maxdepth 1 -type f -name '*-linux-arm64.deb' -print | sort | head -n 1)"
test -n "${deb_file}"
bash scripts/verify-linux-deb-artifact.sh arm64 "${deb_file}"
- name: Generate Release Body
run: node .github/scripts/generate-release-note.js
env:
@@ -886,7 +828,7 @@ jobs:
GITHUB_SHA: ${{ github.sha }}
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3.0.4
with:
body_path: release_notes.md
prerelease: ${{ contains(github.ref_name, '-') }}
@@ -918,13 +860,13 @@ jobs:
pull-requests: write
steps:
- name: Checkout default branch
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: ${{ github.event.repository.default_branch }}
token: ${{ secrets.RELEASE_TOKEN }}
- name: Download Linux artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v8.0.2
with:
path: artifacts
merge-multiple: true
@@ -1080,10 +1022,12 @@ jobs:
&& (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.publish_release))
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Download macOS artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v8.0.2
with:
name: netcatty-macos
path: artifacts/
+3 -2
View File
@@ -17,14 +17,15 @@ jobs:
!contains(github.event.issue.labels.*.name, 'format-exempt')
steps:
- name: Checkout format helpers
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
sparse-checkout: |
scripts/issue-format.cjs
sparse-checkout-cone-mode: false
- name: Validate title and body
uses: actions/github-script@v9
uses: actions/github-script@v9.0.0
with:
script: |
const format = require(`${process.env.GITHUB_WORKSPACE}/scripts/issue-format.cjs`);
+4 -2
View File
@@ -14,10 +14,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout filter rules
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Hide suspected malware spam
uses: actions/github-script@v9
uses: actions/github-script@v9.0.0
with:
script: |
const path = require('node:path');
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
# Same PAT used for releases — needs stargazers read (admin/collaborator)
# plus contents/PR write so we can open an update PR against protected main.
+3 -111
View File
@@ -20,21 +20,16 @@ jobs:
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Setup Node
uses: actions/setup-node@v7
uses: actions/setup-node@v7.1.0
with:
node-version: 22
cache: npm
- name: Install shell test dependencies
run: |
sudo apt-get update
sudo apt-get install -y fish xvfb
- name: Install deps
run: npm ci
@@ -58,108 +53,5 @@ jobs:
- name: Test
run: npm test
- name: Test SSH cipher negotiation in Electron's crypto runtime
env:
NETCATTY_SSH_TEST_RUNTIME: electron
run: node --test electron/bridges/sshChaChaTransport.test.cjs
- name: Test browser first-link lifecycle
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox electron/hostBrowser/hostBrowser.firstLink.live.test.cjs
- name: Test terminal background rendering
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox --use-angle=swiftshader --enable-unsafe-swiftshader scripts/terminal-background-rendering.live.test.cjs
- name: Test terminal keyword highlight performance
env:
NETCATTY_TERMINAL_PERF_SHOW_WINDOW: "1"
# GitHub-hosted runners do not configure Electron's SUID sandbox helper.
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox scripts/xterm-keyword-highlight-performance.live.test.cjs
- name: Test terminal keyword highlight throughput
env:
NETCATTY_TERMINAL_PERF_MAIN_REF: ${{ github.event.pull_request.base.sha || 'HEAD^' }}
NETCATTY_TERMINAL_PERF_ROUNDS: "3"
NETCATTY_TERMINAL_PERF_SHOW_WINDOW: "1"
run: xvfb-run -a ./node_modules/.bin/electron --no-sandbox scripts/xterm-keyword-highlight-throughput.live.test.cjs
- name: Build
run: npm run build
windows-fido:
name: windows-fido
runs-on: windows-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- name: Install deps
run: npm ci --ignore-scripts
- name: Exercise serial named pipe transport on Windows
run: node --test electron/bridges/serialNamedPipe.test.cjs
- name: Apply production dependency patches
run: npx patch-package --error-on-fail
- name: Install user-mode OpenSSH and software authenticator toolchain
uses: msys2/setup-msys2@v2
with:
msystem: MSYS
update: true
install: gcc openssl-devel openssh
- name: Build disposable software authenticator
shell: msys2 {0}
run: |
gcc -shared -DHAVE_STDINT_H scripts/fixtures/fido/provider.c -lcrypto -o /usr/lib/netcatty-fido-test-provider.dll
printf 'NETCATTY_WINDOWS_SSH_AGENT=%s\n' "$(cygpath -w /usr/bin/ssh-agent.exe)" >> "$GITHUB_ENV"
printf 'NETCATTY_WINDOWS_SSH_KEYGEN=%s\n' "$(cygpath -w /usr/bin/ssh-keygen.exe)" >> "$GITHUB_ENV"
cygpath -w /usr/bin >> "$GITHUB_PATH"
ssh -V
- name: Exercise Windows pipes, PIN bridge, SK signatures and cancellation
env:
NETCATTY_FIDO_WINDOWS: "1"
run: node --test scripts/fido-windows.live.test.cjs electron/bridges/fidoNativeAgent.test.cjs electron/bridges/fidoAskpass.winpath.test.cjs
windows-broadcast-ssh:
name: windows-broadcast-ssh
runs-on: windows-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Setup Node
uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- name: Install deps
run: npm ci
- name: Build
run: npm run build
- name: Test SSH cipher negotiation in Windows Electron's crypto runtime
env:
NETCATTY_SSH_TEST_RUNTIME: electron
run: node --test electron/bridges/sshChaChaTransport.test.cjs
- name: Exercise native PowerShell and CMD directory navigation in ConPTY
env:
NETCATTY_DIRECTORY_WINDOWS_LIVE: "1"
run: |
$env:NETCATTY_TEST_PWSH = (Get-Command pwsh -ErrorAction Stop).Source
node --test --test-force-exit --import tsx infrastructure/services/terminalDirectory.windows.test.ts
- name: Exercise two SSH password prompts in the desktop app
run: node scripts/terminal-broadcast-ssh.live.cjs
+1
View File
@@ -116,6 +116,7 @@ coverage
!/build/installer.nsh
/electron/native/**/build
/electron/bridges/windowsHelloHelper/build/
/electron/preload.bundle.cjs
/release
/out
/public/monaco
+6 -4
View File
@@ -1,12 +1,12 @@
import React, { useMemo, useState } from 'react';
import React, { Suspense, lazy, useMemo, useState } from 'react';
import type { WorkSurfaceHostEditorTarget } from '../state/useWorkSurfaceHostEditor';
import type { EditorTabChrome } from '../state/editorTabStore';
import type { LogView } from '../state/logViewState';
import { useI18n } from '../i18n/I18nProvider';
import HostDetailsPanel from '../../components/HostDetailsPanel';
import LocalShellHostDetailsPanel from '../../components/LocalShellHostDetailsPanel';
import SerialHostDetailsPanel from '../../components/SerialHostDetailsPanel';
const HostDetailsPanel = lazy(() => import('../../components/HostDetailsPanel'));
const LocalShellHostDetailsPanel = lazy(() => import('../../components/LocalShellHostDetailsPanel'));
const SerialHostDetailsPanel = lazy(() => import('../../components/SerialHostDetailsPanel'));
import { PortalContainerProvider } from '../../components/ui/portal-container';
import { resolveGroupDefaults } from '../../domain/groupConfig';
import { STORAGE_KEY_VAULT_HOST_PANEL_WIDTH } from '@/infrastructure/config/storageKeys';
@@ -163,6 +163,7 @@ export const AppHostEditorLayer: React.FC<AppHostEditorLayerProps> = ({
style={getAppHostEditorLayerStyle(surfaceVisible)}
>
<PortalContainerProvider container={portalContainer}>
<Suspense fallback={null}>
{target.mode === 'edit' && target.openedHost.protocol === 'local' ? (
<LocalShellHostDetailsPanel
key={editorKey}
@@ -215,6 +216,7 @@ export const AppHostEditorLayer: React.FC<AppHostEditorLayerProps> = ({
{...hostPanelResizeProps}
/>
)}
</Suspense>
</PortalContainerProvider>
</div>
);
+30 -17
View File
@@ -1,4 +1,4 @@
import React, { memo, useMemo, useRef } from 'react';
import React, { Suspense, lazy, memo, useMemo, useRef, useState } from 'react';
import { useActiveTabId } from '../state/activeTabStore';
import { useAppearanceChromeStore } from '../state/appearanceChromeStore';
@@ -6,7 +6,6 @@ import type { EditorTabChrome } from '../state/editorTabStore';
import type { LogView } from '../state/logViewState';
import { useTerminalHostTreeOpen } from '../state/terminalHostTreeStore';
import { useManualTerminalChromeSurfaceInjection } from '../state/useManualTerminalChromeSurfaceInjection';
import { TerminalHostTreeSidebar } from '../../components/terminalLayer/TerminalHostTreeSidebar';
import type {
ResolvedAppearance,
TerminalAppearanceHostScope,
@@ -18,6 +17,12 @@ import {
resolveWorkTabActiveHostId,
} from './workTabSurface';
const TerminalHostTreeSidebar = lazy(() =>
import('../../components/terminalLayer/TerminalHostTreeSidebar').then((mod) => ({
default: mod.TerminalHostTreeSidebar,
})),
);
interface AppHostTreeLayerProps {
enabled: boolean;
hosts: Host[];
@@ -122,6 +127,10 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
workspaceIds,
});
const sidebarActive = surfaceVisible && enabled && isHostTreeOpen;
const [hasMountedSidebar, setHasMountedSidebar] = useState(sidebarActive);
if (sidebarActive && !hasMountedSidebar) {
setHasMountedSidebar(true);
}
const activeHostId = useMemo(() => (
sidebarActive
@@ -182,21 +191,25 @@ const AppHostTreeLayerInner: React.FC<AppHostTreeLayerProps> = ({
data-section="app-host-tree-layer"
style={getAppHostTreeLayerStyle(surfaceVisible)}
>
<TerminalHostTreeSidebar
enabled={enabled}
surfaceVisible={surfaceVisible}
hosts={hosts}
customGroups={customGroups}
groupConfigs={groupConfigs}
resolvedPreviewTheme={sidebarPreviewTheme}
activeHostId={activeHostId}
onConnect={onConnect}
onConnectRemoteDesktop={onConnectRemoteDesktop}
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
onNewHost={onNewHost}
onEditHost={onEditHost}
onCreateLocalTerminal={onCreateLocalTerminal}
/>
{hasMountedSidebar ? (
<Suspense fallback={null}>
<TerminalHostTreeSidebar
enabled={enabled}
surfaceVisible={surfaceVisible}
hosts={hosts}
customGroups={customGroups}
groupConfigs={groupConfigs}
resolvedPreviewTheme={sidebarPreviewTheme}
activeHostId={activeHostId}
onConnect={onConnect}
onConnectRemoteDesktop={onConnectRemoteDesktop}
onOpenSystemRemoteDesktop={onOpenSystemRemoteDesktop}
onNewHost={onNewHost}
onEditHost={onEditHost}
onCreateLocalTerminal={onCreateLocalTerminal}
/>
</Suspense>
) : null}
</div>
);
};
+4 -15
View File
@@ -196,9 +196,9 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
const isVisible = isTerminalSurfaceActive || !!props.draggingSessionId;
// Silent MCP sessions never become the activeTabId, so `isVisible` alone
// would leave this whole layer (and its PTY-starting TerminalPane) unmounted
// for up to 5s (the idle-callback fallback below) after host_open returns —
// long enough for an immediate terminal_execute to race an unstarted session.
// after host_open returns — racing an immediate terminal_execute.
const hasHiddenSession = props.sessions.some((session) => session.hiddenFromTabs);
const hasTerminalContent = props.sessions.length > 0 || props.workspaces.length > 0;
const [shouldMount, setShouldMount] = useState(isVisible || hasHiddenSession);
useEffect(() => {
@@ -206,19 +206,8 @@ export const TerminalLayerMount: React.FC<TerminalLayerProps> = (props) => {
}, [isVisible, hasHiddenSession]);
useEffect(() => {
if (shouldMount) return;
type IdleWindow = Window & {
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
cancelIdleCallback?: (id: number) => void;
};
const idleWindow = window as IdleWindow;
if (typeof idleWindow.requestIdleCallback === "function") {
const id = idleWindow.requestIdleCallback(() => setShouldMount(true), { timeout: 5000 });
return () => idleWindow.cancelIdleCallback?.(id);
}
const id = window.setTimeout(() => setShouldMount(true), 5000);
return () => window.clearTimeout(id);
}, [shouldMount]);
if (hasTerminalContent) setShouldMount(true);
}, [hasTerminalContent]);
const shouldRender = shouldRenderTerminalLayerMount(isVisible, shouldMount);
+6 -1
View File
@@ -3,6 +3,7 @@ import React, { Suspense, lazy, useMemo, useState } from 'react';
import type { QuickSwitcherProps } from '../../components/QuickSwitcher';
import { LazyLoadBoundary } from '../../components/ui/lazy-load-boundary';
import { getHostSearchMatch } from '../../domain/searchMatcher';
import { usePinyinMatcherVersion } from '../state/usePinyinMatcherVersion';
import type { Host } from '../../types';
const LazyQuickSwitcher = lazy(() =>
@@ -37,7 +38,11 @@ export type QuickSwitcherOverlayProps =
*/
export function QuickSwitcherOverlay({ hosts, ...props }: QuickSwitcherOverlayProps) {
const [query, setQuery] = useState('');
const results = useMemo(() => filterQuickSwitcherHosts(hosts, query), [hosts, query]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const results = useMemo(() => {
void pinyinMatcherVersion;
return filterQuickSwitcherHosts(hosts, query);
}, [hosts, query, pinyinMatcherVersion]);
return (
<LazyLoadBoundary name="Quick switcher" resetKey={query}>
<Suspense fallback={null}>
+9
View File
@@ -835,6 +835,15 @@ export const enAiMessages: Messages = {
'ai.chat.artifact.scriptRunPaused': 'Script run paused',
'ai.chat.artifact.scriptRunResumed': 'Script run resumed',
'ai.chat.artifact.scriptReference': 'nct API reference',
'ai.chat.artifact.rdScreenRead': 'Read remote screen',
'ai.chat.artifact.rdScreenGrid': 'Read remote screen (grid)',
'ai.chat.artifact.rdScreenCropped': 'Captured zoomed region',
'ai.chat.artifact.rdActionExecuted': 'Ran {count} remote actions',
'ai.chat.artifact.rdActionCount': '{count} actions',
'ai.chat.artifact.rdActionPreempted': 'Remote action paused by user',
'ai.chat.artifact.rdScreenFailed': 'Remote screen capture failed',
'ai.chat.artifact.rdActionFailed': 'Remote desktop action failed',
'ai.chat.artifact.rdPreviewScreen': 'Preview captured screen',
'zmodem.waitingForRemote': 'Waiting for remote...',
'zmodem.uploading': 'Uploading',
'zmodem.downloading': 'Downloading',
+3
View File
@@ -1225,7 +1225,10 @@ Highlight the focused split pane:
'vault.groups.details': 'Group Details',
'vault.groups.details.general': 'General',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'Default {protocol} settings are not configured for this group yet.',
'vault.groups.details.advanced': 'Advanced',
'vault.groups.details.appearance': 'Appearance',
'vault.groups.details.mosh': 'Mosh',
+20
View File
@@ -584,6 +584,10 @@ export const enVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Display files in a flat list for the current directory',
'settings.sftp.defaultViewMode.tree': 'Tree View',
'settings.sftp.defaultViewMode.treeDesc': 'Display files in a hierarchical tree structure',
'settings.sftp.treeFolderDoubleClick': 'Tree view folder double-click',
'settings.sftp.treeFolderDoubleClick.desc': 'Choose what happens when double-clicking a folder in SFTP Tree View. Clicking the chevron always expands or collapses in place.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Enter directory',
'settings.sftp.treeFolderDoubleClick.expand': 'Expand or collapse in place',
'sftp.autoSync.success': 'File synced to remote: {fileName}',
'sftp.autoSync.error': 'Failed to sync file: {error}',
@@ -1145,6 +1149,7 @@ export const enVaultMessages: Messages = {
'hostDetails.rdp.resolutionMode.fixed': 'Fixed Size',
'hostDetails.rdp.width': 'Width',
'hostDetails.rdp.height': 'Height',
'hostDetails.rdp.dimensionHint': 'Enter a whole number from 200 to 8192.',
'hostDetails.rdp.colorDepth': 'Color Depth',
'hostDetails.rdp.audio': 'Audio Output',
'hostDetails.rdp.audioDesc': 'Play remote desktop sound locally',
@@ -1258,6 +1263,9 @@ export const enVaultMessages: Messages = {
'remoteDesktop.toolbar.display': 'Display Scaling',
'remoteDesktop.toolbar.sshTunneled': 'Tunneled over SSH',
'remoteDesktop.toolbar.encrypted': 'Encrypted TLS connection',
'remoteDesktop.toolbar.standardRdpSecurity': 'Standard RDP Security ({{cipher}})',
'remoteDesktop.rdp.fallbackStandardRdp': 'Connected using Standard RDP Security.',
'remoteDesktop.rdp.fallbackStandardRdpWithCipher': 'Connected using Standard RDP Security ({{cipher}}).',
'remoteDesktop.toolbar.viewOnly': 'View-Only Mode',
'remoteDesktop.toolbar.viewOnlyBadge': 'View',
'remoteDesktop.toolbar.audio': 'RDP Audio',
@@ -1311,6 +1319,7 @@ export const enVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Record session',
'remoteDesktop.toolbar.stopRecording': 'Stop recording',
'remoteDesktop.toolbar.savingRecording': 'Saving...',
'remoteDesktop.toolbar.recording': 'Recording',
'remoteDesktop.toolbar.askAi': 'Ask AI',
'remoteDesktop.toolbar.askAiFull': 'Capture Screen & Ask AI',
@@ -1416,7 +1425,18 @@ export const enVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Started',
'logView.remoteDesktop.ended': 'Ended',
'logView.remoteDesktop.duration': 'Duration',
'logView.remoteDesktop.resolution': 'Resolution',
'logView.remoteDesktop.security': 'Security',
'logView.remoteDesktop.disconnectReason': 'Disconnect reason',
'logView.remoteDesktop.timeline': 'Session Timeline',
'logView.remoteDesktop.recordingTip': 'Click Record in the remote desktop toolbar or enable Auto-record in Settings -> System to save .webm replays here.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'All',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Remote Desktop',
'logs.filter.recorded': 'Recorded',
'logs.filter.emptyTitle': 'No matching logs',
'logs.filter.emptyDesc': 'No connection logs match the selected filter yet.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Remote Desktop Recordings',
+9
View File
@@ -835,6 +835,15 @@ export const esAiMessages: Messages = {
'ai.chat.artifact.scriptRunPaused': 'Ejecución del script en pausa',
'ai.chat.artifact.scriptRunResumed': 'Ejecución del script reanudada',
'ai.chat.artifact.scriptReference': 'referencia de la API de nct',
'ai.chat.artifact.rdScreenRead': 'Lectura de pantalla remota',
'ai.chat.artifact.rdScreenGrid': 'Lectura de pantalla remota (cuadrícula)',
'ai.chat.artifact.rdScreenCropped': 'Región ampliada capturada',
'ai.chat.artifact.rdActionExecuted': 'Se ejecutaron {count} acciones remotas',
'ai.chat.artifact.rdActionCount': '{count} acciones',
'ai.chat.artifact.rdActionPreempted': 'Acción remota pausada por el usuario',
'ai.chat.artifact.rdScreenFailed': 'Error al capturar la pantalla remota',
'ai.chat.artifact.rdActionFailed': 'Error en la acción de escritorio remoto',
'ai.chat.artifact.rdPreviewScreen': 'Vista previa de la captura',
'zmodem.waitingForRemote': 'Esperando al servidor remoto...',
'zmodem.uploading': 'Subiendo',
'zmodem.downloading': 'Descargando',
+3
View File
@@ -1225,7 +1225,10 @@ Resalta el panel dividido enfocado:
'vault.groups.details': 'Detalles del grupo',
'vault.groups.details.general': 'General',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'La configuración predeterminada de {protocol} aún no está configurada para este grupo.',
'vault.groups.details.advanced': 'Avanzado',
'vault.groups.details.appearance': 'Apariencia',
'vault.groups.details.mosh': 'Mosh',
+20
View File
@@ -584,6 +584,10 @@ export const esVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Muestra los archivos en una lista plana del directorio actual',
'settings.sftp.defaultViewMode.tree': 'Vista de árbol',
'settings.sftp.defaultViewMode.treeDesc': 'Muestra los archivos en una estructura de árbol jerárquica',
'settings.sftp.treeFolderDoubleClick': 'Doble clic en carpetas (vista de árbol)',
'settings.sftp.treeFolderDoubleClick.desc': 'Elige qué ocurre al hacer doble clic en una carpeta en la vista de árbol de SFTP. Hacer clic en la flecha siempre expande o contrae en su lugar.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Entrar en el directorio',
'settings.sftp.treeFolderDoubleClick.expand': 'Expandir o contraer en su lugar',
'sftp.autoSync.success': 'Archivo sincronizado con el remoto: {fileName}',
'sftp.autoSync.error': 'No se pudo sincronizar el archivo: {error}',
@@ -1147,6 +1151,7 @@ export const esVaultMessages: Messages = {
'hostDetails.rdp.resolutionMode.fixed': 'Tamaño fijo',
'hostDetails.rdp.width': 'Ancho',
'hostDetails.rdp.height': 'Alto',
'hostDetails.rdp.dimensionHint': 'Introduce un número entero entre 200 y 8192.',
'hostDetails.rdp.colorDepth': 'Profundidad de color',
'hostDetails.rdp.audio': 'Salida de audio',
'hostDetails.rdp.audioDesc': 'Reproducir el audio del escritorio remoto localmente',
@@ -1260,6 +1265,9 @@ export const esVaultMessages: Messages = {
'remoteDesktop.toolbar.display': 'Escala de pantalla',
'remoteDesktop.toolbar.sshTunneled': 'Tunelizado por SSH',
'remoteDesktop.toolbar.encrypted': 'Conexión TLS cifrada',
'remoteDesktop.toolbar.standardRdpSecurity': 'Seguridad RDP estándar ({{cipher}})',
'remoteDesktop.rdp.fallbackStandardRdp': 'Conectado con seguridad RDP estándar.',
'remoteDesktop.rdp.fallbackStandardRdpWithCipher': 'Conectado con seguridad RDP estándar ({{cipher}}).',
'remoteDesktop.toolbar.viewOnly': 'Modo solo lectura',
'remoteDesktop.toolbar.viewOnlyBadge': 'Ver',
'remoteDesktop.toolbar.audio': 'Audio RDP',
@@ -1370,6 +1378,7 @@ export const esVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Grabar sesión',
'remoteDesktop.toolbar.stopRecording': 'Detener grabación',
'remoteDesktop.toolbar.savingRecording': 'Guardando...',
'remoteDesktop.toolbar.recording': 'Grabando',
'remoteDesktop.toolbar.askAi': 'Preguntar a la IA',
'remoteDesktop.toolbar.askAiFull': 'Capturar pantalla y preguntar a la IA',
@@ -1416,7 +1425,18 @@ export const esVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Inicio',
'logView.remoteDesktop.ended': 'Fin',
'logView.remoteDesktop.duration': 'Duración',
'logView.remoteDesktop.resolution': 'Resolución',
'logView.remoteDesktop.security': 'Seguridad',
'logView.remoteDesktop.disconnectReason': 'Motivo de desconexión',
'logView.remoteDesktop.timeline': 'Cronología de sesión',
'logView.remoteDesktop.recordingTip': 'Haz clic en Grabar en la barra de escritorio remoto o activa la grabación automática en Ajustes → Sistema para guardar repeticiones .webm aquí.',
'logs.recording.clipsCount': '{count} clips',
'logs.filter.all': 'Todos',
'logs.filter.terminal': 'Terminal',
'logs.filter.remoteDesktop': 'Escritorio remoto',
'logs.filter.recorded': 'Con grabación',
'logs.filter.emptyTitle': 'Sin registros coincidentes',
'logs.filter.emptyDesc': 'Todavía no hay registros de conexión que coincidan con este filtro.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Grabaciones de escritorio remoto',
@@ -8,12 +8,6 @@ import ru from "./ru.ts";
import zhCN from "./zh-CN.ts";
import zhTW from "./zh-TW.ts";
// Locales that are not at full key parity with `en` yet. They are tracked here
// so the remaining debt stays visible instead of silently rendering in English
// through the `DEFAULT_UI_LOCALE` fallback in `I18nProvider.resolveMessage`.
// Move a locale out of this list once it covers every `en` key.
const LOCALES_PENDING_PARITY = ["ru"] as const;
const hasKey = (messages: Record<string, string>, key: string) =>
Object.hasOwn(messages, key);
@@ -110,7 +104,7 @@ test("en shortcut labels stay identical to DEFAULT_KEY_BINDINGS", () => {
}
});
test("every locale outside the pending list is at full parity with en", () => {
test("every translated locale defines every message key from en", () => {
const locales = [
{ name: "es", messages: es },
{ name: "ru", messages: ru },
@@ -119,10 +113,6 @@ test("every locale outside the pending list is at full parity with en", () => {
];
for (const locale of locales) {
if ((LOCALES_PENDING_PARITY as readonly string[]).includes(locale.name)) {
continue;
}
const missing = Object.keys(en).filter(
(key) => !hasKey(locale.messages, key),
);
@@ -134,3 +124,9 @@ test("every locale outside the pending list is at full parity with en", () => {
);
}
});
test("every locale explains the fixed RDP dimension limits", () => {
for (const messages of [en, es, ru, zhCN, zhTW]) {
assert.match(messages["hostDetails.rdp.dimensionHint"] ?? "", /200.*8192/);
}
});
+128 -50
View File
@@ -10,9 +10,28 @@ export const ruAiMessages: Messages = {
'ai.chat.preparing': 'Подготовка…',
'ai.chat.modelCatalogWarning': 'Не удалось обновить список моделей. Показаны последние доступные или встроенные модели.',
'ai.chat.modelCatalogRetry': 'Повторить',
'ai.chat.compactingContext': 'Сжимаем предыдущий контекст…',
'ai.chat.compactingStep': 'Сокращаем контекст для следующего шага…',
'ai.chat.contextCompacted': 'Контекст сжат',
'ai.title': 'AI',
'ai.description': 'Настройка AI-провайдеров, агентов и параметров безопасности',
'ai.chat.compactionRetry': 'Запрос слишком большой. Сжимаем контекст и повторяем попытку…',
'ai.chat.compactionBanner': 'Контекст сжат: с {before} тыс. до {after} тыс. токенов',
'ai.chat.activity.title': 'Действия агента',
'ai.chat.activity.plan': 'План',
'ai.chat.activity.webSearch': 'Поиск в интернете',
'ai.chat.activity.fileChanges': 'Изменения файлов',
'ai.chat.activity.status.running': 'Выполняется',
'ai.chat.activity.status.completed': 'Завершено',
'ai.chat.activity.status.failed': 'Ошибка',
'ai.chat.activity.file.add': 'Добавление',
'ai.chat.activity.file.update': 'Изменение',
'ai.chat.activity.file.delete': 'Удаление',
'ai.chat.activity.usage': 'Токены',
'ai.chat.activity.usage.input': 'вход',
'ai.chat.activity.usage.output': 'выход',
'ai.chat.activity.usage.cached': 'из кэша',
'ai.chat.activity.usage.reasoning': 'рассуждение',
'ai.title': 'ИИ',
'ai.description': 'Настройка провайдеров ИИ, агентов и параметров безопасности',
'ai.providers': 'Провайдеры',
'ai.agents': 'Агенты',
'ai.providers.empty': 'Провайдеры не настроены. Добавьте провайдера, чтобы начать.',
@@ -43,6 +62,15 @@ export const ruAiMessages: Messages = {
'ai.providers.apiKey': 'API-ключ',
'ai.providers.apiKey.placeholder': 'Введите API-ключ',
'ai.providers.apiKey.decrypting': 'Расшифровка...',
'ai.providers.headers': 'Пользовательские заголовки HTTP',
'ai.providers.headers.help': 'Необязательные заголовки для этого провайдера. Значения скрыты и шифруются при сохранении.',
'ai.providers.headers.name': 'Имя заголовка',
'ai.providers.headers.value': 'Значение заголовка',
'ai.providers.headers.add': 'Добавить заголовок',
'ai.providers.headers.remove': 'Удалить заголовок',
'ai.providers.headers.invalid': 'Укажите корректные заголовки HTTP без повторяющихся имён. Content-Length и Transfer-Encoding задаются автоматически.',
'ai.providers.headers.loadError': 'Не удалось открыть сохранённые заголовки. Отмените операцию, разблокируйте системное хранилище ключей и повторите попытку.',
'ai.providers.headers.saveError': 'Не удалось сохранить заголовки в зашифрованном виде. Проверьте, доступно ли системное хранилище ключей, и повторите попытку.',
'ai.providers.opencodeGo.help': 'Вставьте API-ключ OpenCode, чтобы использовать OpenCode Go. Базовый URL и список моделей настроятся автоматически.',
'ai.providers.opencodeGo.getKey': 'Получить API-ключ',
'ai.providers.fixedBaseUrl.help': 'Задаётся провайдером. Netcatty автоматически выбирает путь эндпоинта для каждой модели.',
@@ -166,20 +194,20 @@ export const ruAiMessages: Messages = {
'ai.cursor.detected': 'Доступен',
'ai.cursor.notFound': 'Недоступен',
'ai.cursor.path': 'Среда:',
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на CLI login.',
'ai.cursor.notFoundHint': 'Укажите API-ключ или переключитесь на вход через CLI.',
'ai.cursor.notInstalledHint': 'Cursor SDK / Agent CLI не обнаружен.',
'ai.cursor.installStatus': 'Среда Cursor',
'ai.cursor.installed': 'Обнаружено',
'ai.cursor.notInstalled': 'Не обнаружено',
'ai.cursor.modeCli': 'CLI login',
'ai.cursor.modeApiKey': 'API Key',
'ai.cursor.modeCli': 'Вход через CLI',
'ai.cursor.modeApiKey': 'API-ключ',
'ai.cursor.modeCliHint': 'Использует локальный `cursor-agent login` и квоту подписки Auto. Сохранённый API-ключ сохраняется, но в этом режиме не используется.',
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. CLI login в этом режиме игнорируется.',
'ai.cursor.cliLoginStatus': 'CLI login',
'ai.cursor.modeApiKeyHint': 'Использует платный Cursor API. Вход через CLI в этом режиме игнорируется.',
'ai.cursor.cliLoginStatus': 'Вход через CLI',
'ai.cursor.cliLoginOk': 'Вход выполнен',
'ai.cursor.cliLoginAs': 'Вход как {{email}}',
'ai.cursor.cliLoginMissing': 'Нет входа',
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите Check.',
'ai.cursor.cliLoginHint': 'Выполните `cursor-agent login` в терминале, затем нажмите «Проверить».',
'ai.cursor.apiKeyStatus': 'API-ключ',
'ai.cursor.apiKeyConfigured': 'Настроен',
'ai.cursor.apiKeyMissing': 'Не указан',
@@ -210,22 +238,22 @@ export const ruAiMessages: Messages = {
'ai.codebuddy.configSection': 'Аутентификация и конфигурация (необязательно)',
'ai.codebuddy.internetEnv': 'Сетевая среда',
'ai.codebuddy.internetEnv.default': 'По умолчанию (зарубежная)',
'ai.codebuddy.internetEnv.internal': 'Internal',
'ai.codebuddy.internetEnv.internal': 'Внутренняя',
'ai.codebuddy.internetEnv.ioa': 'IOA',
'ai.codebuddy.internetEnv.hint': 'Устанавливает CODEBUDDY_INTERNET_ENVIRONMENT — выберите Internal или IOA для ограниченных сетевых сред.',
'ai.codebuddy.internetEnv.hint': 'Задаёт переменную CODEBUDDY_INTERNET_ENVIRONMENT. Для сетей с ограниченным доступом выберите «Внутренняя» или IOA.',
'ai.codebuddy.envVars': 'Переменные окружения',
'ai.codebuddy.envVars.placeholder': 'CODEBUDDY_API_KEY=...\nCODEBUDDY_AUTH_TOKEN=...\nOTHER_VAR=...',
'ai.codebuddy.envVars.hint': 'По одной записи KEY=VALUE на строку, передаются агенту CodeBuddy. Укажите CODEBUDDY_API_KEY или CODEBUDDY_AUTH_TOKEN для аутентификации. Хранятся локально в открытом виде.',
'ai.codebuddy.advancedSection': 'Расширенные параметры (SDK 0.3.258)',
'ai.codebuddy.effort': 'Усилие рассуждения',
'ai.codebuddy.effort': 'Глубина рассуждения',
'ai.codebuddy.effort.default': 'По умолчанию',
'ai.codebuddy.effort.minimal': 'Minimal',
'ai.codebuddy.effort.low': 'Low',
'ai.codebuddy.effort.medium': 'Medium',
'ai.codebuddy.effort.high': 'High',
'ai.codebuddy.effort.xhigh': 'XHigh',
'ai.codebuddy.effort.max': 'Max',
'ai.codebuddy.effort.hint': 'Управляет глубиной рассуждения модели. Для простых команд используйте Minimal/Low, чтобы экономить токены, а для сложной диагностики — Max/High.',
'ai.codebuddy.effort.minimal': 'Минимальная',
'ai.codebuddy.effort.low': 'Низкая',
'ai.codebuddy.effort.medium': 'Средняя',
'ai.codebuddy.effort.high': 'Высокая',
'ai.codebuddy.effort.xhigh': 'Очень высокая',
'ai.codebuddy.effort.max': 'Максимальная',
'ai.codebuddy.effort.hint': 'Для простых команд выбирайте минимальную или низкую глубину рассуждения, чтобы экономить токены. Для сложной диагностики выбирайте высокую или максимальную.',
'ai.codebuddy.maxTurns': 'Максимум шагов',
'ai.codebuddy.maxTurns.hint': 'Ограничивает максимальное число шагов диалога за запрос, предотвращая зацикливание. Оставьте пустым для значения по умолчанию.',
'ai.codebuddy.maxBudget': 'Максимальный бюджет (USD)',
@@ -274,22 +302,54 @@ export const ruAiMessages: Messages = {
'ai.grok.runtime.streamingJson.hint':
'Режим headless streaming-json (grok -p --output-format streaming-json). MCP внедряется через .grok/config.toml проекта.',
// OpenCode
'ai.opencode.title': 'OpenCode',
'ai.opencode.description': 'Подключается к OpenCode через официальный SDK. Настройте провайдеров и ключи в OpenCode, затем выберите его как внешнего агента для программирования.',
'ai.opencode.detecting': 'Поиск…',
'ai.opencode.detected': 'Найден',
'ai.opencode.notFound': 'Не найден',
'ai.opencode.path': 'Путь:',
'ai.opencode.notFoundHint': 'Не удалось найти opencode в PATH. Установите OpenCode или укажите путь к исполняемому файлу ниже.',
'ai.opencode.customPathPlaceholder': 'например, /usr/local/bin/opencode',
'ai.opencode.check': 'Проверить',
'ai.opencode.resetPath': 'Сбросить',
'ai.opencode.v2.startupTimeout': 'OpenCode 2 не успел запуститься. Убедитесь, что команда `opencode serve` работает в терминале, и повторите попытку.',
'ai.opencode.v2.exited': 'OpenCode 2 завершил работу до запуска чата.',
'ai.opencode.v2.unauthorized': 'OpenCode 2 отклонил подключение. Повторите попытку в чате.',
'ai.opencode.v2.unavailable': 'Не удалось подключиться к OpenCode 2. Проверьте, установлен ли он, и повторите попытку.',
'ai.opencode.v2.sessionFailed': 'OpenCode 2 не смог завершить обработку запроса.',
'ai.opencode.v2.empty': 'OpenCode 2 вернул пустой ответ. Запустите `opencode` в терминале, чтобы настроить вход и модели.',
'ai.opencode.v2.contextSkipped': 'OpenCode 2 не смог использовать контекст чата Netcatty.',
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
// MiMo Code
'ai.mimo.title': 'MiMo Code',
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
'ai.mimo.detecting': 'Поиск…',
'ai.mimo.detected': 'Найден',
'ai.mimo.notFound': 'Не найден',
'ai.mimo.path': 'Путь:',
'ai.mimo.notFoundHint': 'Не удалось найти mimo в PATH. Установите MiMo Code или укажите путь к исполняемому файлу ниже.',
'ai.mimo.customPathPlaceholder': 'например, /usr/local/bin/mimo',
'ai.mimo.check': 'Проверить',
'ai.mimo.resetPath': 'Сбросить',
// AI Default Agent
'ai.defaultAgent': 'Агент по умолчанию',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске новой AI-сессии',
'ai.defaultAgent.description': 'Агент, который будет использоваться при запуске нового сеанса ИИ',
'ai.defaultAgent.catty': 'Catty (встроенный)',
'ai.defaultAgent.unavailable': 'Недоступен',
'ai.toolAccess.title': 'Доступ к инструментам',
'ai.toolAccess.mode': 'Режим доступа Netcatty',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сессиям Netcatty. MCP предоставляет встроенный сервер, а Skills + CLI указывает агентам на локальный skill Netcatty и команды CLI.',
'ai.toolAccess.description': 'Выберите, как внешние агенты получают доступ к сеансам Netcatty. MCP предоставляет встроенный сервер, а режим «Навыки + CLI» указывает агентам на локальный навык Netcatty и команды CLI.',
'ai.toolAccess.mode.mcp': 'MCP',
'ai.toolAccess.mode.skills': 'Skills + CLI',
'ai.toolAccess.mode.skills': 'Навыки + CLI',
'ai.toolAccess.mcpPrompt.title': 'Промпт для вашего ИИ-клиента',
'ai.toolAccess.mcpPrompt.description': 'Вставьте этот промпт в ИИ-клиент (Codex, Claude Code и т. д.), и он сам зарегистрирует MCP Netcatty.',
'ai.toolAccess.mcpPrompt.enableHint': 'Включите внешний MCP ниже, чтобы в промпт попал путь к лаунчеру.',
'ai.toolAccess.skills.file': 'Файл skill',
'ai.toolAccess.skills.description': 'В режиме Skills + CLI агенты автоматически получают путь к этому локальному skill-файлу. Путь к лаунчеру Netcatty CLI передаётся агенту в каждой сессии.',
'ai.toolAccess.skills.unavailable': 'Путь к skill-файлу недоступен',
'ai.toolAccess.skills.file': 'Файл навыка',
'ai.toolAccess.skills.description': 'В режиме «Навыки + CLI» агенты автоматически получают путь к локальному файлу навыка. Путь к файлу запуска Netcatty CLI передаётся агенту в каждом сеансе.',
'ai.toolAccess.skills.unavailable': 'Путь к файлу навыка недоступен',
'ai.externalMcp.title': 'Внешний MCP',
'ai.externalMcp.allowCommandOnHost': 'Всегда',
@@ -323,13 +383,13 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.sessionIdleTimeout': 'Тайм-аут открытого сеанса',
'ai.externalMcp.sessionIdleTimeout.description': 'Автоматически закрывать сеансы, открытые ИИ, после указанного числа минут без операций терминала или файлов.',
'ai.externalMcp.usage.title': 'Как пользоваться',
'ai.externalMcp.usage.keepRunning': '1. Включите External MCP и держите Netcatty запущенным.',
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный launcher (только 127.0.0.1). Discovery удаляется при отключении.',
'ai.externalMcp.usage.permissions': '3. Запись следует Settings → AI → Safety и списку блокировки команд.',
'ai.externalMcp.usage.capabilities': '4. Доступен полный catalog: терминал, SFTP, Vault и проброс портов. Секреты не возвращаются.',
'ai.externalMcp.help.ariaLabel': 'Справка External MCP',
'ai.externalMcp.usage.keepRunning': '1. Включите внешний MCP и оставьте Netcatty запущенным.',
'ai.externalMcp.usage.localhost': '2. Клиенты подключаются через локальный файл запуска (только 127.0.0.1). При отключении файл обнаружения удаляется.',
'ai.externalMcp.usage.permissions': '3. Для операций записи действуют параметры в разделе «Настройки → ИИ → Безопасность» и список заблокированных команд.',
'ai.externalMcp.usage.capabilities': '4. Доступен полный каталог: терминал, SFTP, хранилище и проброс портов. Секреты не возвращаются.',
'ai.externalMcp.help.ariaLabel': 'Справка по внешнему MCP',
'ai.externalMcp.security': 'Безопасность',
'ai.externalMcp.security.description': 'Слушает только 127.0.0.1 с ротацией token, использует AI Permission Mode для записи и удаляет discovery при отключении.',
'ai.externalMcp.security.description': 'Принимает подключения только на 127.0.0.1, обновляет токен, применяет режим разрешений ИИ к операциям записи и удаляет файл обнаружения при отключении. Локальный мост приложения работает без OAuth.',
"ai.privacy.title": "Конфиденциальность ИИ",
"ai.privacy.description": "Фильтрует известные шаблоны конфиденциального текста в контексте и результатах инструментов, управляемых Netcatty, для Catty, встроенных агентов и внешних MCP-клиентов. По умолчанию отключено. Не обнаруживает все секреты. При включении двоичные ответы инструментов блокируются.",
"ai.privacy.boundary": "Защищаются только данные и инструменты, управляемые Netcatty. Собственные инструменты сторонних агентов, их прямой доступ к файлам и другие MCP-серверы не входят в эту область.",
@@ -362,11 +422,11 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.http.invalidClientHost': 'Адрес клиента должен быть доступным IP, а не 0.0.0.0 или ::.',
'ai.externalMcp.http.warning': 'Прослушивание не только 127.0.0.1 открывает External MCP другим машинам, которые могут достичь этого адреса. Храните bearer token в секрете и не публикуйте этот порт.',
'ai.externalMcp.http.url': 'URL',
'ai.externalMcp.http.token': 'Bearer token',
'ai.externalMcp.http.token': 'Токен Bearer',
'ai.externalMcp.http.regenerate': 'Создать заново',
'ai.externalMcp.http.regenerateHint': 'Выпускает новый bearer token. HTTP-клиенты должны использовать новый token. Файл discovery для stdio обновляется; уже подключенные stdio-клиенты остаются подключенными.',
'ai.externalMcp.http.wslHint': 'При mirrored networking в WSL достаточно localhost. Иначе слушайте 0.0.0.0 или IP vEthernet и укажите IP узла Windows как адрес клиента.',
'ai.externalMcp.http.codexSnippet': 'Codex config.toml',
'ai.externalMcp.http.codexSnippet': 'Файл config.toml для Codex',
'ai.externalMcp.http.claudeCommand': 'Claude Code',
'ai.externalMcp.http.genericSnippet': 'Общий JSON',
'ai.externalMcp.http.envLine': 'Переменная окружения token для Codex',
@@ -380,12 +440,12 @@ export const ruAiMessages: Messages = {
'ai.externalMcp.http.legacySseNote': 'Устаревший HTTP+SSE (2024-11-05) не предоставляется. Используйте этот URL Streamable HTTP.',
'ai.externalMcp.permissionMode': 'Текущий режим разрешений: {mode}',
'ai.externalMcp.permissionMode.label': 'Режим разрешений на запись',
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что Settings → AI → Safety. Auto выполняет write-инструменты Netcatty без запросов; Confirm спрашивает каждый раз. Внешние клиенты (Codex / Claude / Grok) могут показывать своё подтверждение инструментов.',
'ai.externalMcp.permissionMode.hint': 'Тот же параметр, что в разделе «Настройки → ИИ → Безопасность». В режиме «Авто» Netcatty выполняет операции записи без запроса. В режиме «Подтверждение» Netcatty запрашивает разрешение каждый раз. Внешние клиенты (Codex, Claude, Grok) могут запрашивать собственное подтверждение.',
'ai.externalMcp.permissionMode.unknown': 'Неизвестно',
'ai.externalMcp.discovery': 'Discovery',
'ai.externalMcp.launcher': 'Launcher',
'ai.externalMcp.discovery': 'Файл обнаружения',
'ai.externalMcp.launcher': 'Файл запуска',
'ai.externalMcp.unavailable': 'Недоступно',
'ai.externalMcp.bridgeUnavailable': 'Мост External MCP недоступен',
'ai.externalMcp.bridgeUnavailable': 'Мост внешнего MCP недоступен',
'ai.externalMcp.copy': 'Копировать',
'ai.externalMcp.copied': 'Скопировано',
'ai.externalMcp.copyFailed': 'Не удалось скопировать. Скопируйте вручную.',
@@ -440,7 +500,7 @@ export const ruAiMessages: Messages = {
// AI Quick Messages
'ai.quickMessages.title': 'Быстрые сообщения',
'ai.quickMessages.description': 'Создавайте часто используемые подсказки и вставляйте их в AI-чат через / или кнопку быстрых сообщений. В отличие от user skills, быстрые сообщения заполняют поле ввода текстом.',
'ai.quickMessages.description': 'Создавайте подсказки для повторного использования. Чтобы вставить текст подсказки в поле ввода чата с ИИ, наберите / или нажмите кнопку быстрых сообщений.',
'ai.quickMessages.add': 'Добавить быстрое сообщение',
'ai.quickMessages.createTitle': 'Новое быстрое сообщение',
'ai.quickMessages.editTitle': 'Редактировать быстрое сообщение',
@@ -462,14 +522,14 @@ export const ruAiMessages: Messages = {
'ai.quickMessages.error.maxItems': 'Можно сохранить не более {max} быстрых сообщений.',
// AI Chat
'ai.chat.noProvider': 'AI-провайдер не настроен. Перейдите в **Настройки → AI → Провайдеры**, чтобы добавить и включить провайдера.',
'ai.chat.noProvider': 'Провайдер ИИ не настроен. Перейдите в **Настройки → ИИ → Провайдеры**, чтобы добавить и включить провайдера.',
'ai.chat.toolDenied': 'Действие было отклонено пользователем.',
'ai.chat.toolApproved': 'Одобрено',
'ai.chat.toolApprovalHint': 'Enter — разрешить один раз, Escape — отклонить',
'ai.chat.approve': 'Одобрить',
'ai.chat.approveOnce': 'Разрешить один раз',
'ai.chat.alwaysAllow': 'Всегда разрешать',
'ai.chat.slashStopDesc': 'Остановить текущий ход AI и отменить выполняющиеся инструменты',
'ai.chat.slashStopDesc': 'Остановить текущий ход ИИ и отменить выполняющиеся инструменты',
'ai.chat.slashCompactDesc': 'Сжать ранний контекст разговора',
'ai.chat.slashRenameDesc': 'Переименовать текущий чат (/rename <название>)',
'ai.chat.slashChatsDesc': 'Показать чаты, видимые в этой панели',
@@ -480,12 +540,12 @@ export const ruAiMessages: Messages = {
'ai.chat.copyCommand': 'Копировать',
'ai.chat.commandCopied': 'Скопировано',
'ai.chat.approvalSession': 'Сессия',
'ai.chat.approvalShell': 'Shell',
'ai.chat.approvalShell': 'Оболочка',
'ai.chat.approvalCwd': 'Каталог',
'ai.chat.approvalReason': 'Причина',
'ai.chat.approvalInvocation': 'Вызов',
'ai.chat.permissionRequired': 'Требуется разрешение',
'ai.chat.permissionDescription': 'AI-агент хочет выполнить вызов инструмента, для которого требуется ваше одобрение.',
'ai.chat.permissionDescription': 'Агент ИИ хочет вызвать инструмент, для которого требуется ваше разрешение.',
'ai.chat.commandBlocked': 'Эта команда заблокирована вашей политикой безопасности и не может быть выполнена.',
'ai.chat.recommendAllow': 'Разрешить',
'ai.chat.recommendConfirm': 'Подтвердить',
@@ -511,7 +571,7 @@ export const ruAiMessages: Messages = {
'ai.chat.placeholder': 'Сообщение {agent} — @ для добавления контекста, / для команд',
'ai.chat.placeholderDefault': 'Сообщение агенту Catty...',
'ai.chat.noModel': 'Нет модели',
'ai.chat.noProviderModel': 'Модель по умолчанию не задана — настройте её в Настройки → AI → Провайдеры.',
'ai.chat.noProviderModel': 'Модель по умолчанию не задана. Выберите её в разделе «Настройки → ИИ → Провайдеры».',
'ai.chat.selectProvider': 'Выберите провайдера',
'ai.chat.selectProviderAndModel': 'Выберите провайдера и модель',
'ai.chat.selectModel': 'Выберите модель',
@@ -548,7 +608,7 @@ export const ruAiMessages: Messages = {
'ai.chat.importNone': 'В выбранном файле не найдено чатов ИИ.',
'ai.chat.chatsHeader': 'Чаты, видимые в этой панели:',
'ai.chat.chatsEmpty': 'В этой панели нет видимых чатов.',
'ai.chat.chatsScopeWorkspace': 'Workspace',
'ai.chat.chatsScopeWorkspace': 'Рабочая область',
'ai.chat.chatsScopeTerminal': 'Терминал',
'ai.chat.chatsScopeGlobal': 'Глобально',
'ai.chat.chatsScopeDangling': 'Связь потеряна',
@@ -617,12 +677,12 @@ export const ruAiMessages: Messages = {
'ai.chat.slashUserSkills': 'Пользовательские навыки',
'ai.chat.quickMessages': 'Команды /',
'ai.chat.slashNoResults': 'Нет подходящих команд',
'ai.chat.slashEmptyHint': 'Добавьте подсказки в Настройки → AI → Быстрые сообщения.',
'ai.chat.slashEmptyHint': 'Добавьте подсказки в разделе «Настройки → ИИ → Быстрые сообщения».',
// AI Chat Shortcuts
'ai.chatShortcuts.title': 'Быстрые действия чата',
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку AI рядом с выделенным текстом терминала.',
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
'ai.chatHistory.title': 'История чата',
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
@@ -634,7 +694,7 @@ export const ruAiMessages: Messages = {
// AI Web Search
'ai.webSearch.title': 'Веб-поиск',
'ai.webSearch.enable': 'Включить веб-поиск',
'ai.webSearch.enable.description': 'Разрешить AI-агенту искать в интернете актуальную информацию.',
'ai.webSearch.enable.description': 'Разрешить агенту ИИ искать в интернете актуальную информацию.',
'ai.webSearch.provider': 'Провайдер поиска',
'ai.webSearch.provider.description': 'Выберите провайдера API веб-поиска.',
'ai.webSearch.apiKey': 'API-ключ',
@@ -649,7 +709,7 @@ export const ruAiMessages: Messages = {
// AI Safety Settings
'ai.safety.title': 'Безопасность',
'ai.safety.permissionMode': 'Режим разрешений',
'ai.safety.permissionMode.description': 'Управляет тем, как AI взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
'ai.safety.permissionMode.description': 'Управляет тем, как ИИ взаимодействует с вашими терминалами. Режим наблюдателя блокирует все операции записи через Netcatty и применяется как к встроенным, так и к внешним агентам. Режим подтверждения носит рекомендательный характер для внешних агентов (они управляют собственным потоком одобрения инструментов).',
'ai.safety.permissionMode.observer': 'Наблюдатель — только чтение, без действий',
'ai.safety.permissionMode.confirm': 'Подтверждение — спрашивать перед действиями',
'ai.safety.permissionMode.auto': 'Авто — выполнять свободно',
@@ -660,7 +720,7 @@ export const ruAiMessages: Messages = {
'ai.safety.responseIdleTimeout.description': 'Отменяет запрос встроенного ИИ после указанного числа секунд без нового ответа. Не управляет общей длительностью ответа и выполнением команд.',
'ai.safety.responseIdleTimeout.unit': 'с',
'ai.safety.maxIterations': 'Макс. число итераций',
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов ИИ, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
'ai.safety.toolOutputMaxChars.unit': 'симв.',
@@ -693,12 +753,15 @@ export const ruAiMessages: Messages = {
'terminal.layer.history': 'История',
'terminal.layer.theme': 'Тема',
'terminal.layer.notes': 'Заметки',
'terminal.layer.aiChat': 'AI-чат',
'terminal.layer.aiChat': 'Чат с ИИ',
'terminal.layer.choosePanelPosition': 'Изменить положение',
'terminal.layer.dockLeft': 'Слева',
'terminal.layer.dockRight': 'Справа',
'terminal.layer.dockBottom': 'Снизу',
'terminal.layer.closePanel': 'Закрыть панель',
'terminal.layer.saveLayoutAsDefault': 'Сохранить расположение панелей по умолчанию',
'terminal.layer.layoutSavedAsDefault': 'Расположение панелей по умолчанию сохранено',
'terminal.layer.layoutSaveFailed': 'Не удалось сохранить расположение панелей',
'terminal.layer.closePane': 'Закрыть область',
'terminal.layer.resizeSplit': 'Изменить размер области',
'terminal.layer.splitHorizontal': 'Разделить сверху и снизу',
@@ -718,9 +781,15 @@ export const ruAiMessages: Messages = {
'terminal.layer.hostTree.collapse': 'Свернуть список хостов',
'terminal.layer.hostTree.expand': 'Развернуть список хостов',
'terminal.layer.hostTree.empty': 'Хосты не найдены',
'terminal.layer.hostTree.details.host': 'Хост',
'terminal.layer.hostTree.details.user': 'Пользователь',
'terminal.layer.hostTree.details.port': 'Порт',
'terminal.layer.hostTree.details.protocol': 'Протокол',
'terminal.layer.hostTree.details.group': 'Группа',
'terminal.layer.hostTree.details.tags': 'Теги',
'topTabs.openQuickSwitcher': 'Открыть быстрый переключатель',
'topTabs.moreTabs': 'Больше вкладок',
'topTabs.aiAssistant': 'AI-помощник',
'topTabs.aiAssistant': 'ИИ-помощник',
'topTabs.controlPanel': 'Быстрые настройки',
'topTabs.controlPanel.externalMcp': 'Внешний MCP',
'topTabs.controlPanel.theme': 'Тема',
@@ -765,6 +834,15 @@ export const ruAiMessages: Messages = {
'ai.chat.artifact.scriptRunPaused': 'Запуск скрипта приостановлен',
'ai.chat.artifact.scriptRunResumed': 'Запуск скрипта возобновлён',
'ai.chat.artifact.scriptReference': 'Справка nct API',
'ai.chat.artifact.rdScreenRead': 'Снимок удалённого экрана',
'ai.chat.artifact.rdScreenGrid': 'Снимок удалённого экрана (сетка)',
'ai.chat.artifact.rdScreenCropped': 'Снимок увеличенной области',
'ai.chat.artifact.rdActionExecuted': 'Выполнено удалённых действий: {count}',
'ai.chat.artifact.rdActionCount': 'действий: {count}',
'ai.chat.artifact.rdActionPreempted': 'Удалённое действие прервано пользователем',
'ai.chat.artifact.rdScreenFailed': 'Не удалось снять удалённый экран',
'ai.chat.artifact.rdActionFailed': 'Ошибка действия на удалённом рабочем столе',
'ai.chat.artifact.rdPreviewScreen': 'Предпросмотр снимка экрана',
'zmodem.waitingForRemote': 'Ожидание удалённой стороны...',
'zmodem.uploading': 'Загрузка',
'zmodem.downloading': 'Скачивание',
+111 -31
View File
@@ -38,6 +38,33 @@ export const ruCoreMessages: Messages = {
"settings.plugins.github.error.failed": "Не удалось проверить или установить плагин. Изучите технические подробности перед повторной попыткой.",
"settings.plugins.github.error.details": "Технические подробности",
"settings.plugins.landing.checkUpdates": "Проверить обновления",
"settings.plugins.landing.checkingUpdates": "Проверка…",
"settings.plugins.landing.updateSummary": "Проверено: {checked} · Опубликовано обновлений: {updates} · Пропущено: {skipped}.",
"settings.plugins.landing.updateSourcesFailed": "Недоступных источников: {count}.",
"settings.plugins.landing.updateReview": "Перед установкой проверьте обновления в менеджере плагинов.",
"settings.plugins.landing.updateAvailable": "Доступна версия {version}",
"settings.plugins.landing.loading": "Загрузка установленных плагинов…",
"settings.plugins.landing.settingsUnavailable": "Здесь настройки плагинов недоступны.",
"settings.plugins.landing.options": "Параметры плагина",
"settings.plugins.landing.manager": "Менеджер плагинов",
"settings.plugins.landing.managerDescription": "Просматривайте плагины и управляйте установленными пакетами и источниками.",
"settings.plugins.landing.browse": "Обзор",
"settings.plugins.landing.refresh": "Обновить список установленных плагинов",
"settings.plugins.landing.unavailable": "Управление плагинами недоступно в этом сеансе.",
"settings.plugins.landing.empty": "Плагины ещё не установлены. Откройте менеджер плагинов, чтобы посмотреть доступные варианты.",
"settings.plugins.landing.search": "Поиск установленных плагинов",
"settings.plugins.landing.settingsFor": "Настройки плагина {name}",
"settings.plugins.landing.enableSettings": "Включите плагин, чтобы открыть его настройки.",
"settings.plugins.landing.sourceUnknown": "Источник неизвестен",
"settings.plugins.landing.status.running": "Работает",
"settings.plugins.landing.status.starting": "Запускается",
"settings.plugins.landing.status.stopping": "Останавливается",
"settings.plugins.landing.status.error": "Ошибка",
"settings.plugins.landing.status.quarantined": "В карантине",
"settings.plugins.landing.status.unknown": "Состояние неизвестно",
"settings.plugins.landing.status.idle": "Включён, не запущен",
// Common
'common.save': 'Сохранить',
'common.cancel': 'Отмена',
@@ -150,7 +177,7 @@ export const ruCoreMessages: Messages = {
'settings.tab.appearance': 'Внешний вид',
'settings.tab.terminal': 'Терминал',
'settings.tab.shortcuts': 'Горячие клавиши',
'settings.tab.ai': 'AI',
'settings.tab.ai': 'ИИ',
'settings.tab.syncCloud': 'Синхронизация и облако',
'settings.tab.system': 'Система',
'settings.search.open': 'Поиск настроек',
@@ -245,7 +272,7 @@ export const ruCoreMessages: Messages = {
// Settings > System > Network Proxy
'settings.system.networkProxy.title': 'Сетевой прокси',
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и AI-провайдеров. Не связан с SSH ProxyJump / ProxyCommand.',
'settings.system.networkProxy.description': 'HTTP(S)-прокси для облачной синхронизации и провайдеров ИИ. Не связан с SSH ProxyJump / ProxyCommand.',
'settings.system.networkProxy.mode': 'Режим прокси',
'settings.system.networkProxy.mode.system': 'Системный прокси',
'settings.system.networkProxy.mode.direct': 'Напрямую (без прокси)',
@@ -256,7 +283,7 @@ export const ruCoreMessages: Messages = {
'settings.system.networkProxy.bypass': 'Список исключений',
'settings.system.networkProxy.bypass.placeholder': '<local>,localhost,127.0.0.1',
'settings.system.networkProxy.bypass.desc': 'Хосты через запятую, для которых прокси не используется. <local> — localhost и локальные имена.',
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive / OneDrive / GitHub sync и запросы к AI-провайдерам. SSH-подключения не меняет.',
'settings.system.networkProxy.hint': 'Влияет на вход в Google Drive, OneDrive и GitHub для синхронизации и на запросы к провайдерам ИИ. SSH-подключения не меняет.',
// Settings > System > Crash Logs
'settings.system.crashLogs.title': 'Журналы сбоев',
@@ -296,6 +323,21 @@ export const ruCoreMessages: Messages = {
'settings.update.autoUpdateEnabled': 'Автоматические обновления',
'settings.update.autoUpdateEnabledDesc': 'Автоматически проверять и загружать обновления, когда они доступны.',
// Settings > Session Restore
'settings.sessionRestore.title': 'Восстановление сеансов',
'settings.sessionRestore.startupLanding': 'При запуске',
'settings.sessionRestore.startupLandingDesc': 'Выберите, что открывать при запуске Netcatty, если сеансы не восстановлены: главную страницу с хостами или локальный терминал.',
'settings.sessionRestore.startupLanding.vault': 'Главная (хосты)',
'settings.sessionRestore.startupLanding.localTerminal': 'Локальный терминал',
'settings.sessionRestore.restorePreviousSession': 'Восстанавливать вкладки и рабочие области',
'settings.sessionRestore.restorePreviousSessionDesc': 'Открывать вкладки терминала и восстанавливать расположение панелей в рабочих областях из предыдущего сеанса приложения.',
'settings.sessionRestore.restoreTerminalCwd': 'Восстанавливать рабочий каталог терминала',
'settings.sessionRestore.restoreTerminalCwdDesc': 'При переподключении восстановленного терминала пытаться перейти в последний известный рабочий каталог, не задерживая подключение.',
'terminal.restore.placeholder.title': 'Восстановленный сеанс',
'terminal.restore.placeholder.desc': 'Терминал отключён. Подключитесь снова, чтобы запустить новую оболочку в этой вкладке.',
'terminal.restore.placeholder.reconnect': 'Переподключиться',
'terminal.restore.cwdLog': 'Восстановление рабочего каталога: {cwd}',
// Settings > Session Logs
'settings.sessionLogs.title': 'Журналы сессий',
'settings.sessionLogs.description': 'Настройка экспорта журналов сессий и параметров автосохранения.',
@@ -495,7 +537,7 @@ export const ruCoreMessages: Messages = {
### Боковая панель терминала
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / AI (только пока открыта)
- \`terminal-side-panel\` — панель SFTP / скриптов / темы / ИИ (только пока открыта)
- \`terminal-side-panel-tabs\`
- \`terminal-side-panel-content\`
@@ -597,6 +639,7 @@ export const ruCoreMessages: Messages = {
'settings.terminal.section.keyboard': 'Клавиатура',
'settings.terminal.section.accessibility': 'Доступность',
'settings.terminal.section.behavior': 'Поведение',
'settings.terminal.section.sidePanel': 'Боковая панель',
'settings.terminal.section.scrollback': 'Буфер прокрутки',
'settings.terminal.section.keywordHighlight': 'Подсветка ключевых слов',
'settings.terminal.font.family': 'Шрифт',
@@ -822,6 +865,18 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShell.startDir.placeholder': 'Домашний каталог',
'settings.terminal.localShell.startDir.notFound': 'Каталог не найден',
'settings.terminal.localShell.startDir.isFile': 'Путь указывает на файл, а не на каталог',
'settings.terminal.sidePanel.autoOpen': 'Открывать боковую панель при подключении',
'settings.terminal.sidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после подключения терминала.',
'settings.terminal.sidePanel.autoOpenPane': 'Боковая панель по умолчанию',
'settings.terminal.sidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.sidePanel.pane.sftp': 'SFTP',
'settings.terminal.sidePanel.pane.scripts': 'Скрипты',
'settings.terminal.sidePanel.pane.history': 'История',
'settings.terminal.sidePanel.pane.theme': 'Тема',
'settings.terminal.sidePanel.pane.system': 'Система',
'settings.terminal.sidePanel.pane.notes': 'Заметки',
'settings.terminal.sidePanel.pane.ai': 'ИИ',
'settings.terminal.section.localShellSidePanel': 'Боковая панель локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen': 'Развернуть боковую панель при открытии локальной оболочки',
'settings.terminal.localShellSidePanel.autoOpen.desc': 'Автоматически открывать боковую панель после открытия локальной оболочки.',
@@ -829,10 +884,14 @@ export const ruCoreMessages: Messages = {
'settings.terminal.localShellSidePanel.autoOpenPane.desc': 'Выберите, какую панель открывать в первую очередь.',
'settings.terminal.localShellSidePanel.pane.files': 'Файлы',
'settings.terminal.section.connection': 'Подключение',
'settings.terminal.connection.verifyHostKeys': 'Проверять ключи SSH-хостов',
'settings.terminal.connection.verifyHostKeys.desc': 'Запрашивать подтверждение при подключении к SSH-хосту с новым или изменившимся ключом. Отключайте проверку только в доверенных частных сетях.',
'settings.terminal.connection.temporaryLegacyAlgorithms': 'Устаревшие алгоритмы для временных подключений',
'settings.terminal.connection.temporaryLegacyAlgorithms.desc': 'SSH-подключения без сохранённого хоста, включая запуск в стиле PuTTY и быстрое подключение, предлагают те же устаревшие алгоритмы, что и настройка хоста. Сохранённые хосты используют свою настройку. По умолчанию выключено: у этих алгоритмов есть известные слабости.',
'settings.terminal.connection.temporaryNetworkDeviceMode': 'Режим сетевого устройства для временных подключений',
'settings.terminal.connection.temporaryNetworkDeviceMode.desc': 'SSH-подключения без сохранённого хоста, включая внешний запуск и быстрое подключение, открываются в режиме сетевого устройства. Сохранённые хосты и группы сохраняют свой тип устройства. По умолчанию выключено.',
'settings.terminal.connection.sshAutoReconnectEnabled': 'Автоматически переподключать SSH-сеансы',
'settings.terminal.connection.sshAutoReconnectEnabled.desc': 'При неожиданном разрыве SSH-соединения повторять попытки с заданным интервалом, пока соединение не восстановится или вкладка не будет закрыта.',
'settings.terminal.connection.sshAutoReconnectInterval': 'Интервал переподключения SSH (секунды)',
'settings.terminal.connection.sshAutoReconnectInterval.desc': 'Ожидание между попытками: 5–3600 секунд (по умолчанию 5). Изменение применяется к следующему ожиданию; уже запущенный таймер не меняется.',
'settings.terminal.connection.keepaliveInterval': 'Интервал keepalive',
@@ -872,6 +931,18 @@ export const ruCoreMessages: Messages = {
'settings.terminal.rendering.renderer': 'Рендерер',
'settings.terminal.rendering.renderer.desc': 'Выберите технологию рендеринга терминала. В режиме "Авто" на устройствах с малым объёмом памяти будет использоваться DOM. Изменения применяются к новым терминальным сессиям.',
'settings.terminal.rendering.auto': 'Авто',
'settings.terminal.rendering.hibernateHiddenTabs': 'Переводить скрытые вкладки в спящий режим',
'settings.terminal.rendering.hibernateHiddenTabs.desc': 'В спящем режиме скрытые вкладки освобождают память, занятую рендерером, и сохраняют SSH-соединение. Во время передачи файлов режим не включается.',
'settings.terminal.rendering.hibernateHiddenTabsDelay': 'Задержка перед переходом в спящий режим',
'settings.terminal.rendering.hibernateHiddenTabsDelay.desc': 'Сколько времени вкладка должна оставаться скрытой до освобождения рендерера (5–600 секунд).',
'settings.terminal.rendering.hibernateSkipAltScreen': 'Отключать спящий режим для полноэкранных приложений',
'settings.terminal.rendering.hibernateSkipAltScreen.desc': 'Сохранять рендерер терминала, пока vim, htop или агенты с текстовым интерфейсом используют альтернативный экранный буфер.',
'settings.terminal.rendering.hibernateKeepRendererCount': 'Сохранять рендереры скрытых вкладок',
'settings.terminal.rendering.hibernateKeepRendererCount.desc': 'Количество скрытых вкладок, для которых рендерер сохраняется с приостановленным WebGL перед переходом в спящий режим.',
'settings.terminal.rendering.hibernateReplayChunkBytes': 'Объём вывода за кадр при восстановлении',
'settings.terminal.rendering.hibernateReplayChunkBytes.desc': 'Сколько данных вывода восстанавливать за один кадр анимации при выходе терминала из спящего режима (4–64 КБ).',
'settings.terminal.rendering.hibernatePreferWasmSerialize': 'Предпочитать сериализацию через WASM',
'settings.terminal.rendering.hibernatePreferWasmSerialize.desc': 'По возможности сериализовать состояние терминала через WASM. Если WASM недоступен, использовать JavaScript.',
// Settings > Terminal > Inline Images
'settings.terminal.section.inlineImages': 'Встроенные изображения',
@@ -1129,6 +1200,7 @@ export const ruCoreMessages: Messages = {
'vault.groups.selectedCount': 'Выбрано групп: {count}',
'vault.groups.deleteMultiple.success': 'Удалено выбранных элементов: {count}',
'vault.groups.ungrouped': 'Без группы',
'vault.groups.unnamed': 'Группа без имени',
'vault.groups.field.name': 'Имя группы',
'vault.groups.placeholder.example': 'например, Production',
'vault.groups.parentLabel': 'Родитель',
@@ -1137,7 +1209,10 @@ export const ruCoreMessages: Messages = {
'vault.groups.details': 'Сведения о группе',
'vault.groups.details.general': 'Общие',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': 'Параметры {protocol} по умолчанию для этой группы ещё не настроены.',
'vault.groups.details.advanced': 'Дополнительно',
'vault.groups.details.appearance': 'Внешний вид',
'vault.groups.details.mosh': 'Mosh',
@@ -1163,6 +1238,7 @@ export const ruCoreMessages: Messages = {
'vault.hosts.header.entries': 'Записей: {count}',
'vault.hosts.header.live': 'Активных: {count}',
'vault.hosts.errors.nameRequired': 'Укажите имя хоста.',
'deepLink.ssh.invalid': 'Недопустимая ссылка ssh://',
'deepLink.telnet.invalid': 'Недопустимая ссылка telnet://',
'deepLink.jms.invalid': 'Недопустимая ссылка JumpServer',
@@ -1196,15 +1272,19 @@ export const ruCoreMessages: Messages = {
"plugins.interaction.copy": "Копировать в буфер обмена",
"plugins.interaction.failed": "Запрос истёк или не выполнен.",
"plugins.command.failed": "Не удалось выполнить команду плагина. Проверьте необходимые выбранные объекты и разрешения.",
"plugins.interaction.terminalDisclosure": "Only the current selection from this terminal is shared, up to 4096 UTF-8 bytes. Terminal text can contain passwords, tokens, and other secrets. Inspect the exact preview before sharing. No redaction guarantee is made.",
"plugins.interaction.terminalTarget": "Selected terminal",
"plugins.interaction.terminalPreview": "Preview terminal selection",
"plugins.interaction.draftNote": "Editable draft for review only. This dialog sends no terminal input or Enter. Copy text yourself and use the normal terminal UI if you choose to send it. Your edits stay in this dialog.",
"plugins.interaction.draft": "Terminal input draft",
"plugins.interaction.exactText": "Exact text with escaped controls",
"plugins.interaction.closeDraft": "Close draft",
"plugins.interaction.terminalDisclosure": "Плагину передаётся только выделенный в этом терминале текст (до 4096 байт в UTF-8). Он может содержать пароли, токены и другие секреты. Перед передачей проверьте текст целиком. Автоматическое скрытие секретов не гарантируется.",
"plugins.interaction.terminalTarget": "Выбранный терминал",
"plugins.interaction.terminalPreview": "Предпросмотр выделенного текста",
"plugins.interaction.draftNote": "Здесь можно просмотреть и отредактировать черновик. Диалог не отправляет в терминал текст или нажатие Enter. Чтобы отправить текст, скопируйте его и вставьте в терминал. Изменения сохраняются только в этом диалоге.",
"plugins.interaction.draft": "Черновик ввода в терминал",
"plugins.interaction.exactText": "Исходный текст с экранированными управляющими символами",
"plugins.interaction.closeDraft": "Закрыть черновик",
"settings.plugins.permissions.current": "Соответствует текущему запуску",
"settings.plugins.permissions.inactive": "Не действует для текущего запуска",
"settings.plugins.permissions.note": "Заявленные возможности по умолчанию разрешены. В режиме «Спрашивать» Netcatty запрашивает разрешение с ограниченной областью действия. Режим «Запретить» сразу блокирует доступ. Цель можно выбрать, а черновик отредактировать в интерфейсе Netcatty.",
"settings.plugins.permissions.allow": "Разрешить",
"settings.plugins.permissions.ask": "Спрашивать",
"settings.plugins.permissions.deny": "Запретить",
"settings.plugins.permissions.title": "Сохранённые разрешения",
"settings.plugins.permissions.refresh": "Обновить",
"settings.plugins.permissions.loading": "Загрузка разрешений...",
@@ -1214,7 +1294,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.permissions.session": "До закрытия сеанса",
"settings.plugins.permissions.audit": "Последние события безопасности (до 100)",
"settings.plugins.permissions.revoke": "Отключить и отозвать все разрешения",
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения удалены. Включите его для нового запроса доступа.",
"settings.plugins.permissions.revokeNote": "Плагин будет отключён, его задачи отменены, а сохранённые разрешения отозваны. Выбранные режимы «Разрешить», «Спрашивать» и «Запретить» сохранятся.",
"settings.plugins.permissions.unavailable": "Управление разрешениями недоступно",
"settings.plugins.manager.permissions": "Заявленные разрешения",
"settings.plugins.manager.permissionNote": "Заявленные поддерживаемые возможности по умолчанию разрешены. Для каждой можно выбрать запрос или запрет в настройках разрешений. Проверки приложения и область ресурсов действуют всегда.",
@@ -1272,28 +1352,28 @@ export const ruCoreMessages: Messages = {
"settings.plugins.manager.unbounded": "Более узкая область ресурсов не заявлена. Проверки приложения и выбранный режим разрешений продолжают действовать.",
"settings.plugins.openView": "Открыть",
"settings.plugins.openManager": "Открыть управление плагинами",
"settings.plugins.sources.conflict": "This ID is installed from another source. Uninstall and explicitly reset its private data before switching. Existing source:",
"settings.plugins.sources.clearPrivate": "Also clear this source’s private data, grants and secrets to reinstall from another source. This cannot be undone.",
"settings.plugins.sources.conflict": "Плагин с этим идентификатором установлен из другого источника. Перед сменой источника удалите плагин и очистите его приватные данные. Текущий источник:",
"settings.plugins.sources.clearPrivate": "Также удалить приватные данные, выданные разрешения и секреты этого источника, чтобы установить плагин из другого источника. Это действие нельзя отменить.",
"settings.plugins.sources.short.official": "Официальный",
"settings.plugins.sources.short.thirdparty": "Сторонний",
"settings.plugins.sources.short.local": "Локальный",
"settings.plugins.sources.official": "Official marketplace",
"settings.plugins.sources.thirdparty": "Third-party marketplace",
"settings.plugins.sources.manage": "Manage sources",
"settings.plugins.sources.select": "Select a source",
"settings.plugins.sources.empty": "Choose or add a third-party source.",
"settings.plugins.sources.add": "Add source",
"settings.plugins.sources.remove": "Remove source",
"settings.plugins.sources.name": "Source name",
"settings.plugins.sources.address": "HTTPS source address",
"settings.plugins.sources.risk": "Third-party sources are not maintained or endorsed by Netcatty. Review the real domain, package permissions and author before installing.",
"settings.plugins.sources.accept": "I trust this domain to supply plugin metadata and packages. This does not grant plugin permissions.",
"settings.plugins.sources.removeNote": "Installed plugins and their data remain. Updates from this source stop; another source will not replace it.",
"settings.plugins.sources.disablePlugins": "Also disable plugins installed from this source",
"settings.plugins.sources.installConfirm": "Review third-party installation",
"settings.plugins.sources.source": "Source",
"settings.plugins.sources.local": "Local import",
"settings.plugins.sources.all": "All sources",
"settings.plugins.sources.official": "Официальный каталог",
"settings.plugins.sources.thirdparty": "Сторонний каталог",
"settings.plugins.sources.manage": "Управление источниками",
"settings.plugins.sources.select": "Выбрать источник",
"settings.plugins.sources.empty": "Выберите или добавьте сторонний источник.",
"settings.plugins.sources.add": "Добавить источник",
"settings.plugins.sources.remove": "Удалить источник",
"settings.plugins.sources.name": "Название источника",
"settings.plugins.sources.address": "HTTPS-адрес источника",
"settings.plugins.sources.risk": "Netcatty не поддерживает и не рекомендует сторонние источники. Перед установкой проверьте фактический домен, разрешения пакета и сведения об авторе.",
"settings.plugins.sources.accept": "Я доверяю этому домену как источнику метаданных и пакетов плагинов. Это не выдаёт плагинам разрешений.",
"settings.plugins.sources.removeNote": "Установленные плагины и их данные сохранятся. Обновления из этого источника прекратятся. Другой источник не заменит его.",
"settings.plugins.sources.disablePlugins": "Также отключить плагины из этого источника",
"settings.plugins.sources.installConfirm": "Проверка установки из стороннего источника",
"settings.plugins.sources.source": "Источник",
"settings.plugins.sources.local": "Импорт из файла",
"settings.plugins.sources.all": "Все источники",
"settings.plugins.title": "Плагины",
"settings.plugins.configuration": "Настройки плагина",
"settings.plugins.description": "Управляйте плагинами и просматривайте каталог.",
+18 -1
View File
@@ -26,6 +26,9 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.errors.loadDockerImages': 'Не удалось загрузить образы',
'systemManager.errors.loadKubernetes': 'Не удалось загрузить ресурсы Kubernetes',
'systemManager.errors.loadPods': 'Не удалось загрузить поды',
'systemManager.errors.nerdctlUnreachable': 'nerdctl не может подключиться к containerd',
'systemManager.errors.clusterUnreachable': 'Не удалось подключиться к кластеру для контекста {{context}}',
'systemManager.errors.clusterUnreachableGeneric': 'Не удалось подключиться к кластеру',
'systemManager.errors.loadGpu': 'Не удалось загрузить статистику GPU / NPU',
'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты',
'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd',
@@ -187,6 +190,20 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.k8s.restarts': '{{count}} перезапусков',
'systemManager.k8s.chooseContainer': 'Выберите контейнер',
'systemManager.k8s.noContext': 'На этом хосте нет контекста Kubernetes',
'systemManager.k8s.status.Running': 'Работает',
'systemManager.k8s.status.Pending': 'Ожидает запуска',
'systemManager.k8s.status.Completed': 'Завершён',
'systemManager.k8s.status.Succeeded': 'Завершён успешно',
'systemManager.k8s.status.Failed': 'Завершён с ошибкой',
'systemManager.k8s.status.Unknown': 'Состояние неизвестно',
'systemManager.k8s.status.CrashLoopBackOff': 'Циклические сбои',
'systemManager.k8s.status.ContainerCreating': 'Создаётся контейнер',
'systemManager.k8s.status.Terminating': 'Завершается',
'systemManager.k8s.status.ImagePullBackOff': 'Повтор загрузки',
'systemManager.k8s.status.ErrImagePull': 'Ошибка загрузки образа',
'systemManager.k8s.status.Error': 'Ошибка',
'systemManager.k8s.status.Evicted': 'Вытеснен',
'systemManager.k8s.status.OOMKilled': 'Нехватка памяти',
'systemManager.ports.unavailable': 'На этом хосте не обнаружены инструменты портов (ss / netstat).',
'systemManager.ports.loading': 'Загрузка слушающих портов…',
@@ -232,7 +249,7 @@ export const ruSystemManagerMessages: Messages = {
'systemManager.services.enable': 'Включить автозапуск',
'systemManager.services.disable': 'Отключить автозапуск',
'systemManager.services.reload': 'Перезагрузить',
'systemManager.services.scope.user': 'user',
'systemManager.services.scope.user': 'Пользовательская служба',
'systemManager.services.confirmAction': '{{action}} {{name}}?',
'systemManager.gpu.unavailable': 'На этом хосте не обнаружены инструменты NVIDIA GPU или Ascend NPU.',
+17 -9
View File
@@ -21,8 +21,8 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.readFailed': 'Не удалось прочитать каталог. Попробуйте обновить.',
'terminal.directory.changeFailed': 'Не удалось подтвердить смену каталога. Обновите перед повтором.',
'terminal.directory.unsupportedPath': 'Это имя каталога нельзя безопасно передать в терминал.',
'settings.terminal.behavior.contextChips': 'Context Chips',
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами.',
'settings.terminal.behavior.contextChips': 'Панель контекста',
'settings.terminal.behavior.contextChips.desc': 'Показывать панель контекста под быстрыми командами в области ввода.',
'terminal.toolbar.openSessionLog': 'Открыть журнал сессии',
'terminal.toolbar.sessionLogActions': 'Действия с журналом',
@@ -75,13 +75,13 @@ export const ruTerminalMessages: Messages = {
'terminal.browser.title': 'Браузер',
'terminal.browser.sshOnly': 'Выберите SSH-терминал, чтобы открыть его браузер.',
'terminal.browser.open': 'Открыть браузер',
'terminal.toolbar.availableAfterConnect': 'Доступно после подключения',
'terminal.toolbar.availableAfterConnect': 'Нужно подключение',
'terminal.toolbar.sendYmodem': 'Отправить через YMODEM',
'terminal.toolbar.receiveYmodem': 'Получить через YMODEM',
'terminal.toolbar.more': 'Другие действия',
'terminal.toolbar.scripts': 'Скрипты',
'terminal.toolbar.history': 'История команд',
'terminal.toolbar.configureOsc7': 'Настроить отслеживание каталога',
'terminal.toolbar.configureOsc7': 'Отслеживание каталога',
'history.scope.label': 'Область истории',
'history.tab.host': 'Хост',
'history.tab.global': 'Глобальная',
@@ -236,7 +236,7 @@ export const ruTerminalMessages: Messages = {
'terminal.clipboardImageUpload.noImage': 'В буфере обмена нет изображения',
'terminal.clipboardImageUpload.failed': 'Не удалось загрузить изображение из буфера обмена',
'terminal.selection.addToAI': 'Добавить в чат',
'terminal.selection.addToAIDesc': 'Прикрепить выбранный вывод терминала к черновику AI',
'terminal.selection.addToAIDesc': 'Прикрепить выделенный вывод терминала к черновику сообщения для ИИ',
'terminal.auth.password': 'Пароль',
'terminal.auth.sshKey': 'SSH-ключ',
'terminal.auth.username': 'Имя пользователя',
@@ -273,8 +273,11 @@ export const ruTerminalMessages: Messages = {
'terminal.connection.protocol.ssh': 'SSH',
'terminal.connection.protocol.telnet': 'Telnet',
'terminal.connection.protocol.mosh': 'Mosh',
'terminal.connection.protocol.et': 'EternalTerminal',
'terminal.connection.protocol.plugin': 'Подключение плагина',
'terminal.connection.protocol.serial': 'Serial',
'terminal.et.proxyUnsupported': 'EternalTerminal пока не поддерживает настройки прокси Netcatty. Используйте SSH или уберите прокси для этого хоста.',
'terminal.et.multiJumpUnsupported': 'В Netcatty EternalTerminal пока поддерживает только один промежуточный хост.',
'terminal.connection.protocol.serial': 'Последовательный порт',
'terminal.connection.protocol.local': 'Локальная оболочка',
'terminal.hostKey.unknownTitle': 'Подтвердите этот ключ хоста',
'terminal.hostKey.changedTitle': 'Ключ хоста изменился',
@@ -736,6 +739,8 @@ export const ruTerminalMessages: Messages = {
'snippets.action.selectSnippets': 'Выбрать сниппеты',
'snippets.panel.newTitle': 'Новый сниппет',
'snippets.panel.editTitle': 'Редактировать сниппет',
'snippets.panel.newAutomationTitle': 'Новый скрипт автоматизации',
'snippets.panel.editAutomationTitle': 'Редактировать скрипт автоматизации',
'snippets.panel.resizeWidth': 'Изменить ширину панели',
'snippets.field.description': 'Описание действия',
'snippets.field.descriptionPlaceholder': 'Например: проверить сетевую нагрузку',
@@ -762,6 +767,9 @@ export const ruTerminalMessages: Messages = {
'snippets.targets.selectHosts': 'Хосты',
'snippets.targets.selectGroups': 'Группы',
'snippets.targets.noGroups': 'Группы не найдены',
'snippets.targets.allHosts': 'Применять ко всем хостам',
'snippets.targets.allHostsShort': 'Все хосты',
'snippets.targets.allHostsActive': 'Применяется ко всем хостам, к которым можно подключиться.',
'snippets.history.title': 'История оболочки',
'snippets.history.subtitle': '{count} команд',
'snippets.history.emptyTitle': 'История оболочки пока пуста',
@@ -844,7 +852,7 @@ export const ruTerminalMessages: Messages = {
'snippets.shortkey.error.snippetConflict': 'Это сочетание уже используется сниппетом: {name}',
// Serial Port
'serial.button': 'Серийный',
'serial.button': 'Serial',
'serial.modal.title': 'Подключение к последовательному порту',
'serial.modal.desc': 'Настройте параметры подключения к последовательному порту',
'serial.field.port': 'Последовательный порт',
@@ -862,8 +870,8 @@ export const ruTerminalMessages: Messages = {
'serial.parity.none': 'Нет',
'serial.parity.even': 'Чётная',
'serial.parity.odd': 'Нечётная',
'serial.parity.mark': 'Mark',
'serial.parity.space': 'Space',
'serial.parity.mark': 'Всегда 1 (Mark)',
'serial.parity.space': 'Всегда 0 (Space)',
'serial.flowControl.none': 'Нет',
'serial.flowControl.xon/xoff': 'XON/XOFF (программный)',
'serial.flowControl.rts/cts': 'RTS/CTS (аппаратный)',
+28 -5
View File
@@ -627,6 +627,10 @@ export const ruVaultMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': 'Показывать файлы в виде плоского списка для текущего каталога',
'settings.sftp.defaultViewMode.tree': 'Дерево',
'settings.sftp.defaultViewMode.treeDesc': 'Показывать файлы в иерархической древовидной структуре',
'settings.sftp.treeFolderDoubleClick': 'Двойной щелчок по папке в дереве',
'settings.sftp.treeFolderDoubleClick.desc': 'Выберите действие при двойном щелчке по папке в режиме дерева SFTP. Щелчок по стрелке всегда раскрывает или сворачивает папку на месте.',
'settings.sftp.treeFolderDoubleClick.navigate': 'Перейти в каталог',
'settings.sftp.treeFolderDoubleClick.expand': 'Раскрыть или свернуть на месте',
'sftp.autoSync.success': 'Файл синхронизирован с удалённым сервером: {fileName}',
'sftp.autoSync.error': 'Не удалось синхронизировать файл: {error}',
@@ -857,6 +861,9 @@ export const ruVaultMessages: Messages = {
'hostDetails.distro.option.zyxel': 'ZyXEL',
'hostDetails.distro.option.ruijie': 'Ruijie',
'hostDetails.section.mosh': 'Mosh',
'hostDetails.section.et': 'EternalTerminal',
'hostDetails.et.port': 'Порт сервера ET',
'hostDetails.et.port.desc': 'Порт, на котором etserver принимает подключения (по умолчанию 2022)',
'hostDetails.username.placeholder': 'Имя пользователя',
'hostDetails.password.placeholder': 'Пароль',
'hostDetails.password.show': 'Показать пароль',
@@ -935,7 +942,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.section.deviceType': 'Тип устройства',
'hostDetails.deviceType': 'Режим сетевого устройства',
'hostDetails.deviceType.desc': 'Включайте для сетевого оборудования (коммутаторов, маршрутизаторов, межсетевых экранов), подключённого по SSH. Команды отправляются как есть, без обёртки оболочки, что совместимо с CLI вендоров вроде Huawei VRP и Cisco IOS.',
'hostDetails.deviceType.warning': 'Команды AI-агента будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
'hostDetails.deviceType.warning': 'Команды агента ИИ будут отправляться напрямую без отслеживания кода выхода. Включайте только для устройств, на которых нет стандартной оболочки.',
'hostDetails.section.sshAlgorithms': 'SSH-алгоритмы',
'hostDetails.section.terminalBehavior': 'Поведение терминала',
'hostDetails.lineTimestamps': 'Показывать время вывода',
@@ -1021,7 +1028,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.startupCommand': 'Команда запуска',
'hostDetails.startupCommand.placeholder': 'Команда для запуска при подключении (например, cd /app && ls)',
'hostDetails.startupCommand.help':
'This command will be executed automatically after SSH connection is established.',
'Команда выполняется автоматически после подключения по SSH.',
'hostDetails.startupCommand.runMode': 'Многострочный запуск',
'hostDetails.startupCommand.runMode.help': 'Выберите, как отправлять многострочные команды запуска после подключения.',
'hostDetails.startupCommand.runMode.lineDelay': 'Отправлять построчно',
@@ -1163,6 +1170,7 @@ export const ruVaultMessages: Messages = {
'hostDetails.rdp.resolutionMode.fixed': 'Фиксированный размер',
'hostDetails.rdp.width': 'Ширина',
'hostDetails.rdp.height': 'Высота',
'hostDetails.rdp.dimensionHint': 'Введите целое число от 200 до 8192.',
'hostDetails.rdp.colorDepth': 'Глубина цвета',
'hostDetails.rdp.audio': 'Вывод звука',
'hostDetails.rdp.audioDesc': 'Воспроизводить звук удалённого рабочего стола локально',
@@ -1276,6 +1284,9 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.toolbar.display': 'Масштаб экрана',
'remoteDesktop.toolbar.sshTunneled': 'Туннель через SSH',
'remoteDesktop.toolbar.encrypted': 'Шифрованное TLS-соединение',
'remoteDesktop.toolbar.standardRdpSecurity': 'Стандартная безопасность RDP ({{cipher}})',
'remoteDesktop.rdp.fallbackStandardRdp': 'Подключено через стандартную безопасность RDP.',
'remoteDesktop.rdp.fallbackStandardRdpWithCipher': 'Подключено через стандартную безопасность RDP ({{cipher}}).',
'remoteDesktop.toolbar.viewOnly': 'Режим «Только просмотр»',
'remoteDesktop.toolbar.viewOnlyBadge': 'Просмотр',
'remoteDesktop.toolbar.audio': 'Звук RDP',
@@ -1323,8 +1334,8 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.cert.rejected': 'TLS-сертификат отклонён пользователем.',
'remoteDesktop.step.bastion': 'Бастион',
'remoteDesktop.step.network': 'Сеть',
'remoteDesktop.step.nla': 'NLA Auth',
'remoteDesktop.step.rfb': 'RFB Auth',
'remoteDesktop.step.nla': 'Аутентификация NLA',
'remoteDesktop.step.rfb': 'Аутентификация RFB',
'remoteDesktop.step.desktop': 'Рабочий стол',
'remoteDesktop.display.resolutionPresets': 'Пресеты разрешения',
'remoteDesktop.display.customWidth': 'Ширина',
@@ -1386,6 +1397,7 @@ export const ruVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': 'Записать сессию',
'remoteDesktop.toolbar.stopRecording': 'Остановить запись',
'remoteDesktop.toolbar.savingRecording': 'Сохранение...',
'remoteDesktop.toolbar.recording': 'Запись',
'remoteDesktop.toolbar.askAi': 'Спросить ИИ',
'remoteDesktop.toolbar.askAiFull': 'Снять экран и спросить ИИ',
@@ -1432,7 +1444,18 @@ export const ruVaultMessages: Messages = {
'logView.remoteDesktop.started': 'Начало',
'logView.remoteDesktop.ended': 'Окончание',
'logView.remoteDesktop.duration': 'Длительность',
'logView.remoteDesktop.resolution': 'Разрешение',
'logView.remoteDesktop.security': 'Безопасность',
'logView.remoteDesktop.disconnectReason': 'Причина отключения',
'logView.remoteDesktop.timeline': 'Хронология сессии',
'logView.remoteDesktop.recordingTip': 'Нажмите «Записать сессию» на панели удалённого рабочего стола или включите автозапись в Настройки → Система, чтобы сохранять повторы .webm.',
'logs.recording.clipsCount': 'Клипов: {count}',
'logs.filter.all': 'Все',
'logs.filter.terminal': 'Терминал',
'logs.filter.remoteDesktop': 'Удалённый рабочий стол',
'logs.filter.recorded': 'С записью',
'logs.filter.emptyTitle': 'Нет подходящих журналов',
'logs.filter.emptyDesc': 'Для выбранного фильтра пока нет записей подключений.',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': 'Записи удалённого рабочего стола',
@@ -1440,7 +1463,7 @@ export const ruVaultMessages: Messages = {
'settings.remoteDesktopRecordings.autoRecordDesc': 'Автоматически начинать запись RDP и VNC после подключения (выключено по умолчанию для экономии места).',
'settings.remoteDesktopRecordings.fps': 'Частота кадров записи',
'settings.remoteDesktopRecordings.fpsDesc': 'Более высокая частота делает видео плавнее, но увеличивает нагрузку на ЦП и размер файлов.',
'settings.remoteDesktopRecordings.fpsOption': '{fps} FPS',
'settings.remoteDesktopRecordings.fpsOption': '{fps} кадр/с',
'settings.remoteDesktopRecordings.includeAudio': 'Включать звук RDP',
'settings.remoteDesktopRecordings.includeAudioDesc': 'Записывать звук удалённого рабочего стола в видео .webm, если он доступен.',
'settings.remoteDesktopRecordings.maxStorage': 'Лимит места на диске',
@@ -285,3 +285,22 @@ test("localized vault messages include interactive authentication labels", () =>
assert.deepEqual(missing, [], `${locale.name} is missing interactive authentication labels`);
}
});
test("localized settings include SFTP tree folder double-click labels across all locales", () => {
const keys = [
"settings.sftp.treeFolderDoubleClick",
"settings.sftp.treeFolderDoubleClick.desc",
"settings.sftp.treeFolderDoubleClick.navigate",
"settings.sftp.treeFolderDoubleClick.expand",
];
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = keys.filter((key) => !locale.messages[key]);
assert.deepEqual(missing, [], `${locale.name} is missing SFTP tree folder double-click labels`);
if (locale.name !== "en") {
for (const key of keys) {
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
}
}
}
});
+9
View File
@@ -835,6 +835,15 @@ export const zhCNAiMessages: Messages = {
'ai.chat.artifact.scriptRunPaused': '脚本运行已暂停',
'ai.chat.artifact.scriptRunResumed': '脚本运行已恢复',
'ai.chat.artifact.scriptReference': 'nct API 参考',
'ai.chat.artifact.rdScreenRead': '读取远程屏幕',
'ai.chat.artifact.rdScreenGrid': '读取远程屏幕(坐标网格)',
'ai.chat.artifact.rdScreenCropped': '局部放大截屏',
'ai.chat.artifact.rdActionExecuted': '已执行 {count} 步远程操作',
'ai.chat.artifact.rdActionCount': '{count} 个操作',
'ai.chat.artifact.rdActionPreempted': '远程操作已由用户接管',
'ai.chat.artifact.rdScreenFailed': '远程截屏失败',
'ai.chat.artifact.rdActionFailed': '远程桌面操作失败',
'ai.chat.artifact.rdPreviewScreen': '预览截取的画面',
'zmodem.waitingForRemote': '等待远端...',
'zmodem.uploading': '上传中',
'zmodem.downloading': '下载中',
+3
View File
@@ -785,7 +785,10 @@ Vaults 标签保持扁平,不使用这块背景。
'vault.groups.details': '分组详情',
'vault.groups.details.general': '常规',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': '当前分组尚未配置 {protocol} 默认协议设置。',
'vault.groups.details.advanced': '高级',
'vault.groups.details.appearance': '外观',
'vault.groups.details.mosh': 'Mosh',
@@ -191,6 +191,10 @@ export const zhCNTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表显示当前目录的文件',
'settings.sftp.defaultViewMode.tree': '树形视图',
'settings.sftp.defaultViewMode.treeDesc': '以层级树形结构显示文件',
'settings.sftp.treeFolderDoubleClick': '树形视图双击文件夹',
'settings.sftp.treeFolderDoubleClick.desc': '选择在 SFTP 树形视图中双击文件夹时的操作。点击左侧箭头始终在原处展开或折叠。',
'settings.sftp.treeFolderDoubleClick.navigate': '进入目录',
'settings.sftp.treeFolderDoubleClick.expand': '原地展开/折叠',
'sftp.autoSync.success': '文件已同步到远程:{fileName}',
'sftp.autoSync.error': '同步文件失败:{error}',
+16
View File
@@ -1113,6 +1113,7 @@ export const zhCNVaultMessages: Messages = {
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
'hostDetails.rdp.width': '宽度',
'hostDetails.rdp.height': '高度',
'hostDetails.rdp.dimensionHint': '请输入 200 到 8192 之间的整数。',
'hostDetails.rdp.colorDepth': '色深',
'hostDetails.rdp.audio': '音频输出',
'hostDetails.rdp.audioDesc': '在本地播放远程桌面声音',
@@ -1226,6 +1227,9 @@ export const zhCNVaultMessages: Messages = {
'remoteDesktop.toolbar.display': '显示缩放',
'remoteDesktop.toolbar.sshTunneled': '通过 SSH 隧道加密转发',
'remoteDesktop.toolbar.encrypted': 'TLS 加密连接',
'remoteDesktop.toolbar.standardRdpSecurity': '标准 RDP 安全层({{cipher}})',
'remoteDesktop.rdp.fallbackStandardRdp': '已回退并使用标准 RDP 安全层连接。',
'remoteDesktop.rdp.fallbackStandardRdpWithCipher': '已回退并使用标准 RDP 安全层连接({{cipher}})。',
'remoteDesktop.toolbar.viewOnly': '只读模式',
'remoteDesktop.toolbar.viewOnlyBadge': '只读',
'remoteDesktop.toolbar.audio': 'RDP 音频',
@@ -1279,6 +1283,7 @@ export const zhCNVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '录制会话',
'remoteDesktop.toolbar.stopRecording': '停止录制',
'remoteDesktop.toolbar.savingRecording': '保存中...',
'remoteDesktop.toolbar.recording': '录制中',
'remoteDesktop.toolbar.askAi': '问 AI',
'remoteDesktop.toolbar.askAiFull': '截全屏问 AI',
@@ -1384,7 +1389,18 @@ export const zhCNVaultMessages: Messages = {
'logView.remoteDesktop.started': '开始时间',
'logView.remoteDesktop.ended': '结束时间',
'logView.remoteDesktop.duration': '持续时长',
'logView.remoteDesktop.resolution': '分辨率',
'logView.remoteDesktop.security': '安全协议',
'logView.remoteDesktop.disconnectReason': '断开原因',
'logView.remoteDesktop.timeline': '会话时间轴',
'logView.remoteDesktop.recordingTip': '点击远程桌面工具栏的录制按钮,或在「设置 → 系统」中开启自动录制,即可在此回放 .webm 录屏。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '终端',
'logs.filter.remoteDesktop': '远程桌面',
'logs.filter.recorded': '有录屏',
'logs.filter.emptyTitle': '没有匹配的日志',
'logs.filter.emptyDesc': '当前筛选条件下暂无连接日志记录。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '远程桌面录屏',
+9
View File
@@ -834,6 +834,15 @@ export const zhTWAiMessages: Messages = {
'ai.chat.artifact.scriptRunPaused': '指令碼執行已暫停',
'ai.chat.artifact.scriptRunResumed': '指令碼執行已恢復',
'ai.chat.artifact.scriptReference': 'nct API 參考',
'ai.chat.artifact.rdScreenRead': '讀取遠端畫面',
'ai.chat.artifact.rdScreenGrid': '讀取遠端畫面(座標網格)',
'ai.chat.artifact.rdScreenCropped': '局部放大截圖',
'ai.chat.artifact.rdActionExecuted': '已執行 {count} 步遠端操作',
'ai.chat.artifact.rdActionCount': '{count} 個操作',
'ai.chat.artifact.rdActionPreempted': '遠端操作已由使用者接管',
'ai.chat.artifact.rdScreenFailed': '遠端截圖失敗',
'ai.chat.artifact.rdActionFailed': '遠端桌面操作失敗',
'ai.chat.artifact.rdPreviewScreen': '預覽擷取的畫面',
'zmodem.waitingForRemote': '等待遠端...',
'zmodem.uploading': '上傳中',
'zmodem.downloading': '下載中',
+3
View File
@@ -785,7 +785,10 @@ Vaults 分頁維持扁平,不使用這塊背景。
'vault.groups.details': '群組詳情',
'vault.groups.details.general': '常規',
'vault.groups.details.ssh': 'SSH',
'vault.groups.details.rdp': 'RDP',
'vault.groups.details.vnc': 'VNC',
'vault.groups.details.telnet': 'Telnet',
'vault.groups.details.protocolNotEnabledDesc': '目前群組尚未設定 {protocol} 預設協定設定。',
'vault.groups.details.advanced': '高階',
'vault.groups.details.appearance': '外觀',
'vault.groups.details.mosh': 'Mosh',
@@ -191,6 +191,10 @@ export const zhTWTerminalMessages: Messages = {
'settings.sftp.defaultViewMode.listDesc': '以平面列表顯示目前目錄的檔案',
'settings.sftp.defaultViewMode.tree': '樹形檢視',
'settings.sftp.defaultViewMode.treeDesc': '以層級樹形結構顯示檔案',
'settings.sftp.treeFolderDoubleClick': '樹形檢視雙擊資料夾',
'settings.sftp.treeFolderDoubleClick.desc': '選擇在 SFTP 樹形檢視中雙擊資料夾時的操作。點選左側箭頭始終在原地展開或摺疊。',
'settings.sftp.treeFolderDoubleClick.navigate': '進入目錄',
'settings.sftp.treeFolderDoubleClick.expand': '原地展開/摺疊',
'sftp.autoSync.success': '檔案已同步到遠端:{fileName}',
'sftp.autoSync.error': '同步檔案失敗:{error}',
+16
View File
@@ -1113,6 +1113,7 @@ export const zhTWVaultMessages: Messages = {
'hostDetails.rdp.resolutionMode.fixed': '固定尺寸',
'hostDetails.rdp.width': '寬度',
'hostDetails.rdp.height': '高度',
'hostDetails.rdp.dimensionHint': '請輸入 200 到 8192 之間的整數。',
'hostDetails.rdp.colorDepth': '色彩深度',
'hostDetails.rdp.audio': '音訊輸出',
'hostDetails.rdp.audioDesc': '在本機播放遠端桌面音效',
@@ -1217,6 +1218,7 @@ export const zhTWVaultMessages: Messages = {
'remoteDesktop.toolbar.openSftp': 'SFTP',
'remoteDesktop.toolbar.record': '錄製工作階段',
'remoteDesktop.toolbar.stopRecording': '停止錄製',
'remoteDesktop.toolbar.savingRecording': '儲存中...',
'remoteDesktop.toolbar.recording': '錄製中',
'remoteDesktop.toolbar.askAi': '詢問 AI',
'remoteDesktop.toolbar.askAiFull': '擷取全螢幕詢問 AI',
@@ -1254,6 +1256,9 @@ export const zhTWVaultMessages: Messages = {
'remoteDesktop.toolbar.display': '顯示縮放',
'remoteDesktop.toolbar.sshTunneled': '透過 SSH 通道連線',
'remoteDesktop.toolbar.encrypted': 'TLS 加密連線',
'remoteDesktop.toolbar.standardRdpSecurity': '標準 RDP 安全層({{cipher}})',
'remoteDesktop.rdp.fallbackStandardRdp': '已回退並使用標準 RDP 安全層連線。',
'remoteDesktop.rdp.fallbackStandardRdpWithCipher': '已回退並使用標準 RDP 安全層連線({{cipher}})。',
'remoteDesktop.toolbar.viewOnly': '唯讀檢視模式',
'remoteDesktop.toolbar.viewOnlyBadge': '檢視',
'remoteDesktop.toolbar.audio': 'RDP 音訊',
@@ -1384,7 +1389,18 @@ export const zhTWVaultMessages: Messages = {
'logView.remoteDesktop.started': '開始時間',
'logView.remoteDesktop.ended': '結束時間',
'logView.remoteDesktop.duration': '持續時間',
'logView.remoteDesktop.resolution': '解析度',
'logView.remoteDesktop.security': '安全協定',
'logView.remoteDesktop.disconnectReason': '斷線原因',
'logView.remoteDesktop.timeline': '工作階段時間軸',
'logView.remoteDesktop.recordingTip': '點擊遠端桌面工具列的錄製按鈕,或在「設定 → 系統」中開啟自動錄製,即可在此重播 .webm 錄影。',
'logs.recording.clipsCount': '{count} 段',
'logs.filter.all': '全部',
'logs.filter.terminal': '終端機',
'logs.filter.remoteDesktop': '遠端桌面',
'logs.filter.recorded': '含錄影',
'logs.filter.emptyTitle': '沒有符合的日誌',
'logs.filter.emptyDesc': '目前篩選條件下尚無連線日誌記錄。',
// Settings -> System -> Remote Desktop Recordings
'settings.remoteDesktopRecordings.title': '遠端桌面錄影',
+1 -1
View File
@@ -9,7 +9,7 @@ export type ConnectionLogsSnapshot = {
};
export type ConnectionLogsActions = {
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void;
updateConnectionLog: (id: string, updates: Partial<ConnectionLog>) => void | Promise<unknown>;
toggleConnectionLogSaved: (id: string) => void;
deleteConnectionLog: (id: string) => void;
clearUnsavedConnectionLogs: () => void;
+3 -12
View File
@@ -1,21 +1,12 @@
import type { ApprovalRequest } from '../../infrastructure/ai/shared/approvalGate';
import cattyToolSpecs from '../../infrastructure/ai/harness/generated/cattyToolSpecs.json';
import toolNameIndex from '../../infrastructure/ai/harness/generated/toolNameIndex.json';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import {
readExternalMcpApprovalAlertMode,
type ExternalMcpApprovalAlertMode,
} from './useExternalMcpToggleState';
type CatalogToolSpec = {
toolName?: string;
rpcMethod?: string | null;
};
const mcpToolNameByRpcMethod = new Map<string, string>();
for (const spec of cattyToolSpecs as CatalogToolSpec[]) {
if (!spec.rpcMethod || !spec.toolName || mcpToolNameByRpcMethod.has(spec.rpcMethod)) continue;
mcpToolNameByRpcMethod.set(spec.rpcMethod, spec.toolName);
}
const mcpToolNameByRpcMethod = toolNameIndex.sidebarByRpcMethod as Record<string, string>;
/**
* Name shown on the External MCP approval card.
@@ -25,7 +16,7 @@ for (const spec of cattyToolSpecs as CatalogToolSpec[]) {
export function externalMcpApprovalToolLabel(toolName: string | undefined): string {
const raw = toolName?.trim() || '';
if (!raw) return '';
return mcpToolNameByRpcMethod.get(raw) || raw;
return mcpToolNameByRpcMethod[raw] || raw;
}
export type ExternalMcpApprovalNotification = {
@@ -14,11 +14,15 @@ const getSession = (sessionId: string) => (
function createHarness() {
const changes: Change[] = [];
const nested: boolean[] = [];
const controller = createPromptHostnameSessionSignalController({
getSession,
onChange: (sessionId, hostname) => changes.push([sessionId, hostname]),
onChange: (sessionId, hostname, options) => {
changes.push([sessionId, hostname]);
nested.push(options?.fromJumpServer === true);
},
});
return { changes, controller };
return { changes, controller, nested };
}
test('prompt observations are independent of IP, alias, and matching connection addresses', () => {
@@ -52,11 +56,56 @@ test('prompt host controller observes the initial jumpserver prompt', () => {
});
test('prompt host controller publishes a nested target and de-duplicates it', () => {
const { changes, controller } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@jump.example.com ~]# ');
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Welcome\r\nOpt> ');
controller.handleTerminalOutput('ssh-1', 'ssh root@10.1.64.1\r\n[root@10.1.64.1 ~]# ');
controller.handleTerminalOutput('ssh-1', '\r\n[root@10.1.64.1 ~]# ');
assert.deepEqual(changes, [['ssh-1', getSession('ssh-1').hostname], ['ssh-1', '10.1.64.1']]);
assert.deepEqual(changes, [['ssh-1', '10.1.64.1']]);
assert.deepEqual(nested, [true]);
});
test('prompt host controller marks ordinary direct prompts as non-jump hosts', () => {
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Last login\r\n[root@vm-prod ~]# ');
assert.deepEqual(changes, [['ssh-1', 'vm-prod']]);
assert.deepEqual(nested, [false]);
});
test('prompt host controller tracks a JumpServer menu split across chunks', () => {
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Welcome\r\nO');
controller.handleTerminalOutput('ssh-1', 'pt> ');
controller.handleTerminalOutput('ssh-1', '10.1.64.1\r\n[root@k8s-10-1-64-1 ~]# ');
assert.deepEqual(changes, [['ssh-1', 'k8s-10-1-64-1']]);
assert.deepEqual(nested, [true]);
});
test('prompt host controller detects ANSI-styled JumpServer menus and upgrades matching hostnames', () => {
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', '[root@app-01 ~]# ');
controller.handleTerminalOutput('ssh-1', 'ssh jump\r\n\x1b[32mOpt\x1b[0m> \r\n[root@app-01 ~]# ');
assert.deepEqual(changes, [['ssh-1', 'app-01'], ['ssh-1', 'app-01']]);
assert.deepEqual(nested, [false, true]);
});
test('prompt host controller detects consumed JumpServer prompts in coalesced output', () => {
for (const coalesced of [
'Welcome\r\nOpt> 42\r\n[root@target-01 ~]# ',
'Welcome\r\n[Host]> 10.1.64.1\r\n[root@target-01 ~]# ',
'Welcome\r\n\x1b[32mOpt> \x1b[0m42\r\n[root@target-01 ~]# ',
]) {
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', coalesced);
assert.deepEqual(changes, [['ssh-1', 'target-01']], JSON.stringify(coalesced));
assert.deepEqual(nested, [true], JSON.stringify(coalesced));
}
// Also works when the consumed menu prompt is split across chunks.
const { changes, controller, nested } = createHarness();
controller.handleTerminalOutput('ssh-1', 'Welcome\r\nO');
controller.handleTerminalOutput('ssh-1', 'pt> 42\r\n[root@target-02 ~]# ');
assert.deepEqual(changes, [['ssh-1', 'target-02']]);
assert.deepEqual(nested, [true]);
});
test('prompt host controller observes the original host when returning from a target', () => {
@@ -1,12 +1,17 @@
import type { TerminalSession } from '../../domain/models';
import {
extractTerminalPromptHostname,
isJumpServerMenuLine,
isJumpServerMenuPrompt,
} from '../../domain/terminalPromptSecurity';
type PromptHostnameSessionSignalOptions = {
getSession: (sessionId: string) => Pick<TerminalSession, 'protocol'> | undefined;
onChange: (sessionId: string, hostname: string | null) => void;
onChange: (
sessionId: string,
hostname: string | null,
options: { fromJumpServer: boolean },
) => void;
maxTailChars?: number;
};
@@ -23,17 +28,19 @@ export function createPromptHostnameSessionSignalController({
}: PromptHostnameSessionSignalOptions) {
const tails = new Map<string, string>();
const published = new Map<string, string>();
const jumpServerSessions = new Set<string>();
const tailLimit = Math.max(256, maxTailChars);
const forgetSession = (sessionId: string): void => {
tails.delete(sessionId);
published.delete(sessionId);
jumpServerSessions.delete(sessionId);
};
return {
forgetSession,
pruneSessions(validSessionIds: ReadonlySet<string>): void {
for (const sessionId of [...tails.keys(), ...published.keys()]) {
for (const sessionId of [...tails.keys(), ...published.keys(), ...jumpServerSessions]) {
if (!validSessionIds.has(sessionId)) {
forgetSession(sessionId);
}
@@ -50,12 +57,19 @@ export function createPromptHostnameSessionSignalController({
const combined = `${tails.get(sessionId) ?? ''}${chunk}`;
const tail = combined.slice(-tailLimit);
tails.set(sessionId, tail);
if (
!jumpServerSessions.has(sessionId)
&& combined.includes('>')
&& combined.split(/\r\n|\r|\n/u).some((line) => isJumpServerMenuLine(line))
) {
jumpServerSessions.add(sessionId);
}
const detected = extractTerminalPromptHostname(tail);
if (!detected) {
if (isJumpServerMenuPrompt(tail) && published.has(sessionId)) {
published.delete(sessionId);
onChange(sessionId, null);
onChange(sessionId, null, { fromJumpServer: true });
}
return;
}
@@ -63,11 +77,13 @@ export function createPromptHostnameSessionSignalController({
const detectedKey = normalizedHostname(detected);
if (!detectedKey) return;
const fromJumpServer = jumpServerSessions.has(sessionId);
const publishKey = `${detectedKey}\0${fromJumpServer ? '1' : '0'}`;
// Observe the prompt, not whether its hostname matches an IP or DNS alias.
// The domain title policy decides if this presentation is shown.
if (published.get(sessionId) === detectedKey) return;
published.set(sessionId, detectedKey);
onChange(sessionId, detected);
if (published.get(sessionId) === publishKey) return;
published.set(sessionId, publishKey);
onChange(sessionId, detected, { fromJumpServer });
},
};
}
@@ -0,0 +1,215 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import type { ConnectionLog } from '../../domain/models';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import {
publishConnectionLogsSnapshot,
registerConnectionLogsActions,
} from './connectionLogsStore';
import {
clearAllRemoteDesktopRecordingsAndSyncLogs,
collectProtectedRemoteDesktopMediaIds,
} from './remoteDesktopLogActions';
import { withVaultImportLock } from './vaultManagedImportLock';
function installDomEnv() {
const dom = new JSDOM('', { url: 'http://localhost' });
const heldLocks = new Set<string>();
const fakeLocks = {
request: async <T>(name: string, cb: () => Promise<T>): Promise<T> => {
if (heldLocks.has(name)) {
throw new Error(`DEADLOCK: re-entrant lock acquisition on ${name}`);
}
heldLocks.add(name);
try {
return await cb();
} finally {
heldLocks.delete(name);
}
},
};
const keys = ['window', 'document', 'localStorage', 'navigator'] as const;
const previous = new Map<string, PropertyDescriptor | undefined>(
keys.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
);
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
document: { value: dom.window.document, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
navigator: { value: { locks: fakeLocks }, configurable: true },
});
return {
restore: () => {
dom.window.close();
for (const key of keys) {
const desc = previous.get(key);
if (desc) Object.defineProperty(globalThis, key, desc);
else Reflect.deleteProperty(globalThis, key);
}
},
};
}
test('clearAllRemoteDesktopRecordingsAndSyncLogs protects saved logs and clears unsaved metadata even in detached Settings window', async () => {
const env = installDomEnv();
const savedClipId = '11111111-1111-4111-8111-111111111111';
const unsavedClipId = '22222222-2222-4222-8222-222222222222';
const unsavedThumbId = '33333333-3333-4333-8333-333333333333';
const persistedLogs: ConnectionLog[] = [
{
id: 'log-saved',
hostId: 'h1',
hostLabel: 'Saved RDP',
hostname: '10.0.0.1',
username: 'admin',
protocol: 'rdp',
startTime: 1000,
endTime: 2000,
localUsername: 'u',
localHostname: 'l',
saved: true,
recordingId: savedClipId,
recordings: [
{
id: savedClipId,
startedAt: 1000,
endedAt: 2000,
durationMs: 1000,
bytes: 500,
mimeType: 'video/webm',
hasAudio: false,
},
],
},
{
id: 'log-unsaved',
hostId: 'h2',
hostLabel: 'Unsaved RDP',
hostname: '10.0.0.2',
username: 'admin',
protocol: 'rdp',
startTime: 3000,
endTime: 4000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 3000,
endedAt: 4000,
durationMs: 1000,
bytes: 600,
mimeType: 'video/webm',
hasAudio: false,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
thumbnailId: unsavedThumbId,
},
},
];
globalThis.localStorage.setItem(STORAGE_KEY_CONNECTION_LOGS, JSON.stringify(persistedLogs));
// Simulate detached Settings window: connectionLogsStore is unmounted/empty.
publishConnectionLogsSnapshot({ connectionLogs: [] });
registerConnectionLogsActions(null);
const clearAllCalls: Array<{ protectedIds?: string[] }> = [];
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async (opts: { protectedIds?: string[] }) => {
clearAllCalls.push(opts);
return { deleted: 1 };
},
},
};
try {
assert.deepEqual(collectProtectedRemoteDesktopMediaIds(), [savedClipId]);
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(clearAllCalls.length, 1);
assert.deepEqual(clearAllCalls[0].protectedIds, [savedClipId]);
const after = JSON.parse(
globalThis.localStorage.getItem(STORAGE_KEY_CONNECTION_LOGS) || '[]',
) as ConnectionLog[];
assert.equal(after.length, 2);
assert.equal(after[0].recordingId, savedClipId);
assert.equal(after[0].recordings?.length, 1);
assert.equal(after[1].recordingId, undefined);
assert.equal(after[1].recordings, undefined);
assert.equal(after[1].remoteDesktopMeta?.thumbnailId, undefined);
assert.deepEqual(after[1].remoteDesktopMeta?.resolution, { width: 1920, height: 1080 });
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
test('clearAllRemoteDesktopRecordingsAndSyncLogs does not deadlock when updateConnectionLog acquires connection-logs lock', async () => {
const env = installDomEnv();
const unsavedClipId = '44444444-4444-4444-8444-444444444444';
const liveLog: ConnectionLog = {
id: 'log-live-unsaved',
hostId: 'h3',
hostLabel: 'Live RDP',
hostname: '10.0.0.3',
username: 'admin',
protocol: 'rdp',
startTime: 5000,
endTime: 6000,
localUsername: 'u',
localHostname: 'l',
saved: false,
recordingId: unsavedClipId,
recordings: [
{
id: unsavedClipId,
startedAt: 5000,
endedAt: 6000,
durationMs: 1000,
bytes: 700,
mimeType: 'video/webm',
hasAudio: false,
},
],
};
let updatedCount = 0;
publishConnectionLogsSnapshot({ connectionLogs: [liveLog] });
registerConnectionLogsActions({
updateConnectionLog: async () => {
await withVaultImportLock('connection-logs', async () => {
updatedCount += 1;
});
},
toggleConnectionLogSaved: () => {},
deleteConnectionLog: () => {},
clearUnsavedConnectionLogs: () => {},
});
(globalThis.window as unknown as Record<string, unknown>).netcatty = {
remoteDesktopRecordings: {
clearAll: async () => ({ deleted: 1 }),
},
};
try {
const res = await clearAllRemoteDesktopRecordingsAndSyncLogs();
assert.equal(res.deleted, 1);
assert.equal(updatedCount, 1);
} finally {
registerConnectionLogsActions(null);
publishConnectionLogsSnapshot({ connectionLogs: [] });
env.restore();
}
});
@@ -0,0 +1,207 @@
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type {
ConnectionLog,
RemoteDesktopRecordingClip,
RemoteDesktopSessionEvent,
RemoteDesktopSessionMetadata,
} from '../../domain/models';
import {
buildAppendRecordingClipUpdate,
buildClearRecordingsUpdate,
getConnectionLogMediaIds,
} from '../../domain/remoteDesktopRecording';
import { STORAGE_KEY_CONNECTION_LOGS } from '../../infrastructure/config/storageKeys';
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
import {
listRemoteDesktopAuditEntries,
subscribeRemoteDesktopAuditLog,
type RemoteDesktopAuditEntry,
} from '../../infrastructure/remoteDesktop/remoteDesktopAuditLog';
import {
netcattyBridge,
type RemoteDesktopRecordingsBridgeApi,
} from '../../infrastructure/services/netcattyBridge';
import {
getConnectionLogsActions,
getConnectionLogsSnapshot,
} from './connectionLogsStore';
import { withVaultImportLock } from './vaultManagedImportLock';
export type { RemoteDesktopAuditEntry };
export function getRemoteDesktopRecordingsBridge(): RemoteDesktopRecordingsBridgeApi | null {
return netcattyBridge.get()?.remoteDesktopRecordings ?? null;
}
export function registerSessionLogFinalizer(
finalize: () => void | Promise<void>,
): (() => void) | undefined {
const unsub = netcattyBridge.get()?.onFinalizeSessionLogs?.(finalize);
return typeof unsub === 'function' ? unsub : undefined;
}
export async function getSystemUserHostInfo(): Promise<{ username: string; hostname: string }> {
try {
const info = await netcattyBridge.get()?.getSystemInfo?.();
return {
username: info?.username || 'user',
hostname: info?.hostname || 'localhost',
};
} catch {
return { username: 'user', hostname: 'localhost' };
}
}
export function listRemoteDesktopSessionAuditEntries(
sessionId?: string,
): RemoteDesktopAuditEntry[] {
return listRemoteDesktopAuditEntries(sessionId);
}
export function subscribeRemoteDesktopSessionAuditLog(listener: () => void): () => void {
return subscribeRemoteDesktopAuditLog(listener);
}
function readPersistedConnectionLogs(): ConnectionLog[] {
try {
const stored = localStorageAdapter.read<ConnectionLog[]>(STORAGE_KEY_CONNECTION_LOGS);
return Array.isArray(stored) ? stored : [];
} catch {
return [];
}
}
/**
* Collect all protected media IDs (video clips + thumbnails) across bookmarked
* connection logs from BOTH the in-memory store and persisted localStorage.
* Works identically in the main window and detached Settings window.
*/
export function collectProtectedRemoteDesktopMediaIds(): string[] {
const protectedSet = new Set<string>();
const { connectionLogs } = getConnectionLogsSnapshot();
for (const log of connectionLogs) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
for (const log of readPersistedConnectionLogs()) {
if (log.saved) {
for (const mediaId of getConnectionLogMediaIds(log)) {
protectedSet.add(mediaId);
}
}
}
return Array.from(protectedSet);
}
export async function appendRemoteDesktopClipToConnectionLog(
sessionId: string,
clip: RemoteDesktopRecordingClip,
options?: { stampEndTime?: boolean },
): Promise<boolean> {
const { connectionLogs } = getConnectionLogsSnapshot();
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const updates = buildAppendRecordingClipUpdate(matchingLog, clip, {
stampEndTime: options?.stampEndTime ? Date.now() : undefined,
});
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, updates));
return true;
}
export async function updateRemoteDesktopConnectionLogActivity(
sessionId: string,
updater: (current: {
events: RemoteDesktopSessionEvent[];
meta: RemoteDesktopSessionMetadata | undefined;
}) => {
events?: RemoteDesktopSessionEvent[];
meta?: RemoteDesktopSessionMetadata;
},
): Promise<boolean> {
const actions = getConnectionLogsActions();
if (!actions?.updateConnectionLog) return false;
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture(
[...connectionLogs],
{ sessionId },
);
if (!matchingLog) return false;
const next = updater({
events: Array.isArray(matchingLog.remoteDesktopEvents) ? matchingLog.remoteDesktopEvents : [],
meta: matchingLog.remoteDesktopMeta,
});
const patch: Partial<ConnectionLog> = {};
if (next.events) patch.remoteDesktopEvents = next.events;
if (next.meta) patch.remoteDesktopMeta = next.meta;
if (Object.keys(patch).length === 0) return false;
await Promise.resolve(actions.updateConnectionLog(matchingLog.id, patch));
return true;
}
export async function saveRemoteDesktopThumbnail(options: {
id?: string;
data: Uint8Array;
}): Promise<{ ok: boolean; id?: string; url?: string; bytes?: number } | null> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.saveThumbnail) return null;
return bridge.saveThumbnail(options);
}
/**
* Clear all unprotected remote desktop recordings on disk and atomically clear
* their references from connection logs. Safe to invoke from detached windows
* (such as Settings -> System) where `useVaultState` is not mounted.
*/
export async function clearAllRemoteDesktopRecordingsAndSyncLogs(): Promise<{ deleted: number }> {
const bridge = getRemoteDesktopRecordingsBridge();
if (!bridge?.clearAll) return { deleted: 0 };
const protectedIds = collectProtectedRemoteDesktopMediaIds();
const protectedSet = new Set(protectedIds);
const res = await bridge.clearAll({ protectedIds });
const actions = getConnectionLogsActions();
if (actions?.updateConnectionLog) {
// Call `actions.updateConnectionLog` OUTSIDE `withVaultImportLock('connection-logs')`
// because `useVaultState.commitConnectionLogs` acquires that same non-reentrant Web Lock.
const { connectionLogs } = getConnectionLogsSnapshot();
const persistedById = new Map(readPersistedConnectionLogs().map((log) => [log.id, log]));
const targets = new Map<string, ConnectionLog>();
for (const log of connectionLogs) targets.set(log.id, log);
for (const [id, log] of persistedById) {
if (!targets.has(id)) targets.set(id, log);
}
for (const log of targets.values()) {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (updates) {
await Promise.resolve(actions.updateConnectionLog(log.id, updates));
}
}
} else {
// Detached window (e.g. Settings -> System without Sync tab mounted): update
// localStorage atomically under the shared cross-window Web Lock.
await withVaultImportLock('connection-logs', async () => {
const persisted = readPersistedConnectionLogs();
let changed = false;
const nextPersisted = persisted.map((log) => {
const updates = buildClearRecordingsUpdate(log, protectedSet);
if (!updates) return log;
changed = true;
return { ...log, ...updates };
});
if (changed) {
localStorageAdapter.write(STORAGE_KEY_CONNECTION_LOGS, nextPersisted);
}
});
}
return { deleted: res?.deleted ?? 0 };
}
@@ -131,13 +131,14 @@ test('session snapshot distinguishes missing fields from null tombstones', () =>
test('prompt hostnames overlay as presentation without replacing configured hostname', () => {
sessionPresentationStore.clearSession('prompt-host');
publishSessionPromptHost('prompt-host', '10.1.64.1');
publishSessionPromptHost('prompt-host', '10.1.64.1', { fromJumpServer: true });
const merged = applySessionPresentation(session({
id: 'prompt-host',
hostLabel: 'jumpserver',
hostname: 'jumpserver.example.com',
}));
assert.equal(merged.promptHostname, '10.1.64.1');
assert.equal(merged.promptHostnameFromJumpServer, true);
assert.equal(merged.hostname, 'jumpserver.example.com');
sessionPresentationStore.clearSession('prompt-host');
});
+19 -4
View File
@@ -5,13 +5,14 @@ import type { CodingCliProviderId } from '../../domain/codingCliProviders';
export type SessionPresentation = {
dynamicTitle?: string | null;
promptHostname?: string | null;
promptHostnameFromJumpServer?: boolean | null;
codingCliProviderId?: CodingCliProviderId | null;
};
type Listener = () => void;
/** Encode undefined / null / present distinctly for useSyncExternalStore snapshots. */
function encodePresentationField(value: string | null | undefined): string {
function encodePresentationField(value: string | boolean | null | undefined): string {
if (value === undefined) return 'u';
if (value === null) return 'n';
return `v:${value}`;
@@ -42,7 +43,7 @@ class SessionPresentationStore {
getSessionSnapshot = (sessionId: string): string => {
const presentation = this.bySession.get(sessionId);
if (!presentation) return '';
return `${encodePresentationField(presentation.dynamicTitle)}\0${encodePresentationField(presentation.promptHostname)}\0${encodePresentationField(presentation.codingCliProviderId)}`;
return `${encodePresentationField(presentation.dynamicTitle)}\0${encodePresentationField(presentation.promptHostname)}\0${encodePresentationField(presentation.promptHostnameFromJumpServer)}\0${encodePresentationField(presentation.codingCliProviderId)}`;
};
subscribe = (listener: Listener): (() => void) => {
@@ -61,6 +62,7 @@ class SessionPresentationStore {
if (
prev.dynamicTitle === next.dynamicTitle
&& prev.promptHostname === next.promptHostname
&& prev.promptHostnameFromJumpServer === next.promptHostnameFromJumpServer
&& prev.codingCliProviderId === next.codingCliProviderId
) {
return;
@@ -104,14 +106,22 @@ export function publishSessionCodingCliProvider(
sessionPresentationStore.setPresentation(sessionId, { codingCliProviderId: providerId });
}
export function publishSessionPromptHost(sessionId: string, hostname: string | null): void {
sessionPresentationStore.setPresentation(sessionId, { promptHostname: hostname });
export function publishSessionPromptHost(
sessionId: string,
hostname: string | null,
options: { fromJumpServer?: boolean } = {},
): void {
sessionPresentationStore.setPresentation(sessionId, {
promptHostname: hostname,
promptHostnameFromJumpServer: hostname && options.fromJumpServer === true ? true : null,
});
}
type SessionWithPresentation = {
id: string;
dynamicTitle?: string;
promptHostname?: string;
promptHostnameFromJumpServer?: boolean;
codingCliProviderId?: CodingCliProviderId;
};
@@ -129,12 +139,16 @@ export function applySessionPresentation<T extends SessionWithPresentation>(sess
const nextPromptHost = presentation.promptHostname === undefined
? session.promptHostname
: (presentation.promptHostname ?? undefined);
const nextPromptHostFromJumpServer = presentation.promptHostnameFromJumpServer === undefined
? session.promptHostnameFromJumpServer
: (presentation.promptHostnameFromJumpServer ?? undefined);
const nextProvider = presentation.codingCliProviderId === undefined
? session.codingCliProviderId
: (presentation.codingCliProviderId ?? undefined);
if (
nextTitle === session.dynamicTitle
&& nextPromptHost === session.promptHostname
&& nextPromptHostFromJumpServer === session.promptHostnameFromJumpServer
&& nextProvider === session.codingCliProviderId
) {
return session;
@@ -143,6 +157,7 @@ export function applySessionPresentation<T extends SessionWithPresentation>(sess
...session,
dynamicTitle: nextTitle,
promptHostname: nextPromptHost,
promptHostnameFromJumpServer: nextPromptHostFromJumpServer,
codingCliProviderId: nextProvider,
};
}
+13 -7
View File
@@ -31,8 +31,10 @@ import type {
} from '../../infrastructure/ai/types';
import {
DEFAULT_COMMAND_TIMEOUT_SECONDS,
DEFAULT_MAX_ITERATIONS,
DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS,
normalizeCommandTimeoutSeconds,
normalizeMaxIterations,
normalizeResponseIdleTimeoutSeconds,
} from '../../infrastructure/ai/types';
import { removeProviderReferences } from './aiProviderCleanup';
@@ -132,7 +134,9 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
)
);
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
normalizeMaxIterations(
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? DEFAULT_MAX_ITERATIONS,
)
);
const [toolOutputMaxChars, setToolOutputMaxCharsRaw] = useState<number>(() =>
normalizeAiToolOutputMaxChars(
@@ -253,9 +257,10 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
}, []);
const setMaxIterations = useCallback((value: number) => {
setMaxIterationsRaw(value);
localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, value);
getAIBridge()?.aiMcpSetMaxIterations?.(value);
const normalizedValue = normalizeMaxIterations(value);
setMaxIterationsRaw(normalizedValue);
localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, normalizedValue);
getAIBridge()?.aiMcpSetMaxIterations?.(normalizedValue);
}, []);
const setToolOutputMaxChars = useCallback((value: number) => {
@@ -350,10 +355,11 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
break;
}
case STORAGE_KEY_AI_MAX_ITERATIONS: {
const iters = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20;
const iters = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? DEFAULT_MAX_ITERATIONS;
if (!Number.isFinite(iters)) break;
setMaxIterationsRaw(iters);
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
const normalizedIters = normalizeMaxIterations(iters);
setMaxIterationsRaw(normalizedIters);
getAIBridge()?.aiMcpSetMaxIterations?.(normalizedIters);
break;
}
case STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS: {
@@ -0,0 +1,17 @@
import { useSyncExternalStore } from 'react';
import {
getPinyinMatcherVersion,
subscribePinyinMatcherReady,
} from '../../domain/searchMatcher';
/**
* Subscribes a React component to lazy `pinyin-pro` dictionary load completion
* so active CJK search memos re-evaluate immediately once ready.
*/
export function usePinyinMatcherVersion(): number {
return useSyncExternalStore(
subscribePinyinMatcherReady,
getPinyinMatcherVersion,
getPinyinMatcherVersion,
);
}
+18 -3
View File
@@ -4,6 +4,7 @@ import {
createSessionHistorySearch,
type SessionHistorySearchScan,
} from './sessionHistorySearch';
import { usePinyinMatcherVersion } from './usePinyinMatcherVersion';
/** Search outside rendering, yielding between bounded slices for input/paint. */
export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
@@ -12,10 +13,12 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
untitledLabel: string,
): { filteredSessions: readonly T[]; isSearching: boolean } {
const search = useMemo(() => createSessionHistorySearch(), []);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const latest = useRef({ sessions, query, untitledLabel });
const work = useRef<{
query: string;
untitledLabel: string;
pinyinMatcherVersion: number;
scan: SessionHistorySearchScan<T>;
} | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -44,9 +47,21 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
search.filterSessionHistory(sessions, '');
return;
}
if (work.current?.query !== query || work.current.untitledLabel !== untitledLabel) {
if (
work.current?.query !== query
|| work.current.untitledLabel !== untitledLabel
|| work.current.pinyinMatcherVersion !== pinyinMatcherVersion
) {
if (work.current && work.current.pinyinMatcherVersion !== pinyinMatcherVersion) {
search.clearSessionHistorySearchCache();
}
cancel();
work.current = { query, untitledLabel, scan: search.createScan<T>(query, { untitledLabel }) };
work.current = {
query,
untitledLabel,
pinyinMatcherVersion,
scan: search.createScan<T>(query, { untitledLabel }),
};
}
if (timer.current !== null) return;
const job = work.current;
@@ -65,7 +80,7 @@ export function useSessionHistorySearch<T extends SessionHistorySearchTarget>(
// Session updates reuse the in-flight query's match decisions, so one
// streaming session cannot restart and starve a large history search.
timer.current = setTimeout(run, 0);
}, [sessions, query, untitledLabel, search]);
}, [sessions, query, untitledLabel, search, pinyinMatcherVersion]);
useEffect(() => () => {
if (timer.current !== null) clearTimeout(timer.current);
+6 -2
View File
@@ -605,8 +605,12 @@ export const useSessionState = ({
publishSessionDynamicTitle(sessionId, nextTitle);
}, []);
const updateSessionPromptHost = useCallback((sessionId: string, hostname: string | null) => {
publishSessionPromptHost(sessionId, hostname?.trim() || null);
const updateSessionPromptHost = useCallback((
sessionId: string,
hostname: string | null,
options?: { fromJumpServer?: boolean },
) => {
publishSessionPromptHost(sessionId, hostname?.trim() || null, options);
}, []);
const updateSessionCodingCliProvider = useCallback((
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
import { isDiscoveredGitBash } from '../../lib/localShell.cjs';
import { isDiscoveredGitBash } from '../../lib/localShell';
export function useTerminalDirectorySession(options: {
sessionId: string;
+164 -142
View File
@@ -2,12 +2,8 @@ import { useEffect, useRef } from 'react';
import { applyGroupDefaults, resolveGroupDefaults } from '../../domain/groupConfig';
import type { GroupConfig, Host, Identity, KnownHost, ManagedSource, PortForwardingRule, ProxyProfile, Snippet, SSHKey, TerminalSession, TerminalSettings, VaultNote } from '../../domain/models';
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
import {
handleVaultAgentOp,
registerVaultAgentHandler,
setupVaultAgentBridge,
type VaultAgentApiDeps,
} from '../../infrastructure/ai/vaultAgentBridgeClient';
import type { VaultAgentApiDeps } from '../../infrastructure/ai/vaultAgentBridgeClient';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
import {
clearRememberedKeyPassphrases,
readRememberedKeyPassphrases,
@@ -155,143 +151,169 @@ export function useVaultAgentBridge(input: UseVaultAgentBridgeInput): void {
}, [input.notes]);
useEffect(() => {
registerVaultAgentHandler(async (op, params) => {
const current = inputRef.current;
const applyUpdateNotes = current.updateNotes
?? getNotesActions()?.updateNotes
?? ((notes: VaultNote[]) => {
console.warn('[useVaultAgentBridge] updateNotes unavailable');
void notes;
return false;
});
return handleVaultAgentOp(op, params, {
getHosts: () => vaultSnapshotRef.current.hosts,
getNotes: () => resolveVaultAgentNotes(
current.notes,
vaultSnapshotRef.current.notes,
),
getCustomGroups: () => vaultSnapshotRef.current.customGroups,
getGroupConfigs: () => vaultSnapshotRef.current.groupConfigs,
getPortForwardingRules: () => vaultSnapshotRef.current.portForwardingRules,
getManagedSources: () => vaultSnapshotRef.current.managedSources,
snippets: vaultSnapshotRef.current.snippets,
keys: vaultSnapshotRef.current.keys,
identities: current.identities,
knownHosts: current.knownHosts,
proxyProfiles: current.proxyProfiles,
terminalSettings: current.terminalSettings,
resolveEffectiveHost: (host) => resolveVaultAgentEffectiveHost(
host,
vaultSnapshotRef.current.groupConfigs,
current.proxyProfiles,
),
updateHostNotes: (hostId, notes) => {
const nextHosts = vaultSnapshotRef.current.hosts.map((host) => (
host.id === hostId ? { ...host, notes } : host
));
vaultSnapshotRef.current.hosts = nextHosts;
current.updateHosts(nextHosts);
},
updateCustomGroups: (groups) => {
vaultSnapshotRef.current.customGroups = groups;
current.updateCustomGroups(groups);
},
updateGroupConfigs: (configs) => {
vaultSnapshotRef.current.groupConfigs = configs;
current.updateGroupConfigs(configs);
},
updatePortForwardingRules: (rules) => {
vaultSnapshotRef.current.portForwardingRules = rules;
current.updatePortForwardingRules(rules);
},
updateManagedSources: (sources) => {
vaultSnapshotRef.current.managedSources = sources;
current.updateManagedSources(sources);
},
updateHosts: (hosts) => {
vaultSnapshotRef.current.hosts = hosts;
current.updateHosts(hosts);
},
commitVaultGroupMutation: async (mutate) => {
const result = await current.commitVaultGroupMutation(mutate);
if (result.ok) {
vaultSnapshotRef.current.customGroups = result.state.groups;
vaultSnapshotRef.current.groupConfigs = result.state.configs;
vaultSnapshotRef.current.hosts = result.state.hosts;
vaultSnapshotRef.current.managedSources = result.state.managedSources;
vaultSnapshotRef.current.snippets = result.state.snippets;
const bridge = netcattyBridge.get();
if (!bridge?.onVaultAgentRequest || !bridge.respondVaultAgent) {
return;
}
let disposed = false;
let clientPromise: Promise<typeof import('../../infrastructure/ai/vaultAgentBridgeClient')> | null = null;
const ensureClient = () => {
if (!clientPromise) {
clientPromise = import('../../infrastructure/ai/vaultAgentBridgeClient').then((client) => {
if (!disposed) {
client.registerVaultAgentHandler(async (op, params) => {
const current = inputRef.current;
const applyUpdateNotes = current.updateNotes
?? getNotesActions()?.updateNotes
?? ((notes: VaultNote[]) => {
console.warn('[useVaultAgentBridge] updateNotes unavailable');
void notes;
return false;
});
return client.handleVaultAgentOp(op, params, {
getHosts: () => vaultSnapshotRef.current.hosts,
getNotes: () => resolveVaultAgentNotes(
current.notes,
vaultSnapshotRef.current.notes,
),
getCustomGroups: () => vaultSnapshotRef.current.customGroups,
getGroupConfigs: () => vaultSnapshotRef.current.groupConfigs,
getPortForwardingRules: () => vaultSnapshotRef.current.portForwardingRules,
getManagedSources: () => vaultSnapshotRef.current.managedSources,
snippets: vaultSnapshotRef.current.snippets,
keys: vaultSnapshotRef.current.keys,
identities: current.identities,
knownHosts: current.knownHosts,
proxyProfiles: current.proxyProfiles,
terminalSettings: current.terminalSettings,
resolveEffectiveHost: (host) => resolveVaultAgentEffectiveHost(
host,
vaultSnapshotRef.current.groupConfigs,
current.proxyProfiles,
),
updateHostNotes: (hostId, notes) => {
const nextHosts = vaultSnapshotRef.current.hosts.map((host) => (
host.id === hostId ? { ...host, notes } : host
));
vaultSnapshotRef.current.hosts = nextHosts;
current.updateHosts(nextHosts);
},
updateCustomGroups: (groups) => {
vaultSnapshotRef.current.customGroups = groups;
current.updateCustomGroups(groups);
},
updateGroupConfigs: (configs) => {
vaultSnapshotRef.current.groupConfigs = configs;
current.updateGroupConfigs(configs);
},
updatePortForwardingRules: (rules) => {
vaultSnapshotRef.current.portForwardingRules = rules;
current.updatePortForwardingRules(rules);
},
updateManagedSources: (sources) => {
vaultSnapshotRef.current.managedSources = sources;
current.updateManagedSources(sources);
},
updateHosts: (hosts) => {
vaultSnapshotRef.current.hosts = hosts;
current.updateHosts(hosts);
},
commitVaultGroupMutation: async (mutate) => {
const result = await current.commitVaultGroupMutation(mutate);
if (result.ok) {
vaultSnapshotRef.current.customGroups = result.state.groups;
vaultSnapshotRef.current.groupConfigs = result.state.configs;
vaultSnapshotRef.current.hosts = result.state.hosts;
vaultSnapshotRef.current.managedSources = result.state.managedSources;
vaultSnapshotRef.current.snippets = result.state.snippets;
}
return result;
},
saveKeyPassphrase: (keyPath, passphrase) => rememberKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
saveImportedKeyPassphrase: (keyPath, passphrase) => rememberImportedKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
resolveKeyPassphraseAliases: resolveDefaultKeyPassphraseAliases,
readKeyPassphrases: (keyPath) => readRememberedKeyPassphrases(
keyPath,
vaultSnapshotRef.current.keys,
),
removeKeyPassphrases: (keyPaths) => clearRememberedKeyPassphrases({
keyPaths,
getKeys: () => vaultSnapshotRef.current.keys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
? snippetUpdate(vaultSnapshotRef.current.snippets)
: snippetUpdate;
current.updateSnippets(snippetUpdate);
},
startTunnel: current.startTunnel,
stopTunnel: current.stopTunnel,
stopRuleTunnels: current.stopRuleTunnels,
openHost: current.openHost
? (host, isExternalMcpCall, options) => current.openHost!(host, isExternalMcpCall, options)
: undefined,
findExistingSessionForHost: current.findExistingSessionForHost,
reconnectSession: current.reconnectSession,
inspectSessionRecovery: current.inspectSessionRecovery,
closeSession: current.closeSession
? (sessionId) => current.closeSession!(sessionId)
: undefined,
getScriptSessionMeta: (sessionId) => {
const session = current.getScriptSessionMeta?.(sessionId);
if (!session) return undefined;
return {
connected: session.status === 'connected',
name: session.customName || session.hostLabel,
hostname: session.hostname,
username: session.username,
};
},
});
});
}
return result;
},
saveKeyPassphrase: (keyPath, passphrase) => rememberKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
saveImportedKeyPassphrase: (keyPath, passphrase) => rememberImportedKeyPassphrase({
keyPath,
passphrase,
keys: vaultSnapshotRef.current.keys,
getKeys: () => vaultSnapshotRef.current.keys,
updateKeys: current.updateKeys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
}),
resolveKeyPassphraseAliases: resolveDefaultKeyPassphraseAliases,
readKeyPassphrases: (keyPath) => readRememberedKeyPassphrases(
keyPath,
vaultSnapshotRef.current.keys,
),
removeKeyPassphrases: (keyPaths) => clearRememberedKeyPassphrases({
keyPaths,
getKeys: () => vaultSnapshotRef.current.keys,
setCurrentKeys: (keys) => {
vaultSnapshotRef.current.keys = keys;
},
updateKeys: current.updateKeys,
}),
updateNotes: (notes) => {
const previousNotes = vaultSnapshotRef.current.notes;
const saved = applyAgentNotesUpdate(notes, previousNotes, applyUpdateNotes);
vaultSnapshotRef.current.notes = saved === false ? previousNotes : notes;
return saved;
},
updateSnippets: (snippetUpdate) => {
vaultSnapshotRef.current.snippets = typeof snippetUpdate === 'function'
? snippetUpdate(vaultSnapshotRef.current.snippets)
: snippetUpdate;
current.updateSnippets(snippetUpdate);
},
startTunnel: current.startTunnel,
stopTunnel: current.stopTunnel,
stopRuleTunnels: current.stopRuleTunnels,
openHost: current.openHost
? (host, isExternalMcpCall, options) => current.openHost!(host, isExternalMcpCall, options)
: undefined,
findExistingSessionForHost: current.findExistingSessionForHost,
reconnectSession: current.reconnectSession,
inspectSessionRecovery: current.inspectSessionRecovery,
closeSession: current.closeSession
? (sessionId) => current.closeSession!(sessionId)
: undefined,
getScriptSessionMeta: (sessionId) => {
const session = current.getScriptSessionMeta?.(sessionId);
if (!session) return undefined;
return {
connected: session.status === 'connected',
name: session.customName || session.hostLabel,
hostname: session.hostname,
username: session.username,
};
},
});
return client;
});
}
return clientPromise;
};
const unsubscribe = bridge.onVaultAgentRequest((payload) => {
void ensureClient().then((client) => client.dispatchVaultAgentBridgeRequest(payload));
});
return setupVaultAgentBridge();
return () => {
disposed = true;
unsubscribe();
if (clientPromise) {
void clientPromise.then((client) => client.registerVaultAgentHandler(null));
}
};
}, []);
}
+11 -11
View File
@@ -25,17 +25,7 @@ import {
/** Exit the import lock so a concurrent host save can finish, then retry. */
const RETRY_VAULT_IMPORT_AFTER_CONCURRENT_EDIT = Symbol("retry-vault-import-after-concurrent-edit");
import { sanitizeHost } from "../../domain/host";
import {
applyVaultImportDestination,
applyVaultHostImport,
buildVaultHostEndpointKey,
buildVaultHostMergeKey,
filterVaultImportKeyPassphrasesAgainstExisting,
mergeVaultImportIssues,
resolveVaultImportKeyPassphraseConflicts,
toVaultImportExistingHostRef,
type VaultImportFormat,
} from "../../domain/vaultImport";
import type { VaultImportFormat } from "../../domain/vaultImport";
import type { GroupConfig, Host, ManagedSource, SSHKey } from "../../types";
import type { VaultImportNotifier, VaultImportOptions } from "./vaultImportOptions";
@@ -173,6 +163,16 @@ export function useVaultImportHandlers({
});
try {
const {
applyVaultImportDestination,
applyVaultHostImport,
buildVaultHostEndpointKey,
buildVaultHostMergeKey,
filterVaultImportKeyPassphrasesAgainstExisting,
mergeVaultImportIssues,
resolveVaultImportKeyPassphraseConflicts,
toVaultImportExistingHostRef,
} = await import("../../domain/vaultImport");
let result = await importVaultHostsInWorker({
format,
files,
+24 -15
View File
@@ -12,6 +12,7 @@ import { retainLocalHostLastConnectedAt } from "../../domain/sync";
import { sanitizeGroupConfig } from "../../domain/groupConfig";
import { normalizeKnownHosts } from "../../domain/knownHosts";
import { normalizeNoteGroups, normalizeVaultNotes } from "../../domain/notes";
import { getConnectionLogMediaIds } from "../../domain/remoteDesktopRecording";
import {
applyPluginImporterDestination,
mergePluginImporterDrafts,
@@ -634,16 +635,18 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
}
const remainingRecordingIds = new Set<string>();
for (const log of next) {
if (log.recordingId) remainingRecordingIds.add(log.recordingId);
for (const mediaId of getConnectionLogMediaIds(log)) {
remainingRecordingIds.add(mediaId);
}
}
const removedRecordingIds: string[] = [];
for (const log of prev) {
if (
!nextIds.has(log.id)
&& log.recordingId
&& !remainingRecordingIds.has(log.recordingId)
) {
removedRecordingIds.push(log.recordingId);
if (!nextIds.has(log.id)) {
for (const mediaId of getConnectionLogMediaIds(log)) {
if (!remainingRecordingIds.has(mediaId)) {
removedRecordingIds.push(mediaId);
}
}
}
}
if (removedRecordingIds.length > 0) {
@@ -1586,19 +1589,25 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
// One-time startup GC to sweep orphaned / expired / over-quota remote desktop recordings
// while preserving all bookmarked/saved connection log recordings.
// CRITICAL: Must wait for `isInitialized` so `connectionLogsRef.current` has been hydrated
// from storage; running before boot hydration would pass `referencedIds: []` and wipe files!
const hasRunRecordingStartupGcRef = useRef(false);
useEffect(() => {
if (!syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
if (!isInitialized || !syncConnectionLogTerminalData || hasRunRecordingStartupGcRef.current) return;
hasRunRecordingStartupGcRef.current = true;
const bridge = netcattyBridge.get();
if (!bridge?.remoteDesktopRecordings?.runGc) return;
const logs = connectionLogsRef.current;
const referencedIds = logs
.map((log) => log.recordingId)
.filter((id): id is string => typeof id === "string" && id.length > 0);
const protectedIds = logs
.filter((log) => log.saved && typeof log.recordingId === "string" && log.recordingId.length > 0)
.map((log) => log.recordingId as string);
const referencedSet = new Set<string>();
const protectedSet = new Set<string>();
for (const log of logs) {
for (const mediaId of getConnectionLogMediaIds(log)) {
referencedSet.add(mediaId);
if (log.saved) protectedSet.add(mediaId);
}
}
const referencedIds = Array.from(referencedSet);
const protectedIds = Array.from(protectedSet);
const storedMaxMb = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_MAX_MB);
const maxMb = storedMaxMb != null && storedMaxMb >= 64 ? storedMaxMb : 1024;
const storedRetention = localStorageAdapter.readNumber(STORAGE_KEY_REMOTE_DESKTOP_RECORDING_RETENTION_DAYS);
@@ -1611,7 +1620,7 @@ export const useVaultState = (options?: UseVaultStateOptions) => {
protectedIds,
})
.catch(() => {});
}, [syncConnectionLogTerminalData]);
}, [isInitialized, syncConnectionLogTerminalData]);
useLayoutEffect(() => {
registerConnectionLogsActions({
+32
View File
@@ -2291,6 +2291,38 @@ test("legacy and invalid packed download settings preserve the local preference"
}
});
test("tree folder double-click preference round-trips in sync payloads and preserves local value on missing or invalid input", async () => {
const key = storageKeys.STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR;
assert.ok((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key));
for (const behavior of ["navigate", "expand"] as const) {
localStorage.clear();
localStorage.setItem(key, behavior);
const payload = buildSyncPayload(vault());
assert.equal(payload.settings?.sftpTreeDoubleClickBehavior, behavior);
localStorage.clear();
await applySyncPayload(payload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), behavior);
}
localStorage.clear();
const emptyPayload = buildSyncPayload(vault());
assert.equal(emptyPayload.settings?.sftpTreeDoubleClickBehavior, undefined);
localStorage.setItem(key, "expand");
await applySyncPayload(emptyPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
for (const invalid of ["open", "transfer", 1, null]) {
await applySyncPayload({
...emptyPayload,
settings: { sftpTreeDoubleClickBehavior: invalid },
} as unknown as SyncPayload, { importVaultData: () => {} });
assert.equal(localStorage.getItem(key), "expand");
}
});
test("old bottom tab preference is ignored by settings export and import", async () => {
localStorage.clear();
const legacyKey = "netcatty_tab_bar_position_v1";
+11
View File
@@ -109,6 +109,7 @@ import {
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_CUSTOM_THEMES,
STORAGE_KEY_SHOW_RECENT_HOSTS,
@@ -149,6 +150,7 @@ import {
import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge';
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
import { normalizeAiToolOutputMaxChars } from '../domain/aiToolOutputLimit';
import { isSftpTreeFolderDoubleClickBehavior } from '../domain/sftpTreeFolderDoubleClick';
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
// ---------------------------------------------------------------------------
@@ -345,6 +347,7 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [
STORAGE_KEY_SFTP_AUTO_OPEN_SIDEBAR,
STORAGE_KEY_SFTP_FOLLOW_TERMINAL_CWD,
STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE,
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS,
STORAGE_KEY_SHOW_RECENT_HOSTS,
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
@@ -576,6 +579,8 @@ export function collectSyncableSettings(): SyncPayload['settings'] {
if (followTerminalCwd === 'true' || followTerminalCwd === 'false') settings.sftpFollowTerminalCwd = followTerminalCwd === 'true';
const defaultViewMode = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE);
if (defaultViewMode === 'list' || defaultViewMode === 'tree') settings.sftpDefaultViewMode = defaultViewMode;
const treeDblClick = localStorageAdapter.readString(STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR);
if (isSftpTreeFolderDoubleClickBehavior(treeDblClick)) settings.sftpTreeDoubleClickBehavior = treeDblClick;
// SFTP Bookmarks (global only - local bookmarks are device-specific)
const globalBookmarks = localStorageAdapter.read<SftpBookmark[]>(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS);
@@ -895,6 +900,12 @@ async function applySyncableSettings(
if (settings.sftpDefaultViewMode != null) {
localStorageAdapter.writeString(STORAGE_KEY_SFTP_DEFAULT_VIEW_MODE, settings.sftpDefaultViewMode);
}
if (isSftpTreeFolderDoubleClickBehavior(settings.sftpTreeDoubleClickBehavior)) {
localStorageAdapter.writeString(
STORAGE_KEY_SFTP_TREE_DOUBLE_CLICK_BEHAVIOR,
settings.sftpTreeDoubleClickBehavior,
);
}
// SFTP Bookmarks (global only)
if (settings.sftpGlobalBookmarks != null) localStorageAdapter.write(STORAGE_KEY_SFTP_GLOBAL_BOOKMARKS, settings.sftpGlobalBookmarks);
+2 -1
View File
@@ -16,6 +16,7 @@ import type {
import type { VaultNote } from '../domain/models';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import {
DEFAULT_MAX_ITERATIONS,
filterAgentModelPresetsForCliVersion,
getAgentModelPresets,
resolveAgentCliVersion,
@@ -321,7 +322,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
commandBlocklist,
commandTimeout,
responseIdleTimeout,
maxIterations = 20,
maxIterations = DEFAULT_MAX_ITERATIONS,
toolOutputMaxChars,
webSearchConfig,
quickMessages = [],
+60
View File
@@ -81,4 +81,64 @@ test("ConnectionLogsManager renders RDP/VNC icons and compact recording pill whe
assert.match(markup, /vnc, 10\.0\.0\.20/);
assert.match(markup, /bg-blue-500\/15 text-blue-600/);
assert.match(markup, /bg-teal-500\/15 text-teal-600/);
assert.match(markup, /data-testid="logs-filter-bar"/);
assert.match(markup, /data-logs-filter="remoteDesktop"/);
assert.match(markup, /data-logs-filter="recorded"/);
});
test("ConnectionLogsManager renders multi-clip count and remote desktop resolution metadata", () => {
const logs: ConnectionLog[] = [
{
id: "log-multi-rec",
hostId: "h-1",
hostLabel: "Windows Multi",
hostname: "10.0.0.10",
username: "Administrator",
protocol: "rdp",
startTime: 1_700_000_000_000,
endTime: 1_700_000_200_000,
localUsername: "alice",
localHostname: "macbook",
saved: false,
recordings: [
{
id: "11111111-1111-4111-8111-111111111111",
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_040_000,
durationMs: 30_000,
bytes: 1_048_576,
mimeType: "video/webm",
hasAudio: false,
},
{
id: "22222222-2222-4222-8222-222222222222",
startedAt: 1_700_000_060_000,
endedAt: 1_700_000_120_000,
durationMs: 60_000,
bytes: 2_097_152,
mimeType: "video/webm",
hasAudio: true,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
securityLabel: "TLS / NLA",
},
},
];
const markup = renderWithI18n(
React.createElement(ConnectionLogsManager, {
logs,
hosts: [],
onToggleSaved: () => {},
onDelete: () => {},
onClearUnsaved: () => {},
onOpenLogView: () => {},
}),
);
assert.match(markup, /2 clips · 01:30 · 3 MB/);
assert.match(markup, /1920×1080/);
assert.match(markup, /TLS \/ NLA/);
});
+116 -21
View File
@@ -2,6 +2,7 @@ import {
Bookmark,
ChevronDown,
CircleUserRound,
Monitor,
Server,
Terminal,
Trash2,
@@ -11,7 +12,8 @@ import {
import React, { memo, useCallback, useMemo, useState } from "react";
import { useI18n } from "../application/i18n/I18nProvider";
import { resolveHostIconAppearance } from "../domain/hostIcon";
import { isRdpProtocol, isVncProtocol } from "../domain/remoteDesktop";
import { isRdpProtocol, isRemoteDesktopProtocol, isVncProtocol } from "../domain/remoteDesktop";
import { getConnectionLogRecordingSummary } from "../domain/remoteDesktopRecording";
import { cn } from "../lib/utils";
import { ConnectionLog, Host } from "../types";
import { DistroAvatar } from "./DistroAvatar";
@@ -28,6 +30,8 @@ interface ConnectionLogsManagerProps {
onOpenLogView: (log: ConnectionLog) => void;
}
export type ConnectionLogFilter = "all" | "terminal" | "remoteDesktop" | "recorded";
export function formatRecordingDuration(durationMs?: number): string {
if (!durationMs || !Number.isFinite(durationMs) || durationMs <= 0) {
return "00:00";
@@ -110,8 +114,28 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
iconColorCustom: log.hostIconColorCustom,
});
const hasPersistedHostIcon = !isLocal && !isSerial && !isRemoteDesktop && (!!log.hostDistro || !!customHostIcon);
const recordingSizeText = formatRecordingBytes(log.recordingBytes);
const recordingDurationText = formatRecordingDuration(log.recordingDurationMs);
const recordingSummary = getConnectionLogRecordingSummary(log);
const recordingSizeText = formatRecordingBytes(recordingSummary.totalBytes);
const recordingDurationText = formatRecordingDuration(recordingSummary.totalDurationMs);
const resolutionText = log.remoteDesktopMeta?.resolution
? `${log.remoteDesktopMeta.resolution.width}\u00d7${log.remoteDesktopMeta.resolution.height}`
: "";
const subtitleParts: string[] = [];
if (isLocal) {
subtitleParts.push("local");
} else if (isSerial) {
subtitleParts.push(`serial, ${log.hostname}`);
} else if (log.username) {
subtitleParts.push(`${log.protocol}, ${log.username}`);
} else {
subtitleParts.push(`${log.protocol}, ${log.hostname}`);
}
if (isRemoteDesktop && resolutionText) {
subtitleParts.push(resolutionText);
}
if (isRemoteDesktop && log.remoteDesktopMeta?.securityLabel) {
subtitleParts.push(log.remoteDesktopMeta.securityLabel);
}
return (
<div
@@ -185,13 +209,16 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
<div className="text-sm font-medium truncate">
{isLocal ? t("logs.localTerminal") : log.hostLabel}
</div>
{log.recordingId && (
{recordingSummary.primaryClip && (
<span
data-recording-badge={log.recordingId}
data-recording-badge={recordingSummary.primaryClip.id}
className="inline-flex items-center gap-1 rounded-md border border-primary/25 bg-primary/10 px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-primary shrink-0"
>
<Video size={12} />
<span>
{recordingSummary.clipCount > 1
? `${t("logs.recording.clipsCount", { count: recordingSummary.clipCount })} · `
: ""}
{recordingDurationText}
{recordingSizeText ? ` · ${recordingSizeText}` : ""}
</span>
@@ -199,13 +226,7 @@ const LogItem = memo<LogItemProps>(({ log, onToggleSaved, onDelete, onClick }) =
)}
</div>
<div className="text-xs text-muted-foreground truncate">
{isLocal
? "local"
: isSerial
? `serial, ${log.hostname}`
: log.username
? `${log.protocol}, ${log.username}`
: `${log.protocol}, ${log.hostname}`}
{subtitleParts.join(" · ")}
</div>
</div>
</div>
@@ -264,20 +285,52 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
const INITIAL_RENDER_LIMIT = 30;
const LOAD_MORE_COUNT = 30;
// Track how many items to show
const [filter, setFilter] = useState<ConnectionLogFilter>("all");
const [renderLimit, setRenderLimit] = useState(INITIAL_RENDER_LIMIT);
// Sort logs by newest first
const filteredLogs = useMemo(() => {
return [...logs].sort((a, b) => b.startTime - a.startTime);
const filterCounts = useMemo(() => {
let terminal = 0;
let remoteDesktop = 0;
let recorded = 0;
for (const log of logs) {
if (isRemoteDesktopProtocol(log.protocol)) {
remoteDesktop += 1;
} else {
terminal += 1;
}
if (getConnectionLogRecordingSummary(log).clipCount > 0) {
recorded += 1;
}
}
return { all: logs.length, terminal, remoteDesktop, recorded };
}, [logs]);
const showFilterBar = logs.length > 0 && (filterCounts.remoteDesktop > 0 || filterCounts.recorded > 0);
const effectiveFilter: ConnectionLogFilter = showFilterBar ? filter : "all";
// Filter and sort logs by newest first
const filteredLogs = useMemo(() => {
const subset = effectiveFilter === "all"
? logs
: logs.filter((log) => {
if (effectiveFilter === "remoteDesktop") return isRemoteDesktopProtocol(log.protocol);
if (effectiveFilter === "terminal") return !isRemoteDesktopProtocol(log.protocol);
return getConnectionLogRecordingSummary(log).clipCount > 0;
});
return [...subset].sort((a, b) => b.startTime - a.startTime);
}, [effectiveFilter, logs]);
const displayedLogs = useMemo(() => {
return filteredLogs.slice(0, renderLimit);
}, [filteredLogs, renderLimit]);
const hasMore = filteredLogs.length > renderLimit;
const handleChangeFilter = useCallback((next: ConnectionLogFilter) => {
setFilter(next);
setRenderLimit(INITIAL_RENDER_LIMIT);
}, []);
const handleLoadMore = useCallback(() => {
setRenderLimit(prev => prev + LOAD_MORE_COUNT);
}, []);
@@ -292,7 +345,6 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
[onDelete],
);
// Rendered items
const renderedItems = useMemo(() => {
return displayedLogs.map((log) => (
<LogItem
@@ -307,9 +359,46 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
return (
<div className="h-full flex flex-col">
{/* Protocol / Recording Filter Bar */}
{showFilterBar && (
<div
data-testid="logs-filter-bar"
className="flex flex-wrap items-center gap-1.5 px-4 py-2 border-b border-border/30 bg-background shrink-0"
>
{(
[
{ id: "all" as const, label: t("logs.filter.all"), count: filterCounts.all, icon: null },
{ id: "terminal" as const, label: t("logs.filter.terminal"), count: filterCounts.terminal, icon: <Terminal size={12} /> },
{ id: "remoteDesktop" as const, label: t("logs.filter.remoteDesktop"), count: filterCounts.remoteDesktop, icon: <Monitor size={12} /> },
{ id: "recorded" as const, label: t("logs.filter.recorded"), count: filterCounts.recorded, icon: <Video size={12} /> },
]
).map((item) => {
const active = effectiveFilter === item.id;
return (
<button
key={item.id}
type="button"
data-logs-filter={item.id}
onClick={() => handleChangeFilter(item.id)}
className={cn(
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
active
? "bg-primary/12 text-primary border border-primary/25"
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
)}
>
{item.icon}
<span>{item.label}</span>
<span className="font-mono text-[10px] opacity-75 tabular-nums">{item.count}</span>
</button>
);
})}
</div>
)}
{/* Table Header */}
{displayedLogs.length > 0 && (
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30">
<div className="flex items-center gap-4 px-4 py-2 text-xs font-medium text-muted-foreground border-b border-border/30 bg-secondary/30 shrink-0">
<div className="w-32 shrink-0 flex items-center gap-1">
{t("logs.table.date")}
<ChevronDown size={12} />
@@ -329,13 +418,19 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
{displayedLogs.length === 0 ? (
<div className="flex flex-col items-center justify-center py-16 text-muted-foreground">
<div className="h-16 w-16 rounded-2xl bg-secondary/80 flex items-center justify-center mb-4">
<Terminal size={32} className="opacity-60" />
{effectiveFilter === "recorded" ? (
<Video size={32} className="opacity-60" />
) : effectiveFilter === "remoteDesktop" ? (
<Monitor size={32} className="opacity-60" />
) : (
<Terminal size={32} className="opacity-60" />
)}
</div>
<h3 className="text-lg font-semibold text-foreground mb-2">
{t("logs.empty.title")}
{effectiveFilter === "all" ? t("logs.empty.title") : t("logs.filter.emptyTitle")}
</h3>
<p className="text-sm text-center max-w-sm">
{t("logs.empty.desc")}
{effectiveFilter === "all" ? t("logs.empty.desc") : t("logs.filter.emptyDesc")}
</p>
</div>
) : (
+4 -1
View File
@@ -1,6 +1,7 @@
import { Search } from 'lucide-react';
import React, { useMemo, useState, useEffect, useCallback } from 'react';
import { useI18n } from '../application/i18n/I18nProvider';
import { usePinyinMatcherVersion } from '../application/state/usePinyinMatcherVersion';
import { matchesWorkspaceHostPickerQuery } from '../domain/searchMatcher';
import { Host } from '../types';
import { DistroAvatar } from './DistroAvatar';
@@ -29,12 +30,14 @@ export const CreateWorkspaceDialog: React.FC<CreateWorkspaceDialogProps> = ({
const [name, setName] = useState('');
const [search, setSearch] = useState('');
const [selectedHostIds, setSelectedHostIds] = useState<Set<string>>(new Set());
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
const term = search.trim();
if (!term) return hosts;
return hosts.filter((host) => matchesWorkspaceHostPickerQuery(term, host));
}, [hosts, search]);
}, [hosts, search, pinyinMatcherVersion]);
const toggleHost = useCallback((hostId: string) => {
setSelectedHostIds(prev => {
+305 -1
View File
@@ -1,14 +1,27 @@
import test from "node:test";
import assert from "node:assert/strict";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import {
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { GroupConfig, Identity } from "../types.ts";
import GroupDetailsPanel, {
hasGroupRdpFields,
hasGroupSshFields,
hasGroupTelnetFields,
hasGroupVncFields,
includeMissingIdentityOption,
resolveGroupFormIdentityId,
selectGroupRdpIdentity,
selectGroupSshIdentity,
selectGroupTelnetIdentity,
selectGroupVncIdentity,
} from "./GroupDetailsPanel.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
import { AsidePanelFooter } from "./ui/aside-panel.tsx";
import { Button } from "./ui/button.tsx";
import { Input } from "./ui/input.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
test("GroupDetailsPanel treats an empty SSH identity as an explicit setting", () => {
assert.equal(hasGroupSshFields({ identityId: "" }), true);
@@ -114,4 +127,295 @@ test("GroupDetailsPanel shows saved child manual credentials instead of a parent
),
undefined,
);
assert.equal(
resolveGroupFormIdentityId(
{ rdpConfig: { enabled: true, username: "child-rdp-user" } },
"parent-rdp-identity",
"rdp",
),
undefined,
);
assert.equal(
resolveGroupFormIdentityId(
{ vncConfig: { enabled: true, useHostCredentials: true } },
"parent-vnc-identity",
"vnc",
),
undefined,
);
});
test("GroupDetailsPanel detects RDP and VNC configs without falsely enabling SSH on RDP-only groups with proxy/chain", () => {
assert.equal(hasGroupRdpFields({ rdpConfig: { enabled: true } }), true);
assert.equal(hasGroupRdpFields({}), false);
assert.equal(hasGroupVncFields({ vncConfig: { enabled: true } }), true);
assert.equal(hasGroupVncFields({}), false);
// RDP-only group with proxy/chain stays RDP-only.
assert.equal(
hasGroupSshFields({
rdpConfig: { enabled: true, port: 3389 },
proxyProfileId: "corp-proxy",
hostChain: { hostIds: ["bastion-1"] },
}),
false,
);
// Legacy group with only proxy/chain still shows SSH enabled.
assert.equal(hasGroupSshFields({ proxyProfileId: "corp-proxy" }), true);
// Telnet-only group with startupCommand does not falsely enable SSH.
assert.equal(
hasGroupSshFields({ telnetEnabled: true, startupCommand: "enable" }),
false,
);
});
test("GroupDetailsPanel selects and clears RDP and VNC identities cleanly", () => {
const identity: Identity = {
id: "win-admin",
label: "Windows Admin",
username: "Administrator",
domain: "CORP",
authMethod: "password",
password: "secret",
created: 1,
};
const withRdp = selectGroupRdpIdentity({}, identity, identity.id);
assert.equal(withRdp.rdpConfig?.identityId, "win-admin");
assert.equal(withRdp.rdpConfig?.domain, "CORP");
assert.equal(withRdp.rdpConfig?.useHostCredentials, false);
const clearedRdp = selectGroupRdpIdentity({}, undefined, "", "parent-rdp-id");
assert.equal(clearedRdp.rdpConfig?.identityId, "");
const withVnc = selectGroupVncIdentity({}, identity, identity.id);
assert.equal(withVnc.vncConfig?.identityId, "win-admin");
assert.equal(withVnc.vncConfig?.useHostCredentials, false);
const clearedVnc = selectGroupVncIdentity({}, undefined, "", "parent-vnc-id");
assert.equal(clearedVnc.vncConfig?.identityId, "");
});
test("GroupDetailsPanel unifies 4-protocol tabs, adds RDP/VNC defaults, and saves via footer without plaintext passwords", async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let savedConfig: GroupConfig | undefined;
const createdIdentities: Identity[] = [];
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath="Windows"
config={undefined}
availableKeys={[]}
identities={[]}
onCreateIdentity={(identity) => createdIdentities.push(identity)}
allHosts={[]}
groups={["Windows"]}
terminalThemeId="default"
terminalFontSize={14}
layout="inline"
onSave={(value) => {
savedConfig = value;
}}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const protocolTabs = renderer!.root.findAll(
(node) => node.type === "button" && typeof node.props["data-group-protocol"] === "string",
);
assert.deepEqual(
protocolTabs.map((node) => node.props["data-group-protocol"]),
["ssh", "rdp", "vnc", "telnet"],
);
const collectText = (node: unknown): string => {
if (typeof node === "string") return node;
if (Array.isArray(node)) return node.map(collectText).join("");
if (node && typeof node === "object" && "children" in node) {
return collectText((node as { children: unknown }).children);
}
return "";
};
const buttonText = (btn: { children: unknown[] }) => collectText(btn.children);
// Switch to RDP tab and enable RDP
const rdpTab = protocolTabs.find((node) => node.props["data-group-protocol"] === "rdp")!;
await act(async () => {
rdpTab.props.onClick();
});
const addRdpBtn = renderer!.root.findAllByType(Button).find((btn) =>
buttonText(btn).includes("Add RDP"),
);
assert.ok(addRdpBtn, "expected Add RDP button when RDP is not enabled");
await act(async () => {
addRdpBtn.props.onClick();
});
// Set RDP port, domain, username, and password (password must become a Keychain identity)
const rdpPortInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "3389",
);
const rdpDomainInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "CORP (optional)",
);
const rdpUserInput = renderer!.root.findAllByType(Input).find(
(input) => typeof input.props.placeholder === "string" && input.props.placeholder.includes("DOMAIN"),
);
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(rdpPortInput && rdpDomainInput && rdpUserInput && rdpPasswordInput);
await act(async () => {
rdpPortInput.props.onChange({ target: { value: "13389" } });
rdpDomainInput.props.onChange({ target: { value: "CORP" } });
rdpUserInput.props.onChange({ target: { value: "admin" } });
rdpPasswordInput.props.onChange({ target: { value: "rdp-secret" } });
});
// Switch to VNC tab and enable VNC with :2 display port
const vncTab = renderer!.root.findAll(
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
)[0];
await act(async () => {
vncTab.props.onClick();
});
const addVncBtn = renderer!.root.findAllByType(Button).find((btn) =>
buttonText(btn).includes("Add VNC"),
);
assert.ok(addVncBtn, "expected Add VNC button when VNC is not enabled");
await act(async () => {
addVncBtn.props.onClick();
});
const vncPortInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.placeholder === "5900 or :0",
);
assert.ok(vncPortInput);
await act(async () => {
vncPortInput.props.onChange({ target: { value: ":2" } });
});
// Save via the unified AsidePanelFooter Save button
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
await act(async () => {
footerSaveBtn.props.onClick();
});
assert.ok(savedConfig, "expected GroupDetailsPanel footer save button to emit GroupConfig");
assert.equal(savedConfig.protocol, undefined, "SSH should remain disabled");
assert.equal(createdIdentities.length, 1);
assert.equal(createdIdentities[0].username, "admin");
assert.equal(createdIdentities[0].domain, "CORP");
assert.equal(createdIdentities[0].password, "rdp-secret");
assert.equal(savedConfig.rdpConfig?.enabled, true);
assert.equal(savedConfig.rdpConfig?.port, 13389);
assert.equal(savedConfig.rdpConfig?.domain, "CORP");
assert.equal(savedConfig.rdpConfig?.identityId, createdIdentities[0].id);
assert.equal("password" in (savedConfig.rdpConfig ?? {}), false);
assert.equal(savedConfig.vncConfig?.enabled, true);
assert.equal(savedConfig.vncConfig?.port, 5902);
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
test("GroupDetailsPanel preserves inherited parent RDP/VNC username and domain when creating a password-only identity", async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let savedConfig: GroupConfig | undefined;
const createdIdentities: Identity[] = [];
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath="Corp/EU"
config={{ path: "Corp/EU", rdpConfig: { enabled: true }, vncConfig: { enabled: true } }}
availableKeys={[]}
identities={[]}
onCreateIdentity={(identity) => createdIdentities.push(identity)}
allHosts={[]}
groups={["Corp", "Corp/EU"]}
groupConfigs={[
{
path: "Corp",
rdpConfig: { enabled: true, username: "corp-admin", domain: "CORP" },
vncConfig: { enabled: true, username: "corp-vnc" },
},
]}
terminalThemeId="default"
terminalFontSize={14}
layout="inline"
onSave={(value) => {
savedConfig = value;
}}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const rdpPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(rdpPasswordInput);
await act(async () => {
rdpPasswordInput.props.onChange({ target: { value: "eu-rdp-secret" } });
});
const vncTab = renderer!.root.findAll(
(node) => node.type === "button" && node.props["data-group-protocol"] === "vnc",
)[0];
await act(async () => {
vncTab.props.onClick();
});
const vncPasswordInput = renderer!.root.findAllByType(Input).find(
(input) => input.props.type === "password",
);
assert.ok(vncPasswordInput);
await act(async () => {
vncPasswordInput.props.onChange({ target: { value: "eu-vnc-secret" } });
});
const footerSaveBtn = renderer!.root.findByType(AsidePanelFooter).findByType(Button);
await act(async () => {
footerSaveBtn.props.onClick();
});
assert.ok(savedConfig);
assert.equal(createdIdentities.length, 2);
assert.equal(createdIdentities[0].username, "corp-admin");
assert.equal(createdIdentities[0].domain, "CORP");
assert.equal(createdIdentities[0].password, "eu-rdp-secret");
assert.equal(createdIdentities[1].username, "corp-vnc");
assert.equal(createdIdentities[1].password, "eu-vnc-secret");
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+54 -14
View File
@@ -132,6 +132,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
onCreateIdentity,
companionCredentialDrafts,
onCompanionCredentialDraftChange,
resolutionDraft,
onResolutionDraftChange,
effectiveTelnetPort,
effectiveTelnetUsername,
effectiveTelnetPassword,
@@ -190,14 +192,36 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
);
const [vncPortText, setVncPortText] = useState<string>(() =>
String(form.port ?? DEFAULT_VNC_PORT),
form.port !== undefined
? String(form.port)
: groupDefaults?.vncConfig?.port !== undefined
? ""
: String(DEFAULT_VNC_PORT),
);
useEffect(() => {
if (isVncPrimary) {
setVncPortText(String(form.port ?? DEFAULT_VNC_PORT));
setVncPortText(
form.port !== undefined
? String(form.port)
: groupDefaults?.vncConfig?.port !== undefined
? ""
: String(DEFAULT_VNC_PORT),
);
}
}, [form.id, form.port, isVncPrimary]);
}, [form.id, form.port, isVncPrimary, groupDefaults?.vncConfig?.port]);
const updateStandaloneDesktopPort = (nextPort: number | undefined) => {
setForm((prev: Host) => ({
...prev,
port: nextPort,
...(isRdpPrimary && prev.rdpConfig
? { rdpConfig: { ...prev.rdpConfig, port: nextPort } }
: isVncPrimary && prev.vncConfig
? { vncConfig: { ...prev.vncConfig, port: nextPort } }
: {}),
}));
};
const handleTabClick = (next: "ssh" | "rdp" | "vnc" | "telnet") => {
if (onSelectProtocolTab) {
@@ -213,7 +237,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
(identity: Identity) => identity.authMethod === "password" || Boolean(identity.password),
);
const vncDisplayLabel = isVncPrimary
? formatVncDisplayNumber(form.port ?? DEFAULT_VNC_PORT)
? formatVncDisplayNumber(form.port ?? groupDefaults?.vncConfig?.port ?? DEFAULT_VNC_PORT)
: null;
const selectAuthMethod = (authMethod: "auto" | "password" | "key" | "certificate") => {
@@ -380,6 +404,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
protocol="vnc"
form={form}
setForm={setForm}
groupDefaults={groupDefaults}
identities={identities}
availableKeys={availableKeys}
onCreateIdentity={onCreateIdentity}
@@ -392,9 +417,12 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
protocol="rdp"
form={form}
setForm={setForm}
groupDefaults={groupDefaults}
identities={identities}
availableKeys={availableKeys}
onCreateIdentity={onCreateIdentity}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
credentialDraft={companionCredentialDrafts?.rdp}
onCredentialDraftChange={(draft) => onCompanionCredentialDraftChange?.("rdp", draft)}
t={t}
@@ -412,18 +440,30 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
onChange={(e) => {
const raw = e.target.value;
setVncPortText(raw);
if (!raw.trim()) {
updateStandaloneDesktopPort(undefined);
return;
}
const parsed = parseVncPortOrDisplay(raw);
if (parsed !== null) {
update("port", parsed);
updateStandaloneDesktopPort(parsed);
}
}}
onBlur={() => {
if (!vncPortText.trim() && groupDefaults?.vncConfig?.port !== undefined) {
updateStandaloneDesktopPort(undefined);
return;
}
const parsed = parseVncPortOrDisplay(vncPortText);
const resolved = parsed ?? DEFAULT_VNC_PORT;
setVncPortText(String(resolved));
update("port", resolved);
const resolved = parsed ?? (groupDefaults?.vncConfig?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
setVncPortText(resolved !== undefined ? String(resolved) : "");
updateStandaloneDesktopPort(resolved);
}}
placeholder={t("hostDetails.vnc.displayPlaceholder")}
placeholder={
groupDefaults?.vncConfig?.port
? String(groupDefaults.vncConfig.port)
: t("hostDetails.vnc.displayPlaceholder")
}
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
/>
{vncDisplayLabel ? (
@@ -437,9 +477,9 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
type="number"
value={form.port ?? ""}
onChange={(e) =>
update("port", e.target.value ? Number(e.target.value) : undefined)
updateStandaloneDesktopPort(e.target.value ? Number(e.target.value) : undefined)
}
placeholder={String(DEFAULT_RDP_PORT)}
placeholder={String(groupDefaults?.rdpConfig?.port ?? DEFAULT_RDP_PORT)}
className="h-8 w-44 text-center font-mono text-sm"
/>
)}
@@ -497,8 +537,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
onChange={(next) => update("username", next)}
placeholder={
isRdpPrimary
? t("hostDetails.rdp.usernamePlaceholder")
: t("hostDetails.vnc.usernamePlaceholder")
? (groupDefaults?.rdpConfig?.username || t("hostDetails.rdp.usernamePlaceholder"))
: (groupDefaults?.vncConfig?.username || t("hostDetails.vnc.usernamePlaceholder"))
}
identities={passwordCompatibleIdentities}
availableKeys={availableKeys}
@@ -559,7 +599,7 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
label={t("hostDetails.rdp.domainLabel")}
>
<Input
placeholder={t("hostDetails.rdp.domainPlaceholder")}
placeholder={groupDefaults?.rdpConfig?.domain || t("hostDetails.rdp.domainPlaceholder")}
value={form.rdpConfig?.domain ?? ""}
onChange={(e) =>
setForm((prev: Host) => ({
+12 -2
View File
@@ -23,6 +23,8 @@ export const resolvePrimaryProtocolSwitchPort = (
nextProtocol: "ssh" | "telnet" | "rdp" | "vnc",
hasGroupTelnetPortDefault: boolean,
hasGroupSshPortDefault: boolean,
hasGroupRdpPortDefault = false,
hasGroupVncPortDefault = false,
): number | undefined => {
const isKnownDefaultPort =
currentPort === undefined ||
@@ -32,9 +34,11 @@ export const resolvePrimaryProtocolSwitchPort = (
currentPort === 5900;
if (nextProtocol === "rdp") {
if (hasGroupRdpPortDefault && isKnownDefaultPort) return undefined;
return isKnownDefaultPort ? 3389 : currentPort;
}
if (nextProtocol === "vnc") {
if (hasGroupVncPortDefault && isKnownDefaultPort) return undefined;
return isKnownDefaultPort ? 5900 : currentPort;
}
if (nextProtocol === "telnet") {
@@ -56,12 +60,18 @@ export const resolvePrimaryProtocolSavePort = (
currentPort: number | undefined,
hasGroupSshPortDefault: boolean,
hasGroupTelnetPortDefault: boolean,
hasGroupRdpPortDefault = false,
hasGroupVncPortDefault = false,
): number | undefined => {
if (protocol === "rdp") {
return currentPort ?? 3389;
if (currentPort !== undefined) return currentPort;
if (hasGroupRdpPortDefault) return undefined;
return 3389;
}
if (protocol === "vnc") {
return currentPort ?? 5900;
if (currentPort !== undefined) return currentPort;
if (hasGroupVncPortDefault) return undefined;
return 5900;
}
if (protocol === "telnet") {
if (currentPort !== undefined) return currentPort;
@@ -220,3 +220,159 @@ test("Host Details can restore group jump hosts from the empty-override Direct r
assert.ok(section().findAllByType(Badge).some((badge) => badge.props.children === "Inherited from group"));
});
});
test("Host Details keeps standalone RDP fields sparse so group RDP defaults are inherited on save", async () => {
const group: Partial<GroupConfig> = {
rdpConfig: {
enabled: true,
port: 13389,
domain: "CORP",
securityMode: "nla",
audioEnabled: false,
},
};
const rdpHost: Host = {
...host,
protocol: "rdp",
port: undefined,
username: "",
password: undefined,
authMethod: undefined,
rdpConfig: undefined,
};
await withPanel(group, async ({ root, save }) => {
const securitySelect = root.findAllByType(Select).find((item) => item.props.value === "nla");
assert.ok(securitySelect, "expected standalone RDP editor to reflect inherited securityMode");
const saved = await save();
assert.equal(saved.port, undefined);
assert.equal(saved.rdpConfig, undefined);
const effective = applyGroupDefaults(saved, group);
assert.equal(effective.port, 13389);
assert.equal(effective.rdpConfig?.domain, "CORP");
assert.equal(effective.rdpConfig?.securityMode, "nla");
assert.equal(effective.rdpConfig?.audioEnabled, false);
}, rdpHost);
});
test("Host Details preserves useHostCredentials fallback when adding companion RDP without group credential defaults", async () => {
await withPanel({}, async ({ root, save }) => {
const rdpTab = root.findAll(
(node) => node.type === "button" && node.props["data-primary-protocol"] === "rdp",
)[0];
assert.ok(rdpTab);
await act(async () => { rdpTab.props.onClick(); });
const addRdpBtn = root.findAllByType(Button).find((btn) => {
const collect = (n: unknown): string =>
typeof n === "string"
? n
: Array.isArray(n)
? n.map(collect).join("")
: n && typeof n === "object" && "children" in n
? collect((n as { children: unknown }).children)
: "";
return collect(btn.children).includes("Add RDP");
});
assert.ok(addRdpBtn);
await act(async () => { addRdpBtn.props.onClick(); });
const saved = await save();
assert.equal(saved.rdpConfig?.enabled, true);
assert.equal(saved.rdpConfig?.useHostCredentials, true);
});
});
test("Host Details preserves cleared inherited companion RDP identity across save", async () => {
const group: Partial<GroupConfig> = {
rdpConfig: {
enabled: true,
identityId: "group-rdp-id",
},
};
const companionHost: Host = {
...host,
rdpConfig: { enabled: true },
};
await withPanel(group, async ({ root, save }) => {
const rdpTab = root.findAll(
(node) => node.type === "button" && node.props["data-primary-protocol"] === "rdp",
)[0];
await act(async () => { rdpTab.props.onClick(); });
const clearBtn = root.findAllByType(Button).find(
(btn) => btn.props.size === "icon" && btn.props.className?.includes("h-8 w-8 shrink-0"),
);
assert.ok(clearBtn, "expected Clear button on inherited companion RDP identity");
await act(async () => { clearBtn.props.onClick({ defaultPrevented: false }); });
const saved = await save();
assert.equal(saved.rdpConfig?.identityId, "");
assert.equal(saved.rdpConfig?.useHostCredentials, false);
const effective = applyGroupDefaults(saved, group);
assert.equal(effective.rdpConfig?.identityId, "");
}, companionHost);
});
test("Host Details retains the inherited desktop username and domain when detaching a standalone RDP identity", async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
let saved: Host | undefined;
const group: Partial<GroupConfig> = {
rdpConfig: { enabled: true, identityId: "win-admin" },
};
const standaloneRdp: Host = {
...host,
protocol: "rdp",
port: undefined,
username: "",
password: undefined,
authMethod: undefined,
rdpConfig: undefined,
};
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<HostDetailsPanel
{...panelProps(group, standaloneRdp)}
identities={[
{
id: "win-admin",
label: "Windows Admin",
username: "Administrator",
domain: "CORP",
authMethod: "password",
password: "group-secret",
created: 1,
},
]}
onSave={(value) => { saved = value; }}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const clearBtn = renderer!.root.findAllByType(Button).find(
(btn) => btn.props.size === "icon" && btn.props.className?.includes("h-8 w-8 shrink-0"),
);
assert.ok(clearBtn, "expected Clear button on inherited standalone RDP identity");
await act(async () => { clearBtn.props.onClick({ defaultPrevented: false }); });
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
await act(async () => { await buttons[buttons.length - 1].props.onClick(); });
assert.ok(saved);
assert.equal(saved.identityId, "");
assert.equal(saved.username, "Administrator");
assert.equal(saved.rdpConfig?.domain, "CORP");
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
@@ -0,0 +1,97 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider";
import type { Host } from "../types";
import HostDetailsPanel from "./HostDetailsPanel";
import { installDomEnvironment } from "./test-support/renderReactDom";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Select } from "./ui/select";
import { TooltipProvider } from "./ui/tooltip";
for (const kind of ["standalone", "companion", "new"] as const) {
test(`${kind} RDP keeps invalid resolution drafts visible and blocks saving`, async () => {
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let renderer: ReactTestRenderer | undefined;
const saved: Host[] = [];
const host: Host = {
id: "rdp-host", label: "Desktop", hostname: "desktop.example.com",
username: "root", password: "password", authMethod: "password",
protocol: kind === "companion" ? "ssh" : "rdp", tags: [], os: "windows",
rdpConfig: {
enabled: true, defaultConnect: true, resolutionMode: "fixed", width: 1920, height: 1080,
},
};
try {
await act(async () => {
renderer = create(
<I18nProvider locale="en"><TooltipProvider>
<HostDetailsPanel
initialData={kind === "new" ? undefined : host}
initialProtocol="rdp"
availableKeys={[]} identities={[]} groups={[]}
terminalThemeId="default" terminalFontSize={14} layout="inline"
onSave={(value) => saved.push(value)} onCancel={() => {}}
/>
</TooltipProvider></I18nProvider>,
);
});
if (kind === "new") {
await act(async () => {
const hostname = renderer!.root.findAllByType(Input).find((input) =>
input.props.placeholder === "IP or Hostname");
assert.ok(hostname);
hostname.props.onChange({ target: { value: host.hostname } });
const mode = renderer!.root.findAllByType(Select).find((select) => select.props.value === "dynamic");
assert.ok(mode);
mode.props.onValueChange("fixed");
});
}
const input = (dimension: string) => renderer!.root.findAllByType(Input).find((field) =>
field.props.id?.endsWith(`-${dimension}`))!;
const change = async (dimension: string, value: string) => {
await act(async () => { input(dimension).props.onChange({ target: { value } }); });
};
const save = async () => {
await act(async () => {
const button = renderer!.root.findAllByType(Button).find((item) => item.props["aria-label"] === "Save");
assert.ok(button);
await button.props.onClick();
});
};
assert.equal(input("width").props.value, "1920");
for (const value of ["192", "19", "", "199", "8193", "3840.5", "abc"]) {
await change("width", value);
assert.equal(input("width").props.value, value);
assert.equal(input("width").props["aria-invalid"], true);
assert.match(JSON.stringify(renderer!.toJSON()), /Enter a whole number from 200 to 8192/);
await save();
assert.equal(saved.length, 0);
assert.equal(input("width").props.value, value, "save must preserve the invalid draft");
}
await change("width", "3840");
assert.equal(input("width").props.value, "3840");
assert.equal(input("width").props["aria-invalid"], false);
await change("height", "192");
await save();
assert.equal(saved.length, 0);
assert.equal(input("height").props.value, "192");
await change("height", "2160");
await save();
assert.equal(saved.length, 1);
assert.equal(saved[0].rdpConfig?.width, 3840);
assert.equal(saved[0].rdpConfig?.height, 2160);
} finally {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
}
});
}
+193 -49
View File
@@ -82,16 +82,16 @@ import {
} from "../domain/pluginConnection";
import {
applyHostDefaultConnectProtocol,
DEFAULT_RDP_CONFIG,
DEFAULT_RDP_PORT,
DEFAULT_VNC_CONFIG,
DEFAULT_VNC_PORT,
getHostEnabledProtocols,
hasValidRdpFixedResolution,
isRemoteDesktopProtocol,
resolveHostDefaultConnectProtocol,
sanitizeRdpConfig,
sanitizeVncConfig,
shouldPromptHostProtocolOnConnect,
type RdpResolutionDraft,
} from "../domain/remoteDesktop";
import { PluginConnectionSection } from "./PluginConnectionSection";
import { useHostConnectionTest } from "../application/state/useHostConnectionTest";
@@ -197,7 +197,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
id: crypto.randomUUID(),
label: "",
hostname: "",
port: DEFAULT_RDP_PORT,
port: groupDefaults?.rdpConfig?.port ? undefined : DEFAULT_RDP_PORT,
username: "",
protocol: "rdp",
tags: [],
@@ -205,7 +205,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
authMethod: "password",
authPolicyVersion: 1,
distroMode: "auto",
rdpConfig: { ...DEFAULT_RDP_CONFIG },
rdpConfig: {},
createdAt: Date.now(),
group: defaultGroup || undefined,
} as Host;
@@ -215,7 +215,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
id: crypto.randomUUID(),
label: "",
hostname: "",
port: DEFAULT_VNC_PORT,
port: groupDefaults?.vncConfig?.port ? undefined : DEFAULT_VNC_PORT,
username: "",
protocol: "vnc",
tags: [],
@@ -223,7 +223,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
authMethod: "password",
authPolicyVersion: 1,
distroMode: "auto",
vncConfig: { ...DEFAULT_VNC_CONFIG },
vncConfig: {},
createdAt: Date.now(),
group: defaultGroup || undefined,
} as Host;
@@ -248,6 +248,15 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
},
);
const hasRdpProtocol = form.protocol === "rdp" || form.rdpConfig?.enabled === true;
const [resolutionDraft, setResolutionDraft] = useState<RdpResolutionDraft>({});
useEffect(() => {
setResolutionDraft({});
}, [form.id, hasRdpProtocol]);
const onResolutionDraftChange = (dimension: "width" | "height", value: string) => {
setResolutionDraft((prev) => ({ ...prev, [dimension]: value }));
};
const [activeSubPanel, setActiveSubPanel] = useState<SubPanel>("none");
const [credentialPopoverOpen, setCredentialPopoverOpen] = useState(false);
@@ -445,10 +454,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
[effectiveGroupDefaults, form],
);
const effectiveIdentityId =
form.protocol === "rdp"
? (effectiveAuthHost.identityId || effectiveAuthHost.rdpConfig?.identityId)
: form.protocol === "vnc"
? (effectiveAuthHost.identityId || effectiveAuthHost.vncConfig?.identityId)
: effectiveAuthHost.identityId;
const selectedIdentity = useMemo(() => {
if (!effectiveAuthHost.identityId) return undefined;
return identities.find((i) => i.id === effectiveAuthHost.identityId);
}, [effectiveAuthHost.identityId, identities]);
if (!effectiveIdentityId) return undefined;
return identities.find((i) => i.id === effectiveIdentityId);
}, [effectiveIdentityId, identities]);
const effectiveAuth = useMemo(() => resolveHostAuth({
host: effectiveAuthHost,
@@ -647,13 +663,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
nextProtocol,
Boolean(effectiveGroupDefaults?.telnetPort),
Boolean(effectiveGroupDefaults?.port),
Boolean(effectiveGroupDefaults?.rdpConfig?.port),
Boolean(effectiveGroupDefaults?.vncConfig?.port),
);
const isFreshHost = !initialData;
if (nextProtocol === "rdp") {
const carriedIdentityId = prev.rdpConfig?.identityId || prev.identityId;
return {
...prev,
protocol: "rdp",
port: prev.rdpConfig?.port ?? nextPort ?? DEFAULT_RDP_PORT,
port: prev.rdpConfig?.port ?? nextPort,
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
os: isFreshHost && prev.os === "linux" ? "windows" : prev.os,
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
authMethod: "password",
@@ -662,20 +682,22 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
telnetEnabled: false,
vncConfig: undefined,
rdpConfig: {
...DEFAULT_RDP_CONFIG,
...(prev.rdpConfig ?? {}),
enabled: undefined,
defaultConnect: undefined,
identityId: undefined,
tunnelViaHostSsh: undefined,
tunnelTargetHost: undefined,
},
};
}
if (nextProtocol === "vnc") {
const carriedIdentityId = prev.vncConfig?.identityId || prev.identityId;
return {
...prev,
protocol: "vnc",
port: prev.vncConfig?.port ?? nextPort ?? DEFAULT_VNC_PORT,
port: prev.vncConfig?.port ?? nextPort,
...(carriedIdentityId ? { identityId: carriedIdentityId } : {}),
username: isFreshHost && prev.username === "root" ? "" : (prev.username ?? ""),
authMethod: "password",
moshEnabled: false,
@@ -683,10 +705,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
telnetEnabled: false,
rdpConfig: undefined,
vncConfig: {
...DEFAULT_VNC_CONFIG,
...(prev.vncConfig ?? {}),
enabled: undefined,
defaultConnect: undefined,
identityId: undefined,
tunnelViaHostSsh: undefined,
tunnelTargetHost: undefined,
},
@@ -716,7 +738,14 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
};
});
},
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.telnetPort, effectiveGroupDefaults?.username, initialData],
[
effectiveGroupDefaults?.port,
effectiveGroupDefaults?.rdpConfig?.port,
effectiveGroupDefaults?.telnetPort,
effectiveGroupDefaults?.username,
effectiveGroupDefaults?.vncConfig?.port,
initialData,
],
);
const isUntouchedNewHost = !initialData
@@ -744,30 +773,44 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
setActiveProtocolTab(proto);
setForm((prev) => {
const hasSsh = !prev.protocol || prev.protocol === "ssh" || prev.protocol === "mosh" || prev.protocol === "et";
const hasGroupRdpCreds = Boolean(
effectiveGroupDefaults?.rdpConfig?.identityId
|| effectiveGroupDefaults?.rdpConfig?.username
|| effectiveGroupDefaults?.rdpConfig?.useHostCredentials !== undefined,
);
const hasGroupVncCreds = Boolean(
effectiveGroupDefaults?.vncConfig?.identityId
|| effectiveGroupDefaults?.vncConfig?.username
|| effectiveGroupDefaults?.vncConfig?.useHostCredentials !== undefined,
);
if (hasSsh) {
if (proto === "vnc") {
const hasExplicitVncCreds = Boolean(
prev.vncConfig?.identityId !== undefined
|| prev.vncConfig?.username
|| prev.vncConfig?.useHostCredentials !== undefined,
);
return {
...prev,
vncConfig: {
...DEFAULT_VNC_CONFIG,
...(prev.vncConfig ?? {}),
enabled: true,
port: prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
tunnelViaHostSsh: prev.vncConfig?.tunnelViaHostSsh ?? true,
useHostCredentials: prev.vncConfig?.identityId ? false : (prev.vncConfig?.useHostCredentials ?? true),
...(!hasExplicitVncCreds && !hasGroupVncCreds ? { useHostCredentials: true } : {}),
},
};
}
if (proto === "rdp") {
const hasExplicitRdpCreds = Boolean(
prev.rdpConfig?.identityId !== undefined
|| prev.rdpConfig?.username
|| prev.rdpConfig?.useHostCredentials !== undefined,
);
return {
...prev,
rdpConfig: {
...DEFAULT_RDP_CONFIG,
...(prev.rdpConfig ?? {}),
enabled: true,
port: prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
tunnelViaHostSsh: prev.rdpConfig?.tunnelViaHostSsh ?? true,
useHostCredentials: prev.rdpConfig?.identityId ? false : (prev.rdpConfig?.useHostCredentials ?? true),
...(!hasExplicitRdpCreds && !hasGroupRdpCreds ? { useHostCredentials: true } : {}),
},
};
}
@@ -782,38 +825,54 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
// while keeping the existing protocol enabled (and default for RDP/VNC).
if (proto === "ssh") {
if (prev.protocol === "rdp") {
const existingPort = prev.port ?? prev.rdpConfig?.port;
const hasExplicitRdpCreds = Boolean(
prev.identityId
|| prev.rdpConfig?.identityId !== undefined
|| prev.rdpConfig?.username
|| prev.rdpConfig?.useHostCredentials !== undefined,
);
return {
...prev,
protocol: "ssh",
port: effectiveGroupDefaults?.port ? undefined : 22,
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
rdpConfig: {
...DEFAULT_RDP_CONFIG,
...(prev.rdpConfig ?? {}),
enabled: true,
defaultConnect: true,
port: prev.port ?? prev.rdpConfig?.port ?? DEFAULT_RDP_PORT,
tunnelViaHostSsh: true,
useHostCredentials: prev.identityId ? false : true,
...(prev.identityId ? { identityId: prev.identityId } : {}),
...(existingPort !== undefined ? { port: existingPort } : {}),
...(prev.identityId
? { useHostCredentials: false, identityId: prev.identityId }
: !hasExplicitRdpCreds && !hasGroupRdpCreds
? { useHostCredentials: true }
: {}),
},
};
}
if (prev.protocol === "vnc") {
const existingPort = prev.port ?? prev.vncConfig?.port;
const hasExplicitVncCreds = Boolean(
prev.identityId
|| prev.vncConfig?.identityId !== undefined
|| prev.vncConfig?.username
|| prev.vncConfig?.useHostCredentials !== undefined,
);
return {
...prev,
protocol: "ssh",
port: effectiveGroupDefaults?.port ? undefined : 22,
username: prev.username || (effectiveGroupDefaults?.username ? "" : "root"),
vncConfig: {
...DEFAULT_VNC_CONFIG,
...(prev.vncConfig ?? {}),
enabled: true,
defaultConnect: true,
port: prev.port ?? prev.vncConfig?.port ?? DEFAULT_VNC_PORT,
tunnelViaHostSsh: true,
useHostCredentials: prev.identityId ? false : true,
...(prev.identityId ? { identityId: prev.identityId } : {}),
...(existingPort !== undefined ? { port: existingPort } : {}),
...(prev.identityId
? { useHostCredentials: false, identityId: prev.identityId }
: !hasExplicitVncCreds && !hasGroupVncCreds
? { useHostCredentials: true }
: {}),
},
};
}
@@ -831,7 +890,16 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
return prev;
});
},
[effectiveGroupDefaults?.port, effectiveGroupDefaults?.username],
[
effectiveGroupDefaults?.port,
effectiveGroupDefaults?.rdpConfig?.identityId,
effectiveGroupDefaults?.rdpConfig?.useHostCredentials,
effectiveGroupDefaults?.rdpConfig?.username,
effectiveGroupDefaults?.username,
effectiveGroupDefaults?.vncConfig?.identityId,
effectiveGroupDefaults?.vncConfig?.useHostCredentials,
effectiveGroupDefaults?.vncConfig?.username,
],
);
const handleSetDefaultProtocol = useCallback((proto: EditableHostProtocol) => {
@@ -909,6 +977,12 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
if (savingHostRef.current) return;
savingHostRef.current = true;
try {
if (!pluginProtocolActive && (form.protocol === "rdp" || form.rdpConfig?.enabled)
&& !hasValidRdpFixedResolution(effectiveAuthHost.rdpConfig, resolutionDraft)) {
setActiveProtocolTab("rdp");
toast.error(t("hostDetails.rdp.dimensionHint"));
return;
}
const flushed = isRemoteDesktopPrimary ? undefined : await totpFlushRef.current?.();
if (flushed && !flushed.ok) return;
const hostname = form.hostname.trim()
@@ -959,11 +1033,15 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
}
const { proxyConfig: _draftProxyConfig, ...formWithoutProxyDraft } = form;
const hasGroupRdpPortDefault = Boolean(effectiveGroupDefaults?.rdpConfig?.port);
const hasGroupVncPortDefault = Boolean(effectiveGroupDefaults?.vncConfig?.port);
const finalPort = resolvePrimaryProtocolSavePort(
form.protocol,
form.port,
Boolean(groupDefaults?.port),
Boolean(groupDefaults?.telnetPort),
Boolean(effectiveGroupDefaults?.port),
Boolean(effectiveGroupDefaults?.telnetPort),
hasGroupRdpPortDefault,
hasGroupVncPortDefault,
);
let cleaned: Host = {
...formWithoutProxyDraft,
@@ -997,7 +1075,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const sanitizedRdp = cleaned.protocol === "rdp"
? sanitizeRdpConfig({
...(cleaned.rdpConfig ?? {}),
port: finalPort ?? DEFAULT_RDP_PORT,
port: finalPort ?? (hasGroupRdpPortDefault ? undefined : DEFAULT_RDP_PORT),
enabled: undefined,
tunnelViaHostSsh: undefined,
tunnelTargetHost: undefined,
@@ -1006,7 +1084,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const sanitizedVnc = cleaned.protocol === "vnc"
? sanitizeVncConfig({
...(cleaned.vncConfig ?? {}),
port: finalPort ?? DEFAULT_VNC_PORT,
port: finalPort ?? (hasGroupVncPortDefault ? undefined : DEFAULT_VNC_PORT),
enabled: undefined,
tunnelViaHostSsh: undefined,
tunnelTargetHost: undefined,
@@ -1018,7 +1096,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
username: typeof cleaned.username === "string" ? cleaned.username.trim() : "",
tags: Array.isArray(cleaned.tags) ? cleaned.tags : [],
os: cleaned.os || (cleaned.protocol === "rdp" ? "windows" : "linux"),
port: finalPort ?? (cleaned.protocol === "rdp" ? DEFAULT_RDP_PORT : DEFAULT_VNC_PORT),
port: finalPort,
authMethod: hasInlinePassword || cleaned.identityId ? "password" : undefined,
authPolicyVersion: 1,
identityFileId: undefined,
@@ -1038,13 +1116,22 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
nextRdpConfig &&
onCreateIdentity &&
rdpDraft &&
rdpDraft.password.length > 0
rdpDraft.password.length > 0 &&
!nextRdpConfig.useHostCredentials &&
!nextRdpConfig.identityId
) {
const effectiveRdpDomain =
nextRdpConfig.domain || effectiveGroupDefaults?.rdpConfig?.domain;
const identity: Identity = {
id: crypto.randomUUID(),
label: `${finalLabel} RDP`,
username: rdpDraft.username.trim(),
...(nextRdpConfig.domain ? { domain: nextRdpConfig.domain } : {}),
username: (
rdpDraft.username ||
nextRdpConfig.username ||
effectiveGroupDefaults?.rdpConfig?.username ||
""
).trim(),
...(effectiveRdpDomain ? { domain: effectiveRdpDomain } : {}),
authMethod: "password",
password: rdpDraft.password,
created: Date.now(),
@@ -1062,12 +1149,19 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
nextVncConfig &&
onCreateIdentity &&
vncDraft &&
vncDraft.password.length > 0
vncDraft.password.length > 0 &&
!nextVncConfig.useHostCredentials &&
!nextVncConfig.identityId
) {
const identity: Identity = {
id: crypto.randomUUID(),
label: `${finalLabel} VNC`,
username: vncDraft.username.trim(),
username: (
vncDraft.username ||
nextVncConfig.username ||
effectiveGroupDefaults?.vncConfig?.username ||
""
).trim(),
authMethod: "password",
password: vncDraft.password,
created: Date.now(),
@@ -1325,9 +1419,17 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
password: undefined,
identityFileId: undefined,
identityFilePaths: undefined,
...(prev.protocol === "rdp" && identity.domain
? { rdpConfig: { ...(prev.rdpConfig ?? {}), domain: identity.domain } }
: {}),
...(prev.protocol === "rdp"
? {
rdpConfig: {
...(prev.rdpConfig ?? {}),
identityId: undefined,
...(identity.domain ? { domain: identity.domain } : {}),
},
}
: prev.protocol === "vnc" && prev.vncConfig?.identityId !== undefined
? { vncConfig: { ...prev.vncConfig, identityId: undefined } }
: {}),
}));
setPendingReferenceKeyPath(null);
setSelectedCredentialType(null);
@@ -1338,9 +1440,46 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const clearIdentity = useCallback(() => {
setForm((prev) => detachEffectiveHostIdentity(prev, effectiveAuth.username));
const effectiveDetachUsername =
selectedIdentity?.username
|| (form.protocol === "rdp"
? effectiveAuthHost.rdpConfig?.username
: form.protocol === "vnc"
? effectiveAuthHost.vncConfig?.username
: undefined)
|| effectiveAuth.username;
setForm((prev) => {
const detached = detachEffectiveHostIdentity(prev, effectiveDetachUsername);
if (prev.protocol === "rdp") {
const nextDomain = prev.rdpConfig?.domain || selectedIdentity?.domain;
if (prev.rdpConfig?.identityId !== undefined || (nextDomain && !prev.rdpConfig?.domain)) {
return {
...detached,
rdpConfig: {
...(prev.rdpConfig ?? {}),
identityId: undefined,
...(nextDomain ? { domain: nextDomain } : {}),
},
};
}
}
if (prev.protocol === "vnc" && prev.vncConfig?.identityId !== undefined) {
return {
...detached,
vncConfig: { ...prev.vncConfig, identityId: undefined },
};
}
return detached;
});
setIdentitySuggestionsOpen(false);
}, [effectiveAuth.username]);
}, [
effectiveAuth.username,
effectiveAuthHost.rdpConfig?.username,
effectiveAuthHost.vncConfig?.username,
form.protocol,
selectedIdentity?.domain,
selectedIdentity?.username,
]);
const updateTelnetIdentity = useCallback((identityId: string) => {
setForm((prev) => ({
@@ -1626,12 +1765,14 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
t={t}
form={form}
setForm={setForm}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
totpFlushRef={totpFlushRef}
update={update}
groupDefaults={effectiveGroupDefaults}
effectiveAuthMethod={effectiveAuthMethod}
effectiveUsername={effectiveAuth.username}
effectiveIdentityId={effectiveAuthHost.identityId}
effectiveIdentityId={effectiveIdentityId}
selectedIdentity={selectedIdentity}
clearIdentity={clearIdentity}
identities={identities}
@@ -1689,8 +1830,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
{isRemoteDesktopPrimary && isCurrentTabEnabled && (activeProtocolTab === "rdp" || activeProtocolTab === "vnc") ? (
<RemoteDesktopOptionsSection
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
form={form}
setForm={setForm}
groupDefaults={effectiveGroupDefaults}
t={t}
/>
) : null}
+76 -1
View File
@@ -126,10 +126,85 @@ test("LogView renders clean non-terminal metadata card for unrecorded VNC/RDP se
assert.doesNotMatch(markup, /Appearance/);
});
test("LogView memo comparator checks recordingId and recordingBytes", () => {
test("LogView memo comparator checks recordingId, recordings, remoteDesktopEvents, and recordingBytes", () => {
const source = readFileSync(new URL("./LogView.tsx", import.meta.url), "utf8");
const comparator = source.match(/const logViewAreEqual[\s\S]*?^};/m)?.[0] ?? "";
assert.ok(comparator, "expected logViewAreEqual in LogView.tsx");
assert.match(comparator, /prev\.log\.recordingId === next\.log\.recordingId/);
assert.match(comparator, /prev\.log\.recordingBytes === next\.log\.recordingBytes/);
assert.match(comparator, /prev\.log\.recordings === next\.log\.recordings/);
assert.match(comparator, /prev\.log\.remoteDesktopEvents === next\.log\.remoteDesktopEvents/);
});
test("LogView renders multi-clip strip and video-linked session timeline with seek chips", () => {
const log: ConnectionLog = {
id: "log-multi",
sessionId: "sess-rdp-multi",
hostId: "h-1",
hostLabel: "Windows Multi",
hostname: "10.0.0.11",
username: "Administrator",
protocol: "rdp",
startTime: 1_700_000_000_000,
endTime: 1_700_000_180_000,
localUsername: "alice",
localHostname: "macbook",
saved: true,
recordingId: "22222222-2222-4222-8222-222222222222",
recordings: [
{
id: "11111111-1111-4111-8111-111111111111",
startedAt: 1_700_000_010_000,
endedAt: 1_700_000_040_000,
durationMs: 30_000,
bytes: 1_048_576,
mimeType: "video/webm;codecs=vp9",
hasAudio: false,
width: 1920,
height: 1080,
},
{
id: "22222222-2222-4222-8222-222222222222",
startedAt: 1_700_000_060_000,
endedAt: 1_700_000_120_000,
durationMs: 60_000,
bytes: 2_097_152,
mimeType: "video/webm;codecs=vp9,opus",
hasAudio: true,
width: 1920,
height: 1080,
},
],
remoteDesktopMeta: {
resolution: { width: 1920, height: 1080 },
securityLabel: "TLS / NLA",
tunneled: true,
},
remoteDesktopEvents: [
{
id: "ev-1",
timestamp: 1_700_000_075_000,
kind: "clipboard_download",
summary: "Downloaded report.pdf",
detail: "1.2 MB",
},
],
};
const markup = renderWithI18n(
React.createElement(LogView, {
log,
defaultTerminalTheme: defaultTheme,
defaultFontSize: 13,
isVisible: true,
onClose: () => {},
onUpdateLog: () => {},
}),
);
assert.match(markup, /data-testid="log-view-clip-strip"/);
assert.match(markup, /data-testid="log-view-timeline-drawer"/);
assert.match(markup, /Downloaded report\.pdf/);
assert.match(markup, /data-seek-seconds="15"/);
assert.match(markup, /TLS \/ NLA/);
});
+669 -192
View File
File diff suppressed because it is too large. Load diff
+20 -2
View File
@@ -61,12 +61,23 @@ test("QuickAddSnippetDialog blocks shortkey recording while app lock overlay is
Object.defineProperty(globalThis, "DocumentFragment", { value: dom.window.DocumentFragment, configurable: true });
Object.defineProperty(globalThis, "MutationObserver", { value: dom.window.MutationObserver, configurable: true });
Object.defineProperty(globalThis, "getComputedStyle", { value: dom.window.getComputedStyle.bind(dom.window), configurable: true });
const pendingRafIds = new Set<ReturnType<typeof setTimeout>>();
Object.defineProperty(globalThis, "requestAnimationFrame", {
value: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
value: (cb: FrameRequestCallback) => {
const id = setTimeout(() => {
pendingRafIds.delete(id);
cb(Date.now());
}, 0);
pendingRafIds.add(id);
return id;
},
configurable: true,
});
Object.defineProperty(globalThis, "cancelAnimationFrame", {
value: (id: number) => clearTimeout(id),
value: (id: ReturnType<typeof setTimeout>) => {
pendingRafIds.delete(id);
clearTimeout(id);
},
configurable: true,
});
@@ -142,6 +153,13 @@ test("QuickAddSnippetDialog blocks shortkey recording while app lock overlay is
await act(async () => {
root?.unmount();
});
// Radix FocusScope dispatches its unmount autofocus CustomEvent in a 0ms setTimeout;
// flush it before restoring globalThis.CustomEvent and closing the JSDOM window.
await new Promise((resolve) => setTimeout(resolve, 0));
for (const id of pendingRafIds) {
clearTimeout(id);
}
pendingRafIds.clear();
env.IS_REACT_ACT_ENVIRONMENT = prevAct;
Object.defineProperty(globalThis, "window", { value: prevWindow, configurable: true });
Object.defineProperty(globalThis, "document", { value: prevDocument, configurable: true });
+15 -7
View File
@@ -24,6 +24,7 @@ import {
isVncProtocol,
} from "../domain/remoteDesktop";
import { matchesSearchQuery } from "../domain/searchMatcher";
import { usePinyinMatcherVersion } from "../application/state/usePinyinMatcherVersion";
import { getProtocolBadgeClass } from "./protocolVisuals";
import { buildQuickSwitcherShells, useDiscoveredShells, getShellIconPath, isMonochromeShellIcon } from "../lib/useDiscoveredShells";
import { usePluginContributions } from "../application/state/usePluginContributions";
@@ -214,7 +215,9 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
)
), [discoveredShells, terminalSettings?.localShell, terminalSettings?.localShellArgs]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredShells = useMemo(() => {
void pinyinMatcherVersion;
const list = !query.trim()
? quickSwitcherShells
: quickSwitcherShells.filter(
@@ -222,7 +225,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
);
// Default shell first
return [...list].sort((a, b) => (a.isDefault === b.isDefault ? 0 : a.isDefault ? -1 : 1));
}, [quickSwitcherShells, query]);
}, [quickSwitcherShells, query, pinyinMatcherVersion]);
// Get hotkey display strings
const getHotkeyLabel = useCallback((actionId: string) => {
@@ -302,6 +305,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
return matched;
}, [showSftpTab, trimmedQuery]);
const filteredOrphanSessions = useMemo(() => {
void pinyinMatcherVersion;
if (!trimmedQuery) return orphanSessions;
return orphanSessions.filter((session) =>
matchesSearchQuery(
@@ -311,18 +315,22 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
session.id,
),
);
}, [orphanSessions, trimmedQuery]);
}, [orphanSessions, trimmedQuery, pinyinMatcherVersion]);
const filteredWorkspaces = useMemo(() => {
void pinyinMatcherVersion;
if (!trimmedQuery) return workspaces;
return workspaces.filter((workspace) =>
matchesSearchQuery(trimmedQuery, workspace.title, workspace.id),
);
}, [trimmedQuery, workspaces]);
}, [trimmedQuery, workspaces, pinyinMatcherVersion]);
const shouldShowLocalTerminalFallback = filteredShells.length === 0 && !!onCreateLocalTerminal && !trimmedQuery;
const pluginPaletteItems = useMemo(() => buildPluginPaletteItems(
pluginContributions.snapshot.plugins,
trimmedQuery,
), [pluginContributions.snapshot.plugins, trimmedQuery]);
const pluginPaletteItems = useMemo(() => {
void pinyinMatcherVersion;
return buildPluginPaletteItems(
pluginContributions.snapshot.plugins,
trimmedQuery,
);
}, [pluginContributions.snapshot.plugins, trimmedQuery, pinyinMatcherVersion]);
const paneMagnificationAction = useMemo(
() => buildPaneMagnificationPaletteAction(paneMagnificationState, t),
[paneMagnificationState, t],
+23 -18
View File
@@ -9,10 +9,11 @@ import {
Search,
Square,
} from 'lucide-react';
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import React, { Suspense, lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { cn } from '../lib/utils';
import { matchesHostSearchQuery, matchesSearchQuery } from '../domain/searchMatcher';
import { useI18n } from '../application/i18n/I18nProvider';
import { usePinyinMatcherVersion } from '../application/state/usePinyinMatcherVersion';
import {
collectSelectableHostIdsInGroup,
getGroupSelectionState,
@@ -21,7 +22,7 @@ import {
import { Host, ProxyProfile, SSHKey } from '../types';
import { ManagedSource } from '../domain/models';
import { DistroAvatar } from './DistroAvatar';
import HostDetailsPanel from './HostDetailsPanel';
const HostDetailsPanel = lazy(() => import('./HostDetailsPanel'));
import { Button } from './ui/button';
import { Input } from './ui/input';
import { SortDropdown, SortMode } from './ui/sort-dropdown';
@@ -186,7 +187,9 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
return groups;
}, [allGroupPaths, currentPath, groupHostCounts]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
let result = selectableHosts;
if (currentPath) {
@@ -227,7 +230,7 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
});
return result;
}, [selectableHosts, currentPath, searchQuery, selectedTags, sortMode]);
}, [selectableHosts, currentPath, searchQuery, selectedTags, sortMode, pinyinMatcherVersion]);
const breadcrumbs = useMemo(() => {
if (!currentPath) return [];
@@ -655,21 +658,23 @@ export const SelectHostPanelContent: React.FC<SelectHostPanelContentProps> = ({
</div>
{showNewHostPanel && onSaveHost ? (
<HostDetailsPanel
initialData={null}
availableKeys={availableKeys}
identities={identities}
proxyProfiles={proxyProfiles}
groups={customGroups}
managedSources={managedSources}
allHosts={hosts}
onSave={(host) => {
onSaveHost(host);
setShowNewHostPanel(false);
}}
onCancel={() => setShowNewHostPanel(false)}
onCreateGroup={onCreateGroup}
/>
<Suspense fallback={null}>
<HostDetailsPanel
initialData={null}
availableKeys={availableKeys}
identities={identities}
proxyProfiles={proxyProfiles}
groups={customGroups}
managedSources={managedSources}
allHosts={hosts}
onSave={(host) => {
onSaveHost(host);
setShowNewHostPanel(false);
}}
onCancel={() => setShowNewHostPanel(false)}
onCreateGroup={onCreateGroup}
/>
</Suspense>
) : null}
</div>
</TooltipProvider>
+101 -10
View File
@@ -227,12 +227,17 @@ import {
} from "./terminal/sftpCwd";
import { useTerminalEffects } from "./terminal/useTerminalEffects";
import { useTerminalHibernateEffect } from "./terminal/useTerminalHibernateEffect";
import { readActiveTerminalBufferTextRange } from "./terminal/terminalContextBuffer";
import {
readActiveTerminalBufferTextRange,
readCursorLogicalTailForReadiness,
} from "./terminal/terminalContextBuffer";
import {
applyAuthoritativeHibernateSnapshot,
appendHibernatePendingBuffer,
compressHibernateSnapshot,
isTerminalAlternateScreenActive,
readTerminalHibernateContext,
resolveHibernateWakeHistoryAsync,
resolveTerminalSnapshotCapture,
serializeTerminalForHibernate,
} from "./terminal/terminalHibernateRuntime";
@@ -534,6 +539,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const softHiddenRef = useRef(false);
const hasRuntimeRef = useRef(false);
const hibernateSnapshotRef = useRef("");
const hibernateCompressedSnapshotRef = useRef<Uint8Array | null>(null);
const hibernateCompressionGenRef = useRef(0);
const hibernateViewportSnapshotRef = useRef("");
const hibernateScrollbackSnapshotRef = useRef("");
const hibernateContextSnapshotRef = useRef("");
@@ -781,6 +788,10 @@ const TerminalComponent: React.FC<TerminalProps> = ({
viewportY?: number;
};
const totalLines = Math.max(0, activeBuffer.length);
const includeReadinessContext = request.includeReadinessContext === true;
const cursorTail = includeReadinessContext
? readCursorLogicalTailForReadiness(term)
: null;
const viewportStartLine = alternateScreen
? 0
: Math.max(0, activeBuffer.viewportY ?? Math.max(0, totalLines - term.rows));
@@ -819,6 +830,13 @@ const TerminalComponent: React.FC<TerminalProps> = ({
hasMoreAfter: lineWindow.endLine >= 0 && lineWindow.endLine < totalLines - 1,
source: 'live',
alternateScreen,
...(cursorTail
? {
...(cursorTail.cursorLine !== undefined ? { cursorLine: cursorTail.cursorLine } : {}),
cursorAtLineEnd: cursorTail.cursorAtLineEnd,
readinessContext: alternateScreen ? '' : cursorTail.text,
}
: {}),
};
}
@@ -1773,8 +1791,16 @@ const TerminalComponent: React.FC<TerminalProps> = ({
snapshot = serializeAddonRef.current.serialize() || "";
} else if (hibernatedRef.current || softHiddenRef.current) {
// Hibernate path: live xterm is torn down; use retained snapshot.
const retainedHistory = await resolveHibernateWakeHistoryAsync({
snapshot: hibernateSnapshotRef.current,
compressedSnapshot: hibernateCompressedSnapshotRef.current,
viewportSnapshot: hibernateViewportSnapshotRef.current,
scrollbackSnapshot: hibernateScrollbackSnapshotRef.current,
pendingBuffer: "",
alternateScreen: hibernateAlternateScreenRef.current,
});
snapshot = [
hibernateSnapshotRef.current || "",
retainedHistory || "",
hibernatePendingBufferRef.current || "",
].join("");
}
@@ -1872,6 +1898,10 @@ const TerminalComponent: React.FC<TerminalProps> = ({
xtermRuntimeRef.current?.cursorLineHighlighter.refresh({ force: true });
try { term.scrollToBottom?.(); } catch { /* ignore */ }
} else if (hibernatedRef.current || softHiddenRef.current) {
if (typeof hibernateCompressedSnapshotRef !== "undefined") {
hibernateCompressionGenRef.current += 1;
hibernateCompressedSnapshotRef.current = null;
}
applyAuthoritativeHibernateSnapshot({
snapshot: hibernateSnapshotRef,
viewportSnapshot: hibernateViewportSnapshotRef,
@@ -2101,6 +2131,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
hibernatedRef.current = false;
softHiddenRef.current = false;
hibernateSnapshotRef.current = "";
hibernateCompressionGenRef.current += 1;
hibernateCompressedSnapshotRef.current = null;
hibernateViewportSnapshotRef.current = "";
hibernateScrollbackSnapshotRef.current = "";
hibernateContextSnapshotRef.current = "";
@@ -2114,9 +2146,28 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const forceCloseHibernatedSession = useCallback(() => {
let pendingCapture: void | Promise<void>;
if (!terminalDataCapturedRef.current) {
const hibernatedData = hibernateSnapshotRef.current + hibernatePendingBufferRef.current;
if (hibernatedData) {
pendingCapture = handleTerminalDataCaptureOnce(sessionId, hibernatedData);
const compressed = hibernateCompressedSnapshotRef.current;
const pending = hibernatePendingBufferRef.current;
if (compressed && compressed.byteLength > 0 && !hibernateSnapshotRef.current) {
const snapshotPayload = {
snapshot: "",
compressedSnapshot: compressed,
viewportSnapshot: hibernateViewportSnapshotRef.current,
scrollbackSnapshot: hibernateScrollbackSnapshotRef.current,
pendingBuffer: "",
alternateScreen: hibernateAlternateScreenRef.current,
};
pendingCapture = resolveHibernateWakeHistoryAsync(snapshotPayload).then((history) => {
const hibernatedData = history + pending;
if (hibernatedData) {
return handleTerminalDataCaptureOnce(sessionId, hibernatedData);
}
});
} else {
const hibernatedData = hibernateSnapshotRef.current + pending;
if (hibernatedData) {
pendingCapture = handleTerminalDataCaptureOnce(sessionId, hibernatedData);
}
}
}
disposeDataRef.current?.();
@@ -2310,6 +2361,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const applyHibernateSnapshot = useCallback((
snapshot: {
snapshot: string;
compressedSnapshot?: Uint8Array | null;
viewportSnapshot: string;
scrollbackSnapshot: string;
contextSnapshot?: string;
@@ -2318,12 +2370,29 @@ const TerminalComponent: React.FC<TerminalProps> = ({
alternateScreen: boolean;
},
) => {
hibernateSnapshotRef.current = snapshot.snapshot;
hibernateCompressionGenRef.current += 1;
if (snapshot.compressedSnapshot && snapshot.compressedSnapshot.byteLength > 0) {
hibernateCompressedSnapshotRef.current = snapshot.compressedSnapshot;
hibernateSnapshotRef.current = "";
hibernateScrollbackSnapshotRef.current = "";
} else {
hibernateCompressedSnapshotRef.current = null;
hibernateSnapshotRef.current = snapshot.snapshot;
hibernateScrollbackSnapshotRef.current = snapshot.snapshot ? "" : snapshot.scrollbackSnapshot;
}
hibernateViewportSnapshotRef.current = snapshot.viewportSnapshot;
hibernateScrollbackSnapshotRef.current = snapshot.scrollbackSnapshot;
hibernateContextSnapshotRef.current = snapshot.contextSnapshot ?? "";
hibernateContextViewportSnapshotRef.current = snapshot.contextViewportSnapshot ?? "";
hibernateContextScrollbackSnapshotRef.current = snapshot.contextScrollbackSnapshot ?? "";
const contextViewport = snapshot.contextViewportSnapshot ?? "";
const contextScrollback = snapshot.contextScrollbackSnapshot ?? "";
const contextFull = snapshot.contextSnapshot ?? "";
// Avoid retaining a duplicate full-scrollback plain-text string when
// buildTerminalContextSnapshotText already reconstructs it from scrollback + viewport.
const isRedundantFullContext =
Boolean(contextScrollback)
&& Boolean(contextViewport)
&& contextFull === `${contextScrollback}\n${contextViewport}`;
hibernateContextSnapshotRef.current = isRedundantFullContext ? "" : contextFull;
hibernateContextViewportSnapshotRef.current = contextViewport;
hibernateContextScrollbackSnapshotRef.current = contextScrollback;
hibernateAlternateScreenRef.current = snapshot.alternateScreen;
}, []);
@@ -2403,6 +2472,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
preferWasm: resolveHibernatePreferWasmSerialize(terminalSettingsRef.current),
prepare: () => xtermRuntimeRef.current?.keywordHighlighter.prepareForSerialization()
?? Promise.resolve(),
compress: false,
},
);
@@ -2414,6 +2484,8 @@ const TerminalComponent: React.FC<TerminalProps> = ({
}
applyHibernateSnapshot(snapshot);
const compressionGen = hibernateCompressionGenRef.current;
const rawSnapshotToCompress = hibernateSnapshotRef.current;
isBootActiveRef.current = false;
const connectedBackendId = hibernateStatus === "connected" ? backendId : null;
if (connectedBackendId) {
@@ -2428,6 +2500,22 @@ const TerminalComponent: React.FC<TerminalProps> = ({
beginHibernatedSessionListeners(connectedBackendId);
}
hibernatedRef.current = true;
// Compress the retained snapshot only after the live runtime is detached
// and incoming output is safely routed to hibernatePendingBufferRef.
if (rawSnapshotToCompress) {
void compressHibernateSnapshot(rawSnapshotToCompress).then((compressed) => {
if (
compressed
&& compressed.byteLength > 0
&& hibernatedRef.current
&& hibernateCompressionGenRef.current === compressionGen
&& hibernateSnapshotRef.current === rawSnapshotToCompress
) {
hibernateCompressedSnapshotRef.current = compressed;
hibernateSnapshotRef.current = "";
}
});
}
// Hibernation rebuilds the autofill controller on wake; drop any open
// picker so it cannot stay visible against a non-pending controller.
setPasswordPickerState(null);
@@ -4920,6 +5008,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
const getPayload = (): TerminalHibernateWakePayload => ({
snapshot: hibernateSnapshotRef.current,
compressedSnapshot: hibernateCompressedSnapshotRef.current,
viewportSnapshot: hibernateViewportSnapshotRef.current || hibernateSnapshotRef.current,
scrollbackSnapshot: hibernateScrollbackSnapshotRef.current,
pendingBuffer: hibernatePendingBufferRef.current,
@@ -4930,6 +5019,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
sessionId,
sessionConnected,
snapshotChars: hibernateSnapshotRef.current.length,
compressedBytes: hibernateCompressedSnapshotRef.current?.byteLength ?? 0,
viewportChars: hibernateViewportSnapshotRef.current.length,
scrollbackChars: hibernateScrollbackSnapshotRef.current.length,
pendingChars: hibernatePendingBufferRef.current.length,
@@ -4975,6 +5065,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
softHiddenRef,
hibernatePendingBufferRef,
hibernateSnapshotRef,
hibernateCompressedSnapshotRef,
hibernateViewportSnapshotRef,
hibernateScrollbackSnapshotRef,
hibernateContextSnapshotRef,
+4 -2
View File
@@ -64,7 +64,7 @@ import { useI18n } from '../application/i18n/I18nProvider';
import { SftpSidePanel } from './SftpSidePanel';
import { ScriptsSidePanel } from './ScriptsSidePanel';
import { HistorySidePanel } from './HistorySidePanel';
import { NotesManager } from './notes/NotesManager';
import { LazyNotesManager as NotesManager } from './notes/LazyNotesManager';
import { terminalCwdStore } from '../application/state/terminalCwdStore';
import { resolveSnippetCommand } from './SnippetExecutionProvider';
import type { Snippet } from '../types';
@@ -448,7 +448,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const promptHostnameSignalController = useMemo(
() => createPromptHostnameSessionSignalController({
getSession: (sessionId) => sessionsRef.current.find((session) => session.id === sessionId),
onChange: (sessionId, hostname) => onUpdateSessionPromptHost?.(sessionId, hostname),
onChange: (sessionId, hostname, options) => {
onUpdateSessionPromptHost?.(sessionId, hostname, options);
},
}),
[onUpdateSessionPromptHost],
);
+68 -1
View File
@@ -14,10 +14,15 @@ import { upsertKnownHost } from '../domain/knownHosts';
import { isPluginHostProtocol, sanitizePluginConnection } from '../domain/pluginConnection';
import {
isRemoteDesktopProtocol,
resolveRemoteDesktopConnectionSpec,
sanitizeRdpConfig,
sanitizeVncConfig,
type RemoteDesktopProtocol,
} from '../domain/remoteDesktop';
import { selectConnectionLogForTerminalDataCapture } from '../domain/connectionLog';
import { getConnectionLogsSnapshot } from '../application/state/connectionLogsStore';
import { getSystemUserHostInfo } from '../application/state/remoteDesktopLogActions';
import { captureClosingTerminalSessions } from '../application/state/terminalSessionCloseCapture';
import type { ResolveDefaultLocalShellContext } from '../domain/localShellHost';
import {
resolveEffectiveTerminalHost,
@@ -362,6 +367,8 @@ function TerminalPopupPageInner({
snippets,
snippetPackages,
groupConfigs,
addConnectionLog,
updateConnectionLog,
updateKnownHosts,
deleteSelectedSnippets,
} = useVaultState({ syncConnectionLogTerminalData: false });
@@ -397,6 +404,8 @@ function TerminalPopupPageInner({
}
await markAttachClosePrepared(attachSessionId, attachAuthorization);
} catch { /* The main-process close handshake owns the final fallback. */ }
} else {
captureClosingTerminalSessions([sessionId]);
}
await close();
})();
@@ -406,7 +415,7 @@ function TerminalPopupPageInner({
};
void closePromise.then(clearClosePromise, clearClosePromise);
return closePromise;
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared]);
}, [attachAuthorization, attachSessionId, close, isAttachMode, markAttachClosePrepared, sessionId]);
const effectiveKnownHosts = useMemo(
() => getEffectiveKnownHosts(knownHosts) ?? [],
[knownHosts],
@@ -486,6 +495,63 @@ function TerminalPopupPageInner({
if (readyToStart) setSessionStarted(true);
}, [readyToStart]);
const ready = sessionStarted || readyToStart;
const popupRemoteDesktopLogCreatedRef = React.useRef<string | null>(null);
useEffect(() => {
if (!ready || !host || !remoteDesktopProtocol) return;
if (popupRemoteDesktopLogCreatedRef.current === sessionId) return;
popupRemoteDesktopLogCreatedRef.current = sessionId;
const existingLog = selectConnectionLogForTerminalDataCapture(
[...getConnectionLogsSnapshot().connectionLogs],
{ sessionId },
);
if (existingLog) return;
const spec = resolveRemoteDesktopConnectionSpec(host, remoteDesktopProtocol, identities);
// Create the ConnectionLog synchronously before RemoteDesktopPane connects
// so early connected/error events are never dropped, then enrich local user/host.
addConnectionLog({
sessionId,
hostId: host.id,
hostLabel: spec.isCompanion ? `${spec.label} (${remoteDesktopProtocol.toUpperCase()})` : spec.label,
hostname: spec.hostHostname,
username: spec.username,
protocol: remoteDesktopProtocol,
startTime: Date.now(),
localUsername: 'user',
localHostname: 'localhost',
saved: false,
});
let cancelled = false;
void getSystemUserHostInfo().then((info) => {
if (cancelled) return;
const log = selectConnectionLogForTerminalDataCapture(
[...getConnectionLogsSnapshot().connectionLogs],
{ sessionId },
);
if (log && (info.username !== 'user' || info.hostname !== 'localhost')) {
void updateConnectionLog(log.id, {
localUsername: info.username,
localHostname: info.hostname,
});
}
});
return () => {
cancelled = true;
};
}, [addConnectionLog, host, identities, ready, remoteDesktopProtocol, sessionId, updateConnectionLog]);
const handlePopupRemoteDesktopCloseCapture = useCallback(
async (closingSessionId: string) => {
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture([...connectionLogs], {
sessionId: closingSessionId,
});
if (matchingLog) {
await updateConnectionLog(matchingLog.id, { endTime: Date.now() });
}
},
[updateConnectionLog],
);
const startupRevealDelayMs = useMemo(() => {
// Attach mode shows the live session immediately (no startup command).
if (isAttachMode) return 0;
@@ -562,6 +628,7 @@ function TerminalPopupPageInner({
knownHosts={effectiveKnownHosts}
isVisible
isFocused
onTerminalDataCapture={handlePopupRemoteDesktopCloseCapture}
onCloseSession={() => {
void handleClose();
}}
+13
View File
@@ -44,6 +44,7 @@ const {
} = await import("./top-tabs/TopTabItems.tsx");
const { activeTabStore } = await import("../application/state/activeTabStore.ts");
const {
applySessionPresentation,
publishSessionPromptHost,
sessionPresentationStore,
} = await import("../application/state/sessionPresentationStore.ts");
@@ -144,6 +145,18 @@ test("workspace tabs keep explicit names ahead of live prompt hosts", () => {
sessionPresentationStore.clearSession("s1");
});
test("agent-mode session tabs show a published jump target host", () => {
const session = topTabSession("jump-target", "jump-host", {
customName: "",
hostLabel: "jumpssh.riverbegin.cn",
promptHostname: "",
promptHostnameFromJumpServer: undefined,
});
publishSessionPromptHost("jump-target", "k8s-10-1-64-1", { fromJumpServer: true });
assert.equal(formatSessionTopTabLabel(applySessionPresentation(session), "agent"), "k8s-10-1-64-1");
sessionPresentationStore.clearSession("jump-target");
});
test("host tree tab gutter never goes negative", () => {
assert.equal(computeHostTreeTabGutter(120, 280), 0);
});
+13 -9
View File
@@ -61,7 +61,6 @@ import type {
VaultGroupMutationState,
} from "../domain/vaultGroupMutation";
import type { PluginImporterCommitRequest } from "../application/state/usePluginImporterCommit";
import { buildVaultCsvCredentialOptions } from "../application/vaultCsvExportCredentials";
import { sanitizeCredentialValue } from "../domain/credentials";
import {
resolveGroupDefaults,
@@ -81,7 +80,6 @@ import {
buildHostForProtocolOverride,
shouldPromptHostProtocolOnConnect,
} from "../domain/remoteDesktop";
import { exportHostsToCsvWithStats } from "../domain/vaultImport";
import { saveWorkSurfaceHostDraft, type WorkSurfaceHostEditorTarget } from "../application/state/useWorkSurfaceHostEditor";
import { upsertKnownHost } from "../domain/knownHosts";
import {
@@ -117,19 +115,13 @@ import {
import { AppLogo } from "./AppLogo";
import { connectHostsStaggered } from "./connectHostsStaggered";
import { DistroAvatar } from "./DistroAvatar";
import GroupDetailsPanel from "./GroupDetailsPanel";
import { getVaultHostGridColumnCount } from "./vault/vaultHostGridLayout";
import HostDetailsPanel from "./HostDetailsPanel";
import { HostTreeView } from "./HostTreeView";
import QuickConnectWizard from "./QuickConnectWizard";
import {
isQuickConnectInput,
parseQuickConnectInputWithWarnings,
} from "../domain/quickConnect";
import SerialConnectModal from "./SerialConnectModal";
import SerialHostDetailsPanel from "./SerialHostDetailsPanel";
import { NotesManager } from "./notes/NotesManager";
import { ImportVaultDialog } from "./vault/ImportVaultDialog";
import { LazyNotesManager as NotesManager } from "./notes/LazyNotesManager";
import { HostTreeGroupDeleteDialog } from "./host/HostTreeGroupDeleteDialog";
import { useHostTreeInlineGroupActions } from "./vault/useHostTreeInlineGroupActions";
import { useHostTreeInlineHostActions } from "./vault/useHostTreeInlineHostActions";
@@ -170,6 +162,14 @@ import { useVaultImportHandlers } from "../application/state/useVaultImportHandl
import { useVaultGroupDragHandlers } from "./vault/useVaultGroupDragHandlers";
import { usePluginVaultPages } from "../application/state/usePluginVaultPages";
const GroupDetailsPanel = lazy(() => import("./GroupDetailsPanel"));
const HostDetailsPanel = lazy(() => import("./HostDetailsPanel"));
const QuickConnectWizard = lazy(() => import("./QuickConnectWizard"));
const SerialConnectModal = lazy(() => import("./SerialConnectModal"));
const SerialHostDetailsPanel = lazy(() => import("./SerialHostDetailsPanel"));
const ImportVaultDialog = lazy(() =>
import("./vault/ImportVaultDialog").then((mod) => ({ default: mod.ImportVaultDialog })),
);
const LazyProtocolSelectDialog = lazy(() => import("./ProtocolSelectDialog"));
const LazyConnectionLogsManager = lazy(() => import("./ConnectionLogsManager"));
const KeychainManager = lazy(() => import("./KeychainManager"));
@@ -839,6 +839,10 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
return;
}
const [{ buildVaultCsvCredentialOptions }, { exportHostsToCsvWithStats }] = await Promise.all([
import("../application/vaultCsvExportCredentials"),
import("../domain/vaultImport"),
]);
const {
keyPathsById,
keyPassphrasesById,
+10 -1
View File
@@ -1,12 +1,13 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import type { HTMLAttributes } from 'react';
import { cn } from '../../lib/utils';
import { Check, ChevronDown, ChevronRight, CheckCircle2, Copy, Loader2, ShieldAlert, X, XCircle, Slash } from 'lucide-react';
import { Check, ChevronDown, ChevronRight, CheckCircle2, Copy, Loader2, Monitor, MousePointerClick, ShieldAlert, X, XCircle, Slash } from 'lucide-react';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
import { useI18n } from '../../application/i18n/I18nProvider';
import { cancelApprovalTimeout } from '../../infrastructure/ai/shared/approvalGate';
import { extractRemoteDesktopPendingLabel } from '../ai/toolArtifacts/remoteDesktopToolArtifact';
export const MAX_TOOL_COMMAND_TOOLTIP_CHARS = 240;
/** Collapsed approval command block max height (px). Full text remains scrollable. */
@@ -466,6 +467,7 @@ export const ToolCall = ({
) : null;
const headerCommand = reviewCommand ?? liveDisplayCommand;
const remoteDesktopPending = !headerCommand ? extractRemoteDesktopPendingLabel(name, args) : null;
return (
<div
@@ -504,6 +506,13 @@ export const ToolCall = ({
{truncateToolCommandTooltip(headerCommand)}
</TooltipContent>
</Tooltip>
) : remoteDesktopPending ? (
<span className="inline-flex min-w-0 items-center gap-1.5 text-foreground/80 truncate">
{remoteDesktopPending.kind === 'screen'
? <Monitor size={12} className="shrink-0 text-sky-400" />
: <MousePointerClick size={12} className="shrink-0 text-violet-400" />}
<span className="truncate font-medium">{remoteDesktopPending.label}</span>
</span>
) : (
<span className="font-mono text-muted-foreground/70 truncate">{name}</span>
)}
+1 -1
View File
@@ -671,7 +671,7 @@ test('ChatMessageList renders a non-error iteration limit notice with a Continue
assert.match(source, /onClick=\{onContinue\}/);
assert.match(panel, /onContinue=\{handleContinue\}/);
assert.match(panel, /handleContinue = React.useCallback\(\(\) => handleSend\(t\('ai.chat.continue'\)\)/);
assert.match(sidePanel, /const handleSend = useCallback\(async \(textOverride\?: string\)/);
assert.match(sidePanel, /const handleSend = useCallback\(async \(\s*textOverride\?: string/);
assert.match(sidePanel, /const trimmed = \(textOverride \?\? draft\?\.text \?\? ''\)\.trim\(\)/);
});
+21
View File
@@ -30,6 +30,8 @@ import {
VaultArtifactNavigationProvider,
type VaultArtifactNavSection,
} from './toolArtifacts/VaultArtifactNavigationContext';
import { parseRemoteDesktopToolArtifact } from './toolArtifacts/remoteDesktopToolArtifact';
import { RemoteDesktopArtifactToolResult } from './toolArtifacts/RemoteDesktopArtifactToolResult';
import { parseTerminalToolArtifact } from './toolArtifacts/terminalToolArtifact';
import { TerminalArtifactToolResult } from './toolArtifacts/TerminalArtifactToolResult';
import {
@@ -619,6 +621,25 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
const renderToolResultItem = (item: typeof toolResults[number]) => {
const artifactToolName = item.artifactToolName ?? item.name;
const remoteDesktopArtifact = parseRemoteDesktopToolArtifact(
artifactToolName,
item.content,
item.args,
item.isError,
);
if (remoteDesktopArtifact) {
return (
<RemoteDesktopArtifactToolResult
key={item.toolCallId}
artifact={remoteDesktopArtifact}
toolName={artifactToolName}
args={item.args}
result={item.content}
isError={item.isError}
onOpenImagePreview={openPreview}
/>
);
}
const terminalArtifact = parseTerminalToolArtifact(artifactToolName, item.content);
if (terminalArtifact) {
return (
+20 -16
View File
@@ -4,8 +4,10 @@
* even when the Catty AI side panel has never been opened.
*/
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ToolCall } from '../ai-elements/tool-call';
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
const ToolCall = lazy(() =>
import('../ai-elements/tool-call').then((mod) => ({ default: mod.ToolCall })),
);
import { Button } from '../ui/button';
import {
onApprovalCleared,
@@ -153,20 +155,22 @@ export const ExternalMcpApprovalsHost: React.FC = () => {
<div className="space-y-2">
{entries.map(([id, req]) => (
<div key={id} className="space-y-1.5">
<ToolCall
name={externalMcpApprovalToolLabel(req.toolName)}
args={req.args}
approvalTarget={req.target}
isLoading={false}
isInterrupted={false}
approvalStatus="pending"
approvalId={id}
onApproveOnce={() => handleApproveOnce(id)}
onAlwaysAllow={req.target && !req.target.hostId ? undefined : () => handleAlwaysAllow(id, req)}
onReject={() => handleReject(id)}
alwaysAllowLabel={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHost') : undefined}
alwaysAllowTitle={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHostHint') : undefined}
/>
<Suspense fallback={null}>
<ToolCall
name={externalMcpApprovalToolLabel(req.toolName)}
args={req.args}
approvalTarget={req.target}
isLoading={false}
isInterrupted={false}
approvalStatus="pending"
approvalId={id}
onApproveOnce={() => handleApproveOnce(id)}
onAlwaysAllow={req.target && !req.target.hostId ? undefined : () => handleAlwaysAllow(id, req)}
onReject={() => handleReject(id)}
alwaysAllowLabel={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHost') : undefined}
alwaysAllowTitle={req.target?.hostId ? t('ai.externalMcp.allowCommandOnHostHint') : undefined}
/>
</Suspense>
{(req.allowSession || req.target?.hostId) && (
<div className="space-y-1.5">
<div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground/60">
@@ -0,0 +1,109 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { I18nProvider } from '../../../application/i18n/I18nProvider.tsx';
import { RemoteDesktopArtifactCard } from './RemoteDesktopArtifactCard.tsx';
test('RemoteDesktopArtifactCard renders remote_desktop_act summary card', () => {
const html = renderToStaticMarkup(
<I18nProvider locale="en">
<RemoteDesktopArtifactCard
artifact={{
kind: 'remoteDesktop.act',
sessionId: 'rdp-1',
protocol: 'rdp',
hostLabel: 'Win11 Dev',
summary: 'Press Escape → Drag (852, 500) → (852, 700)',
completedActions: 2,
totalActions: 2,
durationMs: 410,
actionVisualKind: 'mixed',
}}
/>
</I18nProvider>,
);
assert.match(html, /Press Escape → Drag \(852, 500\) → \(852, 700\)/);
assert.match(html, /Win11 Dev/);
assert.match(html, /RDP/);
assert.match(html, /2 actions/);
assert.match(html, /410ms/);
});
test('RemoteDesktopArtifactCard renders remote_desktop_read_screen card', () => {
const html = renderToStaticMarkup(
<I18nProvider locale="en">
<RemoteDesktopArtifactCard
artifact={{
kind: 'remoteDesktop.screen',
sessionId: 'vnc-1',
protocol: 'vnc',
hostLabel: 'Ubuntu',
width: 1280,
height: 720,
grid: true,
}}
/>
</I18nProvider>,
);
assert.match(html, /Read remote screen \(grid\)/);
assert.match(html, /Ubuntu/);
assert.match(html, /VNC/);
assert.match(html, /1280×720/);
});
test('RemoteDesktopArtifactCard renders user-preempted and error states distinctly', () => {
const preemptedHtml = renderToStaticMarkup(
<I18nProvider locale="en">
<RemoteDesktopArtifactCard
artifact={{
kind: 'error',
toolKind: 'act',
code: 'USER_PREEMPTED',
message: 'User interacted with the remote desktop.',
}}
/>
</I18nProvider>,
);
assert.match(preemptedHtml, /Remote action paused by user/);
assert.match(preemptedHtml, /border-amber-500/);
const errorHtml = renderToStaticMarkup(
<I18nProvider locale="en">
<RemoteDesktopArtifactCard
artifact={{
kind: 'error',
toolKind: 'screen',
message: 'Session disconnected.',
}}
/>
</I18nProvider>,
);
assert.match(errorHtml, /Remote screen capture failed/);
assert.match(errorHtml, /border-destructive/);
});
test('RemoteDesktopArtifactCard forwards Radix TooltipTrigger DOM props to the root element', () => {
const html = renderToStaticMarkup(
<I18nProvider locale="en">
<RemoteDesktopArtifactCard
artifact={{
kind: 'remoteDesktop.act',
sessionId: 'rdp-1',
summary: 'Click (100, 200)',
completedActions: 1,
totalActions: 1,
actionVisualKind: 'click',
}}
data-state="closed"
aria-describedby="tooltip-1"
/>
</I18nProvider>,
);
assert.match(html, /data-state="closed"/);
assert.match(html, /aria-describedby="tooltip-1"/);
});
@@ -0,0 +1,243 @@
import {
AlertCircle,
CheckCircle2,
ChevronsUpDown,
Hand,
Keyboard,
Monitor,
MonitorCog,
MousePointerClick,
Move,
ScanSearch,
Timer,
} from 'lucide-react';
import React from 'react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { getCapturedRemoteDesktopFrame } from '../../../infrastructure/remoteDesktop/remoteDesktopSnapshotRegistry';
import { cn } from '../../../lib/utils';
import type {
RemoteDesktopActionVisualKind,
RemoteDesktopToolArtifact,
} from './remoteDesktopToolArtifact';
interface RemoteDesktopArtifactCardProps extends React.HTMLAttributes<HTMLDivElement> {
artifact: RemoteDesktopToolArtifact;
onOpenImagePreview?: (src: string, name: string) => void;
className?: string;
}
const ACTION_ICON_SIZE = 16;
const ACTION_VISUAL_STYLES: Record<RemoteDesktopActionVisualKind, { wrapper: string; icon: string }> = {
click: { wrapper: 'bg-violet-500/12', icon: 'text-violet-400' },
drag: { wrapper: 'bg-violet-500/12', icon: 'text-violet-400' },
scroll: { wrapper: 'bg-cyan-500/12', icon: 'text-cyan-400' },
keyboard: { wrapper: 'bg-amber-500/12', icon: 'text-amber-400' },
wait: { wrapper: 'bg-muted/30', icon: 'text-muted-foreground/70' },
mixed: { wrapper: 'bg-violet-500/12', icon: 'text-violet-400' },
};
function renderActionIcon(kind: RemoteDesktopActionVisualKind): React.ReactNode {
const iconClass = ACTION_VISUAL_STYLES[kind].icon;
switch (kind) {
case 'click':
return <MousePointerClick size={ACTION_ICON_SIZE} className={iconClass} />;
case 'drag':
return <Move size={ACTION_ICON_SIZE} className={iconClass} />;
case 'scroll':
return <ChevronsUpDown size={ACTION_ICON_SIZE} className={iconClass} />;
case 'keyboard':
return <Keyboard size={ACTION_ICON_SIZE} className={iconClass} />;
case 'wait':
return <Timer size={ACTION_ICON_SIZE} className={iconClass} />;
case 'mixed':
return <MonitorCog size={ACTION_ICON_SIZE} className={iconClass} />;
}
}
function resolveCachedFramePreview(captureId?: string): { thumbSrc: string; fullSrc: string } | null {
if (!captureId) return null;
const frame = getCapturedRemoteDesktopFrame(captureId);
if (!frame || !frame.base64Data) return null;
const fullSrc = `data:${frame.mediaType};base64,${frame.base64Data}`;
const thumbSrc = frame.previewDataUrl || fullSrc;
return { thumbSrc, fullSrc };
}
export const RemoteDesktopArtifactCard = React.forwardRef<HTMLDivElement, RemoteDesktopArtifactCardProps>(({
artifact,
onOpenImagePreview,
className,
...props
}, ref) => {
const { t } = useI18n();
if (artifact.kind === 'error') {
const isPreempted = artifact.code === 'USER_PREEMPTED';
const errorTitle = isPreempted
? t('ai.chat.artifact.rdActionPreempted')
: artifact.toolKind === 'screen'
? t('ai.chat.artifact.rdScreenFailed')
: t('ai.chat.artifact.rdActionFailed');
return (
<div
{...props}
ref={ref}
className={cn(
'flex w-full items-center gap-2.5 rounded-md border px-2.5 py-2',
isPreempted
? 'border-amber-500/25 bg-amber-500/5'
: 'border-destructive/25 bg-destructive/5',
className,
)}
>
<div
className={cn(
'flex h-8 w-8 shrink-0 items-center justify-center rounded-md',
isPreempted
? 'bg-amber-500/12 text-amber-400'
: 'bg-destructive/10 text-destructive',
)}
>
{isPreempted ? <Hand size={ACTION_ICON_SIZE} /> : <AlertCircle size={ACTION_ICON_SIZE} />}
</div>
<div className="min-w-0 flex-1 text-left">
<div className="truncate text-[12px] font-medium text-foreground/85">
{errorTitle}
</div>
<div className="truncate text-[11px] text-muted-foreground/60">
{artifact.message}
</div>
</div>
</div>
);
}
const cachedPreview = resolveCachedFramePreview(artifact.captureId);
const hostDisplay = artifact.hostLabel || artifact.hostname || artifact.sessionId;
const protocolBadge = artifact.protocol ? artifact.protocol.toUpperCase() : null;
if (artifact.kind === 'remoteDesktop.screen') {
const isCropped = Boolean(artifact.crop);
const title = isCropped
? t('ai.chat.artifact.rdScreenCropped')
: artifact.grid
? t('ai.chat.artifact.rdScreenGrid')
: t('ai.chat.artifact.rdScreenRead');
const subtitleParts = [
hostDisplay,
protocolBadge,
`${artifact.width}×${artifact.height}`,
artifact.crop ? `${artifact.crop.width}×${artifact.crop.height}` : null,
].filter(Boolean);
return (
<div
{...props}
ref={ref}
className={cn(
'flex w-full items-center gap-2.5 rounded-md border border-border/25 bg-muted/10 px-2.5 py-2',
className,
)}
>
<div
className={cn(
'flex h-8 w-8 shrink-0 items-center justify-center rounded-md',
isCropped
? 'bg-indigo-500/12 text-indigo-400'
: 'bg-sky-500/12 text-sky-400',
)}
>
{isCropped ? <ScanSearch size={ACTION_ICON_SIZE} /> : <Monitor size={ACTION_ICON_SIZE} />}
</div>
<div className="min-w-0 flex-1 text-left">
<div className="truncate text-[12px] font-medium text-foreground/85">
{title}
</div>
<div className="truncate text-[11px] text-muted-foreground/60">
{subtitleParts.join(' · ')}
</div>
</div>
{cachedPreview && onOpenImagePreview && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onOpenImagePreview(cachedPreview.fullSrc, `${hostDisplay} (${artifact.width}×${artifact.height})`);
}}
className="shrink-0 overflow-hidden rounded border border-border/35 bg-background/40 hover:opacity-85 transition-opacity cursor-pointer"
title={t('ai.chat.artifact.rdPreviewScreen')}
aria-label={t('ai.chat.artifact.rdPreviewScreen')}
>
<img
src={cachedPreview.thumbSrc}
alt={title}
className="h-7 w-11 object-cover block"
/>
</button>
)}
<CheckCircle2 size={12} className="shrink-0 text-green-400/70" />
</div>
);
}
const title = artifact.summary || t('ai.chat.artifact.rdActionExecuted', { count: artifact.completedActions });
const styles = ACTION_VISUAL_STYLES[artifact.actionVisualKind];
const subtitleParts = [
hostDisplay,
protocolBadge,
artifact.totalActions > 1
? t('ai.chat.artifact.rdActionCount', { count: artifact.completedActions })
: null,
artifact.durationMs != null ? `${artifact.durationMs}ms` : null,
].filter(Boolean);
return (
<div
{...props}
ref={ref}
className={cn(
'flex w-full items-center gap-2.5 rounded-md border border-border/25 bg-muted/10 px-2.5 py-2',
className,
)}
>
<div
className={cn(
'flex h-8 w-8 shrink-0 items-center justify-center rounded-md',
styles.wrapper,
)}
>
{renderActionIcon(artifact.actionVisualKind)}
</div>
<div className="min-w-0 flex-1 text-left">
<div className="truncate text-[12px] font-medium text-foreground/85">
{title}
</div>
<div className="truncate text-[11px] text-muted-foreground/60">
{subtitleParts.join(' · ')}
</div>
</div>
{cachedPreview && onOpenImagePreview && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onOpenImagePreview(cachedPreview.fullSrc, `${hostDisplay} · ${title}`);
}}
className="shrink-0 overflow-hidden rounded border border-border/35 bg-background/40 hover:opacity-85 transition-opacity cursor-pointer"
title={t('ai.chat.artifact.rdPreviewScreen')}
aria-label={t('ai.chat.artifact.rdPreviewScreen')}
>
<img
src={cachedPreview.thumbSrc}
alt={title}
className="h-7 w-11 object-cover block"
/>
</button>
)}
<CheckCircle2 size={12} className="shrink-0 text-green-400/70" />
</div>
);
});
RemoteDesktopArtifactCard.displayName = 'RemoteDesktopArtifactCard';
@@ -0,0 +1,43 @@
import React from 'react';
import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip';
import { formatRemoteDesktopToolTooltip } from './formatRemoteDesktopToolTooltip';
import { RemoteDesktopArtifactCard } from './RemoteDesktopArtifactCard';
import type { RemoteDesktopToolArtifact } from './remoteDesktopToolArtifact';
interface RemoteDesktopArtifactToolResultProps {
artifact: RemoteDesktopToolArtifact;
toolName: string;
args?: Record<string, unknown>;
result?: unknown;
isError?: boolean;
onOpenImagePreview?: (src: string, name: string) => void;
}
export const RemoteDesktopArtifactToolResult: React.FC<RemoteDesktopArtifactToolResultProps> = ({
artifact,
toolName,
args,
result,
isError,
onOpenImagePreview,
}) => {
const tooltip = formatRemoteDesktopToolTooltip(toolName, args, result, isError);
return (
<Tooltip>
<TooltipTrigger asChild>
<RemoteDesktopArtifactCard
artifact={artifact}
onOpenImagePreview={onOpenImagePreview}
/>
</TooltipTrigger>
<TooltipContent
side="top"
align="start"
className="max-w-md whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed"
>
{tooltip}
</TooltipContent>
</Tooltip>
);
};
@@ -0,0 +1,52 @@
import {
sanitizeRemoteDesktopActionsForAudit,
validateAndNormalizeRemoteDesktopActions,
} from '../../../domain/remoteDesktopActionCodec';
function sanitizeArgsForTooltip(args?: Record<string, unknown>): Record<string, unknown> | undefined {
if (!args) return undefined;
if (!Array.isArray(args.actions)) return args;
const parsed = validateAndNormalizeRemoteDesktopActions(args.actions);
if (!parsed.ok) return args;
return {
...args,
actions: sanitizeRemoteDesktopActionsForAudit(parsed.actions),
};
}
function serialize(value: unknown): string {
if (value == null) return '';
if (typeof value === 'string') {
try {
const parsed = JSON.parse(value);
if (parsed && typeof parsed === 'object') {
return JSON.stringify(parsed, null, 2);
}
} catch {
return value;
}
return value;
}
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
export function formatRemoteDesktopToolTooltip(
toolName: string,
args?: Record<string, unknown>,
result?: unknown,
isError?: boolean,
): string {
const safeArgs = sanitizeArgsForTooltip(args);
const sections = [
`Tool: ${toolName}`,
safeArgs && Object.keys(safeArgs).length > 0 ? `Args:\n${serialize(safeArgs)}` : null,
result !== undefined && result !== '' ? `Result:\n${serialize(result)}` : null,
isError ? 'Status: error' : null,
].filter(Boolean);
return sections.join('\n\n');
}
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
extractRemoteDesktopPendingLabel,
parseRemoteDesktopToolArtifact,
resolveRemoteDesktopActionVisualKind,
} from './remoteDesktopToolArtifact.ts';
import { formatRemoteDesktopToolTooltip } from './formatRemoteDesktopToolTooltip.ts';
test('parseRemoteDesktopToolArtifact parses remote_desktop_read_screen payloads', () => {
const artifact = parseRemoteDesktopToolArtifact('remote_desktop_read_screen', JSON.stringify({
ok: true,
captureId: 'rdcap-1',
sessionId: 'rdp-1',
protocol: 'rdp',
hostLabel: 'Win11 Dev',
hostname: '10.0.0.5',
width: 1280,
height: 720,
naturalWidth: 1920,
naturalHeight: 1080,
grid: true,
}));
assert.deepEqual(artifact, {
kind: 'remoteDesktop.screen',
sessionId: 'rdp-1',
captureId: 'rdcap-1',
protocol: 'rdp',
hostLabel: 'Win11 Dev',
hostname: '10.0.0.5',
width: 1280,
height: 720,
naturalWidth: 1920,
naturalHeight: 1080,
crop: undefined,
grid: true,
});
});
test('parseRemoteDesktopToolArtifact parses remote_desktop_act payloads and resolves visual kind', () => {
const artifact = parseRemoteDesktopToolArtifact(
'remote_desktop_act',
JSON.stringify({
ok: true,
sessionId: 'vnc-1',
protocol: 'vnc',
hostLabel: 'Ubuntu Desktop',
completedActions: 2,
totalActions: 2,
durationMs: 380,
summary: 'Press Escape -> Drag (852, 500) -> (852, 700)',
captureId: 'rdcap-2',
width: 1280,
height: 720,
}),
{
actions: [
{ type: 'key', key: 'Escape' },
{ type: 'drag', fromX: 852, fromY: 500, toX: 852, toY: 700 },
],
},
);
assert.equal(artifact?.kind, 'remoteDesktop.act');
if (artifact?.kind === 'remoteDesktop.act') {
assert.equal(artifact.summary, 'Press Escape → Drag (852, 500) → (852, 700)');
assert.equal(artifact.actionVisualKind, 'mixed');
assert.equal(artifact.durationMs, 380);
assert.equal(artifact.completedActions, 2);
}
});
test('parseRemoteDesktopToolArtifact turns plain string errors into error artifacts', () => {
const artifact = parseRemoteDesktopToolArtifact(
'remote_desktop_act',
'Tool execution denied.',
undefined,
true,
);
assert.deepEqual(artifact, {
kind: 'error',
toolKind: 'act',
message: 'Tool execution denied.',
});
});
test('resolveRemoteDesktopActionVisualKind infers icon category from summary when args are absent', () => {
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Click (120, 240)'), 'click');
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Drag (10, 20) -> (30, 40)'), 'drag');
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Scroll down (400, 300)'), 'scroll');
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Type "hello" -> Press Enter'), 'keyboard');
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Wait 500ms'), 'wait');
assert.equal(resolveRemoteDesktopActionVisualKind(undefined, 'Click (10, 20) -> Wait 300ms'), 'click');
});
test('extractRemoteDesktopPendingLabel summarizes pending act and read_screen calls', () => {
assert.deepEqual(
extractRemoteDesktopPendingLabel('remote_desktop_act', {
actions: [{ type: 'click', x: 500, y: 300 }],
}),
{ kind: 'act', label: 'Click (500, 300)' },
);
assert.deepEqual(
extractRemoteDesktopPendingLabel('remote_desktop_read_screen', {
cropX: 100,
cropY: 100,
cropWidth: 300,
cropHeight: 200,
quality: 'high',
}),
{ kind: 'screen', label: 'Read zoomed region · high' },
);
});
test('formatRemoteDesktopToolTooltip redacts secret-like typed text in args', () => {
const tooltip = formatRemoteDesktopToolTooltip(
'remote_desktop_act',
{ actions: [{ type: 'type', text: 'ghp_1234567890abcdefghijklmnop' }] },
{ ok: true, summary: 'Type "[REDACTED]"' },
false,
);
assert.doesNotMatch(tooltip, /ghp_1234567890/);
assert.match(tooltip, /\[REDACTED\]/);
});
@@ -0,0 +1,290 @@
import {
summarizeRemoteDesktopActions,
validateAndNormalizeRemoteDesktopActions,
type RemoteDesktopAction,
} from '../../../domain/remoteDesktopActionCodec';
import { normalizeArtifactToolName } from './toolArtifactNames';
import { parseResultPayload } from './toolArtifactResultPayload';
export type RemoteDesktopActionVisualKind =
| 'click'
| 'drag'
| 'scroll'
| 'keyboard'
| 'wait'
| 'mixed';
export interface RemoteDesktopArtifactCrop {
x: number;
y: number;
width: number;
height: number;
}
export type RemoteDesktopToolArtifact =
| {
kind: 'remoteDesktop.screen';
sessionId: string;
captureId?: string;
protocol?: 'vnc' | 'rdp';
hostLabel?: string;
hostname?: string;
width: number;
height: number;
naturalWidth?: number;
naturalHeight?: number;
crop?: RemoteDesktopArtifactCrop;
grid?: boolean;
}
| {
kind: 'remoteDesktop.act';
sessionId: string;
captureId?: string;
protocol?: 'vnc' | 'rdp';
hostLabel?: string;
hostname?: string;
summary: string;
completedActions: number;
totalActions: number;
durationMs?: number;
actionVisualKind: RemoteDesktopActionVisualKind;
width?: number;
height?: number;
grid?: boolean;
}
| {
kind: 'error';
toolKind: 'screen' | 'act';
code?: string;
message: string;
completedActions?: number;
totalActions?: number;
};
const REMOTE_DESKTOP_READ_SCREEN_TOOL = 'remote_desktop_read_screen';
const REMOTE_DESKTOP_ACT_TOOL = 'remote_desktop_act';
function readString(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() ? value.trim() : undefined;
}
function readNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
function readProtocol(value: unknown): 'vnc' | 'rdp' | undefined {
if (typeof value !== 'string') return undefined;
const lower = value.trim().toLowerCase();
return lower === 'vnc' || lower === 'rdp' ? lower : undefined;
}
function readCrop(value: unknown): RemoteDesktopArtifactCrop | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const record = value as Record<string, unknown>;
const x = readNumber(record.x);
const y = readNumber(record.y);
const width = readNumber(record.width);
const height = readNumber(record.height);
if (x == null || y == null || width == null || height == null) return undefined;
return { x, y, width, height };
}
function classifySingleAction(action: RemoteDesktopAction): Exclude<RemoteDesktopActionVisualKind, 'mixed'> {
switch (action.type) {
case 'click':
case 'move':
return 'click';
case 'drag':
return 'drag';
case 'scroll':
return 'scroll';
case 'type':
case 'key':
return 'keyboard';
case 'wait':
return 'wait';
}
}
export function resolveRemoteDesktopActionVisualKind(
actions?: readonly RemoteDesktopAction[],
summary?: string,
): RemoteDesktopActionVisualKind {
if (actions && actions.length > 0) {
const categories = new Set(actions.map(classifySingleAction));
// Ignore trailing/intermediate waits when picking the primary visual icon.
if (categories.size > 1 && categories.has('wait')) {
categories.delete('wait');
}
if (categories.size === 1) {
return categories.values().next().value!;
}
return 'mixed';
}
const trimmed = summary?.trim();
if (!trimmed) return 'click';
const segments = trimmed.split(/\s*(?:->|→)\s*/).filter(Boolean);
const categories = new Set<Exclude<RemoteDesktopActionVisualKind, 'mixed'>>();
for (const seg of segments) {
if (/^(?:Click|Double-click|Triple-click|Right-click|Middle-click|Move)\b/i.test(seg)) {
categories.add('click');
} else if (/^Drag\b/i.test(seg)) {
categories.add('drag');
} else if (/^Scroll\b/i.test(seg)) {
categories.add('scroll');
} else if (/^(?:Type|Press)\b/i.test(seg)) {
categories.add('keyboard');
} else if (/^Wait\b/i.test(seg)) {
categories.add('wait');
}
}
if (categories.size > 1 && categories.has('wait')) {
categories.delete('wait');
}
if (categories.size === 1) {
return categories.values().next().value!;
}
return categories.size > 1 ? 'mixed' : 'click';
}
export function formatRemoteDesktopActionSummaryText(summary: string): string {
return summary.replace(/\s*->\s*/g, ' → ');
}
/**
* Human-readable one-line summary for pending/running/approval remote desktop
* tool cards before a tool result arrives.
*/
export function extractRemoteDesktopPendingLabel(
toolName: string,
args?: Record<string, unknown>,
): { kind: 'screen' | 'act'; label: string } | null {
const normalized = normalizeArtifactToolName(toolName);
if (normalized === REMOTE_DESKTOP_ACT_TOOL) {
const parsed = args ? validateAndNormalizeRemoteDesktopActions(args.actions) : null;
if (parsed && parsed.ok && parsed.actions.length > 0) {
return {
kind: 'act',
label: formatRemoteDesktopActionSummaryText(
summarizeRemoteDesktopActions(parsed.actions, { redactSecrets: true }),
),
};
}
return { kind: 'act', label: 'remote_desktop_act' };
}
if (normalized === REMOTE_DESKTOP_READ_SCREEN_TOOL) {
const hasCrop = args != null
&& readNumber(args.cropWidth) != null
&& readNumber(args.cropHeight) != null;
const hasGrid = args?.grid === true || args?.grid === 'true';
const parts = [
hasCrop ? 'Read zoomed region' : 'Read remote screen',
hasGrid ? 'grid' : null,
readString(args?.quality) === 'high' ? 'high' : null,
].filter(Boolean);
return { kind: 'screen', label: parts.join(' · ') };
}
return null;
}
export function parseRemoteDesktopToolArtifact(
toolName: string,
result: unknown,
args?: Record<string, unknown>,
isError?: boolean,
): RemoteDesktopToolArtifact | null {
const normalizedToolName = normalizeArtifactToolName(toolName);
if (
normalizedToolName !== REMOTE_DESKTOP_READ_SCREEN_TOOL
&& normalizedToolName !== REMOTE_DESKTOP_ACT_TOOL
) {
return null;
}
const toolKind = normalizedToolName === REMOTE_DESKTOP_READ_SCREEN_TOOL ? 'screen' : 'act';
const payload = parseResultPayload(result);
if (!payload) {
if (isError) {
const fallbackMessage = typeof result === 'string' && result.trim()
? result.trim()
: toolKind === 'screen'
? 'Remote desktop screen capture failed.'
: 'Remote desktop action failed.';
return {
kind: 'error',
toolKind,
message: fallbackMessage,
};
}
return null;
}
if (payload.ok === false || payload.isError === true || typeof payload.error === 'string') {
return {
kind: 'error',
toolKind,
code: readString(payload.code),
message: readString(payload.error) ?? (
toolKind === 'screen'
? 'Remote desktop screen capture failed.'
: 'Remote desktop action failed.'
),
completedActions: readNumber(payload.completedActions),
totalActions: readNumber(payload.totalActions),
};
}
const sessionId = readString(payload.sessionId) ?? readString(args?.sessionId);
if (!sessionId) return null;
if (toolKind === 'screen') {
const width = readNumber(payload.width);
const height = readNumber(payload.height);
if (width == null || height == null) return null;
return {
kind: 'remoteDesktop.screen',
sessionId,
captureId: readString(payload.captureId),
protocol: readProtocol(payload.protocol),
hostLabel: readString(payload.hostLabel),
hostname: readString(payload.hostname),
width,
height,
naturalWidth: readNumber(payload.naturalWidth),
naturalHeight: readNumber(payload.naturalHeight),
crop: readCrop(payload.crop),
grid: payload.grid === true,
};
}
const parsedActions = args ? validateAndNormalizeRemoteDesktopActions(args.actions) : null;
const actions = parsedActions && parsedActions.ok ? parsedActions.actions : undefined;
const rawSummary = readString(payload.summary)
?? (actions && actions.length > 0
? summarizeRemoteDesktopActions(actions, { redactSecrets: true })
: '');
const completedActions = readNumber(payload.completedActions) ?? actions?.length ?? 0;
const totalActions = readNumber(payload.totalActions) ?? completedActions;
return {
kind: 'remoteDesktop.act',
sessionId,
captureId: readString(payload.captureId),
protocol: readProtocol(payload.protocol),
hostLabel: readString(payload.hostLabel),
hostname: readString(payload.hostname),
summary: formatRemoteDesktopActionSummaryText(rawSummary),
completedActions,
totalActions,
durationMs: readNumber(payload.durationMs),
actionVisualKind: resolveRemoteDesktopActionVisualKind(actions, rawSummary),
width: readNumber(payload.width),
height: readNumber(payload.height),
grid: payload.grid === true,
};
}
@@ -2,6 +2,8 @@ const MCP_TOOL_NAME_PREFIX = 'mcp__';
const KNOWN_ARTIFACT_TOOL_NAMES = [
'terminal_read_context',
'remote_desktop_read_screen',
'remote_desktop_act',
'vault_notes_create',
'vault_notes_update',
'vault_notes_get',
@@ -27,6 +27,7 @@ import {
} from "../../domain/remoteDesktop";
import { cn } from "../../lib/utils";
import type {
GroupConfig,
Host,
Identity,
RdpConfig,
@@ -48,6 +49,7 @@ import { Switch } from "../ui/switch";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
import { HostDetailsSettingRow } from "./HostDetailsSection";
import { IdentitySuggestInput } from "./IdentitySuggestInput";
import { RdpResolutionFields, type RdpResolutionDraftProps } from "./RdpResolutionFields";
type Translate = (key: string, params?: Record<string, unknown>) => string;
@@ -65,8 +67,9 @@ interface CompanionRemoteDesktopSectionsProps {
t: Translate;
}
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps {
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps, RdpResolutionDraftProps {
protocol: "vnc" | "rdp";
groupDefaults?: Partial<GroupConfig>;
credentialDraft?: CompanionCredentialDraft;
onCredentialDraftChange?: (draft: CompanionCredentialDraft | undefined) => void;
}
@@ -79,22 +82,35 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
protocol,
form,
setForm,
groupDefaults,
identities,
availableKeys = [],
credentialDraft,
onCredentialDraftChange,
resolutionDraft,
onResolutionDraftChange,
t,
}) => {
const [vncPortInput, setVncPortInput] = useState<string>(() =>
String(form.vncConfig?.port ?? DEFAULT_VNC_PORT),
form.vncConfig?.port !== undefined
? String(form.vncConfig.port)
: groupDefaults?.vncConfig?.port !== undefined
? ""
: String(DEFAULT_VNC_PORT),
);
const [showManualPassword, setShowManualPassword] = useState(false);
useEffect(() => {
if (protocol === "vnc") {
setVncPortInput(String(form.vncConfig?.port ?? DEFAULT_VNC_PORT));
setVncPortInput(
form.vncConfig?.port !== undefined
? String(form.vncConfig.port)
: groupDefaults?.vncConfig?.port !== undefined
? ""
: String(DEFAULT_VNC_PORT),
);
}
}, [form.id, protocol, form.vncConfig?.port]);
}, [form.id, protocol, form.vncConfig?.port, groupDefaults?.vncConfig?.port]);
const passwordCompatibleIdentities = useMemo(
() =>
@@ -108,12 +124,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
setForm((prev) => ({
...prev,
vncConfig: {
...(prev.vncConfig ?? {
...DEFAULT_VNC_CONFIG,
enabled: true,
tunnelViaHostSsh: true,
useHostCredentials: true,
}),
...(prev.vncConfig ?? { enabled: true }),
...patch,
},
}));
@@ -123,25 +134,38 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
setForm((prev) => ({
...prev,
rdpConfig: {
...(prev.rdpConfig ?? {
...DEFAULT_RDP_CONFIG,
enabled: true,
tunnelViaHostSsh: true,
useHostCredentials: true,
}),
...(prev.rdpConfig ?? { enabled: true }),
...patch,
},
}));
};
if (protocol === "vnc") {
const vncTunneled = form.vncConfig?.tunnelViaHostSsh ?? true;
const vncNormalized = normalizeVncConfig(form.vncConfig);
const groupVnc = groupDefaults?.vncConfig;
const effectiveVnc = { ...(groupVnc ?? {}), ...(form.vncConfig ?? {}) };
const vncTunneled = effectiveVnc.tunnelViaHostSsh ?? true;
const vncNormalized = normalizeVncConfig(effectiveVnc);
const vncDisplayLabel = formatVncDisplayNumber(vncNormalized.port);
const hostHasManualVncCreds =
form.vncConfig?.useHostCredentials === false
|| Boolean(form.vncConfig?.username?.trim())
|| form.vncConfig?.identityId !== undefined;
const effectiveVncIdentityId = form.vncConfig?.identityId !== undefined
? (form.vncConfig.identityId || undefined)
: (form.vncConfig?.useHostCredentials === true || Boolean(form.vncConfig?.username?.trim()))
? undefined
: (groupVnc?.identityId || undefined);
const useHostCreds =
!form.vncConfig?.identityId && form.vncConfig?.useHostCredentials !== false;
const selectedVncIdentity = form.vncConfig?.identityId
? identities.find((i) => i.id === form.vncConfig?.identityId)
!effectiveVncIdentityId
&& (
form.vncConfig?.useHostCredentials !== undefined
? form.vncConfig.useHostCredentials
: hostHasManualVncCreds
? false
: groupVnc?.useHostCredentials === true
);
const selectedVncIdentity = effectiveVncIdentityId
? identities.find((i) => i.id === effectiveVncIdentityId)
: undefined;
return (
@@ -156,18 +180,26 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onChange={(e) => {
const raw = e.target.value;
setVncPortInput(raw);
if (!raw.trim()) {
updateVncConfig({ port: undefined });
return;
}
const parsed = parseVncPortOrDisplay(raw);
if (parsed !== null) {
updateVncConfig({ port: parsed });
}
}}
onBlur={() => {
if (!vncPortInput.trim() && groupVnc?.port !== undefined) {
updateVncConfig({ port: undefined });
return;
}
const parsed = parseVncPortOrDisplay(vncPortInput);
const resolved = parsed ?? DEFAULT_VNC_PORT;
setVncPortInput(String(resolved));
const resolved = parsed ?? (groupVnc?.port !== undefined ? undefined : DEFAULT_VNC_PORT);
setVncPortInput(resolved !== undefined ? String(resolved) : "");
updateVncConfig({ port: resolved });
}}
placeholder={t("hostDetails.vnc.displayPlaceholder")}
placeholder={groupVnc?.port ? String(groupVnc.port) : t("hostDetails.vnc.displayPlaceholder")}
className="h-8 flex-1 min-w-0 text-center font-mono text-sm"
/>
{vncDisplayLabel ? (
@@ -199,7 +231,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onChange={(e) =>
updateVncConfig({ tunnelTargetHost: e.target.value || undefined })
}
placeholder="127.0.0.1"
placeholder={groupVnc?.tunnelTargetHost || "127.0.0.1"}
className="h-8 w-44 font-mono text-sm"
/>
</HostDetailsSettingRow>
@@ -214,7 +246,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onCheckedChange={(checked) => {
if (checked) {
onCredentialDraftChange?.(undefined);
updateVncConfig({ useHostCredentials: true, identityId: undefined });
updateVncConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
} else {
updateVncConfig({ useHostCredentials: false });
}
@@ -224,7 +256,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
{!useHostCreds && (
<div className="space-y-2">
{form.vncConfig?.identityId ? (
{effectiveVncIdentityId ? (
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
<User size={16} className="text-muted-foreground shrink-0" />
<div className="min-w-0 flex-1">
@@ -241,7 +273,10 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => updateVncConfig({ identityId: undefined, useHostCredentials: false })}
onClick={() => updateVncConfig({
identityId: groupVnc?.identityId ? "" : undefined,
useHostCredentials: false,
})}
>
<X size={14} />
</Button>
@@ -254,13 +289,17 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
<IdentitySuggestInput
value={credentialDraft?.username ?? form.vncConfig?.username ?? ""}
onChange={(next) => {
updateVncConfig({ username: next || undefined, useHostCredentials: false });
updateVncConfig({
username: next || undefined,
useHostCredentials: false,
...(groupVnc?.identityId ? { identityId: "" } : {}),
});
onCredentialDraftChange?.({
username: next,
password: credentialDraft?.password ?? "",
});
}}
placeholder={t("hostDetails.vnc.usernamePlaceholder")}
placeholder={groupVnc?.username || t("hostDetails.vnc.usernamePlaceholder")}
identities={passwordCompatibleIdentities}
availableKeys={availableKeys}
onSelectIdentity={(identity) => {
@@ -347,12 +386,30 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
);
}
const rdpTunneled = form.rdpConfig?.tunnelViaHostSsh ?? true;
const rdpNormalized = normalizeRdpConfig(form.rdpConfig);
const groupRdp = groupDefaults?.rdpConfig;
const effectiveRdp = { ...(groupRdp ?? {}), ...(form.rdpConfig ?? {}) };
const rdpTunneled = effectiveRdp.tunnelViaHostSsh ?? true;
const rdpNormalized = normalizeRdpConfig(effectiveRdp);
const hostHasManualRdpCreds =
form.rdpConfig?.useHostCredentials === false
|| Boolean(form.rdpConfig?.username?.trim())
|| form.rdpConfig?.identityId !== undefined;
const effectiveRdpIdentityId = form.rdpConfig?.identityId !== undefined
? (form.rdpConfig.identityId || undefined)
: (form.rdpConfig?.useHostCredentials === true || Boolean(form.rdpConfig?.username?.trim()))
? undefined
: (groupRdp?.identityId || undefined);
const useHostCreds =
!form.rdpConfig?.identityId && form.rdpConfig?.useHostCredentials !== false;
const selectedRdpIdentity = form.rdpConfig?.identityId
? identities.find((i) => i.id === form.rdpConfig?.identityId)
!effectiveRdpIdentityId
&& (
form.rdpConfig?.useHostCredentials !== undefined
? form.rdpConfig.useHostCredentials
: hostHasManualRdpCreds
? false
: groupRdp?.useHostCredentials === true
);
const selectedRdpIdentity = effectiveRdpIdentityId
? identities.find((i) => i.id === effectiveRdpIdentityId)
: undefined;
return (
@@ -365,11 +422,12 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
type="number"
min={1}
max={65535}
value={form.rdpConfig?.port ?? DEFAULT_RDP_PORT}
value={form.rdpConfig?.port ?? (groupRdp?.port !== undefined ? "" : DEFAULT_RDP_PORT)}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10);
updateRdpConfig({ port: Number.isFinite(n) ? n : undefined });
}}
placeholder={String(groupRdp?.port ?? DEFAULT_RDP_PORT)}
className="h-8 w-44 text-center font-mono text-sm"
/>
</HostDetailsSettingRow>
@@ -395,7 +453,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onChange={(e) =>
updateRdpConfig({ tunnelTargetHost: e.target.value || undefined })
}
placeholder="127.0.0.1"
placeholder={groupRdp?.tunnelTargetHost || "127.0.0.1"}
className="h-8 w-44 font-mono text-sm"
/>
</HostDetailsSettingRow>
@@ -410,7 +468,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onCheckedChange={(checked) => {
if (checked) {
onCredentialDraftChange?.(undefined);
updateRdpConfig({ useHostCredentials: true, identityId: undefined });
updateRdpConfig({ useHostCredentials: true, identityId: undefined, username: undefined });
} else {
updateRdpConfig({ useHostCredentials: false });
}
@@ -420,7 +478,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
{!useHostCreds && (
<div className="space-y-2">
{form.rdpConfig?.identityId ? (
{effectiveRdpIdentityId ? (
<div className="flex items-center gap-2 h-10 px-3 rounded-lg border border-border/60 bg-transparent">
<User size={16} className="text-muted-foreground shrink-0" />
<div className="min-w-0 flex-1">
@@ -437,7 +495,10 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => updateRdpConfig({ identityId: undefined, useHostCredentials: false })}
onClick={() => updateRdpConfig({
identityId: groupRdp?.identityId ? "" : undefined,
useHostCredentials: false,
})}
>
<X size={14} />
</Button>
@@ -450,13 +511,17 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
<IdentitySuggestInput
value={credentialDraft?.username ?? form.rdpConfig?.username ?? ""}
onChange={(next) => {
updateRdpConfig({ username: next || undefined, useHostCredentials: false });
updateRdpConfig({
username: next || undefined,
useHostCredentials: false,
...(groupRdp?.identityId ? { identityId: "" } : {}),
});
onCredentialDraftChange?.({
username: next,
password: credentialDraft?.password ?? "",
});
}}
placeholder={t("hostDetails.rdp.usernamePlaceholder")}
placeholder={groupRdp?.username || t("hostDetails.rdp.usernamePlaceholder")}
identities={passwordCompatibleIdentities}
availableKeys={availableKeys}
onSelectIdentity={(identity) => {
@@ -517,7 +582,7 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
onChange={(e) =>
updateRdpConfig({ domain: e.target.value || undefined })
}
placeholder={t("hostDetails.rdp.domainPlaceholder")}
placeholder={groupRdp?.domain || t("hostDetails.rdp.domainPlaceholder")}
className="h-8 w-44 text-sm"
/>
</HostDetailsSettingRow>
@@ -543,6 +608,17 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
</Select>
</HostDetailsSettingRow>
{rdpNormalized.resolutionMode === "fixed" && (
<RdpResolutionFields
form={form}
setForm={setForm}
inheritedRdpConfig={groupRdp}
t={t}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
/>
)}
<HostDetailsSettingRow
icon={<ShieldCheck />}
label={t("hostDetails.rdp.securityMode")}
@@ -0,0 +1,78 @@
import React, { useId, useState } from "react";
import {
DEFAULT_RDP_HEIGHT,
DEFAULT_RDP_WIDTH,
parseRdpDimensionDraft,
type RdpResolutionDraft,
} from "../../domain/remoteDesktop";
import type { Host, RdpConfig } from "../../types";
import { Input } from "../ui/input";
export interface RdpResolutionDraftProps {
resolutionDraft?: RdpResolutionDraft;
onResolutionDraftChange?: (dimension: "width" | "height", value: string) => void;
}
interface RdpResolutionFieldsProps extends RdpResolutionDraftProps {
form: Pick<Host, "rdpConfig">;
setForm: React.Dispatch<React.SetStateAction<Host>>;
inheritedRdpConfig?: Partial<RdpConfig>;
t: (key: string) => string;
}
export const RdpResolutionFields: React.FC<RdpResolutionFieldsProps> = ({
form, setForm, inheritedRdpConfig, t, resolutionDraft, onResolutionDraftChange,
}) => {
const [localDraft, setLocalDraft] = useState<RdpResolutionDraft>({});
const id = useId();
const draft = resolutionDraft ?? localDraft;
return (
<div className="grid grid-cols-2 gap-2">
{(["width", "height"] as const).map((dimension) => {
const value = draft[dimension] ?? String(
form.rdpConfig?.[dimension]
?? inheritedRdpConfig?.[dimension]
?? (dimension === "width" ? DEFAULT_RDP_WIDTH : DEFAULT_RDP_HEIGHT),
);
const invalid = parseRdpDimensionDraft(value) === undefined;
const inputId = `${id}-${dimension}`;
return (
<div key={dimension} className="space-y-1">
<div className="flex items-center justify-between gap-2 bg-transparent px-1 h-10">
<label htmlFor={inputId} className="text-sm font-medium text-foreground shrink-0">
{t(`hostDetails.rdp.${dimension}`)}
</label>
<Input
id={inputId}
type="text"
inputMode="numeric"
value={value}
aria-invalid={invalid}
aria-describedby={invalid ? `${inputId}-hint` : undefined}
onChange={(e) => {
const next = e.target.value;
if (onResolutionDraftChange) onResolutionDraftChange(dimension, next);
else setLocalDraft((prev) => ({ ...prev, [dimension]: next }));
const parsed = parseRdpDimensionDraft(next);
if (parsed !== undefined) {
setForm((prev) => ({
...prev,
rdpConfig: { ...prev.rdpConfig, [dimension]: parsed },
}));
}
}}
className="h-8 w-20 text-sm text-center font-mono"
/>
</div>
{invalid && (
<p id={`${inputId}-hint`} className="px-1 text-xs text-destructive">
{t("hostDetails.rdp.dimensionHint")}
</p>
)}
</div>
);
})}
</div>
);
};
@@ -24,6 +24,7 @@ import {
normalizeVncConfig,
} from "../../domain/remoteDesktop";
import type {
GroupConfig,
Host,
RdpColorDepth,
RdpConfig,
@@ -38,30 +39,41 @@ import { Input } from "../ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { HostDetailsSection, HostDetailsSettingRow } from "./HostDetailsSection";
import { RdpResolutionFields, type RdpResolutionDraftProps } from "./RdpResolutionFields";
type Translate = (key: string, params?: Record<string, unknown>) => string;
interface RemoteDesktopOptionsSectionProps {
interface RemoteDesktopOptionsSectionProps extends RdpResolutionDraftProps {
form: Host;
setForm: React.Dispatch<React.SetStateAction<Host>>;
groupDefaults?: Partial<GroupConfig>;
t: Translate;
}
export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionProps> = ({
form,
setForm,
groupDefaults,
t,
resolutionDraft,
onResolutionDraftChange,
}) => {
const [advancedOpen, setAdvancedOpen] = useState(() =>
Boolean(
form.rdpConfig?.loadBalanceInfo ||
form.rdpConfig?.alternateShell ||
form.rdpConfig?.shellWorkingDir,
form.rdpConfig?.shellWorkingDir ||
groupDefaults?.rdpConfig?.loadBalanceInfo ||
groupDefaults?.rdpConfig?.alternateShell ||
groupDefaults?.rdpConfig?.shellWorkingDir,
),
);
if (form.protocol === "rdp") {
const rdp = normalizeRdpConfig(form.rdpConfig);
const rdp = normalizeRdpConfig({
...(groupDefaults?.rdpConfig ?? {}),
...(form.rdpConfig ?? {}),
});
const updateRdp = <K extends keyof RdpConfig>(key: K, value: RdpConfig[K]) => {
setForm((prev) => ({
...prev,
@@ -99,36 +111,14 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
</HostDetailsSettingRow>
{rdp.resolutionMode === "fixed" && (
<div className="grid grid-cols-2 gap-2">
<div className="flex items-center justify-between gap-2 bg-transparent px-1 h-10">
<span className="text-sm font-medium text-foreground shrink-0">{t("hostDetails.rdp.width")}</span>
<Input
type="number"
min={200}
max={8192}
value={rdp.width}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10);
if (Number.isFinite(n)) updateRdp("width", n);
}}
className="h-8 w-20 text-sm text-center font-mono"
/>
</div>
<div className="flex items-center justify-between gap-2 bg-transparent px-1 h-10">
<span className="text-sm font-medium text-foreground shrink-0">{t("hostDetails.rdp.height")}</span>
<Input
type="number"
min={200}
max={8192}
value={rdp.height}
onChange={(e) => {
const n = Number.parseInt(e.target.value, 10);
if (Number.isFinite(n)) updateRdp("height", n);
}}
className="h-8 w-20 text-sm text-center font-mono"
/>
</div>
</div>
<RdpResolutionFields
form={form}
setForm={setForm}
inheritedRdpConfig={groupDefaults?.rdpConfig}
t={t}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
/>
)}
<HostDetailsSettingRow
@@ -244,7 +234,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
onChange={(e) =>
updateRdp("loadBalanceInfo", e.target.value || undefined)
}
placeholder={t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
placeholder={groupDefaults?.rdpConfig?.loadBalanceInfo || t("hostDetails.rdp.loadBalanceInfoPlaceholder")}
className="h-10 rounded-lg text-sm font-mono"
/>
</div>
@@ -257,7 +247,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
onChange={(e) =>
updateRdp("alternateShell", e.target.value || undefined)
}
placeholder={t("hostDetails.rdp.alternateShellPlaceholder")}
placeholder={groupDefaults?.rdpConfig?.alternateShell || t("hostDetails.rdp.alternateShellPlaceholder")}
className="h-10 rounded-lg text-sm font-mono"
/>
</div>
@@ -270,7 +260,7 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
onChange={(e) =>
updateRdp("shellWorkingDir", e.target.value || undefined)
}
placeholder={t("hostDetails.rdp.shellWorkingDirPlaceholder")}
placeholder={groupDefaults?.rdpConfig?.shellWorkingDir || t("hostDetails.rdp.shellWorkingDirPlaceholder")}
className="h-10 rounded-lg text-sm font-mono"
/>
</div>
@@ -281,7 +271,10 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
}
if (form.protocol === "vnc") {
const vnc = normalizeVncConfig(form.vncConfig);
const vnc = normalizeVncConfig({
...(groupDefaults?.vncConfig ?? {}),
...(form.vncConfig ?? {}),
});
const updateVnc = <K extends keyof VncConfig>(key: K, value: VncConfig[K]) => {
setForm((prev) => ({
...prev,
+2 -1
View File
@@ -64,7 +64,8 @@ test('QuickSwitcher virtualizes categorized rows and clamps empty-list keyboard'
assert.match(source, /QS_PLUGIN_ROW_HEIGHT/);
// Fixed-height slots must clip/truncate so long titles never overlap the next row.
assert.match(source, /overflow-hidden/);
assert.match(source, /max-w-\[12rem\] shrink-0 truncate/);
assert.match(source, /ml-3 flex shrink-0 items-center gap-2/);
assert.match(source, /max-w-\[12rem\] truncate text-\[11px\] text-muted-foreground/);
// List scroller needs a definite max height under max-h-only popup chrome.
assert.match(source, /max-h-\[min\(360px,calc\(100vh-14rem\)\)\]/);
assert.doesNotMatch(source, /results\.map\(\(host\) =>/);
+16
View File
@@ -0,0 +1,16 @@
import React, { Suspense, lazy } from "react";
import type { NotesManagerProps } from "./NotesManager";
const NotesManagerChunk = lazy(() =>
import("./NotesManager").then((mod) => ({ default: mod.NotesManager })),
);
/**
* Code-split wrapper so NotesManager (and its markdown/MDX parser tree)
* is not parsed or retained in the initial startup bundle until opened.
*/
export const LazyNotesManager: React.FC<NotesManagerProps> = (props) => (
<Suspense fallback={null}>
<NotesManagerChunk {...props} />
</Suspense>
);
+4 -2
View File
@@ -3,7 +3,9 @@ import { useI18n } from '../../application/i18n/I18nProvider';
import { describePluginPermission } from '@/domain/pluginPermissionDescriptions.cjs';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
import { Button } from '../ui/button';
import globalAgentToolSpecs from '../../infrastructure/ai/harness/generated/globalAgentToolSpecs.json';
import toolNameIndex from '../../infrastructure/ai/harness/generated/toolNameIndex.json';
const globalToolNameByCapabilityId = toolNameIndex.globalByCapabilityId as Record<string, string>;
/** Rendered only by the trusted app, never inside a plugin view. */
export function PluginPermissionHost() {
@@ -14,7 +16,7 @@ export function PluginPermissionHost() {
const description = describePluginPermission(prompt.permission, resolvedLocale);
const resources = prompt.resources.filter((resource) => resource !== '*' && !resource.startsWith('selected:'));
const action = prompt.displayContext?.action;
const operation = action && (globalAgentToolSpecs.find((tool) => tool.capabilityId === action.capabilityId)?.toolName ?? action.capabilityId);
const operation = action && (globalToolNameByCapabilityId[action.capabilityId] ?? action.capabilityId);
const selections = prompt.displayContext?.selections ?? [];
return <Dialog open onOpenChange={(open) => { if (!open) void respond('cancel'); }}>
<DialogContent data-host-security-surface="" className="max-h-[85vh] overflow-y-auto sm:max-w-[480px]">
+71 -16
View File
@@ -12,10 +12,14 @@ import { useI18n } from '../../application/i18n/I18nProvider';
import {
computeMonitorVirtualBounds,
mapViewportToVirtualDesktopCoords,
resolveEffectiveRdpSecurityMode,
resolveNextRdpAutoFallback,
splitWindowsUserDomain,
type MonitorLayoutSpec,
type NormalizedRdpConfig,
type RdpAutoFallbackStage,
type RdpDisplayControlCaps,
type RdpNegotiatedSecurityInfo,
} from '../../domain/remoteDesktop';
import {
permilleToFramebufferCoord,
@@ -43,7 +47,12 @@ import {
type RemoteDesktopClipboardTransferState,
type RemoteDesktopDisplayMode,
type RemoteDesktopRdpdrRequest,
type RemoteDesktopRecordingCaptureHandle,
} from './remoteDesktopHelpers';
import {
captureCanvasThumbnailJpeg,
createStableCanvasCaptureStream,
} from './remoteDesktopVideoCapture';
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
import type {
@@ -96,7 +105,7 @@ export interface RdpCanvasViewProps {
password: string;
domain: string;
rdpConfig: NormalizedRdpConfig;
fallbackDisableCredSsp: boolean;
autoFallbackStage: RdpAutoFallbackStage;
isVisible: boolean;
displayMode: RemoteDesktopDisplayMode;
highDpi?: boolean;
@@ -113,12 +122,17 @@ export interface RdpCanvasViewProps {
onDisplayControlCaps?: (caps: RdpDisplayControlCaps) => void;
onFpsChange?: (fps: number) => void;
onRequestReleaseGrab: () => void;
onConnected: (info: { width: number; height: number; encrypted?: boolean }) => void;
onConnected: (info: {
width: number;
height: number;
encrypted?: boolean;
securityInfo?: RdpNegotiatedSecurityInfo;
}) => void;
onDesktopResize: (size: { width: number; height: number }) => void;
onRemoteClipboardFilesChange?: (files: RemoteDesktopClipboardFileOffer[]) => void;
onClipboardFileTransferStatus?: (status: string | null) => void;
onClipboardTransferChange?: (transfer: RemoteDesktopClipboardTransferState | null) => void;
onNegotiationFallbackNeeded?: () => void;
onNegotiationFallbackNeeded?: (nextStage: Exclude<RdpAutoFallbackStage, 'none'>) => void;
onError: (error: { message: string; isAuthError?: boolean; kind?: number }) => void;
onDisconnected: (reason?: string) => void;
}
@@ -143,7 +157,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
password,
domain,
rdpConfig,
fallbackDisableCredSsp,
autoFallbackStage,
isVisible,
displayMode,
highDpi = true,
@@ -401,6 +415,12 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
return canvasRef.current?.getBoundingClientRect() ?? null;
}, []);
const captureThumbnailJpeg = useCallback(async (): Promise<Uint8Array | null> => {
const canvas = canvasRef.current;
if (!canvas) return null;
return captureCanvasThumbnailJpeg(canvas);
}, []);
const getCaptureStream = useCallback((fps: number, includeAudio?: boolean): MediaStream | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
@@ -422,6 +442,22 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
}
}, []);
const createRecordingCapture = useCallback(
(fps: number, includeAudio?: boolean): RemoteDesktopRecordingCaptureHandle | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
const audioPlayer = includeAudio ? audioPlayerRef.current : null;
const audioStream = audioPlayer?.ensureCaptureAudioStream() ?? null;
return createStableCanvasCaptureStream(canvas, fps, {
audioStream,
onReleaseAudio: audioStream && audioPlayer
? () => audioPlayer.releaseCaptureAudioStream()
: undefined,
});
},
[],
);
const emitClipboardTransfer = useCallback((transfer: RemoteDesktopClipboardTransferState | null) => {
callbacksRef.current.onClipboardTransferChange?.(transfer);
callbacksRef.current.onClipboardFileTransferStatus?.(transfer?.message ?? null);
@@ -881,9 +917,11 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
typeText,
releaseAllInputs,
captureScreenshot,
captureThumbnailJpeg,
captureFrame,
getCanvasRect,
getCaptureStream,
createRecordingCapture,
focusInput,
syncClipboardNow,
downloadRemoteClipboardFile,
@@ -898,6 +936,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
addSharedDrive,
captureFrame,
captureScreenshot,
captureThumbnailJpeg,
createRecordingCapture,
downloadRemoteClipboardFile,
focusInput,
getCanvasRect,
@@ -967,9 +1007,10 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const { username: cleanUser, domain: cleanDomain } = splitWindowsUserDomain(username, domain);
const authToken = extractAuthTokenFromWsUrl(wsUrl);
const securityMode = rdpConfig.securityMode ?? 'auto';
const enableCredSsp =
securityMode === 'nla' || (securityMode === 'auto' && !fallbackDisableCredSsp);
const enableStandardRdp = securityMode === 'rdp';
const effectiveSecurityMode = resolveEffectiveRdpSecurityMode(securityMode, autoFallbackStage);
const enableCredSsp = effectiveSecurityMode === 'nla' || effectiveSecurityMode === 'auto';
const enableStandardRdp = effectiveSecurityMode === 'rdp';
let negotiatedSecurityInfo: RdpNegotiatedSecurityInfo | null = null;
const rdpdrSessionId = propsRef.current.sessionId;
const bridgeForRdpdr = getRemoteDesktopBridge();
@@ -1046,6 +1087,11 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
.extension(new mod.Extension('color_depth', rdpConfig.colorDepth || 32))
.extension(new mod.Extension('enable_credssp', enableCredSsp))
.extension(new mod.Extension('enable_standard_rdp_security', enableStandardRdp))
.extension(
new mod.Extension('security_info_callback', (info: RdpNegotiatedSecurityInfo) => {
negotiatedSecurityInfo = info;
}),
)
.extension(new mod.Extension('client_name', 'Netcatty'));
// RDPDR sandboxed local drive redirection (always attach callback so live hotplug works)
@@ -1491,14 +1537,16 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
: String(err);
// CRITICAL: In `auto` mode, if negotiation fails BEFORE credentials are sent,
// retry ONCE without CredSSP (pure TLS). NEVER auto-retry on WrongPassword /
// step through NLA -> TLS -> Standard RDP. NEVER auto-retry on WrongPassword /
// LogonFailure / AccessDenied to prevent Windows NLA account lockout!
if (
securityMode === 'auto'
&& !fallbackDisableCredSsp
&& kind === mod.IronErrorKind.NegotiationFailure
) {
callbacksRef.current.onNegotiationFallbackNeeded?.();
const nextFallbackStage = resolveNextRdpAutoFallback({
configuredMode: securityMode,
currentStage: autoFallbackStage,
isNegotiationFailure: kind === mod.IronErrorKind.NegotiationFailure,
errorMessage: msg,
});
if (nextFallbackStage) {
callbacksRef.current.onNegotiationFallbackNeeded?.(nextFallbackStage);
return;
}
@@ -1512,6 +1560,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
kind,
});
return;
} finally {
try { builder.free(); } catch { /* ignore */ }
}
if (disposed) {
@@ -1527,7 +1577,12 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
try { size.free(); } catch { /* ignore */ }
setRemoteSize({ width: w, height: h });
setSessionConnectedSeq((seq) => seq + 1);
callbacksRef.current.onConnected({ width: w, height: h, encrypted: !enableStandardRdp });
callbacksRef.current.onConnected({
width: w,
height: h,
encrypted: !enableStandardRdp,
securityInfo: negotiatedSecurityInfo ?? undefined,
});
try {
const termInfo = await session.run();
@@ -1595,7 +1650,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
emitClipboardTransfer(null);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [wsUrl, fallbackDisableCredSsp]);
}, [wsUrl, autoFallbackStage]);
// Debounced dynamic resize via IronRDP Display Control channel
useEffect(() => {
+298 -25
View File
@@ -1,14 +1,34 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, Check, KeyRound, Loader2, Plug, RefreshCw, ShieldCheck, X } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { getConnectionLogsSnapshot } from '../../application/state/connectionLogsStore';
import {
registerSessionLogFinalizer,
saveRemoteDesktopThumbnail,
updateRemoteDesktopConnectionLogActivity,
} from '../../application/state/remoteDesktopLogActions';
import { useTerminalSessionCloseCapture } from '../../application/state/terminalSessionCloseCapture';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type { Host, Identity, KnownHost, SSHKey, TerminalSession } from '../../types';
import type { RdpMultiMonitorMode } from '../../domain/models/connection';
import type {
RdpMultiMonitorMode,
RemoteDesktopSessionEventKind,
RemoteDesktopSessionMetadata,
} from '../../domain/models';
import {
appendRemoteDesktopSessionEvent,
getConnectionLogRecordingClips,
mergeRemoteDesktopSessionMetadata,
} from '../../domain/remoteDesktopRecording';
import {
computeMonitorLayoutEntries,
formatStandardRdpSecurityBadge,
resolveEffectiveRdpSecurityMode,
resolveRemoteDesktopConnectionSpec,
type MonitorLayoutSpec,
type RdpAutoFallbackStage,
type RdpDisplayControlCaps,
type RdpNegotiatedSecurityInfo,
type RemoteDesktopProtocol,
} from '../../domain/remoteDesktop';
import { stopAgentTurn, type AgentStopBridge } from '../../infrastructure/ai/harness/agentStop';
@@ -72,6 +92,7 @@ import { RemoteDesktopCertDialog } from './RemoteDesktopCertDialog';
import {
buildRemoteDesktopStartPayload,
buildSystemRemoteDesktopPayload,
formatTransferBytes,
getRemoteDesktopBridge,
tr,
type RemoteDesktopCanvasHandle,
@@ -93,6 +114,7 @@ import { VncCanvasView, type VncCapabilities } from './VncCanvasView';
import type { RemoteDesktopSpecialKeyId } from './vncKeymap';
const EMPTY_FINALIZE_LOG = () => '';
const RESIZE_EVENT_DEBOUNCE_MS = 1500;
export interface RemoteDesktopPaneProps {
sessionId: string;
@@ -192,6 +214,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const attemptNonceRef = useRef(0);
const closeCaptureNeverConnectedRef = useRef(false);
const closeCaptureDoneRef = useRef(false);
const closeCapturePromiseRef = useRef<Promise<void> | null>(null);
const spec = useMemo(
() => resolveRemoteDesktopConnectionSpec(host, protocol, identities),
@@ -229,7 +252,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const [disconnectError, setDisconnectError] = useState<string | null>(null);
const [wsUrl, setWsUrl] = useState<string | null>(null);
const [connectAttempt, setConnectAttempt] = useState(0);
const [fallbackDisableCredSsp, setFallbackDisableCredSsp] = useState(false);
const [autoFallbackStage, setAutoFallbackStage] = useState<RdpAutoFallbackStage>('none');
// Display, audio, input, and toolbar controls
const [displayMode, setDisplayMode] = useState<RemoteDesktopDisplayMode>(() => {
@@ -259,6 +282,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const [isFullscreen, setIsFullscreen] = useState(false);
const [resolution, setResolution] = useState<{ width: number; height: number } | null>(null);
const [encrypted, setEncrypted] = useState<boolean>(false);
const [rdpSecurityInfo, setRdpSecurityInfo] = useState<RdpNegotiatedSecurityInfo | null>(null);
const [desktopTitle, setDesktopTitle] = useState<string | null>(null);
// Resolution presets, multi-monitor, RDPDR local shared folders, and live telemetry
const [fixedResolution, setFixedResolution] = useState<{ width: number; height: number } | null>(null);
@@ -303,6 +327,83 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const tunneled = Boolean(spec.tunnelViaHostSsh || (chainHosts && chainHosts.length > 0));
const effectiveLabel = desktopTitle || spec.label || spec.hostHostname;
const hasConnectedOnceRef = useRef(false);
const sessionThumbnailCapturedRef = useRef(false);
const sessionThumbnailInFlightRef = useRef(false);
const isRecordingOrStoppingRef = useRef(false);
const resizeEventTimerRef = useRef<number | null>(null);
const thumbnailTimerRef = useRef<number | null>(null);
const lastLoggedResolutionRef = useRef<string | null>(null);
const appendSessionEvent = useCallback(
(
kind: RemoteDesktopSessionEventKind,
summary: string,
options?: {
timestamp?: number;
detail?: string;
metaPatch?: Partial<RemoteDesktopSessionMetadata>;
},
) => {
const ts = options?.timestamp ?? Date.now();
void updateRemoteDesktopConnectionLogActivity(sessionId, ({ events, meta }) => ({
events: appendRemoteDesktopSessionEvent(events, {
timestamp: ts,
kind,
summary,
detail: options?.detail,
}),
meta: options?.metaPatch ? mergeRemoteDesktopSessionMetadata(meta, options.metaPatch) : undefined,
}));
},
[sessionId],
);
// Capture a compact local JPEG poster for unrecorded sessions before tearing down canvas.
const captureUnrecordedSessionThumbnail = useCallback(async () => {
if (
sessionThumbnailCapturedRef.current
|| sessionThumbnailInFlightRef.current
|| isRecordingOrStoppingRef.current
) {
return;
}
const handle = canvasHandleRef.current;
if (!handle?.captureThumbnailJpeg) return;
const { connectionLogs } = getConnectionLogsSnapshot();
const matchingLog = selectConnectionLogForTerminalDataCapture([...connectionLogs], { sessionId });
if (!matchingLog) return;
if (getConnectionLogRecordingClips(matchingLog).length > 0 || matchingLog.remoteDesktopMeta?.thumbnailId) {
sessionThumbnailCapturedRef.current = true;
return;
}
sessionThumbnailInFlightRef.current = true;
try {
const jpeg = await handle.captureThumbnailJpeg();
if (!jpeg || jpeg.byteLength === 0 || isRecordingOrStoppingRef.current) return;
const saved = await saveRemoteDesktopThumbnail({ data: jpeg });
if (saved?.ok && saved.id) {
sessionThumbnailCapturedRef.current = true;
await updateRemoteDesktopConnectionLogActivity(sessionId, ({ meta }) => ({
meta: mergeRemoteDesktopSessionMetadata(meta, { thumbnailId: saved.id }),
}));
}
} catch {
// Non-fatal: session log works fine without a thumbnail.
} finally {
sessionThumbnailInFlightRef.current = false;
}
}, [sessionId]);
const handleRecordingLifecycleEvent = useCallback(
(ev: { kind: 'recording_started' | 'recording_stopped'; timestamp: number; summary: string; detail?: string }) => {
appendSessionEvent(ev.kind, ev.summary, {
timestamp: ev.timestamp,
detail: ev.detail,
});
},
[appendSessionEvent],
);
const recorder = useRemoteDesktopRecorder({
sessionId,
@@ -311,13 +412,32 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
status,
audioEnabled: isRdp && Boolean(spec.rdpConfig?.audioEnabled),
canvasHandleRef,
onRecordingLifecycleEvent: handleRecordingLifecycleEvent,
});
isRecordingOrStoppingRef.current = recorder.isRecording || recorder.isStopping;
// Stamp ConnectionLog endTime when this remote desktop session closes via any UI/hotkey path.
// Clear debounced timers on unmount to prevent post-unmount leaks.
useEffect(() => () => {
if (resizeEventTimerRef.current !== null) {
window.clearTimeout(resizeEventTimerRef.current);
resizeEventTimerRef.current = null;
}
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
thumbnailTimerRef.current = null;
}
}, []);
// Stamp ConnectionLog endTime when this remote desktop session closes via any UI/hotkey/quit path.
const handleCloseLogCapture = useCallback(
(closingSessionId: string, data: string) => {
if (closeCapturePromiseRef.current) return closeCapturePromiseRef.current;
closeCaptureDoneRef.current = true;
return onTerminalDataCapture?.(closingSessionId, data);
const promise = Promise.resolve(onTerminalDataCapture?.(closingSessionId, data))
.catch(() => {})
.then(() => undefined);
closeCapturePromiseRef.current = promise;
return promise;
},
[onTerminalDataCapture],
);
@@ -330,6 +450,14 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onTerminalDataCapture: handleCloseLogCapture,
});
// Also await endTime stamping on native window close / app quit (even when unrecorded).
useEffect(() => {
if (!onTerminalDataCapture) return undefined;
return registerSessionLogFinalizer(async () => {
await handleCloseLogCapture(sessionId, '');
});
}, [handleCloseLogCapture, onTerminalDataCapture, sessionId]);
const updateStatus = useCallback(
(next: 'connecting' | 'connected' | 'disconnected') => {
setStatus(next);
@@ -383,6 +511,17 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const toastKey = `${next.id}:${next.phase}`;
if (lastToastedTransferKeyRef.current !== toastKey) {
lastToastedTransferKeyRef.current = toastKey;
const fileSummary = next.fileCount > 1
? `${next.fileName} (+${next.fileCount - 1})`
: next.fileName;
const sizeDetail = next.totalBytes > 0 ? formatTransferBytes(next.totalBytes) : undefined;
appendSessionEvent(
next.direction === 'upload' ? 'clipboard_upload' : 'clipboard_download',
next.phase === 'completed'
? `${next.direction === 'upload' ? 'Uploaded' : 'Downloaded'} ${fileSummary}`
: `${next.direction === 'upload' ? 'Upload' : 'Download'} failed: ${fileSummary}`,
{ detail: next.phase === 'error' ? (next.error || sizeDetail) : sizeDetail },
);
if (next.phase === 'completed') {
toast.success(
next.message || tr(t, 'remoteDesktop.clipboard.transferCompleted', 'Clipboard file transfer complete'),
@@ -395,7 +534,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
}
}
},
[t],
[appendSessionEvent, t],
);
useEffect(() => {
@@ -867,6 +1006,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setWsUrl(null);
setDisconnectError(null);
setPendingCert(null);
setRdpSecurityInfo(null);
setRemoteClipboardFiles([]);
setClipboardFileTransferStatus(null);
setClipboardTransfer(null);
@@ -895,7 +1035,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
knownHosts,
quality,
viewOnly,
securityMode: fallbackDisableCredSsp ? 'tls' : spec.rdpConfig?.securityMode,
securityMode: resolveEffectiveRdpSecurityMode(spec.rdpConfig?.securityMode, autoFallbackStage),
ignoreCertErrors: spec.rdpConfig?.ignoreCertErrors,
});
@@ -937,7 +1077,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
// Intentionally reconnect only when connectAttempt, connectionIntent, needsAuthPrompt, or fallback change.
// Quality changes apply live over the active VNC WebSocket without reconnecting.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [connectAttempt, connectionIntent, needsAuthPrompt, fallbackDisableCredSsp]);
}, [connectAttempt, connectionIntent, needsAuthPrompt, autoFallbackStage]);
const handleCertDecision = useCallback(
(decision: RemoteDesktopCertDecisionValue) => {
@@ -973,7 +1113,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setAuthErrorMessage(null);
setNeedsAuthPrompt(false);
setConnectionIntent('active');
setFallbackDisableCredSsp(false);
setAutoFallbackStage('none');
setConnectAttempt((n) => n + 1);
},
[],
@@ -988,13 +1128,19 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const handleReconnect = useCallback(() => {
setDisconnectError(null);
setFallbackDisableCredSsp(false);
setAutoFallbackStage('none');
setConnectionIntent('active');
setConnectAttempt((n) => n + 1);
}, []);
const handleDisconnect = useCallback(() => {
releaseKeyboardGrab();
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
appendSessionEvent('disconnected', 'Session closed by user', {
metaPatch: { disconnectReason: 'Closed by user' },
});
}
const activeId = activeBackendSessionIdRef.current;
if (activeId) {
void getRemoteDesktopBridge()?.stop(activeId).catch(() => {});
@@ -1002,7 +1148,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setWsUrl(null);
updateStatus('disconnected');
onCloseSession?.(sessionId);
}, [onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
}, [appendSessionEvent, captureUnrecordedSessionThumbnail, onCloseSession, releaseKeyboardGrab, sessionId, updateStatus]);
const handleOpenSystemClient = useCallback(async () => {
const rdBridge = getRemoteDesktopBridge();
@@ -1058,12 +1204,13 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
try {
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
appendSessionEvent('screenshot', 'Copied screenshot to clipboard');
toast.success(tr(t, 'remoteDesktop.screenshot.copied', 'Screenshot copied to clipboard'));
}
} catch {
toast.error(tr(t, 'remoteDesktop.screenshot.copyFailed', 'Failed to copy screenshot'));
}
}, [t]);
}, [appendSessionEvent, t]);
const handleScreenshotSave = useCallback(async () => {
const blob = await canvasHandleRef.current?.captureScreenshot();
@@ -1075,6 +1222,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const bytes = new Uint8Array(await blob.arrayBuffer());
const res = await rdBridge.saveClipboardFile({ action: 'oneshot', fileName, data: bytes });
if (res?.ok && !res.canceled) {
appendSessionEvent('screenshot', 'Saved PNG screenshot', { detail: fileName });
toast.success(tr(t, 'remoteDesktop.screenshot.saved', 'Screenshot saved'));
}
return;
@@ -1085,13 +1233,19 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}, [effectiveLabel, protocol, t]);
appendSessionEvent('screenshot', 'Saved PNG screenshot', { detail: fileName });
}, [appendSessionEvent, effectiveLabel, protocol, t]);
const handleCanvasError = useCallback(
(err: { message: string; isAuthError?: boolean }) => {
releaseKeyboardGrab();
publishRemoteDesktopNetworkStats(sessionId, null);
publishRemoteDesktopFps(sessionId, 0);
const cleanMessage = sanitizeRemoteDesktopError(err.message) || err.message;
appendSessionEvent('error', err.isAuthError ? 'Authentication failed' : 'Connection error', {
detail: cleanMessage,
metaPatch: { disconnectReason: cleanMessage },
});
if (err.isAuthError) {
setAuthErrorMessage(err.message);
setConnectionIntent('idle');
@@ -1103,7 +1257,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setDisconnectError(err.message);
updateStatus('disconnected');
},
[releaseKeyboardGrab, sessionId, updateStatus],
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
);
const handleCanvasDisconnected = useCallback(
@@ -1111,15 +1265,27 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
releaseKeyboardGrab();
publishRemoteDesktopNetworkStats(sessionId, null);
publishRemoteDesktopFps(sessionId, 0);
const cleanReason = sanitizeRemoteDesktopError(reason || null) || undefined;
appendSessionEvent('disconnected', 'Remote desktop disconnected', {
detail: cleanReason,
metaPatch: cleanReason ? { disconnectReason: cleanReason } : undefined,
});
if (reason) setDisconnectError(reason);
updateStatus('disconnected');
},
[releaseKeyboardGrab, sessionId, updateStatus],
[appendSessionEvent, releaseKeyboardGrab, sessionId, updateStatus],
);
const handleNegotiationFallback = useCallback(() => {
setFallbackDisableCredSsp(true);
setStageMessage('CredSSP unavailable, retrying with TLS security...');
const handleNegotiationFallback = useCallback((nextStage: Exclude<RdpAutoFallbackStage, 'none'>) => {
// Clear wsUrl synchronously so RdpCanvasView unmounts immediately and never
// starts a stale WASM connect() against the closing WebSocket on this render.
setWsUrl(null);
setAutoFallbackStage(nextStage);
setStageMessage(
nextStage === 'rdp'
? 'TLS unavailable, retrying with Standard RDP security...'
: 'CredSSP unavailable, retrying with TLS security...',
);
setConnectAttempt((n) => n + 1);
}, []);
@@ -1342,6 +1508,9 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
deviceId: result.added.deviceId,
name: result.added.name,
});
appendSessionEvent('shared_folder_mounted', `Mounted shared folder "${result.added.name}"`, {
detail: result.added.readOnly ? 'Read-only' : 'Read / Write',
});
toast.success(
tr(t, 'remoteDesktop.sharedFolders.mounted', 'Mounted "{name}" on remote desktop', {
name: result.added.name,
@@ -1351,7 +1520,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to add shared folder');
}
}, [host.id, syncDrivesToBackend, t]);
}, [appendSessionEvent, host.id, syncDrivesToBackend, t]);
const handleAddSharedFolderClick = useCallback(() => {
void handleAddSharedFolder();
@@ -1365,6 +1534,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
void syncDrivesToBackend(next);
if (target && status === 'connected') {
canvasHandleRef.current?.removeSharedDrive?.(target.deviceId);
appendSessionEvent('shared_folder_unmounted', `Unmounted shared folder "${target.name}"`);
toast.info(
tr(t, 'remoteDesktop.sharedFolders.unmounted', 'Unmounted "{name}"', {
name: target.name,
@@ -1372,7 +1542,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
);
}
},
[host.id, sharedFolders, status, syncDrivesToBackend, t],
[appendSessionEvent, host.id, sharedFolders, status, syncDrivesToBackend, t],
);
const handleToggleSharedFolderReadOnly = useCallback(
@@ -1414,6 +1584,28 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
void handleOpenSystemClient();
}, [handleOpenSystemClient]);
const handleDesktopResize = useCallback(
(size: { width: number; height: number }) => {
setResolution(size);
if (size.width <= 0 || size.height <= 0) return;
if (resizeEventTimerRef.current !== null) {
window.clearTimeout(resizeEventTimerRef.current);
resizeEventTimerRef.current = null;
}
const key = `${size.width}x${size.height}`;
if (lastLoggedResolutionRef.current === key) return;
resizeEventTimerRef.current = window.setTimeout(() => {
resizeEventTimerRef.current = null;
if (lastLoggedResolutionRef.current === key) return;
lastLoggedResolutionRef.current = key;
appendSessionEvent('resized', `Desktop resized to ${size.width}\u00d7${size.height}`, {
metaPatch: { resolution: { width: size.width, height: size.height } },
});
}, RESIZE_EVENT_DEBOUNCE_MS);
},
[appendSessionEvent],
);
const handleVncConnected = useCallback(
(info: {
width: number;
@@ -1430,18 +1622,97 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setSupportsXvp(Boolean(info.supportsXvp));
setStageMessage('Desktop connected');
updateStatus('connected');
const isReconnect = hasConnectedOnceRef.current;
hasConnectedOnceRef.current = true;
lastLoggedResolutionRef.current = `${info.width}x${info.height}`;
const securityLabel = info.encrypted ? 'TLS' : 'RFB';
appendSessionEvent(
isReconnect ? 'reconnected' : 'connected',
isReconnect ? 'Reconnected to VNC desktop' : 'Connected to VNC desktop',
{
detail: `${info.width}\u00d7${info.height} \u00b7 ${securityLabel}${tunneled ? ' \u00b7 SSH Tunnel' : ''}`,
metaPatch: {
resolution: { width: info.width, height: info.height },
securityLabel,
tunneled,
monitorCount: 1,
},
},
);
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
}
thumbnailTimerRef.current = window.setTimeout(() => {
thumbnailTimerRef.current = null;
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
}
}, 1500);
},
[updateStatus],
[appendSessionEvent, captureUnrecordedSessionThumbnail, tunneled, updateStatus],
);
const handleRdpConnected = useCallback(
(info: { width: number; height: number; encrypted?: boolean }) => {
(info: {
width: number;
height: number;
encrypted?: boolean;
securityInfo?: RdpNegotiatedSecurityInfo;
}) => {
setResolution({ width: info.width, height: info.height });
setEncrypted(Boolean(info.encrypted));
setRdpSecurityInfo(info.securityInfo ?? null);
const legacyBadge = formatStandardRdpSecurityBadge(info.securityInfo);
if (autoFallbackStage === 'rdp') {
toast.info(
legacyBadge
? tr(
t,
'remoteDesktop.rdp.fallbackStandardRdpWithCipher',
'Connected using Standard RDP Security ({{cipher}}).',
{ cipher: legacyBadge },
)
: tr(
t,
'remoteDesktop.rdp.fallbackStandardRdp',
'Connected using Standard RDP Security.',
),
);
}
setStageMessage('Desktop connected');
updateStatus('connected');
const isReconnect = hasConnectedOnceRef.current;
hasConnectedOnceRef.current = true;
lastLoggedResolutionRef.current = `${info.width}x${info.height}`;
const securityLabel = info.encrypted
? (autoFallbackStage === 'tls' ? 'TLS' : 'TLS / NLA')
: (legacyBadge || 'Standard RDP');
const activeMonitors = Math.max(1, monitorLayout.length);
appendSessionEvent(
isReconnect ? 'reconnected' : 'connected',
isReconnect ? 'Reconnected to RDP desktop' : 'Connected to RDP desktop',
{
detail: `${info.width}\u00d7${info.height} \u00b7 ${securityLabel}${tunneled ? ' \u00b7 SSH Tunnel' : ''}`,
metaPatch: {
resolution: { width: info.width, height: info.height },
securityLabel,
tunneled,
monitorCount: activeMonitors,
},
},
);
// Capture an early lightweight poster thumbnail once desktop finishes first paint.
if (thumbnailTimerRef.current !== null) {
window.clearTimeout(thumbnailTimerRef.current);
}
thumbnailTimerRef.current = window.setTimeout(() => {
thumbnailTimerRef.current = null;
if (statusRef.current === 'connected') {
void captureUnrecordedSessionThumbnail();
}
}, 1500);
},
[updateStatus],
[appendSessionEvent, autoFallbackStage, captureUnrecordedSessionThumbnail, monitorLayout.length, t, tunneled, updateStatus],
);
const handleRemoteClipboardFilesChange = useCallback(
@@ -1495,6 +1766,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
statusDetail={stageMessage}
tunneled={tunneled}
encrypted={encrypted}
legacySecurityBadge={isRdp ? formatStandardRdpSecurityBadge(rdpSecurityInfo) : null}
resolution={resolution}
isFullscreen={isFullscreen}
keyboardGrabActive={keyboardGrabActive}
@@ -1546,6 +1818,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
aiAuditCount={aiAuditCount}
onOpenAiAuditLog={onAskAi ? handleOpenAiAuditLog : undefined}
isRecording={recorder.isRecording}
isStoppingRecording={recorder.isStopping}
recordingElapsedLabel={recorder.formattedElapsed}
recordingSupported={recorder.isSupported}
onToggleRecording={handleToggleRecordingClick}
@@ -1623,7 +1896,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onRequestReleaseGrab={releaseKeyboardGrab}
onConnected={handleVncConnected}
onCapabilitiesChange={handleVncCapabilitiesChange}
onDesktopResize={setResolution}
onDesktopResize={handleDesktopResize}
onDesktopName={setDesktopTitle}
onBell={handleVncBell}
onFpsChange={handleFpsChange}
@@ -1643,7 +1916,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
password={credentials.password}
domain={credentials.domain}
rdpConfig={spec.rdpConfig}
fallbackDisableCredSsp={fallbackDisableCredSsp}
autoFallbackStage={autoFallbackStage}
isVisible={isVisible}
displayMode={displayMode}
highDpi={highDpi}
@@ -1661,7 +1934,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
onFpsChange={handleFpsChange}
onRequestReleaseGrab={releaseKeyboardGrab}
onConnected={handleRdpConnected}
onDesktopResize={setResolution}
onDesktopResize={handleDesktopResize}
onRemoteClipboardFilesChange={handleRemoteClipboardFilesChange}
onClipboardFileTransferStatus={setClipboardFileTransferStatus}
onClipboardTransferChange={handleClipboardTransferChange}
@@ -48,6 +48,21 @@ test('RemoteDesktopToolbar does not expose SFTP button on graphical remote deskt
assert.doesNotMatch(withSftpProp, /data-testid="remote-desktop-sftp-btn"/);
});
test('RemoteDesktopToolbar fullscreen wrapper passes clicks through except at the hover strip and visible pill', () => {
const html = renderToolbar({ isFullscreen: true });
const layers = html.match(/^<div class="([^"]+)"><div class="([^"]+)"><\/div><div class="([^"]+)">/);
assert.ok(layers, 'fullscreen wrapper should contain the trigger strip and toolbar bar');
const [, wrapperClass, triggerClass, barClass] = layers;
assert.match(wrapperClass, /\bpointer-events-none\b/);
assert.doesNotMatch(wrapperClass, /\bpointer-events-auto\b/);
assert.match(wrapperClass, /\bleft-0 right-0\b/);
assert.match(triggerClass, /\bpointer-events-auto\b/);
assert.match(triggerClass, /\bh-3\b/);
assert.match(barClass, /-translate-y-full opacity-0 pointer-events-none/);
assert.doesNotMatch(barClass, /\bpointer-events-auto\b/);
});
test('RemoteDesktopToolbar renders live clipboard transfer progress pills for all phases', () => {
const staged = renderToolbar({
clipboardTransfer: {
@@ -190,3 +205,22 @@ test('RemoteDesktopToolbar disables Keyboard Grab while connecting', () => {
});
assert.match(connectingHtml, /<button[^>]*disabled=""[^>]*aria-label="Keys: Local"/);
});
test('RemoteDesktopToolbar renders Standard RDP security badge only when not using TLS', () => {
const standardRdpHtml = renderToolbar({
protocol: 'rdp',
encrypted: false,
legacySecurityBadge: 'RC4-128',
});
assert.match(standardRdpHtml, /RC4-128/);
assert.match(standardRdpHtml, /Standard RDP Security \(RC4-128\)/);
assert.doesNotMatch(standardRdpHtml, /Encrypted TLS connection/);
const tlsHtml = renderToolbar({
protocol: 'rdp',
encrypted: true,
legacySecurityBadge: 'RC4-128',
});
assert.match(tlsHtml, /Encrypted TLS connection/);
assert.doesNotMatch(tlsHtml, /Standard RDP Security/);
});
@@ -24,6 +24,7 @@ import {
History,
Keyboard,
Layers,
Loader2,
Lock,
Maximize,
Maximize2,
@@ -100,6 +101,7 @@ export interface RemoteDesktopToolbarProps {
statusDetail?: string;
tunneled?: boolean;
encrypted?: boolean;
legacySecurityBadge?: string | null;
resolution?: { width: number; height: number } | null;
fps?: number;
isFullscreen: boolean;
@@ -160,6 +162,7 @@ export interface RemoteDesktopToolbarProps {
onOpenAiAuditLog?: () => void;
// Session Recording
isRecording?: boolean;
isStoppingRecording?: boolean;
recordingElapsedLabel?: string;
recordingSupported?: boolean;
onToggleRecording?: () => void;
@@ -449,6 +452,7 @@ const RemoteDesktopNetworkTelemetryPill = React.memo(({
fpsProp,
resolutionLabel,
encrypted,
legacySecurityBadge,
tunneled,
narrowMode,
}: {
@@ -458,6 +462,7 @@ const RemoteDesktopNetworkTelemetryPill = React.memo(({
fpsProp?: number;
resolutionLabel: string;
encrypted?: boolean;
legacySecurityBadge?: string | null;
tunneled?: boolean;
narrowMode: boolean;
}) => {
@@ -601,6 +606,12 @@ const RemoteDesktopNetworkTelemetryPill = React.memo(({
<span>{tr(t, 'remoteDesktop.network.tlsEncrypted', 'TLS')}</span>
</span>
)}
{!encrypted && legacySecurityBadge && (
<span className="inline-flex items-center gap-0.5 text-amber-600 dark:text-amber-400">
<ShieldAlert size={10} />
<span>{legacySecurityBadge}</span>
</span>
)}
{tunneled && (
<span className="inline-flex items-center gap-0.5 text-emerald-600 dark:text-emerald-400">
<SshTunnelIcon size={10} />
@@ -623,6 +634,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
statusDetail,
tunneled,
encrypted,
legacySecurityBadge,
resolution,
fps,
isFullscreen,
@@ -672,6 +684,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
aiAuditCount = 0,
onOpenAiAuditLog,
isRecording = false,
isStoppingRecording = false,
recordingElapsedLabel = '00:00',
recordingSupported = true,
onToggleRecording,
@@ -700,6 +713,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
const [customHeightInput, setCustomHeightInput] = useState(() => String(fixedResolution?.height || resolution?.height || 1080));
const barRef = useRef<HTMLDivElement | null>(null);
const localFileInputRef = useRef<HTMLInputElement | null>(null);
const hoverHideTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const isRdp = protocol === 'rdp';
const canPickResolution = Boolean(onSelectResolutionPreset && (isRdp || supportsDynamicResize));
@@ -716,6 +730,8 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
onSelectResolutionPreset(clampedW, clampedH);
};
useEffect(() => () => clearTimeout(hoverHideTimerRef.current), [isFullscreen]);
useEffect(() => {
const el = barRef.current;
if (!el || isFullscreen || typeof ResizeObserver === 'undefined') return undefined;
@@ -792,6 +808,20 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
aria-label={tr(t, 'remoteDesktop.toolbar.encrypted', 'Encrypted TLS connection')}
/>
)}
{!narrowMode && !encrypted && legacySecurityBadge && (
<span
className="inline-flex items-center gap-0.5 rounded bg-amber-500/12 px-1.5 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400 shrink-0"
title={tr(
t,
'remoteDesktop.toolbar.standardRdpSecurity',
'Standard RDP Security ({{cipher}})',
{ cipher: legacySecurityBadge },
)}
>
<ShieldAlert size={10} />
<span>{legacySecurityBadge}</span>
</span>
)}
{viewOnly && (
<span className="inline-flex items-center gap-1 rounded bg-amber-500/12 px-1.5 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400 shrink-0">
<Eye size={10} />
@@ -1329,6 +1359,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
fpsProp={fps}
resolutionLabel={resolutionLabel}
encrypted={encrypted}
legacySecurityBadge={legacySecurityBadge}
tunneled={tunneled}
narrowMode={narrowMode}
/>
@@ -1946,23 +1977,34 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
)}
{/* Session Recording Button / Active Pill (P2-B, visible in fullscreen too) */}
{onToggleRecording && (!narrowMode || isRecording) && (
{onToggleRecording && (!narrowMode || isRecording || isStoppingRecording) && (
<Tooltip>
<TooltipTrigger asChild>
{isRecording ? (
{isRecording || isStoppingRecording ? (
<Button
type="button"
variant="ghost"
size="sm"
data-testid="remote-desktop-record-btn"
data-recording="true"
className="h-7 shrink-0 gap-1.5 rounded-md bg-rose-500/12 px-2 text-xs font-medium text-rose-500 hover:bg-rose-500/20"
data-recording={isStoppingRecording ? 'stopping' : 'true'}
disabled={isStoppingRecording}
className="h-7 shrink-0 gap-1.5 rounded-md bg-rose-500/12 px-2 text-xs font-medium text-rose-500 hover:bg-rose-500/20 disabled:opacity-70"
onClick={onToggleRecording}
aria-label={tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')}
>
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-rose-500 animate-pulse" />
<Square size={9} className="fill-current" />
<span className="font-mono text-[11px] font-medium">{recordingElapsedLabel}</span>
{isStoppingRecording ? (
<Loader2 size={11} className="shrink-0 animate-spin" />
) : (
<>
<span className="h-1.5 w-1.5 shrink-0 rounded-full bg-rose-500 animate-pulse" />
<Square size={9} className="fill-current" />
</>
)}
<span className="font-mono text-[11px] font-medium">
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: recordingElapsedLabel}
</span>
</Button>
) : (
<Button
@@ -1982,9 +2024,11 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
)}
</TooltipTrigger>
<TooltipContent side="bottom" className="text-xs">
{isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
</TooltipContent>
</Tooltip>
)}
@@ -2165,15 +2209,17 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
<PopoverClose asChild>
<button
type="button"
disabled={status !== 'connected' || !recordingSupported}
disabled={status !== 'connected' || !recordingSupported || isStoppingRecording}
onClick={onToggleRecording}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-45"
>
<Circle size={12} className={isRecording ? 'fill-rose-500 text-rose-500' : 'text-muted-foreground'} />
<span>
{isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
{isStoppingRecording
? tr(t, 'remoteDesktop.toolbar.savingRecording', 'Saving...')
: isRecording
? tr(t, 'remoteDesktop.toolbar.stopRecording', 'Stop recording')
: tr(t, 'remoteDesktop.toolbar.record', 'Record session')}
</span>
</button>
</PopoverClose>
@@ -2298,17 +2344,23 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
return (
<div
className="pointer-events-auto absolute left-0 right-0 top-0 z-30 flex justify-center pt-1.5"
onMouseEnter={() => setHoverReveal(true)}
onMouseLeave={() => setHoverReveal(false)}
className="pointer-events-none absolute left-0 right-0 top-0 z-30 flex justify-center pt-1.5"
onMouseEnter={() => {
clearTimeout(hoverHideTimerRef.current);
setHoverReveal(true);
}}
onMouseLeave={() => {
// Allow travel from the trigger strip onto the animating pill.
hoverHideTimerRef.current = setTimeout(() => setHoverReveal(false), 150);
}}
>
{/* Top-edge hover trigger strip */}
<div className="absolute inset-x-0 top-0 h-3" />
<div className="pointer-events-auto absolute inset-x-0 top-0 h-3" />
<div
className={cn(
'transition-all duration-150',
pinnedFullscreen || hoverReveal
? 'translate-y-0 opacity-100'
? 'translate-y-0 opacity-100 pointer-events-auto'
: '-translate-y-full opacity-0 pointer-events-none',
)}
>
@@ -31,7 +31,12 @@ import {
type RemoteDesktopCanvasHandle,
type RemoteDesktopDisplayMode,
type RemoteDesktopQualityPreset,
type RemoteDesktopRecordingCaptureHandle,
} from './remoteDesktopHelpers';
import {
captureCanvasThumbnailJpeg,
createStableCanvasCaptureStream,
} from './remoteDesktopVideoCapture';
// VNC Binary WebSocket Opcodes (must match electron/bridges/remoteDesktopBridge.cjs)
const S2C = {
@@ -375,6 +380,12 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
return canvasRef.current?.getBoundingClientRect() ?? null;
}, []);
const captureThumbnailJpeg = useCallback(async (): Promise<Uint8Array | null> => {
const canvas = canvasRef.current;
if (!canvas) return null;
return captureCanvasThumbnailJpeg(canvas);
}, []);
const getCaptureStream = useCallback((fps: number): MediaStream | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
@@ -386,6 +397,15 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
}
}, []);
const createRecordingCapture = useCallback(
(fps: number): RemoteDesktopRecordingCaptureHandle | null => {
const canvas = canvasRef.current;
if (!canvas || canvas.width === 0 || canvas.height === 0) return null;
return createStableCanvasCaptureStream(canvas, fps);
},
[],
);
const focusInput = useCallback(() => {
imeInputRef.current?.focus({ preventScroll: true });
}, []);
@@ -673,9 +693,11 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
typeText,
releaseAllInputs,
captureScreenshot,
captureThumbnailJpeg,
captureFrame,
getCanvasRect,
getCaptureStream,
createRecordingCapture,
focusInput,
syncClipboardNow,
requestRefresh,
@@ -687,6 +709,8 @@ export const VncCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Vn
[
captureFrame,
captureScreenshot,
captureThumbnailJpeg,
createRecordingCapture,
focusInput,
getCanvasRect,
getCaptureStream,
+222 -41
View File
@@ -31,17 +31,58 @@ function normalizeSampleRate(sampleRate: number): number {
: 48000;
}
/**
* Lightweight linear resampler for 16-bit little-endian PCM when an active
* recording locked the AudioContext sample rate before the first RDPSND wave.
*/
function resamplePcm16(
data: Uint8Array,
channels: 1 | 2,
sourceRate: number,
targetRate: number,
): Uint8Array {
if (sourceRate === targetRate || sourceRate <= 0 || targetRate <= 0) {
const copy = new Uint8Array(data.byteLength);
copy.set(data);
return copy;
}
const srcView = new DataView(data.buffer, data.byteOffset, data.byteLength);
const bytesPerFrame = channels * 2;
const srcFrames = Math.floor(data.byteLength / bytesPerFrame);
if (srcFrames <= 0) return new Uint8Array(0);
const dstFrames = Math.max(1, Math.round((srcFrames * targetRate) / sourceRate));
const out = new Uint8Array(dstFrames * bytesPerFrame);
const dstView = new DataView(out.buffer);
const ratio = srcFrames / dstFrames;
for (let i = 0; i < dstFrames; i += 1) {
const srcPos = i * ratio;
const idx0 = Math.min(srcFrames - 1, Math.floor(srcPos));
const idx1 = Math.min(srcFrames - 1, idx0 + 1);
const frac = srcPos - idx0;
for (let ch = 0; ch < channels; ch += 1) {
const s0 = srcView.getInt16((idx0 * channels + ch) * 2, true);
const s1 = srcView.getInt16((idx1 * channels + ch) * 2, true);
const sample = Math.max(-32768, Math.min(32767, Math.round(s0 + (s1 - s0) * frac)));
dstView.setInt16((i * channels + ch) * 2, sample, true);
}
}
return out;
}
export class RdpAudioPlayer {
private context: AudioContext | null = null;
private workletNode: AudioWorkletNode | null = null;
private captureDest: MediaStreamAudioDestinationNode | null = null;
private keepaliveSource: ConstantSourceNode | null = null;
private keepaliveGain: GainNode | null = null;
private captureRefCount = 0;
private initPromise: Promise<void> | null = null;
private currentSampleRate = 0;
private requestedSampleRate = 0;
private userVolume = 1.0;
private serverVolume = 1.0;
private muted = false;
private disposed = false;
private pendingChunks: Array<{ data: Uint8Array; channels: number }> = [];
private pendingChunks: Array<{ data: Uint8Array; channels: number; sampleRate: number }> = [];
constructor(options?: { muted?: boolean; volume?: number }) {
if (typeof options?.muted === 'boolean') {
@@ -70,71 +111,90 @@ export class RdpAudioPlayer {
if (this.disposed) return;
const targetRate = normalizeSampleRate(sampleRate);
if (this.context && this.workletNode && this.currentSampleRate === targetRate) {
// Once the worklet is live, reuse the existing AudioContext regardless of
// hardware sample-rate differences; `postPcm` resamples when rates differ.
if (this.context && this.workletNode) {
if (this.context.state === 'suspended') {
await this.context.resume().catch(() => {});
}
return;
}
if (this.initPromise && this.currentSampleRate === targetRate) {
if (this.initPromise) {
return this.initPromise;
}
// Tear down any previous AudioContext if sample rate changed, preserving
// freshly queued chunks for the new rate when initializing from scratch.
this.teardownContext({ clearPending: this.currentSampleRate !== 0 && this.currentSampleRate !== targetRate });
this.currentSampleRate = targetRate;
// If a recording already pre-created the AudioContext + captureDest, keep
// it alive so the live MediaRecorder audio track is never severed.
const reusePreCreatedContext = Boolean(this.context && !this.workletNode && this.captureRefCount > 0);
if (!reusePreCreatedContext && this.context && this.requestedSampleRate !== 0 && this.requestedSampleRate !== targetRate) {
this.teardownContext({ clearPending: true });
}
this.requestedSampleRate = targetRate;
this.initPromise = (async () => {
const initTask = (async () => {
if (typeof AudioContext === 'undefined') return;
let ctx: AudioContext;
try {
ctx = new AudioContext({ sampleRate: targetRate, latencyHint: 'interactive' });
} catch {
ctx = new AudioContext({ latencyHint: 'interactive' });
if (reusePreCreatedContext && this.context) {
ctx = this.context;
} else {
try {
ctx = new AudioContext({ sampleRate: targetRate, latencyHint: 'interactive' });
} catch {
ctx = new AudioContext({ latencyHint: 'interactive' });
}
if (this.disposed) {
await ctx.close().catch(() => {});
return;
}
this.context = ctx;
}
if (this.disposed) {
await ctx.close().catch(() => {});
return;
}
this.context = ctx;
try {
await ctx.audioWorklet.addModule(resolveWorkletUrl());
} catch (err) {
console.warn('[RdpAudioPlayer] Failed to load rdp-pcm-worklet.js:', err);
if (this.context === ctx) {
this.pendingChunks.length = 0;
if (this.context === ctx && this.captureRefCount <= 0) {
this.teardownContext({ clearPending: true });
} else {
} else if (this.context !== ctx) {
await ctx.close().catch(() => {});
}
return;
}
if (this.disposed || this.context !== ctx) {
await ctx.close().catch(() => {});
if (this.context !== ctx) await ctx.close().catch(() => {});
return;
}
let node: AudioWorkletNode;
try {
const bufferSampleRate = normalizeSampleRate(ctx.sampleRate || targetRate);
node = new AudioWorkletNode(ctx, 'rdp-pcm-worklet', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [2],
processorOptions: {
bufferFrames: Math.max(8192, targetRate),
bufferFrames: Math.max(8192, bufferSampleRate),
},
});
node.connect(ctx.destination);
} catch (err) {
console.warn('[RdpAudioPlayer] Failed to create AudioWorkletNode:', err);
if (this.context === ctx) {
this.pendingChunks.length = 0;
if (this.context === ctx && this.captureRefCount <= 0) {
this.teardownContext({ clearPending: true });
} else {
} else if (this.context !== ctx) {
await ctx.close().catch(() => {});
}
return;
}
if (typeof ctx.createMediaStreamDestination === 'function') {
if (this.captureDest) {
try {
node.connect(this.captureDest);
} catch {
// ignore
}
} else if (typeof ctx.createMediaStreamDestination === 'function') {
try {
const captureDest = ctx.createMediaStreamDestination();
node.connect(captureDest);
@@ -151,25 +211,44 @@ export class RdpAudioPlayer {
// Drain buffered chunks that arrived during async worklet startup.
const queued = this.pendingChunks.splice(0);
for (const item of queued) {
this.postPcm(item.data, item.channels);
this.postPcm(item.data, item.channels, item.sampleRate);
}
})();
return this.initPromise;
this.initPromise = initTask;
try {
await initTask;
} finally {
if (this.initPromise === initTask) {
this.initPromise = null;
}
if (!this.workletNode && this.captureRefCount <= 0 && this.context) {
this.teardownContext({ clearPending: true });
}
}
}
private postPcm(data: Uint8Array, channels: number): void {
private postPcm(data: Uint8Array, channels: number, sourceSampleRate?: number): void {
if (!this.workletNode || this.disposed) return;
// Copy into a dedicated ArrayBuffer so transfer does not detach WASM linear memory.
const copy = new Uint8Array(data.byteLength);
copy.set(data);
const ch: 1 | 2 = channels === 1 ? 1 : 2;
const ctxRate = this.context?.sampleRate || this.requestedSampleRate;
// Copy (or resample when hardware/recording AudioContext rate differs from stream)
// into a dedicated ArrayBuffer so transfer never detaches WASM linear memory.
const prepared = sourceSampleRate && ctxRate && sourceSampleRate !== ctxRate
? resamplePcm16(data, ch, sourceSampleRate, ctxRate)
: (() => {
const copy = new Uint8Array(data.byteLength);
copy.set(data);
return copy;
})();
if (prepared.byteLength === 0) return;
this.workletNode.port.postMessage(
{
type: 'pcm',
channels: channels === 1 ? 1 : 2,
buffer: copy.buffer,
channels: ch,
buffer: prepared.buffer,
},
[copy.buffer],
[prepared.buffer],
);
}
@@ -180,20 +259,17 @@ export class RdpAudioPlayer {
if (!msg.data || msg.data.byteLength === 0) return;
const channels = msg.channels === 1 ? 1 : 2;
const normalizedRate = normalizeSampleRate(msg.sampleRate || 48000);
if (this.workletNode && this.currentSampleRate === normalizedRate) {
if (this.workletNode) {
if (this.context?.state === 'suspended') {
void this.context.resume().catch(() => {});
}
this.postPcm(msg.data, channels);
this.postPcm(msg.data, channels, normalizedRate);
} else {
if (this.currentSampleRate !== 0 && this.currentSampleRate !== normalizedRate) {
this.pendingChunks.length = 0;
}
// Bound queued startup chunks so memory never grows unbounded.
if (this.pendingChunks.length < 32) {
const copy = new Uint8Array(msg.data.byteLength);
copy.set(msg.data);
this.pendingChunks.push({ data: copy, channels });
this.pendingChunks.push({ data: copy, channels, sampleRate: normalizedRate });
}
void this.ensureInitialized(normalizedRate);
}
@@ -247,6 +323,41 @@ export class RdpAudioPlayer {
this.workletNode?.port.postMessage({ type: 'flush' });
}
private stopCaptureKeepalive(): void {
const source = this.keepaliveSource;
const gain = this.keepaliveGain;
this.keepaliveSource = null;
this.keepaliveGain = null;
try { source?.stop(); } catch { /* ignore */ }
try { source?.disconnect(); } catch { /* ignore */ }
try { gain?.disconnect(); } catch { /* ignore */ }
}
private ensureCaptureKeepalive(ctx: AudioContext, dest: MediaStreamAudioDestinationNode): void {
if (this.keepaliveSource) return;
if (typeof ctx.createConstantSource !== 'function' || typeof ctx.createGain !== 'function') {
return;
}
let source: ConstantSourceNode | null = null;
let gain: GainNode | null = null;
try {
source = ctx.createConstantSource();
source.offset.value = 0;
gain = ctx.createGain();
gain.gain.value = 0;
source.connect(gain);
gain.connect(dest);
source.start();
this.keepaliveSource = source;
this.keepaliveGain = gain;
} catch {
try { source?.stop(); } catch { /* ignore */ }
try { source?.disconnect(); } catch { /* ignore */ }
try { gain?.disconnect(); } catch { /* ignore */ }
this.stopCaptureKeepalive();
}
}
/**
* Returns a live `MediaStream` tapping the RDPSND worklet output for session
* recording without disrupting speaker playback. Returns `null` when audio
@@ -266,10 +377,79 @@ export class RdpAudioPlayer {
return this.captureDest?.stream ?? null;
}
/**
* Acquire a live recording audio stream even if the remote desktop has not
* emitted its first audio packet yet. Pair every successful call with
* `releaseCaptureAudioStream()` so idle keepalive nodes and unused contexts
* are immediately torn down once recording stops.
*/
public ensureCaptureAudioStream(): MediaStream | null {
if (this.disposed) return null;
if (typeof AudioContext === 'undefined') return null;
let ctx = this.context;
let createdNewContext = false;
if (!ctx) {
try {
ctx = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
} catch {
try {
ctx = new AudioContext({ latencyHint: 'interactive' });
} catch {
return null;
}
}
this.context = ctx;
this.requestedSampleRate = normalizeSampleRate(ctx.sampleRate || 48000);
createdNewContext = true;
}
if (!this.captureDest) {
if (typeof ctx.createMediaStreamDestination !== 'function') {
if (createdNewContext) this.teardownContext({ clearPending: false });
return null;
}
try {
const dest = ctx.createMediaStreamDestination();
if (this.workletNode) {
this.workletNode.connect(dest);
}
this.captureDest = dest;
} catch {
this.captureDest = null;
if (createdNewContext) this.teardownContext({ clearPending: false });
return null;
}
}
if (ctx.state === 'suspended') {
void ctx.resume().catch(() => {});
}
this.captureRefCount += 1;
this.ensureCaptureKeepalive(ctx, this.captureDest);
return this.captureDest.stream;
}
/**
* Release a capture hold acquired via `ensureCaptureAudioStream()`. Stops
* silent keepalive nodes immediately, and closes the AudioContext if no
* RDPSND playback worklet was ever needed.
*/
public releaseCaptureAudioStream(): void {
this.captureRefCount = Math.max(0, this.captureRefCount - 1);
if (this.captureRefCount > 0) return;
this.stopCaptureKeepalive();
if (!this.workletNode && !this.initPromise && this.context) {
this.teardownContext({ clearPending: false });
}
}
private teardownContext(options?: { clearPending?: boolean }): void {
if (options?.clearPending !== false) {
this.pendingChunks.length = 0;
}
this.stopCaptureKeepalive();
const node = this.workletNode;
const captureDest = this.captureDest;
const ctx = this.context;
@@ -277,7 +457,7 @@ export class RdpAudioPlayer {
this.captureDest = null;
this.context = null;
this.initPromise = null;
this.currentSampleRate = 0;
this.requestedSampleRate = 0;
try {
node?.port.postMessage({ type: 'reset' });
node?.port.close?.();
@@ -296,6 +476,7 @@ export class RdpAudioPlayer {
public dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.captureRefCount = 0;
this.teardownContext({ clearPending: true });
}
}
@@ -67,11 +67,19 @@ export interface RemoteDesktopClipboardTransferState {
error?: string;
}
export interface RemoteDesktopRecordingCaptureHandle {
stream: MediaStream;
width: number;
height: number;
dispose: () => void;
}
export interface RemoteDesktopCanvasHandle {
sendSpecialKey: (id: RemoteDesktopSpecialKeyId) => void;
typeText: (text: string) => void;
releaseAllInputs: () => void;
captureScreenshot: () => Promise<Blob | null>;
captureThumbnailJpeg?: () => Promise<Uint8Array | null>;
captureFrame?: (
options?: RemoteDesktopCaptureRequest & {
maxWidth?: number;
@@ -83,6 +91,10 @@ export interface RemoteDesktopCanvasHandle {
) => Promise<RemoteDesktopProviderFrame | null> | RemoteDesktopProviderFrame | null;
getCanvasRect?: () => DOMRect | null;
getCaptureStream?: (fps: number, includeAudio?: boolean) => MediaStream | null;
createRecordingCapture?: (
fps: number,
includeAudio?: boolean,
) => RemoteDesktopRecordingCaptureHandle | null;
focusInput?: () => void;
syncClipboardNow?: () => Promise<void> | void;
requestRefresh?: () => void;
@@ -0,0 +1,29 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
computeAspectFitRect,
computeRecordingCanvasDimensions,
} from './remoteDesktopVideoCapture';
test('computeRecordingCanvasDimensions caps 4K/HiDPI canvases at even-aligned 1080p', () => {
assert.deepEqual(computeRecordingCanvasDimensions(3840, 2160), { width: 1920, height: 1080 });
assert.deepEqual(computeRecordingCanvasDimensions(1920, 1080), { width: 1920, height: 1080 });
assert.deepEqual(computeRecordingCanvasDimensions(1281, 721), { width: 1280, height: 720 });
assert.deepEqual(computeRecordingCanvasDimensions(2560, 1600), { width: 1728, height: 1080 });
});
test('computeAspectFitRect letterboxes resized source cleanly inside fixed recording canvas', () => {
assert.deepEqual(computeAspectFitRect(1920, 1080, 1920, 1080), {
dx: 0,
dy: 0,
dw: 1920,
dh: 1080,
});
// Square source inside 16:9 target -> centered horizontally
assert.deepEqual(computeAspectFitRect(1000, 1000, 1920, 1080), {
dx: 420,
dy: 0,
dw: 1080,
dh: 1080,
});
});
Loaded 100 of 270 files, more files were not shown because too many files have changed in this diff. Show more