Compare commits

..
16 Commits
Author SHA1 Message Date
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
182 changed files with 11251 additions and 1869 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 -22
View File
@@ -119,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
@@ -146,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
@@ -214,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
@@ -293,7 +299,7 @@ jobs:
run: npm run ${{ matrix.pack_script }}
- name: Upload artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v7.0.2
with:
name: netcatty-${{ matrix.name }}
path: |
@@ -333,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 }}
@@ -517,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
@@ -594,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: |
@@ -618,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 }}
@@ -670,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
@@ -728,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: |
@@ -755,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
@@ -766,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
@@ -816,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, '-') }}
@@ -848,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
@@ -1010,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.
+4 -2
View File
@@ -20,10 +20,12 @@ jobs:
timeout-minutes: 20
steps:
- 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
+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}>
+4
View File
@@ -1149,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',
@@ -1262,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',
+4
View File
@@ -1151,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',
@@ -1264,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',
@@ -134,3 +134,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/);
}
});
+4
View File
@@ -1167,6 +1167,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': 'Воспроизводить звук удалённого рабочего стола локально',
@@ -1280,6 +1281,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',
+4
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 音频',
+4
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': '在本機播放遠端桌面音效',
@@ -1254,6 +1255,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 音訊',
+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 });
},
};
}
@@ -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,
};
}
@@ -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((
+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,
+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 => {
@@ -132,6 +132,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
onCreateIdentity,
companionCredentialDrafts,
onCompanionCredentialDraftChange,
resolutionDraft,
onResolutionDraftChange,
effectiveTelnetPort,
effectiveTelnetUsername,
effectiveTelnetPassword,
@@ -395,6 +397,8 @@ export const HostDetailsConnectionSections: React.FC<HostDetailsConnectionSectio
identities={identities}
availableKeys={availableKeys}
onCreateIdentity={onCreateIdentity}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
credentialDraft={companionCredentialDrafts?.rdp}
onCredentialDraftChange={(draft) => onCompanionCredentialDraftChange?.("rdp", draft)}
t={t}
@@ -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();
}
});
}
+21
View File
@@ -87,11 +87,13 @@ import {
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";
@@ -248,6 +250,15 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
},
);
const hasRdpConfig = Boolean(form.rdpConfig);
const [resolutionDraft, setResolutionDraft] = useState<RdpResolutionDraft>({});
useEffect(() => {
setResolutionDraft({});
}, [form.id, hasRdpConfig]);
const onResolutionDraftChange = (dimension: "width" | "height", value: string) => {
setResolutionDraft((prev) => ({ ...prev, [dimension]: value }));
};
const [activeSubPanel, setActiveSubPanel] = useState<SubPanel>("none");
const [credentialPopoverOpen, setCredentialPopoverOpen] = useState(false);
@@ -909,6 +920,12 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
if (savingHostRef.current) return;
savingHostRef.current = true;
try {
if (!pluginProtocolActive && (form.protocol === "rdp" || form.rdpConfig?.enabled)
&& !hasValidRdpFixedResolution(form.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()
@@ -1626,6 +1643,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
t={t}
form={form}
setForm={setForm}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
totpFlushRef={totpFlushRef}
update={update}
groupDefaults={effectiveGroupDefaults}
@@ -1689,6 +1708,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
{isRemoteDesktopPrimary && isCurrentTabEnabled && (activeProtocolTab === "rdp" || activeProtocolTab === "vnc") ? (
<RemoteDesktopOptionsSection
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
form={form}
setForm={setForm}
t={t}
+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],
);
+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,
+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\(\)/);
});
+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">
@@ -48,6 +48,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,7 +66,7 @@ interface CompanionRemoteDesktopSectionsProps {
t: Translate;
}
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps {
interface CompanionRemoteDesktopInlineFieldsProps extends CompanionRemoteDesktopSectionsProps, RdpResolutionDraftProps {
protocol: "vnc" | "rdp";
credentialDraft?: CompanionCredentialDraft;
onCredentialDraftChange?: (draft: CompanionCredentialDraft | undefined) => void;
@@ -83,6 +84,8 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
availableKeys = [],
credentialDraft,
onCredentialDraftChange,
resolutionDraft,
onResolutionDraftChange,
t,
}) => {
const [vncPortInput, setVncPortInput] = useState<string>(() =>
@@ -543,6 +546,16 @@ export const CompanionRemoteDesktopInlineFields: React.FC<CompanionRemoteDesktop
</Select>
</HostDetailsSettingRow>
{rdpNormalized.resolutionMode === "fixed" && (
<RdpResolutionFields
form={form}
setForm={setForm}
t={t}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
/>
)}
<HostDetailsSettingRow
icon={<ShieldCheck />}
label={t("hostDetails.rdp.securityMode")}
@@ -0,0 +1,74 @@
import React, { useId, useState } from "react";
import {
DEFAULT_RDP_HEIGHT,
DEFAULT_RDP_WIDTH,
parseRdpDimensionDraft,
type RdpResolutionDraft,
} from "../../domain/remoteDesktop";
import type { Host } from "../../types";
import { Input } from "../ui/input";
export interface RdpResolutionDraftProps {
resolutionDraft?: RdpResolutionDraft;
onResolutionDraftChange?: (dimension: "width" | "height", value: string) => void;
}
interface RdpResolutionFieldsProps extends RdpResolutionDraftProps {
form: Host;
setForm: React.Dispatch<React.SetStateAction<Host>>;
t: (key: string) => string;
}
export const RdpResolutionFields: React.FC<RdpResolutionFieldsProps> = ({
form, setForm, 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]
?? (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>
);
};
@@ -38,10 +38,11 @@ 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>>;
t: Translate;
@@ -51,6 +52,8 @@ export const RemoteDesktopOptionsSection: React.FC<RemoteDesktopOptionsSectionPr
form,
setForm,
t,
resolutionDraft,
onResolutionDraftChange,
}) => {
const [advancedOpen, setAdvancedOpen] = useState(() =>
Boolean(
@@ -99,36 +102,13 @@ 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}
t={t}
resolutionDraft={resolutionDraft}
onResolutionDraftChange={onResolutionDraftChange}
/>
)}
<HostDetailsSettingRow
+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]">
+40 -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,
@@ -96,7 +100,7 @@ export interface RdpCanvasViewProps {
password: string;
domain: string;
rdpConfig: NormalizedRdpConfig;
fallbackDisableCredSsp: boolean;
autoFallbackStage: RdpAutoFallbackStage;
isVisible: boolean;
displayMode: RemoteDesktopDisplayMode;
highDpi?: boolean;
@@ -113,12 +117,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 +152,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
password,
domain,
rdpConfig,
fallbackDisableCredSsp,
autoFallbackStage,
isVisible,
displayMode,
highDpi = true,
@@ -967,9 +976,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 +1056,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 +1506,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 +1529,8 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
kind,
});
return;
} finally {
try { builder.free(); } catch { /* ignore */ }
}
if (disposed) {
@@ -1527,7 +1546,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 +1619,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(() => {
+48 -11
View File
@@ -6,9 +6,13 @@ import type { Host, Identity, KnownHost, SSHKey, TerminalSession } from '../../t
import type { RdpMultiMonitorMode } from '../../domain/models/connection';
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';
@@ -230,7 +234,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>(() => {
@@ -260,6 +264,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);
@@ -868,6 +873,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setWsUrl(null);
setDisconnectError(null);
setPendingCert(null);
setRdpSecurityInfo(null);
setRemoteClipboardFiles([]);
setClipboardFileTransferStatus(null);
setClipboardTransfer(null);
@@ -896,7 +902,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,
});
@@ -938,7 +944,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) => {
@@ -974,7 +980,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
setAuthErrorMessage(null);
setNeedsAuthPrompt(false);
setConnectionIntent('active');
setFallbackDisableCredSsp(false);
setAutoFallbackStage('none');
setConnectAttempt((n) => n + 1);
},
[],
@@ -989,7 +995,7 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
const handleReconnect = useCallback(() => {
setDisconnectError(null);
setFallbackDisableCredSsp(false);
setAutoFallbackStage('none');
setConnectionIntent('active');
setConnectAttempt((n) => n + 1);
}, []);
@@ -1118,9 +1124,16 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
[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);
}, []);
@@ -1436,13 +1449,36 @@ export const RemoteDesktopPane: React.FC<RemoteDesktopPaneProps> = React.memo(({
);
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);
if (autoFallbackStage === 'rdp') {
const badge = formatStandardRdpSecurityBadge(info.securityInfo);
toast.info(
badge
? tr(
t,
'remoteDesktop.rdp.fallbackStandardRdpWithCipher',
'Connected using Standard RDP Security ({{cipher}}).',
{ cipher: badge },
)
: tr(
t,
'remoteDesktop.rdp.fallbackStandardRdp',
'Connected using Standard RDP Security.',
),
);
}
setStageMessage('Desktop connected');
updateStatus('connected');
},
[updateStatus],
[autoFallbackStage, t, updateStatus],
);
const handleRemoteClipboardFilesChange = useCallback(
@@ -1496,6 +1532,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}
@@ -1644,7 +1681,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}
@@ -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/);
});
@@ -100,6 +100,7 @@ export interface RemoteDesktopToolbarProps {
statusDetail?: string;
tunneled?: boolean;
encrypted?: boolean;
legacySecurityBadge?: string | null;
resolution?: { width: number; height: number } | null;
fps?: number;
isFullscreen: boolean;
@@ -449,6 +450,7 @@ const RemoteDesktopNetworkTelemetryPill = React.memo(({
fpsProp,
resolutionLabel,
encrypted,
legacySecurityBadge,
tunneled,
narrowMode,
}: {
@@ -458,6 +460,7 @@ const RemoteDesktopNetworkTelemetryPill = React.memo(({
fpsProp?: number;
resolutionLabel: string;
encrypted?: boolean;
legacySecurityBadge?: string | null;
tunneled?: boolean;
narrowMode: boolean;
}) => {
@@ -601,6 +604,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 +632,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
statusDetail,
tunneled,
encrypted,
legacySecurityBadge,
resolution,
fps,
isFullscreen,
@@ -700,6 +710,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 +727,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 +805,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 +1356,7 @@ export const RemoteDesktopToolbar: React.FC<RemoteDesktopToolbarProps> = React.m
fpsProp={fps}
resolutionLabel={resolutionLabel}
encrypted={encrypted}
legacySecurityBadge={legacySecurityBadge}
tunneled={tunneled}
narrowMode={narrowMode}
/>
@@ -2298,17 +2326,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',
)}
>
@@ -1,6 +1,7 @@
import { Search, X } from "lucide-react";
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { useI18n } from "../../application/i18n/I18nProvider";
import { usePinyinMatcherVersion } from "../../application/state/usePinyinMatcherVersion";
import { filterSettingsSearchCatalog, type SettingsSearchHit } from "../../domain/settingsSearch";
import { cn } from "../../lib/utils";
import { Input } from "../ui/input";
@@ -26,11 +27,12 @@ export function SettingsSearchControl({
const [query, setQuery] = useState("");
const [activeIndex, setActiveIndex] = useState(0);
const [restoreOpenFocus, setRestoreOpenFocus] = useState(false);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const hits = useMemo(
() => filterSettingsSearchCatalog(query, t, { includePlugins, limit: 12 }),
[query, t, includePlugins],
);
const hits = useMemo(() => {
void pinyinMatcherVersion;
return filterSettingsSearchCatalog(query, t, { includePlugins, limit: 12 });
}, [query, t, includePlugins, pinyinMatcherVersion]);
const collapseSearch = useCallback((restoreFocus = false) => {
setExpanded(false);
@@ -60,9 +60,23 @@ function getBridge(): FigSpecBridge | undefined {
}
// Cache by command and target OS: one renderer can contain both Linux and
// macOS sessions, whose option names and meanings can differ.
// macOS sessions, whose option names and meanings can differ. Bounded with LRU
// eviction so long-lived sessions visiting many CLI tools stay memory-bounded.
const FIG_SPEC_CACHE_MAX_ENTRIES = 80;
const specCache = new Map<string, FigSpec>();
function setSpecCacheEntry(cacheKey: string, spec: FigSpec): void {
if (specCache.has(cacheKey)) {
specCache.delete(cacheKey);
}
specCache.set(cacheKey, spec);
while (specCache.size > FIG_SPEC_CACHE_MAX_ENTRIES) {
const oldestKey = specCache.keys().next().value;
if (oldestKey === undefined) break;
specCache.delete(oldestKey);
}
}
// In-flight loading promises to avoid duplicate loads for the same target OS.
const inFlightLoads = new Map<string, Promise<FigSpec | null>>();
@@ -119,7 +133,11 @@ export async function getAvailableSpecs(hostOs?: FigHostOs): Promise<string[]> {
export async function loadSpec(commandName: string, hostOs?: FigHostOs): Promise<FigSpec | null> {
const cacheKey = specCacheKey(commandName, hostOs);
const cached = specCache.get(cacheKey);
if (cached) return cached;
if (cached) {
specCache.delete(cacheKey);
specCache.set(cacheKey, cached);
return cached;
}
const existing = inFlightLoads.get(cacheKey);
if (existing) return existing;
@@ -136,7 +154,7 @@ export async function loadSpec(commandName: string, hostOs?: FigHostOs): Promise
const spec = await bridge.loadFigSpec(commandName, hostOs);
if (spec) {
specCache.set(cacheKey, spec);
setSpecCacheEntry(cacheKey, spec);
rememberLoadedSpecName(commandName, hostOs);
}
// Don't cache null — the load may have failed transiently (bridge not ready, etc.)
@@ -20,7 +20,6 @@ import type { Snippet } from "../../../domain/models";
import { recordCommand, subscribeCommandHistoryCleared } from "../../../application/state/commandHistoryStore";
import { seedLocalShellHistoryFromHistfiles } from "./localShellHistorySeed";
import { shellEscape } from "./completionEngine";
import { preloadCommonSpecs } from "./figSpecLoader";
import {
listDirectoryEntries,
normalizePathTokenForLookup,
@@ -390,12 +389,9 @@ export function useTerminalAutocomplete(
*/
const typedBufferReliableRef = useRef<boolean>(true);
// Warm the cache for this session's target OS, including when it changes.
useEffect(() => {
if (settings.enabled) {
preloadCommonSpecs(hostOs);
}
}, [settings.enabled, hostOs]);
// Fig command specs are loaded on demand in completionEngine.ts via loadSpec()
// when a command is typed, avoiding ~25 MiB of permanent main-process ESM
// cache and renderer specCache overhead from eagerly importing 67 specs.
// Local Terminal: seed autocomplete history from ~/.zsh_history (etc.) once
// per stable hostId so prefix suggestions match Ghostty-style histfile recall
+131 -43
View File
@@ -36,10 +36,11 @@ type InternalBufferLine = {
};
type LineOriginals = {
fg: Uint32Array;
content: Uint32Array;
mask: Uint8Array;
fingerprint: string;
/** Packed [col, origFg, origContent] triples for highlighted cells only. */
cells: Uint32Array;
/** Number of active triples stored in `cells`. */
count: number;
fingerprint: number;
};
type LogicalLine = {
@@ -66,6 +67,7 @@ export type KeywordHighlighterOptions = {
const CELL_INDICES = 3;
const CELL_CONTENT = 0;
const CELL_FG = 1;
const SPARSE_STRIDE = 3;
const STYLE_MASK = 0xfc000000;
const CM_MASK = 0x3000000;
const CM_RGB = 0x3000000;
@@ -77,6 +79,19 @@ const BULK_WRITE_LINE_BREAKS = 8;
const MAX_LOGICAL_LINE_ROWS = 128;
const ABSOLUTE_ROW_CONTROL_RE = /(?:\x1b\[|\x9b)\d*(?:(?:;\d*)?[Hf]|d)/; // eslint-disable-line no-control-regex
/**
* Fast 53-bit fingerprint (21-bit length + 32-bit FNV-1a, safe integer, zero
* retained row strings).
*/
const hashRowFingerprint = (text: string): number => {
let h = 0x811c9dc5;
const len = text.length;
for (let i = 0; i < len; i += 1) {
h = Math.imul(h ^ text.charCodeAt(i), 0x01000193);
}
return ((len & 0x1fffff) * 0x100000000) + (h >>> 0);
};
const withRgbFg = (originalFg: number, rgb: number): number => (
(originalFg & STYLE_MASK) | CM_RGB | (rgb & 0xffffff)
);
@@ -214,8 +229,8 @@ export class KeywordHighlighter implements IDisposable {
lastRebuildTimings: Record<string, number> = {};
private readonly originals = new WeakMap<InternalBufferLine, LineOriginals>();
/** No-match rows only need a fingerprint; do not allocate cell snapshots. */
private readonly fingerprints = new WeakMap<InternalBufferLine, string>();
/** No-match rows only need a numeric fingerprint; do not allocate cell snapshots or retain row strings. */
private readonly fingerprints = new WeakMap<InternalBufferLine, number>();
private readonly originalWrite: XTerm["write"];
private readonly originalReset: XTerm["reset"];
private readonly originalClear: XTerm["clear"];
@@ -992,15 +1007,15 @@ export class KeywordHighlighter implements IDisposable {
}
private readLogicalLineFingerprints(startY: number, endY: number): {
rowFingerprints: string[];
rowFingerprints: number[];
fastText: string;
} {
const buffer = this.term.buffer.active;
const rowFingerprints: string[] = [];
const rowFingerprints: number[] = [];
let fastText = "";
for (let y = startY; y <= endY; y += 1) {
const raw = buffer.getLine(y)?.translateToString(false) ?? "";
rowFingerprints.push(raw);
rowFingerprints.push(hashRowFingerprint(raw));
fastText += y === endY ? raw.trimEnd() : raw;
}
return { rowFingerprints, fastText };
@@ -1058,7 +1073,7 @@ export class KeywordHighlighter implements IDisposable {
return false;
}
const originals = this.originals.get(internal);
const fingerprint = publicLine?.translateToString(false) ?? "";
const fingerprint = hashRowFingerprint(publicLine?.translateToString(false) ?? "");
const stamped = originals ? originals.fingerprint : this.fingerprints.get(internal);
// An empty/no-match stamp must not survive when the row is later filled
// or recycled with the same BufferLine identity (yes/log floods).
@@ -1072,14 +1087,17 @@ export class KeywordHighlighter implements IDisposable {
line: InternalBufferLine,
originals: LineOriginals,
): boolean {
for (let x = 0; x < line.length; x += 1) {
if (!originals.mask[x]) continue;
if (line._data[x * CELL_INDICES + CELL_FG] === originals.fg[x]) return false;
const { cells, count } = originals;
for (let i = 0; i < count; i += 1) {
const base = i * SPARSE_STRIDE;
const x = cells[base];
if (x >= line.length) continue;
if (line._data[x * CELL_INDICES + CELL_FG] === cells[base + 1]) return false;
}
return true;
}
private stampLogicalLine(startY: number, endY: number, rowFingerprints?: readonly string[]): void {
private stampLogicalLine(startY: number, endY: number, rowFingerprints?: readonly number[]): void {
const buffer = this.term.buffer.active;
for (let y = startY; y <= endY; y += 1) {
const publicLine = buffer.getLine(y);
@@ -1087,35 +1105,105 @@ export class KeywordHighlighter implements IDisposable {
if (!internal) continue;
this.coloredGeneration.set(internal, this.ruleGeneration);
const fingerprint = rowFingerprints
? rowFingerprints[y - startY] ?? ""
: (publicLine?.translateToString(false) ?? "");
? rowFingerprints[y - startY] ?? hashRowFingerprint("")
: hashRowFingerprint(publicLine?.translateToString(false) ?? "");
const originals = this.originals.get(internal);
if (originals) originals.fingerprint = fingerprint;
else this.fingerprints.set(internal, fingerprint);
}
}
private findSparseCellBase(originals: LineOriginals, x: number): number {
const { cells, count } = originals;
if (count === 0) return -1;
// Matches are applied left-to-right, so new columns are almost always
// strictly greater than the last stored column (O(1) fast path).
const lastBase = (count - 1) * SPARSE_STRIDE;
if (x > cells[lastBase]) return -1;
if (x === cells[lastBase]) return lastBase;
for (let i = count - 2; i >= 0; i -= 1) {
const base = i * SPARSE_STRIDE;
if (cells[base] === x) return base;
}
return -1;
}
private growSparseCells(originals: LineOriginals, requiredCount: number): Uint32Array {
const minNeeded = requiredCount * SPARSE_STRIDE;
if (minNeeded <= originals.cells.length) return originals.cells;
const nextLength = Math.max(minNeeded, originals.cells.length * 2);
const next = new Uint32Array(nextLength);
next.set(originals.cells.subarray(0, originals.count * SPARSE_STRIDE));
originals.cells = next;
return next;
}
private colorPhysicalRange(y: number, startX: number, endX: number, rgb: number): void {
const internal = getInternalLine(this.term.buffer.active.getLine(y));
if (!internal || endX <= startX) return;
const originals = this.ensureOriginals(internal);
const first = Math.max(0, startX);
const last = Math.min(internal.length, endX);
for (let x = Math.max(0, startX); x < last; x += 1) {
if (last <= first) return;
const data = internal._data;
const span = last - first;
let originals = this.originals.get(internal);
// Fast path: matches are applied left-to-right, so when `first` is strictly
// past the last stored column (or the line has no stored cells yet), every
// cell in [first, last) is guaranteed new — skip per-cell lookup entirely.
const countBefore = originals ? originals.count : 0;
const strictlyAfter = countBefore === 0
|| first > originals!.cells[(countBefore - 1) * SPARSE_STRIDE];
if (strictlyAfter) {
let cells = originals
? this.growSparseCells(originals, countBefore + span)
: null;
let count = countBefore;
for (let x = first; x < last; x += 1) {
const dataIndex = x * CELL_INDICES;
const currentFg = data[dataIndex + CELL_FG];
if ((currentFg & CM_MASK) !== 0) continue;
if (!originals) {
originals = this.ensureOriginals(internal, span);
cells = originals.cells;
}
const offset = count * SPARSE_STRIDE;
cells![offset] = x;
cells![offset + 1] = currentFg;
cells![offset + 2] = data[dataIndex + CELL_CONTENT];
count += 1;
data[dataIndex + CELL_FG] = withRgbFg(currentFg, rgb);
}
if (originals) originals.count = count;
return;
}
for (let x = first; x < last; x += 1) {
const dataIndex = x * CELL_INDICES;
const content = internal._data[dataIndex + CELL_CONTENT];
const currentFg = internal._data[dataIndex + CELL_FG];
const content = data[dataIndex + CELL_CONTENT];
const currentFg = data[dataIndex + CELL_FG];
// A cell already carrying a PTY palette/truecolor foreground (starship
// directory segments, ANSI logs) must keep that color. Keyword RGB is
// only for the default foreground.
const maskedForContent = originals.mask[x] === 1 && originals.content[x] === content;
const ptyFg = maskedForContent ? originals.fg[x] : currentFg;
const existingBase = this.findSparseCellBase(originals!, x);
const maskedForContent = existingBase >= 0
&& originals!.cells[existingBase + 2] === content;
const ptyFg = maskedForContent ? originals!.cells[existingBase + 1] : currentFg;
if ((ptyFg & CM_MASK) !== 0) continue;
if (!maskedForContent) {
originals.fg[x] = currentFg;
originals.content[x] = content;
originals.mask[x] = 1;
let origFg = currentFg;
if (maskedForContent) {
origFg = originals!.cells[existingBase + 1];
} else if (existingBase >= 0) {
originals!.cells[existingBase + 1] = currentFg;
originals!.cells[existingBase + 2] = content;
} else {
const cells = this.growSparseCells(originals!, originals!.count + (last - x));
const offset = originals!.count * SPARSE_STRIDE;
cells[offset] = x;
cells[offset + 1] = currentFg;
cells[offset + 2] = content;
originals!.count += 1;
}
internal._data[dataIndex + CELL_FG] = withRgbFg(originals.fg[x], rgb);
data[dataIndex + CELL_FG] = withRgbFg(origFg, rgb);
}
}
@@ -1126,17 +1214,16 @@ export class KeywordHighlighter implements IDisposable {
const originals = this.originals.get(internal);
if (!originals) return;
this.coloredGeneration.delete(internal);
for (let x = 0; x < internal.length; x += 1) {
if (!originals.mask[x]) continue;
const { cells, count } = originals;
for (let i = 0; i < count; i += 1) {
const base = i * SPARSE_STRIDE;
const x = cells[base];
if (x >= internal.length) continue;
const dataIndex = x * CELL_INDICES;
const content = internal._data[dataIndex + CELL_CONTENT];
if (originals.content[x] !== content) {
originals.mask[x] = 0;
continue;
}
internal._data[dataIndex + CELL_FG] = originals.fg[x];
originals.mask[x] = 0;
if (internal._data[dataIndex + CELL_CONTENT] !== cells[base + 2]) continue;
internal._data[dataIndex + CELL_FG] = cells[base + 1];
}
this.originals.delete(internal);
}
private restoreBuffer(): void {
@@ -1144,14 +1231,14 @@ export class KeywordHighlighter implements IDisposable {
for (let y = 0; y < buffer.length; y += 1) this.restorePhysicalLine(y, buffer);
}
private ensureOriginals(line: InternalBufferLine): LineOriginals {
private ensureOriginals(line: InternalBufferLine, initialCells: number): LineOriginals {
let originals = this.originals.get(line);
if (!originals || originals.fg.length < line.length) {
if (!originals) {
const capacity = Math.max(16, initialCells);
originals = {
fg: new Uint32Array(line.length),
content: new Uint32Array(line.length),
mask: new Uint8Array(line.length),
fingerprint: this.fingerprints.get(line) ?? originals?.fingerprint ?? "",
cells: new Uint32Array(capacity * SPARSE_STRIDE),
count: 0,
fingerprint: this.fingerprints.get(line) ?? hashRowFingerprint(""),
};
this.originals.set(line, originals);
this.fingerprints.delete(line);
@@ -1164,7 +1251,8 @@ export class KeywordHighlighter implements IDisposable {
const last = Math.min(buffer.length - 1, Math.max(startY, endY));
for (let y = Math.max(0, Math.min(startY, endY)); y <= last; y += 1) {
const internal = getInternalLine(buffer.getLine(y));
if (internal && this.originals.get(internal)) return true;
const originals = internal ? this.originals.get(internal) : undefined;
if (originals && originals.count > 0) return true;
}
return false;
}
@@ -280,6 +280,65 @@ const resolveKittyKeyboardModeState = (
return kittyKeyboardStates.resolve(owner, ctx.deferWebglUntilReplayComplete === true);
};
type DetachedDisposedKittyBroadcastState = {
sessionId: string;
kittyProtocolEnabled: boolean;
kittyMode: KittyKeyboardModeState;
applicationCursorMode: boolean;
win32InputMode: boolean;
nativeKittyPreservesShiftEnter: boolean;
backspaceBehavior: Host["backspaceBehavior"];
sessionRef: MutableRefObject<string | null>;
statusRef: MutableRefObject<TerminalSession["status"]>;
terminalSettingsRef: MutableRefObject<TerminalSettings | undefined>;
passwordPromptActiveRef?: MutableRefObject<boolean>;
broadcastPasswordBypassRef?: MutableRefObject<boolean>;
terminalBackend: TerminalBackendApi;
encodedKeys: Set<string>;
legacySuppressedKeys: Set<string>;
win32ShiftEnterTextKeys: Set<string>;
};
/**
* Keeps broadcast input working while a connected terminal is hibernated
* without closing over `createXTermRuntime`, `term`, or any DOM/buffer state.
*/
const registerDetachedDisposedKittyBroadcastHandler = (
state: DetachedDisposedKittyBroadcastState,
): void => {
const detachedHandler = createKittyKeyboardBroadcastHandler({
resolveOptions: () => ({
kittyProtocolEnabled: state.kittyProtocolEnabled,
kittyMode: state.kittyMode,
applicationCursorMode: state.applicationCursorMode,
encodedKeys: state.encodedKeys,
legacySuppressedKeys: state.legacySuppressedKeys,
win32InputMode: state.win32InputMode,
shiftEnterSettings: state.terminalSettingsRef.current,
nativeKittyPreservesShiftEnter: state.nativeKittyPreservesShiftEnter,
win32ShiftEnterTextKeys: state.win32ShiftEnterTextKeys,
}),
getSessionId: () => state.sessionRef.current,
isSensitiveInput: () => state.passwordPromptActiveRef?.current === true
&& state.broadcastPasswordBypassRef?.current !== true,
isConnected: () => state.statusRef.current === "connected",
isRuntimeDisposed: () => true,
interruptSession: state.terminalBackend.interruptSession
? (id) => state.terminalBackend.interruptSession?.(id)
: undefined,
writeDisposed: (id, data, writeOptions) => state.terminalBackend.writeToSession(
id,
mapTerminalBackspaceInput(data, state.backspaceBehavior),
{
sensitive: state.passwordPromptActiveRef?.current === true
|| writeOptions?.sensitive === true,
},
),
writeActive: () => {},
});
registerKittyKeyboardBroadcastHandler(state.sessionId, detachedHandler);
};
export type XTermRuntime = {
term: XTerm;
fitAddon: FitAddon;
@@ -3356,7 +3415,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
writeWin32InputModeEvent(event, logicalData, writeOptions);
},
});
registerKittyKeyboardBroadcastHandler(
const disposeKittyKeyboardBroadcast = registerKittyKeyboardBroadcastHandler(
ctx.sessionId,
// Forward the dispatch options (#3488): source-prompt fan-outs tag their
// payload with sourceSensitive / beforeUrgentInterrupt, and dropping the
@@ -3666,6 +3725,28 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
invalidatePendingPasteDraft,
dispose: () => {
runtimeDisposed = true;
disposeKittyKeyboardBroadcast();
if (ctx.statusRef.current === "connected" && ctx.sessionRef.current) {
registerDetachedDisposedKittyBroadcastHandler({
sessionId: ctx.sessionId,
kittyProtocolEnabled: kittyKeyboardProtocolEnabled,
kittyMode: kittyKeyboardMode,
applicationCursorMode: Boolean(term.modes?.applicationCursorKeysMode),
win32InputMode: Boolean(term.modes?.win32InputMode),
nativeKittyPreservesShiftEnter: !kittyKeyboardProtocolEnabled
&& nativeKittyKeyboardPreservesShiftEnter(readNativeKittyKeyboardFlags(term)),
backspaceBehavior: ctx.host.backspaceBehavior,
sessionRef: ctx.sessionRef,
statusRef: ctx.statusRef,
terminalSettingsRef: ctx.terminalSettingsRef,
passwordPromptActiveRef: ctx.passwordPromptActiveRef,
broadcastPasswordBypassRef: ctx.broadcastPasswordBypassRef,
terminalBackend: ctx.terminalBackend,
encodedKeys: broadcastEncodedKeys,
legacySuppressedKeys: broadcastLegacySuppressedKeys,
win32ShiftEnterTextKeys: broadcastWin32ShiftEnterTextKeys,
});
}
disposeLinePasteHandler?.();
disposePasteWriteReceipts?.();
pendingLinePastes.clear();
@@ -5,6 +5,7 @@ import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
import { resolveTerminalBroadcastTargetIds } from "../../../domain/terminalBroadcast";
import { isRemoteDesktopProtocol } from "../../../domain/remoteDesktop";
import * as pacedHelpers from "./terminalPacedBroadcast";
import { setTerminalBootEpoch } from "../../../domain/terminalBootEpoch";
@@ -41,7 +42,7 @@ for (const path of ["source", "broadcast"] as const) {
};
const env = { ...pacedHelpers,
ctx: { host: { protocol: "plugin:test" }, terminalBackend }, id: "s", interruptTrace: {},
terminalBackend, isPluginHostProtocol: () => true,
terminalBackend, isPluginHostProtocol: () => true, isRemoteDesktopProtocol,
useCallback: (fn: unknown) => fn, resolveTerminalBroadcastTargetIds: () => ["s"],
sessionsRef: { current: [{ id: "s", protocol: "plugin:test" }] }, isGlobalBroadcastEnabled: true,
canUseDirectSessionWriteFallback: () => true, broadcastPasswordBypassRef: { current: false }, broadcastInterruptPrioritizersRef: { current: new Map() },
@@ -67,7 +68,7 @@ test("ordinary broadcast typing supersedes the recipient's paced paste", t => {
bridge.init({ sessions: new Map([["s", { stream: { write: (data: string) => writes.push(data) } }]]), electronModule: {} });
const env = { ...pacedHelpers,
terminalBackend: { writeToSession: (sessionId: string, data: string, options: object) => bridge.writeToSession(null, { sessionId, data, ...options }) },
useCallback: (fn: unknown) => fn, resolveTerminalBroadcastTargetIds: () => ["s"],
useCallback: (fn: unknown) => fn, resolveTerminalBroadcastTargetIds: () => ["s"], isRemoteDesktopProtocol,
sessionsRef: { current: [{ id: "s", protocol: "ssh" }] }, isGlobalBroadcastEnabled: true,
canUseDirectSessionWriteFallback: () => true, broadcastPasswordBypassRef: { current: false }, isTerminalSensitiveInputActive: () => false,
invoke: undefined as unknown as (data: string, source: string, options?: object) => void,
@@ -101,7 +102,7 @@ for (const change of ["source-sensitive", "peer-sensitive", "peer-typing", "peer
const batch: pacedHelpers.TerminalPacedBroadcast = {};
setTerminalBootEpoch("peer", 1);
const env = {
...pacedHelpers, useCallback: (fn: unknown) => fn, resolveTerminalBroadcastTargetIds,
...pacedHelpers, useCallback: (fn: unknown) => fn, resolveTerminalBroadcastTargetIds, isRemoteDesktopProtocol,
sessionsRef: { current: [{ id: "source", protocol: "ssh" }, { id: "peer", protocol: "ssh" }] as Array<{ id: string; protocol: string; workspaceId?: string }> },
isGlobalBroadcastEnabled: true, canUseDirectSessionWriteFallback: () => true, broadcastPasswordBypassRef: { current: false },
isTerminalSensitiveInputActive: (id: string) => sensitive.has(id),
@@ -24,6 +24,7 @@ test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keybo
export { DEFAULT_KEY_BINDINGS } from "./domain/models/keyBindings";
export { pasteTextIntoTerminal } from "./components/terminal/runtime/terminalUserPaste";
export { resolveTerminalBroadcastTargetIds } from "./domain/terminalBroadcast";
export { isRemoteDesktopProtocol } from "./domain/remoteDesktop";
export { dispatchKittyKeyboardBroadcastInput } from "./components/terminal/runtime/kittyKeyboardBroadcast";
export * from "./components/terminal/runtime/terminalPacedBroadcast";
`,
@@ -53,7 +54,7 @@ test("Shift+Insert uses onPaste and broadcasts clipboard bytes once across keybo
dom.window.eval(bundle);
const results = await dom.window.eval(`(async () => {
const {createXTermRuntime, DEFAULT_TERMINAL_SETTINGS, DEFAULT_KEY_BINDINGS,
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds,
pasteTextIntoTerminal, resolveTerminalBroadcastTargetIds, isRemoteDesktopProtocol,
dispatchKittyKeyboardBroadcastInput, markTerminalBroadcastUserInput,
captureTerminalBroadcastInput, isTerminalBroadcastInputCurrent} = runtimeTest;
const ref = current => ({current});
@@ -16,6 +16,7 @@ const { normalizeLineEndings } = await load('lib/utils.ts');
const { shouldDelayAutoRunSnippetInput, AUTO_RUN_SNIPPET_LINE_DELAY_MS } = await load('components/terminal/terminalHelpers.ts');
const pacedHelpers = await load('components/terminal/runtime/terminalPacedBroadcast.ts');
const { resolveTerminalBroadcastTargetIds, shouldBroadcastDuringSensitivePrompt } = await load('domain/terminalBroadcast.ts');
const { isRemoteDesktopProtocol } = await load('domain/remoteDesktop.ts');
const { canUseDirectSessionWriteFallback } = await load('components/terminalLayer/terminalLayerSessionRouting.ts');
const sourceAt = file => readFileSync(path.join(root, file), 'utf8');
const compile = source => ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
@@ -78,7 +79,7 @@ for (const mode of ['paste', 'lineDelay']) {
const layerSource = sourceAt('components/TerminalLayer.tsx');
const layerEnv = { ...pacedHelpers,
useCallback: callback => callback, terminalBackend,
resolveTerminalBroadcastTargetIds, canUseDirectSessionWriteFallback,
resolveTerminalBroadcastTargetIds, isRemoteDesktopProtocol, canUseDirectSessionWriteFallback,
sessionsRef: { current: ['source', 'peer'].map(id => ({ id, protocol: 'telnet', status: 'connected' })) },
isGlobalBroadcastEnabled: true,
broadcastPasswordBypassRef: { current: false },
@@ -179,3 +179,44 @@ test("released and forgotten panes free their slot", () => {
assert.equal(budget.tryAcquire(hidden), true, "acquiring twice keeps one slot");
assert.equal(budget.getActiveCount(), 1);
});
test("hidden budget keeps 1 MRU hidden pane warm and releases older hidden panes after idle grace", () => {
const clock = createClock();
const budget = createWebglContextBudget({
maxActiveContexts: 12,
minHiddenMs: 3_000,
maxHiddenContexts: 1,
hiddenIdleReleaseMs: 15_000,
now: clock.now,
setTimer: clock.setTimer,
clearTimer: clock.clearTimer,
});
const [a, b, c] = ["a", "b", "c"].map((name) => new FakeMember(name));
assert.equal(budget.tryAcquire(a), true);
assert.equal(budget.tryAcquire(b), true);
assert.equal(budget.tryAcquire(c), true);
a.hiddenSince = clock.now();
budget.noteHidden(a);
clock.advance(5_000);
b.hiddenSince = clock.now();
budget.noteHidden(b);
// Within 15s of hiding `a`, neither hidden pane is evicted (no rapid-flip thrash).
clock.advance(9_999);
assert.equal(a.releases, 0);
assert.equal(b.releases, 0);
// At t=15_000, oldest hidden pane `a` is released; MRU hidden `b` and visible `c` stay warm.
clock.advance(1);
assert.equal(a.releases, 1);
assert.equal(b.releases, 0);
assert.equal(c.releases, 0);
assert.equal(budget.getActiveCount(), 2);
// Even much later, the single MRU hidden pane `b` stays warm for instant Ctrl-Tab.
clock.advance(60_000);
assert.equal(b.releases, 0);
assert.equal(c.releases, 0);
assert.equal(budget.getActiveCount(), 2);
});
@@ -23,6 +23,14 @@ export const MAX_ACTIVE_WEBGL_CONTEXTS = 12;
*/
export const MIN_HIDDEN_MS_BEFORE_WEBGL_RELEASE = 3_000;
/**
* Keep at most one most-recently-hidden terminal WebGL context warm so rapid
* Ctrl-Tab / back-and-forth switches stay instant while older hidden tabs
* release their GPU surfaces and glyph atlases after the idle grace window.
*/
export const MAX_HIDDEN_WEBGL_CONTEXTS = 1;
export const HIDDEN_WEBGL_IDLE_RELEASE_MS = 15_000;
export interface WebglContextBudgetMember {
/** When the pane was hidden, or null while it is on screen. */
getHiddenSince(): number | null;
@@ -46,6 +54,9 @@ export interface WebglContextBudget {
interface WebglContextBudgetOptions {
maxActiveContexts?: number;
minHiddenMs?: number;
/** Optional cap on retained hidden contexts (oldest released after hiddenIdleReleaseMs). */
maxHiddenContexts?: number;
hiddenIdleReleaseMs?: number;
now?: () => number;
setTimer?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
clearTimer?: (timer: ReturnType<typeof setTimeout>) => void;
@@ -56,6 +67,8 @@ export function createWebglContextBudget(
): WebglContextBudget {
const maxActive = options.maxActiveContexts ?? MAX_ACTIVE_WEBGL_CONTEXTS;
const minHiddenMs = options.minHiddenMs ?? MIN_HIDDEN_MS_BEFORE_WEBGL_RELEASE;
const maxHidden = options.maxHiddenContexts ?? Number.POSITIVE_INFINITY;
const hiddenIdleMs = options.hiddenIdleReleaseMs ?? HIDDEN_WEBGL_IDLE_RELEASE_MS;
const now = options.now ?? Date.now;
const setTimer = options.setTimer
?? ((callback: () => void, delayMs: number) => setTimeout(callback, delayMs));
@@ -78,24 +91,49 @@ export function createWebglContextBudget(
};
const releaseOverflow = () => {
if (active.size <= maxActive) return;
const time = now();
const releasable: Array<{ member: WebglContextBudgetMember; hiddenSince: number }> = [];
let nextReleasableAt = Number.POSITIVE_INFINITY;
const hiddenMembers: Array<{ member: WebglContextBudgetMember; hiddenSince: number }> = [];
for (const member of active) {
const hiddenSince = member.getHiddenSince();
if (hiddenSince === null) continue;
const releasableAt = hiddenSince + minHiddenMs;
if (releasableAt <= time) releasable.push({ member, hiddenSince });
else nextReleasableAt = Math.min(nextReleasableAt, releasableAt);
if (hiddenSince !== null) hiddenMembers.push({ member, hiddenSince });
}
releasable.sort((a, b) => a.hiddenSince - b.hiddenSince);
for (const { member } of releasable) {
if (active.size <= maxActive) break;
active.delete(member);
member.release();
if (hiddenMembers.length === 0) return;
hiddenMembers.sort((a, b) => a.hiddenSince - b.hiddenSince);
let nextReleasableAt = Number.POSITIVE_INFINITY;
// 1. Enforce total active cap (uses shorter minHiddenMs grace).
if (active.size > maxActive) {
for (const entry of hiddenMembers) {
if (active.size <= maxActive) break;
const releasableAt = entry.hiddenSince + minHiddenMs;
if (releasableAt <= time) {
active.delete(entry.member);
entry.member.release();
} else {
nextReleasableAt = Math.min(nextReleasableAt, releasableAt);
}
}
}
if (active.size > maxActive && Number.isFinite(nextReleasableAt)) {
// 2. Enforce idle hidden cap (keeps newest `maxHidden` MRU hidden tabs warm
// and releases older hidden tabs once they stay hidden for `hiddenIdleMs`).
if (Number.isFinite(maxHidden)) {
const remainingHidden = hiddenMembers.filter((entry) => active.has(entry.member));
const excessHidden = remainingHidden.length - maxHidden;
for (let i = 0; i < excessHidden; i += 1) {
const entry = remainingHidden[i];
const releasableAt = entry.hiddenSince + hiddenIdleMs;
if (releasableAt <= time) {
active.delete(entry.member);
entry.member.release();
} else {
nextReleasableAt = Math.min(nextReleasableAt, releasableAt);
}
}
}
if (Number.isFinite(nextReleasableAt)) {
scheduleCheck(nextReleasableAt);
}
};
@@ -116,9 +154,16 @@ export function createWebglContextBudget(
active.delete(member);
},
noteHidden(member) {
if (!active.has(member) || active.size <= maxActive) return;
if (!active.has(member)) return;
const hiddenSince = member.getHiddenSince();
if (hiddenSince !== null) scheduleCheck(hiddenSince + minHiddenMs);
if (hiddenSince === null) return;
if (active.size > maxActive) {
scheduleCheck(hiddenSince + minHiddenMs);
return;
}
if (Number.isFinite(maxHidden)) {
releaseOverflow();
}
},
getActiveCount: () => active.size,
};
@@ -128,6 +173,11 @@ let sharedBudget: WebglContextBudget | null = null;
/** The budget shared by every terminal in this renderer process. */
export function getSharedWebglContextBudget(): WebglContextBudget {
sharedBudget ??= createWebglContextBudget();
sharedBudget ??= createWebglContextBudget({
maxActiveContexts: MAX_ACTIVE_WEBGL_CONTEXTS,
minHiddenMs: MIN_HIDDEN_MS_BEFORE_WEBGL_RELEASE,
maxHiddenContexts: MAX_HIDDEN_WEBGL_CONTEXTS,
hiddenIdleReleaseMs: HIDDEN_WEBGL_IDLE_RELEASE_MS,
});
return sharedBudget;
}
@@ -3,7 +3,9 @@ import test from "node:test";
import {
readActiveTerminalBufferTextRange,
readCursorLogicalTailForReadiness,
readTerminalBufferTextRange,
readTerminalScreenText,
} from "./terminalContextBuffer.ts";
function createBuffer(lines: string[]) {
@@ -58,8 +60,6 @@ test("readActiveTerminalBufferTextRange reads the active alternate buffer withou
);
});
import { readTerminalScreenText } from "./terminalContextBuffer.ts";
test("screen export follows the scrolled viewport and excludes hidden history", () => {
const buffer = { ...createBuffer(["old", "visible one", " visible two", "newest"]),
viewportY: 1, length: 4, type: "normal" };
@@ -80,3 +80,258 @@ test("screen export reads only the alternate screen while fullscreen apps are ac
assert.equal(readTerminalScreenText({ cols: 80, rows: 3, buffer: { active: buffer } } as never),
"vim\ntext\n");
});
type MockCell = { code: number; width: number };
function createCursorTerm(
rows: Array<{ text: string; isWrapped?: boolean; length?: number; cells?: MockCell[] }>,
{ cols = 80, baseY = 0, cursorY = 0, cursorX = 0 }: { cols?: number; baseY?: number; cursorY?: number; cursorX?: number },
) {
return {
cols,
buffer: {
active: {
length: rows.length,
baseY,
cursorY,
cursorX,
getLine(index: number) {
const row = rows[index];
if (!row) return undefined;
return {
length: row.length ?? row.cells?.length ?? cols,
isWrapped: row.isWrapped === true,
...(row.cells
? {
getCell(col: number) {
const cell = row.cells?.[col];
if (!cell) return undefined;
return {
getCode: () => cell.code,
getWidth: () => cell.width,
};
},
}
: {}),
translateToString(trimRight?: boolean, startColumn = 0, endColumn?: number) {
const sliced = row.text.slice(startColumn, endColumn);
return trimRight ? sliced.trimEnd() : sliced;
},
};
},
},
},
};
}
test("readCursorLogicalTailForReadiness joins soft-wrapped rows so wrapped pending commands never look like prompts", () => {
const term = createCursorTerm(
[
{ text: "user@host:~$ echo " + "x".repeat(62), isWrapped: false },
{ text: "user@host:~$ ", isWrapped: true },
{ text: "", isWrapped: false },
],
{ cols: 80, baseY: 0, cursorY: 1, cursorX: 13 },
);
const result = readCursorLogicalTailForReadiness(term as never);
assert.equal(result.cursorAtLineEnd, true);
assert.equal(result.text, `user@host:~$ echo ${"x".repeat(62)}user@host:~$ `);
});
test("readCursorLogicalTailForReadiness preserves trailing prompt spaces and strips empty rows below cursor", () => {
const term = createCursorTerm(
[
{ text: "Last login: Fri Nov 27" },
{ text: "user@host:~$ " },
{ text: "" },
{ text: "" },
],
{ cols: 80, baseY: 0, cursorY: 1, cursorX: 13 },
);
const result = readCursorLogicalTailForReadiness(term as never);
assert.equal(result.cursorLine, 1);
assert.equal(result.cursorAtLineEnd, true);
assert.equal(result.hasContentBelowCursor, false);
assert.equal(result.text, "Last login: Fri Nov 27\nuser@host:~$ ");
});
test("readCursorLogicalTailForReadiness reconstructs wrapped two-line prompts cleanly", () => {
const term = createCursorTerm(
[
{ text: "[root@very-long-host", isWrapped: false },
{ text: "-01 ~] br0 = 10.1.64.1", isWrapped: true },
{ text: "# ", isWrapped: false },
{ text: "", isWrapped: false },
],
{ cols: 80, baseY: 0, cursorY: 2, cursorX: 2 },
);
const result = readCursorLogicalTailForReadiness(term as never);
assert.equal(result.text, "[root@very-long-host-01 ~] br0 = 10.1.64.1\n# ");
});
test("readCursorLogicalTailForReadiness fails closed on mid-line edits, text below cursor, and evicted wrapped heads", () => {
// Mid-line cursor edit
const midLine = createCursorTerm(
[{ text: "user@host:~$ echo hi" }],
{ cols: 80, baseY: 0, cursorY: 0, cursorX: 13 },
);
assert.equal(readCursorLogicalTailForReadiness(midLine as never).text, "");
// Non-empty text below cursor (primary-screen TUI/menu)
const textBelow = createCursorTerm(
[{ text: "user@host:~$ " }, { text: "Menu item" }],
{ cols: 80, baseY: 0, cursorY: 0, cursorX: 13 },
);
assert.equal(readCursorLogicalTailForReadiness(textBelow as never).text, "");
// Evicted scrollback head on cursor's wrapped logical line
const evictedWrap = createCursorTerm(
[{ text: "user@host:~$ ", isWrapped: true }],
{ cols: 80, baseY: 0, cursorY: 0, cursorX: 13 },
);
assert.equal(readCursorLogicalTailForReadiness(evictedWrap as never).text, "");
// Soft-wrapped continuation row below cursor
const wrappedBelow = createCursorTerm(
[{ text: "user@host:~$ ", isWrapped: false }, { text: "", isWrapped: true }],
{ cols: 80, baseY: 0, cursorY: 0, cursorX: 13 },
);
assert.equal(readCursorLogicalTailForReadiness(wrappedBelow as never).text, "");
});
test("readCursorLogicalTailForReadiness discards truncated or evicted preceding wrapped lines", () => {
// 67-row unfinished command whose truncated suffix starts with a host-like header,
// followed by a bare `# ` continuation line: must NOT emit the cut-off suffix as a header.
const longWrappedRows: Array<{ text: string; isWrapped?: boolean }> = [
{ text: "echo 'start ", isWrapped: false },
{ text: "padding-row-1 ", isWrapped: true },
{ text: "user@host: /project", isWrapped: true },
];
for (let i = 0; i < 64; i += 1) {
longWrappedRows.push({ text: "x".repeat(20), isWrapped: true });
}
longWrappedRows.push({ text: "# ", isWrapped: false });
const overCap = createCursorTerm(longWrappedRows, {
cols: 20,
baseY: 0,
cursorY: longWrappedRows.length - 1,
cursorX: 2,
});
assert.equal(readCursorLogicalTailForReadiness(overCap as never).text, "# ");
// Scrollback-evicted preceding wrapped line (`row 0` has `isWrapped: true`) above bare `# `.
const evictedPreceding = createCursorTerm(
[
{ text: "user@host: /project", isWrapped: true },
{ text: "# ", isWrapped: false },
],
{ cols: 80, baseY: 0, cursorY: 1, cursorX: 2 },
);
assert.equal(readCursorLogicalTailForReadiness(evictedPreceding as never).text, "# ");
// Complete single-line prompt below a truncated log line is still preserved cleanly.
const completePromptAfterLongLog = createCursorTerm(
[
...longWrappedRows.slice(0, -1),
{ text: "user@host:~$ ", isWrapped: false },
],
{ cols: 20, baseY: 0, cursorY: longWrappedRows.length - 1, cursorX: 13 },
);
assert.equal(readCursorLogicalTailForReadiness(completePromptAfterLongLog as never).text, "user@host:~$ ");
});
function cellsForAscii(text: string, trailingCell?: MockCell): MockCell[] {
const cells = Array.from(text, (ch) => ({ code: ch.charCodeAt(0), width: 1 }));
if (trailingCell) cells.push(trailingCell);
return cells;
}
test("readCursorLogicalTailForReadiness strips wide-character wrap padding without dropping real spaces or wide glyphs", () => {
const wideCharA = "\u4e2d";
const wideCharB = "\u6587";
// Structural null padding cell (code 0, width 1) before a double-width glyph on the next wrapped row.
const paddedWideWrap = createCursorTerm(
[
{
text: "user@host:~abc ",
isWrapped: false,
length: 15,
cells: cellsForAscii("user@host:~abc", { code: 0, width: 1 }),
},
{
text: `${wideCharA}$ `,
isWrapped: true,
length: 15,
cells: [{ code: 0x4e2d, width: 2 }, { code: 0, width: 0 }, { code: 36, width: 1 }, { code: 32, width: 1 }],
},
],
{ cols: 15, baseY: 0, cursorY: 1, cursorX: 4 },
);
assert.equal(readCursorLogicalTailForReadiness(paddedWideWrap as never).text, `user@host:~abc${wideCharA}$ `);
// Real typed trailing space (code 32, width 1) before a double-width glyph must be preserved.
const realSpaceBeforeWide = createCursorTerm(
[
{
text: "user@host:~ab ",
isWrapped: false,
length: 15,
cells: cellsForAscii("user@host:~ab ", { code: 32, width: 1 }),
},
{
text: `${wideCharA}$ `,
isWrapped: true,
length: 15,
cells: [{ code: 0x4e2d, width: 2 }, { code: 0, width: 0 }, { code: 36, width: 1 }, { code: 32, width: 1 }],
},
],
{ cols: 15, baseY: 0, cursorY: 1, cursorX: 4 },
);
assert.equal(readCursorLogicalTailForReadiness(realSpaceBeforeWide as never).text, `user@host:~ab ${wideCharA}$ `);
// Trailing width-0 continuation cell of a wide glyph at the end of the row must NOT be sliced off.
const wideGlyphAtRowEnd = createCursorTerm(
[
{
text: `user@host:~a${wideCharA}`,
isWrapped: false,
length: 14,
cells: [
...cellsForAscii("user@host:~a"),
{ code: 0x4e2d, width: 2 },
{ code: 0, width: 0 },
],
},
{
text: `${wideCharB}$ `,
isWrapped: true,
length: 14,
cells: [{ code: 0x6587, width: 2 }, { code: 0, width: 0 }, { code: 36, width: 1 }, { code: 32, width: 1 }],
},
],
{ cols: 14, baseY: 0, cursorY: 1, cursorX: 4 },
);
assert.equal(readCursorLogicalTailForReadiness(wideGlyphAtRowEnd as never).text, `user@host:~a${wideCharA}${wideCharB}$ `);
// Null cell ahead of a normal-width continuation is NOT wide-char wrap padding and stays intact.
const nullBeforeNarrow = createCursorTerm(
[
{
text: "user@host:~abc ",
isWrapped: false,
length: 15,
cells: cellsForAscii("user@host:~abc", { code: 0, width: 1 }),
},
{
text: "Z$ ",
isWrapped: true,
length: 15,
cells: cellsForAscii("Z$ "),
},
],
{ cols: 15, baseY: 0, cursorY: 1, cursorX: 3 },
);
assert.equal(readCursorLogicalTailForReadiness(nullBeforeNarrow as never).text, "user@host:~abc Z$ ");
});
@@ -50,3 +50,136 @@ export function readTerminalScreenText(term: Pick<XTerm, "buffer" | "cols" | "ro
endLine: Math.min(buffer.length, startLine + term.rows) - 1,
});
}
export interface CursorLogicalTailResult {
text: string;
cursorLine?: number;
cursorAtLineEnd: boolean;
hasContentBelowCursor: boolean;
}
function readWrappedSegmentText(
buffer: Pick<IBuffer, "getLine">,
row: number,
cols: number,
): string {
const segment = buffer.getLine(row);
if (!segment) return "";
const lineLength = typeof segment.length === "number"
? Math.min(cols, Math.max(0, segment.length))
: cols;
const text = segment.translateToString(false, 0, lineLength);
if (lineLength <= 0 || typeof segment.getCell !== "function") return text;
// When a double-width glyph does not fit at the last column of a wrapped row,
// xterm leaves a single structural null cell (code 0, width !== 0) at
// `lineLength - 1` and places the wide glyph at column 0 of `row + 1`.
// Strip only that structural padding cell so real spaces (code 32) and the
// trailing half of a wide glyph (width 0) are preserved intact.
const nextFirstCell = buffer.getLine(row + 1)?.getCell?.(0);
if (!nextFirstCell || nextFirstCell.getWidth?.() !== 2) return text;
const lastCell = segment.getCell(lineLength - 1);
if (lastCell && lastCell.getCode() === 0 && lastCell.getWidth?.() !== 0) {
return text.slice(0, -1);
}
return text;
}
/**
* Reconstruct logical lines ending at the active xterm cursor for read-only
* shell readiness seeding. Joins soft-wrapped physical rows (`isWrapped`) with
* "" rather than "\n" so a wrapped pending command can never look like an idle
* prompt, preserves trailing prompt spaces up to `cursorX`, and fails closed
* when content exists to the right of or below the cursor.
*/
export function readCursorLogicalTailForReadiness(
term: Pick<XTerm, "buffer" | "cols">,
options: { maxLogicalLines?: number; maxWrappedRows?: number } = {},
): CursorLogicalTailResult {
const buffer = term.buffer.active as typeof term.buffer.active & {
baseY?: number;
cursorY?: number;
cursorX?: number;
};
const totalLines = Math.max(0, buffer.length);
if (
totalLines === 0
|| typeof buffer.baseY !== "number"
|| typeof buffer.cursorY !== "number"
|| typeof buffer.cursorX !== "number"
) {
return { text: "", cursorAtLineEnd: false, hasContentBelowCursor: false };
}
const cols = Math.max(0, Math.floor(term.cols));
const cursorLine = Math.min(totalLines - 1, Math.max(0, buffer.baseY + buffer.cursorY));
const cursorColumn = Math.min(cols, Math.max(0, Math.floor(buffer.cursorX)));
const lineAtCursor = buffer.getLine(cursorLine);
if (!lineAtCursor) {
return { text: "", cursorLine, cursorAtLineEnd: false, hasContentBelowCursor: false };
}
const afterCursor = lineAtCursor.translateToString(true, cursorColumn, cols);
if (afterCursor.length > 0) {
return { text: "", cursorLine, cursorAtLineEnd: false, hasContentBelowCursor: false };
}
for (let row = cursorLine + 1; row < totalLines; row += 1) {
const below = buffer.getLine(row);
if (row === cursorLine + 1 && below?.isWrapped === true) {
return { text: "", cursorLine, cursorAtLineEnd: false, hasContentBelowCursor: false };
}
if (below && below.translateToString(true, 0, cols).trim().length > 0) {
return { text: "", cursorLine, cursorAtLineEnd: true, hasContentBelowCursor: true };
}
}
const maxLogicalLines = Math.max(1, options.maxLogicalLines ?? 8);
const maxWrappedRows = Math.max(1, options.maxWrappedRows ?? 64);
const logicalLines: string[] = [];
let row = cursorLine;
for (let logicalIdx = 0; logicalIdx < maxLogicalLines && row >= 0; logicalIdx += 1) {
let startRow = row;
let wrappedCount = 0;
let truncated = false;
while (startRow > 0 && buffer.getLine(startRow)?.isWrapped === true) {
wrappedCount += 1;
if (wrappedCount > maxWrappedRows) {
truncated = true;
break;
}
startRow -= 1;
}
if (truncated || (startRow === 0 && buffer.getLine(0)?.isWrapped === true)) {
if (logicalIdx === 0) {
return { text: "", cursorLine, cursorAtLineEnd: true, hasContentBelowCursor: false };
}
// Never emit a cut-off or scrollback-evicted wrapped suffix as an
// independent logical line: its surviving tail could look like a
// two-line prompt header above a bare `$`/`#` continuation line.
break;
}
let combined = "";
for (let r = startRow; r <= row; r += 1) {
const segment = buffer.getLine(r);
if (!segment) continue;
if (r === cursorLine) {
combined += segment.translateToString(false, 0, cursorColumn);
} else if (r < row) {
combined += readWrappedSegmentText(buffer, r, cols);
} else {
combined += segment.translateToString(true, 0, cols);
}
}
logicalLines.unshift(combined);
row = startRow - 1;
}
return {
text: logicalLines.join("\n"),
cursorLine,
cursorAtLineEnd: true,
hasContentBelowCursor: false,
};
}
@@ -300,7 +300,7 @@ test("serializeTerminalForHibernate keeps visual capture when context buffer rea
assert.equal(result.contextScrollbackSnapshot, "");
});
test("serializeTerminalForHibernate preserves plain text context for normal screen", async () => {
test("serializeTerminalForHibernate preserves plain text context for normal screen without duplicate scrollback serialization", async () => {
const capturedRanges: unknown[] = [];
const term = createFakeTerm("normal", 3, 5);
const serializeAddon = {
@@ -310,18 +310,89 @@ test("serializeTerminalForHibernate preserves plain text context for normal scre
},
};
const result = await serializeTerminalForHibernate(term as never, serializeAddon as never);
assert.equal(result.snapshot, "serialized");
assert.equal(result.viewportSnapshot, "serialized");
assert.equal(result.scrollbackSnapshot, "serialized");
assert.equal(result.scrollbackSnapshot, "");
assert.equal(result.contextScrollbackSnapshot, "screen-0\nscreen-1");
assert.equal(result.contextViewportSnapshot, "screen-2\nscreen-3\nscreen-4");
assert.equal(result.contextSnapshot, "screen-0\nscreen-1\nscreen-2\nscreen-3\nscreen-4");
assert.deepEqual(capturedRanges, [
{ start: 2, end: 4 },
{ start: 0, end: 1 },
undefined,
]);
});
test("serializeTerminalForHibernate falls back to scrollback slice when full snapshot is empty", async () => {
const capturedRanges: unknown[] = [];
const term = createFakeTerm("normal", 3, 5);
const serializeAddon = {
serialize: (options?: Record<string, unknown>) => {
capturedRanges.push(options?.range);
return options?.range ? "range-serialized" : "";
},
};
const result = await serializeTerminalForHibernate(term as never, serializeAddon as never);
assert.equal(result.snapshot, "");
assert.equal(result.viewportSnapshot, "range-serialized");
assert.equal(result.scrollbackSnapshot, "range-serialized");
assert.deepEqual(capturedRanges, [
{ start: 2, end: 4 },
undefined,
{ start: 0, end: 1 },
]);
});
test("serializeTerminalForHibernate compresses large snapshots and resolves them on wake", async () => {
const { resolveHibernateWakeHistoryAsync } = await import("./terminalHibernateRuntime.ts");
const largeText = Array.from({ length: 200 }, (_, i) => `\x1b[32mINFO\x1b[0m line ${i} hello world`).join("\r\n");
const term = createFakeTerm("normal", 3, 200);
const serializeAddon = {
serialize: (options?: Record<string, unknown>) => (
options?.range ? "viewport-only" : largeText
),
};
const result = await serializeTerminalForHibernate(term as never, serializeAddon as never);
assert.ok(result.compressedSnapshot instanceof Uint8Array);
assert.ok(result.compressedSnapshot.byteLength > 0);
assert.ok(result.compressedSnapshot.byteLength < largeText.length / 4);
const restored = await resolveHibernateWakeHistoryAsync({
snapshot: "",
compressedSnapshot: result.compressedSnapshot,
viewportSnapshot: result.viewportSnapshot,
scrollbackSnapshot: "",
pendingBuffer: "",
alternateScreen: false,
});
assert.equal(restored, largeText);
});
test("serializeTerminalForHibernate with compress:false skips inline gzip so live listeners detach before compressing", async () => {
const { compressHibernateSnapshot, resolveHibernateWakeHistoryAsync } = await import("./terminalHibernateRuntime.ts");
const largeText = Array.from({ length: 200 }, (_, i) => `\x1b[32mINFO\x1b[0m line ${i} hello world`).join("\r\n");
const term = createFakeTerm("normal", 3, 200);
const serializeAddon = {
serialize: (options?: Record<string, unknown>) => (
options?.range ? "viewport-only" : largeText
),
};
const result = await serializeTerminalForHibernate(term as never, serializeAddon as never, { compress: false });
assert.equal(result.snapshot, largeText);
assert.equal(result.compressedSnapshot, null);
const compressed = await compressHibernateSnapshot(result.snapshot);
assert.ok(compressed instanceof Uint8Array);
assert.ok(compressed.byteLength > 0);
const restored = await resolveHibernateWakeHistoryAsync({
snapshot: "",
compressedSnapshot: compressed,
viewportSnapshot: result.viewportSnapshot,
scrollbackSnapshot: "",
pendingBuffer: "",
alternateScreen: false,
});
assert.equal(restored, largeText);
});
test("serializeTerminalForHibernate waits for deferred history preparation", async () => {
const term = createFakeTerm("normal", 3, 5);
const events: string[] = [];
+66 -10
View File
@@ -35,6 +35,7 @@ export function resolveHibernateSerializeOptions(term: XTerm): {
export type TerminalHibernateSnapshot = {
snapshot: string;
compressedSnapshot?: Uint8Array | null;
viewportSnapshot: string;
scrollbackSnapshot: string;
contextSnapshot?: string;
@@ -43,6 +44,39 @@ export type TerminalHibernateSnapshot = {
alternateScreen: boolean;
};
const HIBERNATE_COMPRESS_MIN_CHARS = 4_096;
export async function compressHibernateSnapshot(text: string): Promise<Uint8Array | null> {
if (
!text
|| text.length < HIBERNATE_COMPRESS_MIN_CHARS
|| typeof CompressionStream === "undefined"
) {
return null;
}
try {
const encoded = new TextEncoder().encode(text);
const stream = new Blob([encoded]).stream().pipeThrough(new CompressionStream("gzip"));
const buffer = await new Response(stream).arrayBuffer();
return new Uint8Array(buffer);
} catch {
return null;
}
}
export async function decompressHibernateSnapshot(data: Uint8Array): Promise<string> {
if (!data || data.byteLength === 0 || typeof DecompressionStream === "undefined") {
return "";
}
try {
const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("gzip"));
const buffer = await new Response(stream).arrayBuffer();
return new TextDecoder().decode(buffer);
} catch {
return "";
}
}
type MutableValue<T> = { current: T };
export function applyAuthoritativeHibernateSnapshot(
@@ -189,7 +223,7 @@ async function serializeWithOptions(
export async function serializeTerminalForHibernate(
term: XTerm,
serializeAddon: SerializeAddon,
options: { preferWasm?: boolean; prepare?: () => Promise<void> } = {},
options: { preferWasm?: boolean; prepare?: () => Promise<void>; compress?: boolean } = {},
): Promise<TerminalHibernateSnapshot> {
await options.prepare?.();
const { excludeAltBuffer, excludeModes, alternateScreen } = resolveHibernateSerializeOptions(term);
@@ -235,8 +269,20 @@ export async function serializeTerminalForHibernate(
excludeModes,
range: { start: viewportStart, end: viewportEnd },
}, preferWasm);
const snapshot = capHibernateBufferByLines(
await serializeWithOptions(term, serializeAddon, {
excludeAltBuffer,
excludeModes,
}, preferWasm),
TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES,
);
// Avoid serializing and retaining a duplicate copy of the entire scrollback
// when the coherent full snapshot already succeeded. Only fall back to a
// ranged scrollback slice when full serialization returned empty.
let scrollbackSnapshot = "";
if (viewportStart > 0) {
if (!snapshot && viewportStart > 0) {
const scrollbackStart = Math.max(0, viewportStart - TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES);
scrollbackSnapshot = capHibernateBufferByLines(
await serializeWithOptions(term, serializeAddon, {
@@ -248,16 +294,13 @@ export async function serializeTerminalForHibernate(
);
}
const snapshot = capHibernateBufferByLines(
await serializeWithOptions(term, serializeAddon, {
excludeAltBuffer,
excludeModes,
}, preferWasm),
TERMINAL_HIBERNATE_SNAPSHOT_MAX_LINES,
);
const compressedSnapshot = options.compress === false
? null
: await compressHibernateSnapshot(snapshot);
return {
snapshot,
compressedSnapshot,
viewportSnapshot,
scrollbackSnapshot,
...context,
@@ -266,6 +309,7 @@ export async function serializeTerminalForHibernate(
} catch {
return {
snapshot: "",
compressedSnapshot: null,
viewportSnapshot: "",
scrollbackSnapshot: "",
alternateScreen: isTerminalAlternateScreenActive(term),
@@ -314,6 +358,17 @@ export function resolveHibernateWakeHistory(payload: TerminalHibernateWakePayloa
return `${scrollback}\r\n${viewport}`;
}
export async function resolveHibernateWakeHistoryAsync(
payload: TerminalHibernateWakePayload,
): Promise<string> {
if (payload.snapshot) return payload.snapshot;
if (payload.compressedSnapshot && payload.compressedSnapshot.byteLength > 0) {
const decompressed = await decompressHibernateSnapshot(payload.compressedSnapshot);
if (decompressed) return decompressed;
}
return resolveHibernateWakeHistory(payload);
}
export async function applyHibernateWakeToTerminal(
term: XTerm,
runtime: XTermRuntime,
@@ -321,7 +376,7 @@ export async function applyHibernateWakeToTerminal(
options: ApplyHibernateWakeOptions = {},
): Promise<void> {
const replayOptions = options.replayOptions;
const history = resolveHibernateWakeHistory(payload);
const history = await resolveHibernateWakeHistoryAsync(payload);
// Chunked writes already yield to the event loop for large buffers. Do not
// idle-append older scrollback after the viewport: under a finite xterm
@@ -356,6 +411,7 @@ export function buildHibernateWakePayload(
): TerminalHibernateWakePayload {
return {
snapshot: snapshot.snapshot,
compressedSnapshot: snapshot.compressedSnapshot ?? null,
viewportSnapshot: snapshot.viewportSnapshot,
scrollbackSnapshot: snapshot.scrollbackSnapshot,
pendingBuffer,
@@ -27,6 +27,7 @@ type UseTerminalHibernateEffectOptions = {
softHiddenRef: React.MutableRefObject<boolean>;
hibernatePendingBufferRef: React.MutableRefObject<string>;
hibernateSnapshotRef: React.MutableRefObject<string>;
hibernateCompressedSnapshotRef?: React.MutableRefObject<Uint8Array | null>;
hibernateViewportSnapshotRef: React.MutableRefObject<string>;
hibernateScrollbackSnapshotRef: React.MutableRefObject<string>;
hibernateContextSnapshotRef: React.MutableRefObject<string>;
@@ -57,6 +58,7 @@ export function useTerminalHibernateEffect({
softHiddenRef,
hibernatePendingBufferRef,
hibernateSnapshotRef,
hibernateCompressedSnapshotRef,
hibernateViewportSnapshotRef,
hibernateScrollbackSnapshotRef,
hibernateContextSnapshotRef,
@@ -90,6 +92,7 @@ export function useTerminalHibernateEffect({
const clearHibernateState = () => {
hibernateSnapshotRef.current = "";
if (hibernateCompressedSnapshotRef) hibernateCompressedSnapshotRef.current = null;
hibernateViewportSnapshotRef.current = "";
hibernateScrollbackSnapshotRef.current = "";
hibernateContextSnapshotRef.current = "";
@@ -128,6 +131,7 @@ export function useTerminalHibernateEffect({
const sessionConnected = getSessionConnectedRef.current();
const getPayload = (): TerminalHibernateWakePayload => ({
snapshot: hibernateSnapshotRef.current,
compressedSnapshot: hibernateCompressedSnapshotRef?.current ?? null,
viewportSnapshot: hibernateViewportSnapshotRef.current || hibernateSnapshotRef.current,
scrollbackSnapshot: hibernateScrollbackSnapshotRef.current,
pendingBuffer: hibernatePendingBufferRef.current,
@@ -136,6 +140,7 @@ export function useTerminalHibernateEffect({
logger.info("[Terminal] Waking from hibernate", {
sessionId,
snapshotChars: hibernateSnapshotRef.current.length,
compressedBytes: hibernateCompressedSnapshotRef?.current?.byteLength ?? 0,
viewportChars: hibernateViewportSnapshotRef.current.length,
scrollbackChars: hibernateScrollbackSnapshotRef.current.length,
pendingChars: hibernatePendingBufferRef.current.length,
@@ -204,6 +209,7 @@ export function useTerminalHibernateEffect({
hibernatePendingBufferRef,
hibernateScrollbackSnapshotRef,
hibernateSnapshotRef,
hibernateCompressedSnapshotRef,
hibernateViewportSnapshotRef,
hibernatedRef,
isSearchOpen,
@@ -345,28 +345,30 @@ test('AppHostTreeLayer does not re-render closed TerminalHostTreeSidebar when sw
env.drainFrames();
});
const sidebar = document.querySelector('[data-section="terminal-host-tree-sidebar"]') as HTMLElement;
assert.ok(sidebar);
const initialBg = sidebar.style.backgroundColor;
assert.equal(document.querySelector('[data-section="terminal-host-tree-sidebar"]'), null);
// Switching s1 -> s2 while host tree is closed keeps sidebar preview theme frozen
// and avoids activeHostId churn (memo bails out).
// Switching s1 -> s2 while host tree is closed keeps sidebar unmounted
// and avoids activeHostId/theme churn.
await act(async () => {
activeTabStore.setActiveTabId('s2');
});
await act(async () => {
env.drainFrames();
});
assert.equal(sidebar.style.backgroundColor, initialBg);
assert.equal(document.querySelector('[data-section="terminal-host-tree-sidebar"]'), null);
// Opening the host tree immediately applies the live host theme (theme-b).
// Opening the host tree lazily mounts the sidebar directly with the live host theme (theme-b).
await act(async () => {
terminalHostTreeStore.setIsOpen(true);
await import('./TerminalHostTreeSidebar');
});
await act(async () => {
env.drainFrames();
});
assert.notEqual(sidebar.style.backgroundColor, initialBg);
const sidebar = document.querySelector('[data-section="terminal-host-tree-sidebar"]') as HTMLElement;
assert.ok(sidebar);
assert.notEqual(sidebar.style.backgroundColor, 'rgb(16, 16, 16)');
assert.equal(sidebar.style.backgroundColor, 'rgb(32, 32, 32)');
} finally {
await act(async () => {
root.unmount();
@@ -48,6 +48,7 @@ import { themeFingerprint } from '../../application/state/useActiveChromeTheme';
import { buildHostTreeThemeFromTerminalTheme } from '../../infrastructure/theme/terminalAppearanceTokens';
import { cn } from '../../lib/utils';
import { matchesHostSearchQuery, matchesSearchQuery } from '../../domain/searchMatcher';
import { usePinyinMatcherVersion } from '../../application/state/usePinyinMatcherVersion';
import type { GroupConfig, GroupNode, Host, TerminalTheme } from '../../types';
import { HostTreeGroupContextMenuContent, HostTreeHostContextMenuContent } from '../host/HostTreeContextMenus';
import { HostTreeGroupInlineRenameInput } from '../host/HostTreeGroupInlineRenameInput';
@@ -839,7 +840,9 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
return new Set([inlineEdit.groupPath]);
}, [inlineEdit?.groupPath]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredTree = useMemo(() => {
void pinyinMatcherVersion;
let tree = groupTree;
if (tagsActive) {
tree = tree
@@ -850,12 +853,13 @@ const TerminalHostTreeSidebarInner: React.FC<TerminalHostTreeSidebarProps> = ({
return tree
.map((node) => filterGroupNode(node, searchTerm, preservePaths))
.filter((node): node is GroupNode => node !== null);
}, [groupTree, preservePaths, searchActive, searchTerm, tagsActive]);
}, [groupTree, preservePaths, searchActive, searchTerm, tagsActive, pinyinMatcherVersion]);
const filteredUngrouped = useMemo(() => {
void pinyinMatcherVersion;
if (!searchActive) return ungroupedHosts;
return ungroupedHosts.filter((host) => hostMatchesSearch(host, searchTerm));
}, [searchActive, searchTerm, ungroupedHosts]);
}, [searchActive, searchTerm, ungroupedHosts, pinyinMatcherVersion]);
const flatRows = useMemo(() => {
return flattenHostGroupTree({
@@ -38,15 +38,19 @@ test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it aw
);
});
test('magnified side panels use a continuous 1px inset outline in the side panel accent', () => {
test('magnified side panels use an inner rounded 1px border in the side panel accent', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
const strokeStart = source.indexOf('data-section="pane-magnification-stroke"', chromeStart);
const strokeSource = source.slice(strokeStart, source.indexOf('/>', strokeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /outline: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(chromeSource, /outlineOffset: -1/);
assert.doesNotMatch(chromeSource, /\bborder(?:Color|Width|Style)?\b/);
assert.doesNotMatch(chromeSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
test('AI side panel shell can be force-hidden for layout isolation', () => {
@@ -1585,8 +1585,6 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl animate-in fade-in zoom-in-95 duration-150"
style={{
outline: `1px solid ${sidePanelTheme.accent}`,
outlineOffset: -1,
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
}}
@@ -1612,6 +1610,16 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
className="relative flex-1 min-h-0 overflow-hidden [contain:strict]"
data-section="pane-magnification-content"
/>
<div
aria-hidden="true"
data-section="pane-magnification-stroke"
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sidePanelTheme.accent}`,
borderRadius: 'inherit',
}}
/>
</div>
{showMagnificationHint && (
<div
@@ -81,11 +81,9 @@ const LazyRemoteDesktopPane = lazy(() =>
import('../remoteDesktop/RemoteDesktopPane').then((module) => ({ default: module.RemoteDesktopPane })),
);
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(() => {
void import('../AIChatSidePanel');
});
}
// AIChatSidePanel (along with vendor-ai, globalAgentRuntime, and capability
// tool specs) is loaded on demand via LazyAIChatSidePanel when the user opens
// the AI side panel, avoiding ~15-20 MiB of V8 heap on terminal-only sessions.
const AIChatSidePanelFallback = memo(function AIChatSidePanelFallback() {
return (
@@ -845,7 +843,11 @@ export interface TerminalLayerProps {
onUpdateSessionFontSize?: (sessionId: string, fontSize: number) => void;
onUpdateSessionRestoreCwd?: (sessionId: string, cwd: string | null) => void;
onUpdateSessionDynamicTitle?: (sessionId: string, title: string | null) => void;
onUpdateSessionPromptHost?: (sessionId: string, hostname: string | null) => void;
onUpdateSessionPromptHost?: (
sessionId: string,
hostname: string | null,
options?: { fromJumpServer?: boolean },
) => void;
onUpdateSessionCodingCliProvider?: (sessionId: string, providerId: import('../../domain/codingCliProviders').CodingCliProviderId | null) => void;
onClearSessionFontSizeOverride?: (sessionId: string) => void;
onCloseSession: (sessionId: string, e?: React.MouseEvent) => void;
@@ -1826,13 +1828,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
isVisible && "z-10",
magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",
)}
style={{
...style,
outline: magnifiedSurfaceBounds
? `1px solid ${sessionAppearanceTheme.colors.cursor}`
: undefined,
outlineOffset: magnifiedSurfaceBounds ? -1 : undefined,
}}
style={style}
tabIndex={-1}
onClick={handlePaneClick}
onFocusCapture={handlePaneClick}
@@ -1996,6 +1992,18 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
/>
</>
)}
{magnifiedSurfaceBounds && (
<div
aria-hidden="true"
data-section="pane-magnification-stroke"
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sessionAppearanceTheme.colors.cursor}`,
borderRadius: 'inherit',
}}
/>
)}
</div>
);
}, terminalPanePropsAreEqual);
@@ -9,39 +9,46 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("terminal pane chrome follows retained surface bounds through restore with a continuous 1px inset outline", () => {
test("terminal pane chrome uses an inner rounded 1px border while retaining overflow clipping", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf('TerminalPane.displayName'));
const hostSource = paneSource.slice(0, paneSource.indexOf("<LazyLoadBoundary"));
const strokeSource = paneSource.slice(paneSource.indexOf("{magnifiedSurfaceBounds && ("));
assert.match(paneSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
assert.match(paneSource, /outline: magnifiedSurfaceBounds\s+\? `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`\s+: undefined/);
assert.match(paneSource, /outlineOffset: magnifiedSurfaceBounds \? -1 : undefined/);
assert.doesNotMatch(paneSource, /\bborder(?:Color|Width|Style)?\b/);
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl",$/m);
assert.match(hostSource, /style=\{style\}/);
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /aria-hidden="true"/);
assert.match(strokeSource, /data-section="pane-magnification-stroke"/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
test("restoring terminal chrome keeps its 1px inset outline until surface bounds clear at any DPR", () => {
test("restoring terminal chrome retains its inner 1px border until surface bounds clear at any DPR", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf("<Terminal\n"));
const styleSource = paneSource.match(/style=\{\{([\s\S]*?)\}\}/);
const strokeSource = source.slice(source.indexOf("{magnifiedSurfaceBounds && ("), source.indexOf('TerminalPane.displayName'));
const condition = strokeSource.match(/^\{(\w+) && \(/);
const styleSource = strokeSource.match(/style=\{\{([\s\S]*?)\}\}/);
assert.ok(condition);
assert.ok(styleSource);
const resolveStyle = new Function(
"style", "isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme",
"magnifiedDevicePixelRatio",
`return ({${styleSource[1]}});`,
const resolveStroke = new Function(
"isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme", "magnifiedDevicePixelRatio",
`return ${condition[1]} ? ({${styleSource[1]}}) : null;`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStyle({}, true, bounds, theme, dpr);
const restoring = resolveStyle({}, false, bounds, theme, dpr);
const magnified = resolveStroke(true, bounds, theme, dpr);
const restoring = resolveStroke(false, bounds, theme, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.outline, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.outlineOffset, -1);
assert.equal(restoring.border, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.boxSizing, 'border-box');
assert.equal(restoring.borderRadius, 'inherit');
for (const isMagnified of [false, true]) {
const cleared = resolveStyle({}, isMagnified, null, theme, dpr);
assert.equal(cleared.outline, undefined);
assert.equal(cleared.outlineOffset, undefined);
assert.equal(resolveStroke(isMagnified, null, theme, dpr), null);
}
}
});
+10 -1
View File
@@ -250,7 +250,16 @@ export const formatSessionTopTabTooltip = (
export const formatSessionTopTabLabel = (
session: Pick<
TerminalSession,
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId' | 'protocol' | 'hostname' | 'moshEnabled' | 'etEnabled'
| 'customName'
| 'hostLabel'
| 'promptHostname'
| 'promptHostnameFromJumpServer'
| 'dynamicTitle'
| 'codingCliProviderId'
| 'protocol'
| 'hostname'
| 'moshEnabled'
| 'etEnabled'
>,
dynamicTabTitleMode?: DynamicTabTitleMode,
): string => {
+205 -163
View File
@@ -1,8 +1,11 @@
import { MonitorPanels } from './MonitorPanels';
import { MonitorNavButton } from './MonitorNavButton';
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Combobox } from "../ui/combobox";
import React, { useCallback } from "react";
const LazyMonitorPanels = React.lazy(() =>
import("./MonitorPanels").then((mod) => ({ default: mod.MonitorPanels })),
);
import { deleteVaultKey } from "../../application/defaultKeyPassphrases";
import { VaultGroupDeletionConfirmationChangedError } from "../../application/state/useVaultGroupDeletion";
import { usePluginImporterCommit } from "../../application/state/usePluginImporterCommit";
@@ -16,8 +19,12 @@ import {
import { STORAGE_KEY_VAULT_HOST_PANEL_WIDTH } from "@/infrastructure/config/storageKeys.ts";
import { VaultHostListSection } from "./VaultHostListSection";
import { VAULT_HOST_GRID_MIN_CARD_WIDTH } from "./vaultHostGridLayout";
import { LocalShellHostDetailsPanel } from "../LocalShellHostDetailsPanel";
import { VaultImportProgressPanel } from "./ImportVaultDialog";
const LocalShellHostDetailsPanel = React.lazy(() =>
import("../LocalShellHostDetailsPanel").then((mod) => ({ default: mod.LocalShellHostDetailsPanel })),
);
const VaultImportProgressPanel = React.lazy(() =>
import("./ImportVaultDialog").then((mod) => ({ default: mod.VaultImportProgressPanel })),
);
import {
VaultHeaderSearch,
VaultPageHeader,
@@ -563,6 +570,12 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
const [isMoveHostsOpen, setIsMoveHostsOpen] = React.useState(false);
const [moveTargetGroup, setMoveTargetGroup] = React.useState("");
const [isSidebarResizing, setIsSidebarResizing] = React.useState(false);
const [hasMountedKnownHosts, setHasMountedKnownHosts] = React.useState(
currentSection === "knownhosts",
);
if (currentSection === "knownhosts" && !hasMountedKnownHosts) {
setHasMountedKnownHosts(true);
}
const keyListRef = React.useRef(keys);
keyListRef.current = keys;
const newHostActionsRef = React.useRef<HTMLDivElement>(null);
@@ -1537,7 +1550,16 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</Suspense>
</LazyLoadBoundary>
)}
{currentSection === "monitor" && <MonitorPanels hosts={hosts} customGroups={customGroups} onConnect={onConnect} />}
{currentSection === "monitor" && (
<LazyLoadBoundary
name="Monitor"
resetKey="monitor"
>
<Suspense fallback={<VaultSectionLoading />}>
<LazyMonitorPanels hosts={hosts} customGroups={customGroups} onConnect={onConnect} />
</Suspense>
</LazyLoadBoundary>
)}
{currentSection === "port" && (
<LazyLoadBoundary
name="Port forwarding"
@@ -1564,14 +1586,14 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</Suspense>
</LazyLoadBoundary>
)}
{/* Always render KnownHostsManager but hide with CSS to prevent unmounting */}
<div
style={{
display: currentSection === "knownhosts" ? "contents" : "none",
}}
>
{knownHostsManagerElement}
</div>
{/* Mount KnownHostsManager lazily on first visit, then keep hidden with CSS */}
{hasMountedKnownHosts ? (
<div style={{ display: currentSection === "knownhosts" ? "contents" : "none" }}>
<Suspense fallback={<VaultSectionLoading />}>
{knownHostsManagerElement}
</Suspense>
</div>
) : null}
{/* Connection Logs */}
{currentSection === "logs" && (
<LazyLoadBoundary
@@ -1593,134 +1615,142 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
{currentSection === "hosts" &&
isGroupPanelOpen &&
editingGroupPath && (
<GroupDetailsPanel
key={editingGroupPath}
groupPath={editingGroupPath}
config={groupConfigs.find((c) => c.path === editingGroupPath)}
availableKeys={keys}
identities={identities}
proxyProfiles={proxyProfiles}
allHosts={hosts}
groups={allGroupPaths}
terminalThemeId={terminalThemeId}
groupConfigs={groupConfigs}
terminalFontSize={terminalFontSize}
onSave={handleSaveGroupConfig}
onCancel={() => {
setIsGroupPanelOpen(false);
setEditingGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<GroupDetailsPanel
key={editingGroupPath}
groupPath={editingGroupPath}
config={groupConfigs.find((c) => c.path === editingGroupPath)}
availableKeys={keys}
identities={identities}
proxyProfiles={proxyProfiles}
allHosts={hosts}
groups={allGroupPaths}
terminalThemeId={terminalThemeId}
groupConfigs={groupConfigs}
terminalFontSize={terminalFontSize}
onSave={handleSaveGroupConfig}
onCancel={() => {
setIsGroupPanelOpen(false);
setEditingGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Host Details Panel */}
{currentSection === "hosts" &&
isHostPanelOpen &&
editingHost?.protocol !== "serial" && (
<HostDetailsPanel
key={editingHost?.id ?? `new-${newHostProtocol || "ssh"}`}
initialData={editingHost}
initialProtocol={editingHost ? undefined : newHostProtocol}
availableKeys={keys}
identities={identities}
onCreateIdentity={(identity) =>
onUpdateIdentities([...identities, identity])
}
proxyProfiles={proxyProfiles}
groups={allGroupPaths}
managedSources={managedSources}
allTags={allTags}
allHosts={hosts}
defaultGroup={
editingHost
? undefined
: newHostGroupPath || selectedGroupPath
}
terminalThemeId={terminalThemeId}
terminalFontSize={terminalFontSize}
groupDefaults={editingHostGroupDefaults}
groupConfigs={groupConfigs}
snippets={snippets}
onSnippetsChange={onUpdateSnippets}
onHostsChange={onUpdateHosts}
onImportKey={onImportOrReuseKey}
knownHosts={knownHosts}
onAddKnownHost={onAddKnownHost}
terminalSettings={terminalSettings}
onSave={(host) => {
const latestHost = hosts.find(
(entry: { id: string }) => entry.id === host.id,
);
const nextHost = preserveConcurrentHostLineTimestampUpdate({
draft: host,
openedHost: editingHost,
latestHost,
});
onUpdateHosts((prevHosts) => upsertHostById(prevHosts, nextHost));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCreateGroup={(groupPath) => {
onUpdateCustomGroups(
Array.from(new Set([...customGroups, groupPath])),
);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<HostDetailsPanel
key={editingHost?.id ?? `new-${newHostProtocol || "ssh"}`}
initialData={editingHost}
initialProtocol={editingHost ? undefined : newHostProtocol}
availableKeys={keys}
identities={identities}
onCreateIdentity={(identity) =>
onUpdateIdentities([...identities, identity])
}
proxyProfiles={proxyProfiles}
groups={allGroupPaths}
managedSources={managedSources}
allTags={allTags}
allHosts={hosts}
defaultGroup={
editingHost
? undefined
: newHostGroupPath || selectedGroupPath
}
terminalThemeId={terminalThemeId}
terminalFontSize={terminalFontSize}
groupDefaults={editingHostGroupDefaults}
groupConfigs={groupConfigs}
snippets={snippets}
onSnippetsChange={onUpdateSnippets}
onHostsChange={onUpdateHosts}
onImportKey={onImportOrReuseKey}
knownHosts={knownHosts}
onAddKnownHost={onAddKnownHost}
terminalSettings={terminalSettings}
onSave={(host) => {
const latestHost = hosts.find(
(entry: { id: string }) => entry.id === host.id,
);
const nextHost = preserveConcurrentHostLineTimestampUpdate({
draft: host,
openedHost: editingHost,
latestHost,
});
onUpdateHosts((prevHosts) => upsertHostById(prevHosts, nextHost));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCreateGroup={(groupPath) => {
onUpdateCustomGroups(
Array.from(new Set([...customGroups, groupPath])),
);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Serial Host Details Panel - for editing serial port hosts */}
{currentSection === "hosts" &&
isHostPanelOpen &&
editingHost?.protocol === "serial" && (
<SerialHostDetailsPanel
initialData={editingHost}
allTags={allTags}
groups={allGroupPaths}
groupDefaults={editingHostGroupDefaults}
onSave={(host) => {
onUpdateHosts(upsertHostById(hosts, host));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<SerialHostDetailsPanel
initialData={editingHost}
allTags={allTags}
groups={allGroupPaths}
groupDefaults={editingHostGroupDefaults}
onSave={(host) => {
onUpdateHosts(upsertHostById(hosts, host));
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
onCancel={() => {
setIsHostPanelOpen(false);
setEditingHost(null);
setNewHostGroupPath(null);
}}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
{/* Local Shell Host Details Panel - for editing/saving local shell (CMD) hosts */}
{currentSection === "hosts" &&
isLocalShellHostPanelOpen && (
<LocalShellHostDetailsPanel
key={editingLocalShellHost?.id ?? "local-shell-new"}
initialData={editingLocalShellHost}
groups={allGroupPaths}
defaultGroup={
editingLocalShellHost
? undefined
: newHostGroupPath || selectedGroupPath
}
onSave={(host) => handleSaveLocalShellHost(host)}
onSaveAndConnect={(host) => handleSaveLocalShellHost(host, true)}
onCancel={handleCancelLocalShellHost}
layout="inline"
{...vaultHostPanelResizeProps}
/>
<Suspense fallback={null}>
<LocalShellHostDetailsPanel
key={editingLocalShellHost?.id ?? "local-shell-new"}
initialData={editingLocalShellHost}
groups={allGroupPaths}
defaultGroup={
editingLocalShellHost
? undefined
: newHostGroupPath || selectedGroupPath
}
onSave={(host) => handleSaveLocalShellHost(host)}
onSaveAndConnect={(host) => handleSaveLocalShellHost(host, true)}
onCancel={handleCancelLocalShellHost}
layout="inline"
{...vaultHostPanelResizeProps}
/>
</Suspense>
)}
</div>
</div>
@@ -1990,39 +2020,47 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</DialogContent>
</Dialog>
<ImportVaultDialog
open={isImportOpen}
onOpenChange={setIsImportOpen}
onFileSelected={handleImportFileSelected}
onPluginPreviewCommit={handlePluginPreviewCommit}
getPluginPreviewAnalysis={getPluginPreviewAnalysis}
groups={allGroupPaths}
/>
{isImportOpen && (
<Suspense fallback={null}>
<ImportVaultDialog
open={isImportOpen}
onOpenChange={setIsImportOpen}
onFileSelected={handleImportFileSelected}
onPluginPreviewCommit={handlePluginPreviewCommit}
getPluginPreviewAnalysis={getPluginPreviewAnalysis}
groups={allGroupPaths}
/>
</Suspense>
)}
{importProgress && (
<VaultImportProgressPanel
progress={importProgress}
onCancel={cancelImport}
onClose={resetImportProgress}
t={t}
/>
<Suspense fallback={null}>
<VaultImportProgressPanel
progress={importProgress}
onCancel={cancelImport}
onClose={resetImportProgress}
t={t}
/>
</Suspense>
)}
{/* Quick Connect Wizard */}
{isQuickConnectOpen && quickConnectTarget && (
<QuickConnectWizard
open={isQuickConnectOpen}
target={quickConnectTarget}
keys={keys}
identities={identities}
onConnect={handleQuickConnect}
onSaveHost={handleQuickConnectSaveHost}
onClose={() => {
setIsQuickConnectOpen(false);
setQuickConnectTarget(null);
setQuickConnectWarnings([]);
}}
warnings={quickConnectWarnings}
/>
<Suspense fallback={null}>
<QuickConnectWizard
open={isQuickConnectOpen}
target={quickConnectTarget}
keys={keys}
identities={identities}
onConnect={handleQuickConnect}
onSaveHost={handleQuickConnectSaveHost}
onClose={() => {
setIsQuickConnectOpen(false);
setQuickConnectTarget(null);
setQuickConnectWarnings([]);
}}
warnings={quickConnectWarnings}
/>
</Suspense>
)}
{/* Protocol Select Dialog */}
@@ -2042,18 +2080,22 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
)}
{/* Serial Connect Modal */}
<SerialConnectModal
open={isSerialModalOpen}
onClose={() => setIsSerialModalOpen(false)}
onConnect={(config, options) => {
if (onConnectSerial) {
onConnectSerial(config, options);
}
}}
onSaveHost={(host) => {
onUpdateHosts([...hosts, host]);
}}
/>
{isSerialModalOpen && (
<Suspense fallback={null}>
<SerialConnectModal
open={isSerialModalOpen}
onClose={() => setIsSerialModalOpen(false)}
onConnect={(config, options) => {
if (onConnectSerial) {
onConnectSerial(config, options);
}
}}
onSaveHost={(host) => {
onUpdateHosts([...hosts, host]);
}}
/>
</Suspense>
)}
</div>
);
}
+26 -1
View File
@@ -21,7 +21,7 @@ import {
} from "../../domain/remoteDesktop";
import type { Host } from "../../types";
import { HostDetailsConnectionSections } from "../HostDetailsConnectionSections";
import { CompanionRemoteDesktopSections } from "../host-details/CompanionRemoteDesktopSections";
import { CompanionRemoteDesktopInlineFields, CompanionRemoteDesktopSections } from "../host-details/CompanionRemoteDesktopSections";
import {
resolvePrimaryProtocolSavePort,
resolvePrimaryProtocolSwitchPort,
@@ -316,3 +316,28 @@ test("buildHostForProtocolOverride keeps SSH identity for companion RDP/VNC and
assert.equal(sshDispatch.host.protocol, "ssh");
assert.equal(sshDispatch.host.rdpConfig?.defaultConnect, undefined);
});
for (const resolutionMode of ["fixed", "dynamic", "fit"] as const) {
test(`companion RDP shows dimensions only in fixed mode: ${resolutionMode}`, () => {
const markup = renderToStaticMarkup(
<TooltipProvider>
<CompanionRemoteDesktopInlineFields
protocol="rdp"
form={makeHost({ rdpConfig: { enabled: true, resolutionMode, width: 1920, height: 1080 } })}
setForm={() => {}}
identities={[]}
t={(key) => key}
/>
</TooltipProvider>,
);
for (const dimension of ["width", "height"]) {
const label = new RegExp(`hostDetails\\.rdp\\.${dimension}`);
if (resolutionMode === "fixed") assert.match(markup, label);
else assert.doesNotMatch(markup, label);
}
if (resolutionMode === "fixed") {
assert.match(markup, /inputMode="numeric"[^>]*value="1920"/);
assert.match(markup, /inputMode="numeric"[^>]*value="1080"/);
}
});
}
+15 -4
View File
@@ -1,4 +1,4 @@
import React, { useCallback, useMemo } from "react";
import React, { useCallback, useMemo, useSyncExternalStore } from "react";
import { compareHostAddresses } from "../../domain/hostAddressSort";
import { upsertKnownHost } from "../../domain/knownHosts";
@@ -9,9 +9,14 @@ import {
isVncProtocol,
} from "../../domain/remoteDesktop";
import { sortByVaultOrder, sortVaultStringsByOrder } from "../../domain/vaultOrder";
import { matchesHostSearchQuery, matchesSearchQuery } from "../../domain/searchMatcher";
import {
getPinyinMatcherVersion,
matchesHostSearchQuery,
matchesSearchQuery,
subscribePinyinMatcherReady,
} from "../../domain/searchMatcher";
import type { GroupConfig, GroupNode, Host, KnownHost } from "../../types";
import KnownHostsManager from "../KnownHostsManager";
const KnownHostsManager = React.lazy(() => import("../KnownHostsManager"));
import type { SortMode } from "../ui/sort-dropdown";
const PROTO_TOKEN_RE = /(?:^|\s)proto:([a-z0-9:_-]+)(?=\s|$)/gi;
@@ -130,11 +135,17 @@ export function useVaultHostCollections({
);
}, [groupConfigs]);
const pinyinVersion = useSyncExternalStore(
subscribePinyinMatcherReady,
getPinyinMatcherVersion,
getPinyinMatcherVersion,
);
const searchTerm = useMemo(() => search.trim(), [search]);
const selectedTagSet = useMemo(() => new Set(selectedTags), [selectedTags]);
const hasSelectedTags = selectedTags.length > 0;
const hostMatchesSearchAndTags = useCallback((host: Host): boolean => {
void pinyinVersion;
if (searchTerm && !matchesVaultHostSearch(host, searchTerm)) {
return false;
}
@@ -142,7 +153,7 @@ export function useVaultHostCollections({
return false;
}
return true;
}, [hasSelectedTags, searchTerm, selectedTagSet]);
}, [hasSelectedTags, pinyinVersion, searchTerm, selectedTagSet]);
const filteredHosts = useMemo(
() => hosts.filter(hostMatchesSearchAndTags),
@@ -6,6 +6,7 @@
*/
import { Check, Search, Terminal } from 'lucide-react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { usePinyinMatcherVersion } from '../../application/state/usePinyinMatcherVersion';
import { matchesWorkspaceHostPickerQuery } from '../../domain/searchMatcher';
import { Host } from '../../types';
import { DistroAvatar } from '../DistroAvatar';
@@ -112,11 +113,13 @@ export const AddToWorkspaceDialog: React.FC<AddToWorkspaceDialogProps> = ({
return 'local terminal localhost'.includes(term);
}, [query]);
const pinyinMatcherVersion = usePinyinMatcherVersion();
const filteredHosts = useMemo(() => {
void pinyinMatcherVersion;
const term = query.trim();
if (!term) return selectableHosts;
return selectableHosts.filter((host) => matchesWorkspaceHostPickerQuery(term, host));
}, [selectableHosts, query]);
}, [selectableHosts, query, pinyinMatcherVersion]);
const { items, visualRows, itemIndexToVisualIndex } = useMemo(() => {
const list: Item[] = [];
+2
View File
@@ -757,6 +757,8 @@ export interface TerminalSession {
dynamicTitle?: string;
/** Runtime hostname detected from the current shell prompt (presentation only) */
promptHostname?: string;
/** The prompt hostname came from a target reached through an interactive jump host. */
promptHostnameFromJumpServer?: boolean;
/** Sticky coding CLI provider detected from launch command or window title */
codingCliProviderId?: CodingCliProviderId;
/** Runtime marker for sessions reconstructed from startup restore. */
+141
View File
@@ -10,10 +10,13 @@ import {
DEFAULT_RDP_PORT,
DEFAULT_VNC_PORT,
formatBandwidthBps,
formatStandardRdpSecurityBadge,
formatVncDisplayNumber,
getAvailableRemoteDesktopProtocols,
hasCompanionRdp,
hasCompanionVnc,
hasValidRdpFixedResolution,
parseRdpDimensionDraft,
isRdpProtocol,
isRemoteDesktopProtocol,
isVncProtocol,
@@ -22,6 +25,8 @@ import {
normalizeVncConfig,
parseVncPortOrDisplay,
RDP_RESOLUTION_PRESETS,
resolveEffectiveRdpSecurityMode,
resolveNextRdpAutoFallback,
resolveRemoteDesktopConnectionSpec,
sanitizeRdpConfig,
sanitizeVncConfig,
@@ -418,3 +423,139 @@ test('mapViewportToVirtualDesktopCoords maps full view and cropped single-monito
{ x: 3839, y: 1079 },
);
});
test('fixed RDP resolution validation rejects invalid drafts before sanitization', () => {
const config = { resolutionMode: 'fixed' as const, width: 1920, height: 1080 };
for (const value of ['', ' ', '19', '192', '199', '8193', '3840.5', 'abc', 'Infinity']) {
assert.equal(parseRdpDimensionDraft(value), undefined, value);
assert.equal(hasValidRdpFixedResolution(config, { width: value }), false, value);
assert.equal(hasValidRdpFixedResolution(config, { height: value }), false, value);
}
for (const value of ['200', '3840', '8192']) {
assert.equal(parseRdpDimensionDraft(value), Number(value));
assert.equal(hasValidRdpFixedResolution(config, { width: value, height: value }), true);
}
for (const dimension of [192, 8193, 3840.5, NaN]) {
assert.equal(hasValidRdpFixedResolution({ ...config, width: dimension }), false);
assert.equal(hasValidRdpFixedResolution({ ...config, height: dimension }), false);
}
assert.equal(hasValidRdpFixedResolution(config), true);
assert.equal(hasValidRdpFixedResolution({ resolutionMode: 'fixed' }), true);
for (const resolutionMode of ['dynamic', 'fit'] as const) {
assert.equal(hasValidRdpFixedResolution({ ...config, resolutionMode }, { width: '' }), true);
}
});
test('RDP auto-fallback steps NLA -> TLS -> Standard RDP safely without downgrading explicit modes', () => {
assert.equal(resolveEffectiveRdpSecurityMode('auto', 'none'), 'auto');
assert.equal(resolveEffectiveRdpSecurityMode('auto', 'tls'), 'tls');
assert.equal(resolveEffectiveRdpSecurityMode('auto', 'rdp'), 'rdp');
assert.equal(resolveEffectiveRdpSecurityMode('nla', 'rdp'), 'nla');
assert.equal(resolveEffectiveRdpSecurityMode('tls', 'rdp'), 'tls');
// Generic negotiation failure steps none -> tls -> rdp -> null
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'none',
isNegotiationFailure: true,
errorMessage: 'server requires TLS without CredSSP',
}),
'tls',
);
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'tls',
isNegotiationFailure: true,
errorMessage: 'negotiation failure',
}),
'rdp',
);
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'rdp',
isNegotiationFailure: true,
errorMessage: 'negotiation failure',
}),
null,
);
// Server explicitly advertising Standard-RDP-only jumps straight to 'rdp'
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'none',
isNegotiationFailure: true,
errorMessage: '[negotiation failure] server only supports Standard RDP Security',
}),
'rdp',
);
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'none',
isNegotiationFailure: true,
errorMessage: 'SSL_NOT_ALLOWED_BY_SERVER',
}),
'rdp',
);
// Explicit modes and non-negotiation errors must never fallback
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'nla',
currentStage: 'none',
isNegotiationFailure: true,
errorMessage: 'server only supports Standard RDP Security',
}),
null,
);
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'tls',
currentStage: 'none',
isNegotiationFailure: true,
errorMessage: 'server only supports Standard RDP Security',
}),
null,
);
assert.equal(
resolveNextRdpAutoFallback({
configuredMode: 'auto',
currentStage: 'none',
isNegotiationFailure: false,
errorMessage: 'wrong password',
}),
null,
);
});
test('formatStandardRdpSecurityBadge formats RC4/FIPS/Unencrypted labels and hides TLS', () => {
assert.equal(formatStandardRdpSecurityBadge(null), null);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: false, encrypted: true, method: 'tls', level: 'enhanced' }),
null,
);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: true, encrypted: true, method: 'rc4-128', level: 'client-compatible' }),
'RC4-128',
);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: true, encrypted: true, method: 'rc4-56', level: 'client-compatible' }),
'RC4-56',
);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: true, encrypted: true, method: 'rc4-40', level: 'low' }),
'RC4-40',
);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: true, encrypted: true, method: 'fips', level: 'fips' }),
'FIPS',
);
assert.equal(
formatStandardRdpSecurityBadge({ standardRdp: true, encrypted: false, method: 'none', level: 'none' }),
'Unencrypted',
);
});
+100
View File
@@ -24,6 +24,25 @@ export const DEFAULT_RDP_COLOR_DEPTH: RdpColorDepth = 32;
export const DEFAULT_RDP_RESOLUTION_MODE: RdpResolutionMode = 'dynamic';
export const DEFAULT_RDP_SECURITY_MODE: RdpSecurityMode = 'auto';
// Editor drafts stay separate from the sanitized config until they are valid.
export type RdpResolutionDraft = Partial<Record<'width' | 'height', string>>;
export const parseRdpDimensionDraft = (value: string): number | undefined => {
if (!value.trim()) return undefined;
const dimension = Number(value);
return Number.isInteger(dimension) && dimension >= 200 && dimension <= 8192
? dimension
: undefined;
};
export const hasValidRdpFixedResolution = (
config: RdpConfig | undefined,
draft: RdpResolutionDraft = {},
): boolean => config?.resolutionMode !== 'fixed' || (
parseRdpDimensionDraft(draft.width ?? String(config.width ?? DEFAULT_RDP_WIDTH)) !== undefined
&& parseRdpDimensionDraft(draft.height ?? String(config.height ?? DEFAULT_RDP_HEIGHT)) !== undefined
);
export const DEFAULT_VNC_SCALING_MODE: VncScalingMode = 'fit';
export const DEFAULT_VNC_QUALITY = 6;
export const DEFAULT_VNC_COMPRESSION_LEVEL = 2;
@@ -1156,3 +1175,84 @@ export function mapViewportToVirtualDesktopCoords(
const y = Math.max(0, Math.min(Math.round(virtualSize.height) - 1, Math.round(rawY)));
return { x, y };
}
export type RdpAutoFallbackStage = 'none' | 'tls' | 'rdp';
export interface RdpNegotiatedSecurityInfo {
standardRdp: boolean;
encrypted: boolean;
method: 'tls' | 'rc4-128' | 'rc4-56' | 'rc4-40' | 'fips' | 'none';
level: 'enhanced' | 'low' | 'client-compatible' | 'high' | 'fips' | 'none';
}
const STANDARD_RDP_ONLY_ERROR_RE =
/server only supports standard rdp security|ssl_not_allowed_by_server|standard rdp security is not supported/i;
/**
* Resolve the effective RDP security mode for a connection attempt given the
* user's configured mode and any active `auto`-mode negotiation fallback stage.
*/
export function resolveEffectiveRdpSecurityMode(
configuredMode: RdpSecurityMode | undefined,
autoFallbackStage: RdpAutoFallbackStage,
): RdpSecurityMode {
const mode = configuredMode ?? DEFAULT_RDP_SECURITY_MODE;
if (mode !== 'auto') return mode;
if (autoFallbackStage === 'tls') return 'tls';
if (autoFallbackStage === 'rdp') return 'rdp';
return 'auto';
}
/**
* Decide the next `auto`-mode negotiation fallback stage after a pre-auth
* `NegotiationFailure`. Explicit security modes (`nla`, `tls`, `rdp`) never
* auto-downgrade, and non-negotiation errors (e.g. wrong password) never retry.
*/
export function resolveNextRdpAutoFallback(options: {
configuredMode: RdpSecurityMode | undefined;
currentStage: RdpAutoFallbackStage;
isNegotiationFailure: boolean;
errorMessage?: string;
}): Exclude<RdpAutoFallbackStage, 'none'> | null {
const mode = options.configuredMode ?? DEFAULT_RDP_SECURITY_MODE;
if (mode !== 'auto' || !options.isNegotiationFailure) {
return null;
}
if (options.currentStage === 'rdp') {
return null;
}
if (options.errorMessage && STANDARD_RDP_ONLY_ERROR_RE.test(options.errorMessage)) {
return 'rdp';
}
if (options.currentStage === 'none') {
return 'tls';
}
if (options.currentStage === 'tls') {
return 'rdp';
}
return null;
}
/**
* Format a compact badge label for Standard RDP Security (RC4 / FIPS / None).
* Returns `null` for Enhanced RDP Security (TLS / NLA).
*/
export function formatStandardRdpSecurityBadge(
info: RdpNegotiatedSecurityInfo | null | undefined,
): string | null {
if (!info?.standardRdp) return null;
switch (info.method) {
case 'rc4-128':
return 'RC4-128';
case 'rc4-56':
return 'RC4-56';
case 'rc4-40':
return 'RC4-40';
case 'fips':
return 'FIPS';
case 'none':
return 'Unencrypted';
default:
return null;
}
}
+75 -3
View File
@@ -1,4 +1,67 @@
import { pinyin } from "pinyin-pro";
type PinyinFn = (text: string, options?: { pattern?: string; toneType?: string }) => string;
const CJK_CHAR_REGEX = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/;
let pinyinImpl: PinyinFn | null = null;
let pinyinLoadPromise: Promise<void> | null = null;
let pinyinReadyVersion = 0;
const pinyinReadyListeners = new Set<() => void>();
const shouldEagerLoadPinyin = typeof window === "undefined"
|| (typeof process !== "undefined" && Boolean(
process.env?.NODE_TEST_CONTEXT
|| process.argv?.some((arg) => arg.includes("--test")),
));
if (shouldEagerLoadPinyin && typeof process !== "undefined") {
try {
const getBuiltinModule = (process as unknown as {
getBuiltinModule?: (id: string) => { createRequire?: (filename: string) => NodeRequire };
}).getBuiltinModule;
const nodeModule = getBuiltinModule?.("node:module");
const req = nodeModule?.createRequire?.(`${process.cwd()}/package.json`);
const mod = req?.("pinyin-pro") as { pinyin?: PinyinFn } | undefined;
if (typeof mod?.pinyin === "function") {
pinyinImpl = mod.pinyin;
}
} catch {
// Fall back to async dynamic import on first CJK query.
}
}
/**
* Trigger loading the 447 KB `pinyin-pro` dictionary on demand in browser
* builds when CJK search text is encountered. Notifies subscribers once ready
* so active search views can re-run matching without blocking cold startup.
*/
export function ensurePinyinMatcherLoaded(): void {
if (pinyinImpl || pinyinLoadPromise) return;
pinyinLoadPromise = import("pinyin-pro")
.then((mod) => {
pinyinImpl = mod.pinyin as PinyinFn;
pinyinReadyVersion += 1;
for (const listener of pinyinReadyListeners) {
try {
listener();
} catch {
// ignore listener errors
}
}
})
.catch(() => {
pinyinLoadPromise = null;
});
}
export function subscribePinyinMatcherReady(listener: () => void): () => void {
pinyinReadyListeners.add(listener);
return () => {
pinyinReadyListeners.delete(listener);
};
}
export function getPinyinMatcherVersion(): number {
return pinyinReadyVersion;
}
const SEARCH_SPLIT_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/u;
const SEARCH_REMOVE_REGEX = /[\s\p{Pd}_/\\|.,,。;;::!!??()()[\]{}<>《》、"'`~·]+/gu;
@@ -53,6 +116,10 @@ function pinyinCacheEntryChars(
}
function getPinyinVariants(sourceText: string): { full: string; initials: string } {
// Pure non-CJK strings need neither pinyin transliteration nor cache entries.
if (!CJK_CHAR_REGEX.test(sourceText)) {
return { full: "", initials: "" };
}
const cacheKey = normalizeText(sourceText);
const cached = PINYIN_CACHE.get(cacheKey);
if (cached) {
@@ -61,17 +128,22 @@ function getPinyinVariants(sourceText: string): { full: string; initials: string
return cached;
}
if (!pinyinImpl) {
ensurePinyinMatcherLoaded();
return { full: "", initials: "" };
}
let full = "";
let initials = "";
try {
full = compactText(
pinyin(sourceText, {
pinyinImpl(sourceText, {
toneType: "none",
}),
);
initials = compactText(
pinyin(sourceText, {
pinyinImpl(sourceText, {
pattern: "first",
toneType: "none",
}),
+30
View File
@@ -41,6 +41,24 @@ test('agent mode does not use a prompt hostname when the agent has no title', ()
assert.equal(resolveSessionTabTitle(session, 'agent'), session.hostLabel);
});
test('agent mode uses a jump-server target hostname instead of the configured jump label', () => {
const session = {
hostLabel: 'jumpssh.riverbegin.cn',
promptHostname: 'k8s-10-1-64-1',
promptHostnameFromJumpServer: true,
};
assert.equal(resolveSessionTabTitle(session, 'agent'), session.promptHostname);
});
test('disabled dynamic titles keep the configured jump-server label for nested hosts', () => {
const session = {
hostLabel: 'jumpssh.riverbegin.cn',
promptHostname: 'k8s-10-1-64-1',
promptHostnameFromJumpServer: true,
};
assert.equal(resolveSessionTabTitle(session, 'off'), session.hostLabel);
});
test('persisted merged workspace identities ignore live hostnames', () => {
const sessions = [
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
@@ -69,6 +87,18 @@ test('auto workspace labels use the same agent title policy as session tabs', ()
assert.equal(resolveWorkspaceTabLabel(workspace, [session], 'agent'), session.dynamicTitle);
});
test('auto workspace labels show nested jump targets in agent mode', () => {
const session = {
id: 'a',
hostId: 'h1',
hostLabel: 'jumpssh.riverbegin.cn',
promptHostname: 'k8s-10-1-64-1',
promptHostnameFromJumpServer: true,
};
const workspace = { title: DEFAULT_WORKSPACE_TITLE, autoTitle: true, focusedSessionId: session.id };
assert.equal(resolveWorkspaceTabLabel(workspace, [session], 'agent'), session.promptHostname);
});
test('generated workspace display titles honor mode without changing their saved identity', () => {
const sessions = [
{ id: 'a', hostId: 'h1', hostLabel: 'Production', promptHostname: 'vm-prod' },
+13 -5
View File
@@ -12,7 +12,12 @@ export const getSessionConnectionLabel = (
type SessionTabLabelSession = Pick<
TerminalSession,
'customName' | 'hostLabel' | 'promptHostname' | 'dynamicTitle' | 'codingCliProviderId'
| 'customName'
| 'hostLabel'
| 'promptHostname'
| 'promptHostnameFromJumpServer'
| 'dynamicTitle'
| 'codingCliProviderId'
>;
const joinWorkspaceLabels = (labels: readonly string[]): string | null => {
@@ -160,7 +165,8 @@ const titleHostnameKey = (hostname: string): string =>
/**
* Resolve the label shown on session tabs and pane headers.
* Live prompt and Shell titles require all mode; agent mode permits Agent titles only.
* Live shell titles require all mode; agent mode permits Agent titles and
* nested JumpServer target hostnames.
*/
export const resolveSessionTabTitle = (
session: SessionTabLabelSession,
@@ -176,10 +182,12 @@ export const resolveSessionTabTitle = (
if (session.codingCliProviderId && dynamicTitle) {
return dynamicTitle;
}
if (dynamicTabTitleMode !== 'all') {
return connectionLabel;
}
const promptHostname = session.promptHostname?.trim();
if (dynamicTabTitleMode !== 'all') {
return promptHostname && session.promptHostnameFromJumpServer
? promptHostname
: connectionLabel;
}
if (!dynamicTitle) return promptHostname || connectionLabel;
if (promptHostname) {
const reportedHost = shellTitleHostname(dynamicTitle);
+5
View File
@@ -10,6 +10,8 @@ export interface TerminalContextReadRequest {
range?: TerminalContextReadRange;
startLine?: number;
maxLines?: number;
/** Internal opt-in used only by readiness preflight; never exposed to model tools. */
includeReadinessContext?: boolean;
}
export interface TerminalContextLineWindowInput {
@@ -41,6 +43,9 @@ export interface TerminalContextReadResult {
hasMoreAfter: boolean;
source: TerminalContextReadSource;
alternateScreen?: boolean;
cursorLine?: number;
cursorAtLineEnd?: boolean;
readinessContext?: string;
}
export type TerminalContextReader = (
+2
View File
@@ -206,6 +206,8 @@ export function decideHiddenTabKeepCountAction(input: {
export type TerminalHibernateWakePayload = {
/** Full serialized terminal state -- preferred wake history (coherent ANSI). */
snapshot: string;
/** Gzip-compressed full snapshot used while hibernated to minimize heap usage. */
compressedSnapshot?: Uint8Array | null;
/** Visible viewport rows; used with scrollback only when snapshot is empty. */
viewportSnapshot?: string;
/** Older scrollback rows; used with viewport only when snapshot is empty. */
+8
View File
@@ -22,6 +22,7 @@ const ALPINE_PROMPT_IDENTITY_PATTERN =
const MACOS_ROOT_PROMPT_IDENTITY_PATTERN =
/^([A-Za-z0-9_][A-Za-z0-9_.-]*):(?:~|\/[^#$>\\\s]*)\s+[A-Za-z0-9_.-]+[#$]?$/u;
const JUMP_SERVER_MENU_PROMPT_PATTERN = /^(?:Opt|\[Host\])>$/u;
const JUMP_SERVER_MENU_LINE_PATTERN = /^(?:Opt|\[Host\])>(?:\s+\S.*)?$/u;
const PROMPT_HOST_PATTERN =
/^(?:\[[A-Fa-f0-9:.]+\]|[A-Za-z0-9_][A-Za-z0-9_.-]*)$/u;
@@ -181,6 +182,12 @@ function isJumpServerMenuPrompt(value) {
return JUMP_SERVER_MENU_PROMPT_PATTERN.test(line);
}
function isJumpServerMenuLine(value) {
const line = lastLogicalLine(value).trim();
if (!line) return false;
return JUMP_SERVER_MENU_LINE_PATTERN.test(line);
}
function extractTerminalPromptHostname(value) {
const plain = stripTerminalControlSequences(value);
if (!plain) return null;
@@ -257,5 +264,6 @@ module.exports = {
isBashPs2ContinuationLine,
isUntrustedTerminalInputPrompt,
isJumpServerMenuPrompt,
isJumpServerMenuLine,
extractTerminalPromptHostname,
};
@@ -22,4 +22,5 @@ export function isUntrustedTerminalInputPrompt(
options?: ConfirmedPromptOptions,
): boolean;
export function isJumpServerMenuPrompt(value: string): boolean;
export function isJumpServerMenuLine(value: string): boolean;
export function extractTerminalPromptHostname(value: string): string | null;
+10
View File
@@ -6,6 +6,7 @@ import {
appendTerminalPromptSecurityTail,
foldTerminalPromptSecurityOutput,
isConfirmedTerminalShellPrompt,
isJumpServerMenuLine,
isJumpServerMenuPrompt,
isSensitiveTerminalChallenge,
isUntrustedTerminalInputPrompt,
@@ -98,6 +99,15 @@ test('isJumpServerMenuPrompt detects active JumpServer menus and rejects non-men
}
});
test('isJumpServerMenuLine detects unanswered and consumed JumpServer menu lines', () => {
for (const line of ['Opt> ', 'Opt>', 'Opt> 42', '[Host]> 10.1.64.1', '\x1b[32mOpt> \x1b[0m42']) {
assert.equal(isJumpServerMenuLine(line), true, JSON.stringify(line));
}
for (const text of ['echo Opt> 42', 'OTP> 123456', '[root@target ~]# Opt> 42', 'Opt>42']) {
assert.equal(isJumpServerMenuLine(text), false, JSON.stringify(text));
}
});
test('terminal prompt security recognizes password, MFA, OTP, PIN, and CJK challenges', () => {
const challenges = [
'Password: ',
+2
View File
@@ -3,6 +3,7 @@ import {
extractTerminalPromptHostname,
isBashPs2ContinuationLine,
isConfirmedTerminalShellPrompt,
isJumpServerMenuLine,
isJumpServerMenuPrompt,
isSensitiveTerminalChallenge,
isUntrustedTerminalInputPrompt,
@@ -80,6 +81,7 @@ export {
MAX_PROMPT_SECURITY_TAIL_CHARS,
extractTerminalPromptHostname,
isConfirmedTerminalShellPrompt,
isJumpServerMenuLine,
isJumpServerMenuPrompt,
isSensitiveTerminalChallenge,
isUntrustedTerminalInputPrompt,
+2 -3
View File
@@ -124,9 +124,8 @@ function setAutoLaunchEnabled(enabled, {
try {
app.setLoginItemSettings({
openAtLogin: wantEnabled,
// openAsHidden only applies on macOS App Store builds; Windows relies
// on the --hidden arg below, which main.cjs checks on cold start.
openAsHidden: wantEnabled,
// Windows relies on the --hidden arg below, which main.cjs checks on cold start.
// macOS 13+ detects login launches via wasOpenedAtLogin (openAsHidden was removed in Electron 44).
path: execPath,
args: wantEnabled ? [HIDDEN_LAUNCH_ARG] : [],
});
-1
View File
@@ -204,7 +204,6 @@ test("setAutoLaunchEnabled(true) registers the hidden launch arg", () => {
assert.deepEqual(capturedSettings, {
openAtLogin: true,
openAsHidden: true,
path: EXEC_PATH,
args: [HIDDEN_LAUNCH_ARG],
});
+72 -5
View File
@@ -8,6 +8,7 @@ const {
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
} = require("./shellUtils.cjs");
const { renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
const { classifyLocalShellType } = require("../../../lib/localShell.cjs");
// Build a stateful decoder for a full exec call. Serial data events can
@@ -65,6 +66,45 @@ function subscribeToPtyData(ptyStream, onData) {
// comfortably larger than the prompt including the escape codes it may carry.
const PROMPT_SUFFIX_MIN_WINDOW_CHARS = 2048;
const PROMPT_SUFFIX_WINDOW_PER_PROMPT_CHAR = 8;
// Full-screen clears (ED 2 / RIS) discard prior screen content so earlier
// lines cannot combine with post-clear text. ED 3 (`\x1b[3J`) only clears
// scrollback and leaves the visible screen intact.
// eslint-disable-next-line no-control-regex
const SCREEN_CLEAR_CONTROL_REGEX = /\u001B(?:c|\[2J)/g;
// Only trigger rendered fallback when the tail actually contains a redraw,
// cursor, or erase control (bare CR, BS, or CSI cursor/erase A-H/J/K/f).
// SGR colors (`\x1b[32m`), OSC titles, and bracketed paste modes must stay
// off this path so colored log floods do not invoke TerminalTextRenderer.
// eslint-disable-next-line no-control-regex
const REDRAW_CONTROL_REGEX = /\r(?!\n)|\u0008|(?:\u001B\[|\u009B)[0-9;]*[A-HJKf]/;
function sliceAfterLastScreenClear(text) {
let lastEnd = 0;
SCREEN_CLEAR_CONTROL_REGEX.lastIndex = 0;
let match;
while ((match = SCREEN_CLEAR_CONTROL_REGEX.exec(text)) !== null) {
lastEnd = match.index + match[0].length;
}
return lastEnd > 0 ? text.slice(lastEnd) : text;
}
function hasTabNearPrompt(tail, strippedTailNoCr, normalizedPrompt) {
if (!tail.includes("\t") || !normalizedPrompt.includes(" ")) return false;
const trailingNewlines = normalizedPrompt.match(/\n+$/)?.[0] || "";
if (trailingNewlines && !strippedTailNoCr.endsWith(trailingNewlines)) return false;
const promptBody = trailingNewlines
? normalizedPrompt.slice(0, -trailingNewlines.length)
: normalizedPrompt;
const tailBody = trailingNewlines
? strippedTailNoCr.slice(0, -trailingNewlines.length)
: strippedTailNoCr;
const promptLastLine = promptBody.slice(promptBody.lastIndexOf("\n") + 1);
const trimmedPromptEnd = promptLastLine.trimEnd();
const lastSpaceIdx = trimmedPromptEnd.lastIndexOf(" ");
const trailingToken = lastSpaceIdx >= 0 ? promptLastLine.slice(lastSpaceIdx + 1) : promptLastLine;
return (trailingToken.length > 0 && tailBody.endsWith(trailingToken))
|| /\t[ \t]*$/.test(tailBody);
}
function hasExpectedPromptSuffix(text, expectedPrompt) {
if (!expectedPrompt) return false;
@@ -76,18 +116,45 @@ function hasExpectedPromptSuffix(text, expectedPrompt) {
PROMPT_SUFFIX_MIN_WINDOW_CHARS,
String(expectedPrompt).length * PROMPT_SUFFIX_WINDOW_PER_PROMPT_CHAR,
);
const tail = fullText.length > windowChars ? fullText.slice(-windowChars) : fullText;
const rawTail = fullText.length > windowChars ? fullText.slice(-windowChars) : fullText;
const tail = sliceAfterLastScreenClear(rawTail);
const strippedTail = stripAnsi(tail);
const strippedTailNoCr = strippedTail.replace(/\r/g, "");
// Drop CR so a redraw inside one line (`root@host:~\r# `) still matches
// the cached prompt. That collapses a two-line PS1's `\r\r\n` to a single
// LF, which no longer ends with the cache (`user@host: /root\n\n\n$ `).
if (strippedTail.replace(/\r/g, "").endsWith(normalizedPrompt)) return true;
if (strippedTailNoCr.endsWith(normalizedPrompt)) return true;
// The idle-prompt cache turns those CRs into LFs and keeps the blank
// lines. Compare that form too, only when the cache itself spans lines,
// so a bare `$`/`#` is unchanged.
if (!ansiFreePrompt.includes("\n")) return false;
const crAsLfPrompt = ansiFreePrompt.replace(/\r/g, "\n");
return strippedTail.replace(/\r/g, "\n").endsWith(crAsLfPrompt);
if (ansiFreePrompt.includes("\n")) {
const crAsLfPrompt = ansiFreePrompt.replace(/\r/g, "\n");
if (strippedTail.replace(/\r/g, "\n").endsWith(crAsLfPrompt)) return true;
// Screen-derived multiline prompts trim trailing whitespace on lines above
// the cursor (matching xterm's translateToString(true)) while preserving
// exact spacing on the final cursor line. Normalize trailing spaces on
// non-final lines on CRLF-only streams too, gated on a final-line match.
const promptLastLine = normalizedPrompt.slice(normalizedPrompt.lastIndexOf("\n") + 1);
if (
strippedTailNoCr.endsWith(promptLastLine)
&& strippedTailNoCr.replace(/[ \t]+\n/g, "\n").endsWith(normalizedPrompt)
) {
return true;
}
}
// Only fall back to rendered screen comparison when raw matching fails and
// the tail contains terminal redraw controls (bare CR overwrite, backspace,
// or CSI/C1 erase/cursor controls). Running this strictly after the raw
// fast paths avoids regressing scrolling PTYs that repaint prompts with
// absolute cursor positioning (e.g. `\x1b[24;1H\x1b[Kuser@host:~$ `), while
// letting screen-derived multiline prompts match raw CR+EL redraws.
if (!REDRAW_CONTROL_REGEX.test(tail) && !hasTabNearPrompt(tail, strippedTailNoCr, normalizedPrompt)) {
return false;
}
const rendered = renderCursorBoundScreenText(tail);
if (!rendered) return false;
return rendered.rawText.endsWith(normalizedPrompt)
|| rendered.trimmedAboveText.endsWith(normalizedPrompt);
}
function escapePosixSingleQuoted(text) {
@@ -92,3 +92,111 @@ test("prompt suffix check does not scan the whole buffer on every call", () => {
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
assert.ok(elapsedMs < 250, `50 checks took ${elapsedMs.toFixed(0)} ms`);
});
test("prompt suffix check skips rendered fallback on SGR-colored and tab-delimited log floods", () => {
const coloredLogs = "\x1b[32mINFO\x1b[0m\t\x1b[36mrequest completed\x1b[0m\r\n".repeat(120);
const started = process.hrtime.bigint();
for (let i = 0; i < 5000; i += 1) {
assert.equal(hasExpectedPromptSuffix(coloredLogs, "root@3160T:~# "), false);
}
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
assert.ok(elapsedMs < 500, `5000 colored-log checks took ${elapsedMs.toFixed(0)} ms`);
});
test("screen-derived multiline prompts match raw CR+EL redraws while rejecting unsafe states", () => {
const seededPrompt = "[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\n# ";
const rawRedraw = "^C\r\n[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\r\n# \r\x1b[K# ";
assert.equal(hasExpectedPromptSuffix(rawRedraw, seededPrompt), true);
// ANSI-styled header with trailing spaces on the header line and repeated CR+EL redraws.
const styledRedraw =
"\x1b[?2004h\x1b[32m[root@k8s-10-1-64-1 ~]\x1b[0m br0 = 10.1.64.1 \r\r\n# \r\x1b[K# \r\x1b[2K# ";
assert.equal(hasExpectedPromptSuffix(styledRedraw, seededPrompt), true);
// Pending input after redraw must not match.
assert.equal(
hasExpectedPromptSuffix("[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\r\n# \r\x1b[K# ls", seededPrompt),
false,
);
// Missing trailing space on expected prompt must still not match.
assert.equal(
hasExpectedPromptSuffix(rawRedraw, "[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\n#"),
false,
);
// Mid-line cursor (text remains to the right of cursor) must not match.
assert.equal(
hasExpectedPromptSuffix("[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\r\n# ls\x1b[2D", seededPrompt),
false,
);
// Non-empty text below cursor (primary-screen menu) must not match.
assert.equal(
hasExpectedPromptSuffix("[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\n# \r\nMenu\x1b[1A\x1b[3G", seededPrompt),
false,
);
// Alternate screen active must not match.
assert.equal(
hasExpectedPromptSuffix(`${rawRedraw}\x1b[?1049hvim`, seededPrompt),
false,
);
// Pre-clear header line must not combine with a post-clear bare marker.
assert.equal(
hasExpectedPromptSuffix("[root@k8s-10-1-64-1 ~] br0 = 10.1.64.1\r\n\x1b[2J\x1b[H# ", seededPrompt),
false,
);
// Bare marker without header must not match.
assert.equal(
hasExpectedPromptSuffix("output\r\n# \r\x1b[K# ", seededPrompt),
false,
);
// Scrolling PTY that repaints a prompt with absolute cursor positioning must still match.
assert.equal(
hasExpectedPromptSuffix(`${"row\r\n".repeat(80)}\x1b[24;1H\x1b[Kuser@host:~$ `, "user@host:~$ "),
true,
);
// Scrollback-only clear (ED 3) leaves the visible prompt intact.
assert.equal(
hasExpectedPromptSuffix("user@host:~$ \x1b[3J", "user@host:~$ "),
true,
);
// Rehydrated multiline prompt whose header had trailing spaces matches CRLF-only output
// without requiring redraw controls, while still enforcing trailing space on the cursor line.
assert.equal(
hasExpectedPromptSuffix("user@host: /workspace \r\n$ ", "user@host: /workspace\n$ "),
true,
);
assert.equal(
hasExpectedPromptSuffix("user@host: /workspace \r\n$ ", "user@host: /workspace\n$"),
false,
);
assert.equal(
hasExpectedPromptSuffix("user@host: /workspace \r\n$ ls", "user@host: /workspace\n$ "),
false,
);
// Rehydrated prompts whose literal tabs expanded to spaces in xterm match raw tab output.
assert.equal(
hasExpectedPromptSuffix("output\r\nuser@host:\t~$ ", "user@host: ~$ "),
true,
);
assert.equal(
hasExpectedPromptSuffix("output\r\nuser@host:\t~$ ls", "user@host: ~$ "),
false,
);
assert.equal(
hasExpectedPromptSuffix("output\r\nuser@host:~$\t", "user@host:~$ "),
true,
);
assert.equal(
hasExpectedPromptSuffix("output\r\nuser@host:\t/workspace\r\n$ ", "user@host: /workspace\n$ "),
true,
);
});
+19
View File
@@ -341,8 +341,25 @@ function matchesOsc133EmptyPrompt(session, view) {
&& cursor.line === session._osc133PromptLine;
}
let nextSessionReadinessGeneration = 1;
function getSessionReadinessGeneration(session) {
if (!session || typeof session !== "object") return 0;
if (typeof session._readinessGeneration !== "number") {
session._readinessGeneration = nextSessionReadinessGeneration++;
}
return session._readinessGeneration;
}
function bumpSessionReadinessGeneration(session) {
if (!session || typeof session !== "object") return 0;
session._readinessGeneration = nextSessionReadinessGeneration++;
return session._readinessGeneration;
}
function trackSessionIdlePrompt(session, chunk) {
if (!session || typeof chunk !== "string" || !chunk) return "";
bumpSessionReadinessGeneration(session);
const previousTail = session._promptTrackTail || "";
const combined = `${previousTail}${chunk}`;
@@ -1440,6 +1457,8 @@ module.exports = {
isDefaultCmdPromptLine,
isDefaultPosixPromptLine,
trackSessionIdlePrompt,
getSessionReadinessGeneration,
bumpSessionReadinessGeneration,
looksLikeIdleAutoLogout,
isLocalhostHostname,
extractFirstNonLocalhostUrl,
+11 -3
View File
@@ -226,7 +226,7 @@ function buildExternalAgentContextualPrompt({ mode, prompt, chatSessionId, defau
return `${systemContext}\n\n${prompt}`;
}
const { execViaPty } = require("./ai/ptyExec.cjs");
const execViaPty = (...args) => require("./ai/ptyExec.cjs").execViaPty(...args);
let externalMcpController = null;
let userDataDir = null;
@@ -1065,10 +1065,18 @@ function cleanup() {
registeredContext.sdkActiveStreams.clear();
}
try {
registeredContext?.codexAppServerRuntime?.close?.();
if (typeof registeredContext?.closeCodexAppServerRuntimeIfLoaded === "function") {
registeredContext.closeCodexAppServerRuntimeIfLoaded();
} else {
registeredContext?.codexAppServerRuntime?.close?.();
}
} catch {}
try {
registeredContext?.codebuddySessionManager?.closeAll?.();
if (typeof registeredContext?.closeCodebuddySessionsIfLoaded === "function") {
registeredContext.closeCodebuddySessionsIfLoaded();
} else {
registeredContext?.codebuddySessionManager?.closeAll?.();
}
} catch {}
for (const [id, session] of codexLoginSessions) {
@@ -7,7 +7,8 @@ const { formatSyntheticEcho, getVisibleIdlePrompt } = require("../ai/shellUtils.
const { classifyShellReadiness } = require("../ai/shellReadinessState.cjs");
const { clearSessionFlowState } = require("../terminalFlowAck.cjs");
const { remoteDisallowsExecChannelProbe, sessionDisallowsExtraSshChannel, ensureSessionShellKindForExec } = require("../ai/sessionShellKind.cjs");
const defaultAiPrivacyService = require("../../shared/aiPrivacyService.cjs");
let _defaultAiPrivacyService = null;
const getDefaultAiPrivacyService = () => (_defaultAiPrivacyService ??= require("../../shared/aiPrivacyService.cjs"));
function assertCattyPrivacySession(privacyService, chatSessionId) {
if (chatSessionId) {
@@ -67,6 +68,22 @@ async function proxyCattyExecToWorker({
try {
beforeExecute();
if (
!isNetworkDeviceLike(meta)
&& typeof mcpServerBridge.rehydrateWorkerPromptForExec === "function"
) {
const preflight = await mcpServerBridge.rehydrateWorkerPromptForExec({
sessionId,
chatSessionId,
});
if (!preflight.ok) {
return { ok: false, error: preflight.error };
}
if (mcpServerBridge.getPermissionMode?.() === "observer") {
return { ok: false, error: "Execution blocked: permission mode is 'observer'" };
}
beforeExecute();
}
return await terminalWorkerManager.request("netcatty:ai:exec", {
sessionId,
command,
@@ -86,7 +103,13 @@ async function proxyCattyExecToWorker({
}
function registerCattyExecHandlers(ctx) {
const privacyService = ctx.aiPrivacyService || defaultAiPrivacyService;
const privacyService = ctx.aiPrivacyService || {
isEnabled: () => getDefaultAiPrivacyService().isEnabled(),
restore: (...args) => getDefaultAiPrivacyService().restore(...args),
redact: (...args) => getDefaultAiPrivacyService().redact(...args),
checkSession: (...args) => getDefaultAiPrivacyService().checkSession(...args),
createPolicyGuard: (...args) => getDefaultAiPrivacyService().createPolicyGuard(...args),
};
with (ctx) {
ipcMain.handle("netcatty:ai:exec", async (event, { sessionId, command, chatSessionId, delegationTag }) => {
// Validate IPC sender (Issue #17)
@@ -99,3 +99,136 @@ test("catty AI exec proxies to the terminal worker when the real session lives i
["release", "ssh-1", "token-1"],
]);
});
test("catty worker exec rehydrates prompt readiness via shared preflight and honors cancel during preflight", async (t) => {
const { isolateCliDiscoveryFile } = require("../cliDiscoveryTestIsolation.cjs");
isolateCliDiscoveryFile();
const bridgePath = require.resolve("../mcpServerBridge.cjs");
delete require.cache[bridgePath];
const bridge = require(bridgePath);
t.after(() => bridge.cleanup());
const events = [];
const workerRequests = [];
const terminalWorkerManager = {
getSessionOwnerWebContentsId: () => null,
drainOutputSession: () => true,
send() {},
request(channel, payload, options) {
events.push(`worker:${channel}`);
workerRequests.push({ channel, payload, options });
if (channel === "netcatty:ai:shellReadiness") {
return Promise.resolve({
ok: true,
found: true,
trackedShell: true,
freshIdlePrompt: "",
visibleIdlePrompt: "",
readiness: "unknown",
generation: 7,
bufferedBytes: 4,
unackedBytes: 0,
outputPaused: false,
});
}
if (channel === "netcatty:ai:seedIdlePrompt") {
return Promise.resolve({
ok: true,
found: true,
ready: true,
prompt: "[root@target ~]# ",
generation: 8,
});
}
return Promise.resolve({ ok: true, stdout: "ok\n", exitCode: 0 });
},
};
bridge.init({
sessions: new Map(),
electronModule: null,
terminalWorkerManager,
drainTerminalOutput: async (sessionId) => {
events.push(`drain:${sessionId}`);
return { success: true };
},
});
bridge.setPermissionMode("auto");
bridge.setCommandBlocklist([]);
bridge.updateSessionMetadata([
{ sessionId: "ssh-1", protocol: "ssh", hostname: "jump.example.com", connected: true },
], "chat-catty");
bridge.setVaultAgentInvoker(async (op, params) => {
events.push(`renderer:${op}:${params.includeReadinessContext === true}`);
return {
ok: true,
content: "[root@target ~]# ",
readinessContext: "[root@target ~]# ",
cursorLine: 0,
cursorAtLineEnd: true,
alternateScreen: false,
};
});
const ipcMain = createFakeIpcMain();
const aiPrivacyService = createAiPrivacyService();
aiPrivacyService.checkSession("chat-catty");
registerCattyExecHandlers({
ipcMain,
aiPrivacyService,
validateSender: () => true,
sessions: new Map(),
terminalWorkerManager,
mcpServerBridge: bridge,
electronModule: {},
safeSend() {},
execViaPty() {
throw new Error("main process should not execute without a real session");
},
getFreshIdlePrompt() {
return "";
},
});
const result = await ipcMain.handlers.get("netcatty:ai:exec")(
{ sender: { id: 7 } },
{ sessionId: "ssh-1", command: "pwd", chatSessionId: "chat-catty" },
);
assert.deepEqual(result, { ok: true, stdout: "ok\n", exitCode: 0 });
assert.deepEqual(events, [
"worker:netcatty:ai:shellReadiness",
"drain:ssh-1",
"renderer:terminal.readContext:true",
"worker:netcatty:ai:seedIdlePrompt",
"worker:netcatty:ai:exec",
]);
assert.equal(workerRequests[1].payload.context, "[root@target ~]# ");
assert.equal(workerRequests[1].payload.expectedGeneration, 7);
// Cancelling via netcatty:ai:catty:cancel while preflight awaits renderer context aborts before exec.
workerRequests.length = 0;
let releaseRead;
let readEntered;
const readEnteredPromise = new Promise((resolve) => { readEntered = resolve; });
bridge.setVaultAgentInvoker(async () => {
readEntered();
return await new Promise((resolve) => { releaseRead = resolve; });
});
const pending = ipcMain.handlers.get("netcatty:ai:exec")(
{ sender: { id: 7 } },
{ sessionId: "ssh-1", command: "pwd", chatSessionId: "chat-catty" },
);
await readEnteredPromise;
await ipcMain.handlers.get("netcatty:ai:catty:cancel")(
{ sender: { id: 7 } },
{ chatSessionId: "chat-catty" },
);
const cancelled = await pending;
releaseRead?.({ ok: true, readinessContext: "[root@target ~]# ", alternateScreen: false });
assert.equal(cancelled.ok, false);
assert.match(cancelled.error, /cancel/i);
assert.deepEqual(workerRequests.map((r) => r.channel), ["netcatty:ai:shellReadiness"]);
assert.equal(bridge.getSessionBusyError("ssh-1"), null, "lock must be released after cancelled preflight");
});
+12 -5
View File
@@ -1,12 +1,19 @@
"use strict";
const privacyService = require("../../shared/aiPrivacyService.cjs");
let _defaultPrivacyService = null;
function getDefaultPrivacyService() {
if (!_defaultPrivacyService) {
_defaultPrivacyService = require("../../shared/aiPrivacyService.cjs");
}
return _defaultPrivacyService;
}
function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = privacyService }) {
function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService }) {
const resolveService = () => aiPrivacyService || getDefaultPrivacyService();
ipcMain.handle("netcatty:ai:privacy:status", (event) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized" };
try {
return { ok: true, enabled: aiPrivacyService.isEnabled() };
return { ok: true, enabled: resolveService().isEnabled() };
} catch (error) {
return { ok: false, error: error.message };
}
@@ -19,7 +26,7 @@ function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = p
}
return {
ok: true,
value: aiPrivacyService[request.operation](request.chatSessionId, request.value),
value: resolveService()[request.operation](request.chatSessionId, request.value),
};
} catch (error) {
return { ok: false, error: error.message };
@@ -27,7 +34,7 @@ function registerPrivacyHandlers({ ipcMain, validateSender, aiPrivacyService = p
});
ipcMain.handle("netcatty:ai:privacy:clear", (event, chatSessionId) => {
if (!validateSender(event)) return { ok: false, error: "Unauthorized" };
aiPrivacyService.clearSession(chatSessionId);
resolveService().clearSession(chatSessionId);
return { ok: true };
});
}
+32 -24
View File
@@ -9,17 +9,17 @@
* { prompt, attachments, cwd, model, env, binPath, injectedMcpServers, emitter,
* signal, resumeSessionId, apiKey, baseUrl }
*/
const claude = require("./claudeDriver.cjs");
const codex = require("./codexDriver.cjs");
const copilot = require("./copilotDriver.cjs");
const cursor = require("./cursorDriver.cjs");
const cursorCli = require("./cursorCliDriver.cjs");
const codebuddy = require("./codebuddyDriver.cjs");
const opencode = require("./opencodeDriver.cjs");
const grok = require("./grokDriver.cjs");
const grokAcp = require("./grokAcpDriver.cjs");
const mimo = require("./mimoDriver.cjs");
const { codebuddySessionManager } = require("./codebuddySessionManager.cjs");
const getClaude = () => require("./claudeDriver.cjs");
const getCodex = () => require("./codexDriver.cjs");
const getCopilot = () => require("./copilotDriver.cjs");
const getCursor = () => require("./cursorDriver.cjs");
const getCursorCli = () => require("./cursorCliDriver.cjs");
const getCodebuddy = () => require("./codebuddyDriver.cjs");
const getOpencode = () => require("./opencodeDriver.cjs");
const getGrok = () => require("./grokDriver.cjs");
const getGrokAcp = () => require("./grokAcpDriver.cjs");
const getMimo = () => require("./mimoDriver.cjs");
const getCodebuddySessionManager = () => require("./codebuddySessionManager.cjs").codebuddySessionManager;
function hasCodebuddyQueryOnlyOptions(options) {
return Boolean(
@@ -34,6 +34,7 @@ function hasCodebuddyQueryOnlyOptions(options) {
const DRIVER_REGISTRY = {
claude: {
async runTurn(ctx) {
const claude = getClaude();
const options = claude.buildClaudeQueryOptions({
cwd: ctx.cwd,
model: ctx.model,
@@ -50,7 +51,7 @@ const DRIVER_REGISTRY = {
assertSessionValid: ctx.assertSessionValid, delegatedAgent: ctx.delegatedAgent === true });
},
async listModels(ctx) {
return claude.listClaudeModels({
return getClaude().listClaudeModels({
pathToClaudeCodeExecutable: ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
@@ -60,6 +61,7 @@ const DRIVER_REGISTRY = {
},
codex: {
async runTurn(ctx) {
const codex = getCodex();
const constructorOptions = codex.buildCodexConstructorOptions({
codexPath: ctx.binPath,
env: ctx.env,
@@ -86,6 +88,7 @@ const DRIVER_REGISTRY = {
},
copilot: {
async runTurn(ctx) {
const copilot = getCopilot();
const clientOptions = copilot.buildCopilotClientOptions({ cliPath: ctx.binPath });
const sessionOptions = copilot.buildCopilotSessionOptions({
model: ctx.model,
@@ -106,7 +109,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return copilot.listCopilotModels({
return getCopilot().listCopilotModels({
cliPath: ctx.binPath,
runtimeEnv: ctx.env,
abortController: ctx.abortController,
@@ -118,7 +121,7 @@ const DRIVER_REGISTRY = {
async runTurn(ctx) {
const authMode = ctx.cursorAuthMode === "cli-login" ? "cli-login" : "api-key";
if (authMode === "cli-login") {
return cursorCli.runCursorCliTurn({
return getCursorCli().runCursorCliTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
binPath: ctx.cursorCliBinPath || ctx.binPath,
@@ -134,6 +137,7 @@ const DRIVER_REGISTRY = {
signal: ctx.signal,
});
}
const cursor = getCursor();
const agentOptions = cursor.buildCursorAgentOptions({
apiKey: ctx.apiKey,
env: ctx.env,
@@ -154,14 +158,14 @@ const DRIVER_REGISTRY = {
},
async listModels(ctx) {
if (ctx.cursorAuthMode === "cli-login") {
return cursorCli.listCursorCliModels({
return getCursorCli().listCursorCliModels({
binPath: ctx.cursorCliBinPath || ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
signal: ctx.signal,
});
}
return cursor.listCursorModels({
return getCursor().listCursorModels({
env: ctx.env,
abortController: ctx.abortController,
signal: ctx.signal,
@@ -170,6 +174,8 @@ const DRIVER_REGISTRY = {
},
codebuddy: {
async runTurn(ctx) {
const codebuddy = getCodebuddy();
const codebuddySessionManager = getCodebuddySessionManager();
// Build the permission handler: when the CLI hits a security restriction,
// auto-confirm (auto mode) or prompt the user (confirm mode) instead of
// throwing an error.
@@ -287,7 +293,7 @@ const DRIVER_REGISTRY = {
String(ctx.binPath || ""),
"sdk",
].join("\u0000");
return codebuddySessionManager.steer({
return getCodebuddySessionManager().steer({
sessionKey,
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
@@ -295,7 +301,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return codebuddy.listCodebuddyModels({
return getCodebuddy().listCodebuddyModels({
pathToCodebuddyCode: ctx.binPath,
env: ctx.env,
abortController: ctx.abortController,
@@ -305,7 +311,7 @@ const DRIVER_REGISTRY = {
},
opencode: {
async runTurn(ctx) {
return opencode.runOpenCodeTurn({
return getOpencode().runOpenCodeTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -323,7 +329,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return opencode.listOpenCodeModels({
return getOpencode().listOpenCodeModels({
env: ctx.env,
binPath: ctx.binPath,
abortController: ctx.abortController,
@@ -345,7 +351,7 @@ const DRIVER_REGISTRY = {
// Headless cannot know if -r restored history before the prompt is sent.
// Prefer native -r without seed (common success path). Stale-id fallback
// is handled on ACP (default runtime) via historySeed + session/new.
return grok.runGrokTurn({
return getGrok().runGrokTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
binPath: ctx.binPath,
@@ -360,7 +366,7 @@ const DRIVER_REGISTRY = {
signal: ctx.signal || ctx.abortController?.signal,
});
}
return grokAcp.runGrokAcpTurn({
return getGrokAcp().runGrokAcpTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -378,6 +384,8 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
const grok = getGrok();
const grokAcp = getGrokAcp();
// Run both probes together and union the results. ACP's
// `_meta.modelState` reflects the negotiated agent session and can
// advertise a subset of the account's models (observed: only
@@ -441,7 +449,7 @@ const DRIVER_REGISTRY = {
// mimoDriver.cjs for the details.
mimo: {
async runTurn(ctx) {
return mimo.runMimoTurn({
return getMimo().runMimoTurn({
prompt: ctx.prompt,
assertSessionValid: ctx.assertSessionValid,
systemPrompt: ctx.systemPrompt,
@@ -463,7 +471,7 @@ const DRIVER_REGISTRY = {
});
},
async listModels(ctx) {
return mimo.listMimoModels({
return getMimo().listMimoModels({
env: ctx.env,
binPath: ctx.binPath,
cwd: ctx.cwd,
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more