mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-28 12:49:53 +00:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22c6672f1c | ||
|
|
c48152b15e | ||
|
|
e3310d6b00 | ||
|
|
d81ac36dbd | ||
|
|
8af37bae96 | ||
|
|
0b5143af1d | ||
|
|
29008d5d10 | ||
|
|
066241af89 | ||
|
|
0a209474d1 | ||
|
|
e85b726451 | ||
|
|
1bcf37d777 | ||
|
|
9f52799363 | ||
|
|
a0af73e458 | ||
|
|
e2b3004d4b | ||
|
|
681a200f3f | ||
|
|
3bd49c7470 | ||
|
|
55464713c3 | ||
|
|
394621ec69 |
No files matched your search
@@ -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"
|
||||
@@ -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@v2.6.2'
|
||||
'.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@v2.6.2':
|
||||
ref: 'v2.6.2'
|
||||
commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65'
|
||||
owner_id: 2242
|
||||
repo_id: 204253808
|
||||
@@ -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
@@ -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@v2.6.2
|
||||
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/
|
||||
|
||||
@@ -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`);
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -75,6 +75,8 @@
|
||||
!packages/**
|
||||
!patches/
|
||||
!patches/**
|
||||
!plugins/
|
||||
!plugins/**
|
||||
!public/
|
||||
!public/**
|
||||
!resources/
|
||||
@@ -116,6 +118,7 @@ coverage
|
||||
!/build/installer.nsh
|
||||
/electron/native/**/build
|
||||
/electron/bridges/windowsHelloHelper/build/
|
||||
/electron/preload.bundle.cjs
|
||||
/release
|
||||
/out
|
||||
/public/monaco
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { MonitorHostKeyDialog } from './components/vault/MonitorHostKeyDialog';
|
||||
import { MonitorRuntimeHost } from './application/app/MonitorRuntimeHost';
|
||||
import React, { useEffect } from 'react';
|
||||
|
||||
import { initializeFonts } from './application/state/fontStore';
|
||||
@@ -55,9 +53,7 @@ function App() {
|
||||
}, []);
|
||||
return (
|
||||
<AppLocalStateProvider>
|
||||
<MonitorRuntimeHost />
|
||||
<AppSideEffects />
|
||||
<MonitorHostKeyDialog />
|
||||
<AppShell />
|
||||
</AppLocalStateProvider>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -32,41 +32,66 @@ function loadComponent(path: string, name: string, bindings: Record<string, unkn
|
||||
}) as React.ComponentType;
|
||||
}
|
||||
|
||||
test('monitor controls update their runtime without rendering unrelated app siblings', async () => {
|
||||
test('App no longer mounts retired built-in MonitorRuntimeHost or MonitorHostKeyDialog', async () => {
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let sideEffectRenders = 0;
|
||||
let shellRenders = 0;
|
||||
const appSource = readFileSync(new URL('../../App.tsx', import.meta.url), 'utf8');
|
||||
assert.doesNotMatch(appSource, /MonitorRuntimeHost/, 'App must not mount retired MonitorRuntimeHost');
|
||||
assert.doesNotMatch(appSource, /MonitorHostKeyDialog/, 'App must not mount retired MonitorHostKeyDialog');
|
||||
|
||||
const App = loadComponent('../../App.tsx', 'App', {
|
||||
performance: { mark: () => {} },
|
||||
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
AppSideEffects: () => { sideEffectRenders += 1; return null; },
|
||||
AppShell: React.memo(() => { shellRenders += 1; return null; }),
|
||||
});
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(App)); });
|
||||
assert.equal(sideEffectRenders, 1);
|
||||
assert.equal(shellRenders, 1);
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test('MonitorRuntimeHost keeps monitor runtime updates isolated from sibling components when mounted', async () => {
|
||||
const env = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previous = env.IS_REACT_ACT_ENVIRONMENT;
|
||||
env.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
let updateMonitor: (() => void) | undefined;
|
||||
let runtimeRenders = 0;
|
||||
let sideEffectRenders = 0;
|
||||
let shellRenders = 0;
|
||||
let siblingRenders = 0;
|
||||
const useMonitorRuntime = () => {
|
||||
const [, setVersion] = useState(0);
|
||||
updateMonitor = () => setVersion((version) => version + 1);
|
||||
runtimeRenders += 1;
|
||||
};
|
||||
const MonitorRuntimeHost = loadComponent('./MonitorRuntimeHost.tsx', 'MonitorRuntimeHost', { useMonitorRuntime });
|
||||
const App = loadComponent('../../App.tsx', 'App', {
|
||||
performance: { mark: () => {} },
|
||||
useMonitorRuntime,
|
||||
MonitorRuntimeHost,
|
||||
AppLocalStateProvider: ({ children }: { children: React.ReactNode }) => children,
|
||||
AppSideEffects: () => { sideEffectRenders += 1; return null; },
|
||||
MonitorHostKeyDialog: () => null,
|
||||
AppShell: React.memo(() => { shellRenders += 1; return null; }),
|
||||
});
|
||||
const StableSibling = React.memo(() => { siblingRenders += 1; return null; });
|
||||
let renderer: ReturnType<typeof create> | undefined;
|
||||
try {
|
||||
await act(async () => { renderer = create(React.createElement(App)); });
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(MonitorRuntimeHost),
|
||||
React.createElement(StableSibling),
|
||||
),
|
||||
);
|
||||
});
|
||||
const initialRuntimeRenders = runtimeRenders;
|
||||
const initialSideEffectRenders = sideEffectRenders;
|
||||
const initialShellRenders = shellRenders;
|
||||
const initialSiblingRenders = siblingRenders;
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
await act(async () => updateMonitor!());
|
||||
}
|
||||
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must still run');
|
||||
assert.equal(sideEffectRenders - initialSideEffectRenders, 0, 'monitor-only state must not render AppSideEffects');
|
||||
assert.equal(shellRenders - initialShellRenders, 0, 'monitor controls must leave the shell stable');
|
||||
assert.equal(runtimeRenders - initialRuntimeRenders, 10, 'monitor updates must run inside MonitorRuntimeHost');
|
||||
assert.equal(siblingRenders - initialSiblingRenders, 0, 'monitor updates must not re-render siblings');
|
||||
} finally {
|
||||
await act(async () => renderer?.unmount());
|
||||
env.IS_REACT_ACT_ENVIRONMENT = previous;
|
||||
|
||||
@@ -1174,6 +1174,16 @@ Highlight the focused split pane:
|
||||
'vault.nav.notes': 'Notes',
|
||||
'vault.nav.knownHosts': 'Known Hosts',
|
||||
'vault.nav.logs': 'Logs',
|
||||
'vault.nav.customize': 'Customize sidebar',
|
||||
'vault.nav.customizeHint': 'Drag items to reorder or toggle visibility.',
|
||||
'vault.nav.hideItem': 'Hide {label}',
|
||||
'vault.nav.moveUp': 'Move up',
|
||||
'vault.nav.moveDown': 'Move down',
|
||||
'vault.nav.resetDefault': 'Reset to default',
|
||||
'vault.nav.alwaysVisible': 'Always visible',
|
||||
'vault.nav.pluginBadge': 'Plugin',
|
||||
'vault.nav.dragToReorder': 'Drag to reorder {label}',
|
||||
'vault.nav.toggleVisibility': 'Toggle {label} visibility',
|
||||
|
||||
'proxyProfiles.action.add': 'Add Proxy',
|
||||
'proxyProfiles.search.placeholder': 'Search proxies…',
|
||||
@@ -1318,6 +1328,9 @@ Highlight the focused split pane:
|
||||
"plugins.sidebar.loading": "Loading extension page…",
|
||||
"plugins.vault.loading": "Loading plugin page…",
|
||||
"plugins.interaction.title": "Plugin request",
|
||||
"plugins.interaction.openUrlTitle": "Open external link?",
|
||||
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
|
||||
"plugins.interaction.openUrlAction": "Open URL",
|
||||
"plugins.interaction.sharing": "Text you share becomes available to this plugin and its granted capabilities, including network access. Reading does not approve a new network destination.",
|
||||
"plugins.interaction.input": "Input text",
|
||||
"plugins.interaction.filter": "Filter choices",
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1174,6 +1174,16 @@ Resalta el panel dividido enfocado:
|
||||
'vault.nav.notes': 'Notas',
|
||||
'vault.nav.knownHosts': 'Hosts conocidos',
|
||||
'vault.nav.logs': 'Registros',
|
||||
'vault.nav.customize': 'Personalizar barra lateral',
|
||||
'vault.nav.customizeHint': 'Arrastra elementos para reordenar o alternar visibilidad.',
|
||||
'vault.nav.hideItem': 'Ocultar {label}',
|
||||
'vault.nav.moveUp': 'Subir',
|
||||
'vault.nav.moveDown': 'Bajar',
|
||||
'vault.nav.resetDefault': 'Restablecer a los valores predeterminados',
|
||||
'vault.nav.alwaysVisible': 'Siempre visible',
|
||||
'vault.nav.pluginBadge': 'Complemento',
|
||||
'vault.nav.dragToReorder': 'Arrastra para reordenar {label}',
|
||||
'vault.nav.toggleVisibility': 'Alternar visibilidad de {label}',
|
||||
|
||||
'proxyProfiles.action.add': 'Agregar proxy',
|
||||
'proxyProfiles.search.placeholder': 'Buscar proxies…',
|
||||
@@ -1318,6 +1328,9 @@ Resalta el panel dividido enfocado:
|
||||
"plugins.sidebar.loading": "Cargando página de extensión…",
|
||||
"plugins.vault.loading": "Cargando página del plugin…",
|
||||
"plugins.interaction.title": "Solicitud de complemento",
|
||||
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
|
||||
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
|
||||
"plugins.interaction.openUrlAction": "Abrir URL",
|
||||
"plugins.interaction.sharing": "El texto compartido estará disponible para este complemento y sus capacidades autorizadas, incluida la red. Leer no autoriza un nuevo destino de red.",
|
||||
"plugins.interaction.input": "Introducir texto",
|
||||
"plugins.interaction.filter": "Filtrar opciones",
|
||||
|
||||
@@ -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/);
|
||||
}
|
||||
});
|
||||
@@ -1087,6 +1087,16 @@ export const ruCoreMessages: Messages = {
|
||||
'vault.nav.notes': 'Заметки',
|
||||
'vault.nav.knownHosts': 'Известные хосты',
|
||||
'vault.nav.logs': 'Журналы',
|
||||
'vault.nav.customize': 'Настроить боковую панель',
|
||||
'vault.nav.customizeHint': 'Перетаскивайте элементы для сортировки или переключения видимости.',
|
||||
'vault.nav.hideItem': 'Скрыть «{label}»',
|
||||
'vault.nav.moveUp': 'Переместить выше',
|
||||
'vault.nav.moveDown': 'Переместить ниже',
|
||||
'vault.nav.resetDefault': 'Сбросить по умолчанию',
|
||||
'vault.nav.alwaysVisible': 'Всегда видно',
|
||||
'vault.nav.pluginBadge': 'Плагин',
|
||||
'vault.nav.dragToReorder': 'Перетащите, чтобы изменить порядок «{label}»',
|
||||
'vault.nav.toggleVisibility': 'Переключить видимость «{label}»',
|
||||
|
||||
'proxyProfiles.action.add': 'Добавить прокси',
|
||||
'proxyProfiles.search.placeholder': 'Поиск прокси…',
|
||||
@@ -1186,6 +1196,9 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.sidebar.loading": "Загрузка страницы расширения…",
|
||||
"plugins.vault.loading": "Загрузка страницы плагина…",
|
||||
"plugins.interaction.title": "Запрос плагина",
|
||||
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
|
||||
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
|
||||
"plugins.interaction.openUrlAction": "Открыть URL",
|
||||
"plugins.interaction.sharing": "Переданный текст доступен плагину и его разрешённым возможностям, включая сеть. Чтение не разрешает новый сетевой адрес.",
|
||||
"plugins.interaction.input": "Ввести текст",
|
||||
"plugins.interaction.filter": "Фильтр вариантов",
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -734,6 +734,16 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'vault.nav.notes': '笔记',
|
||||
'vault.nav.knownHosts': '已知主机',
|
||||
'vault.nav.logs': '日志',
|
||||
'vault.nav.customize': '自定义侧边栏',
|
||||
'vault.nav.customizeHint': '拖动项目以调整顺序,或切换显示状态。',
|
||||
'vault.nav.hideItem': '隐藏「{label}」',
|
||||
'vault.nav.moveUp': '上移',
|
||||
'vault.nav.moveDown': '下移',
|
||||
'vault.nav.resetDefault': '恢复默认',
|
||||
'vault.nav.alwaysVisible': '始终显示',
|
||||
'vault.nav.pluginBadge': '插件',
|
||||
'vault.nav.dragToReorder': '拖动以调整「{label}」的顺序',
|
||||
'vault.nav.toggleVisibility': '切换「{label}」的显示状态',
|
||||
|
||||
'proxyProfiles.action.add': '添加代理',
|
||||
'proxyProfiles.search.placeholder': '搜索代理…',
|
||||
@@ -1235,6 +1245,9 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"plugins.sidebar.loading": "正在加载扩展页面…",
|
||||
"plugins.vault.loading": "正在加载插件页面…",
|
||||
"plugins.interaction.title": "插件请求",
|
||||
"plugins.interaction.openUrlTitle": "打开外部链接?",
|
||||
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
|
||||
"plugins.interaction.openUrlAction": "打开链接",
|
||||
"plugins.interaction.sharing": "分享的文本将交给此插件及其已授权的能力(包括网络访问)。读取文本不代表批准新的网络目标。",
|
||||
"plugins.interaction.input": "输入文本",
|
||||
"plugins.interaction.filter": "筛选选项",
|
||||
|
||||
@@ -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 音频',
|
||||
|
||||
@@ -734,6 +734,16 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'vault.nav.notes': '筆記',
|
||||
'vault.nav.knownHosts': '已知主機',
|
||||
'vault.nav.logs': '日誌',
|
||||
'vault.nav.customize': '自訂側邊欄',
|
||||
'vault.nav.customizeHint': '拖曳項目以調整順序,或切換顯示狀態。',
|
||||
'vault.nav.hideItem': '隱藏「{label}」',
|
||||
'vault.nav.moveUp': '上移',
|
||||
'vault.nav.moveDown': '下移',
|
||||
'vault.nav.resetDefault': '恢復預設',
|
||||
'vault.nav.alwaysVisible': '始終顯示',
|
||||
'vault.nav.pluginBadge': '外掛',
|
||||
'vault.nav.dragToReorder': '拖曳以調整「{label}」的順序',
|
||||
'vault.nav.toggleVisibility': '切換「{label}」的顯示狀態',
|
||||
|
||||
'proxyProfiles.action.add': '新增代理',
|
||||
'proxyProfiles.search.placeholder': '搜尋代理…',
|
||||
@@ -1236,6 +1246,9 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.interaction.title": "外掛請求",
|
||||
"plugins.interaction.openUrlTitle": "開啟外部連結?",
|
||||
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
|
||||
"plugins.interaction.openUrlAction": "開啟連結",
|
||||
"plugins.interaction.sharing": "分享的文字會交給此外掛及其已授權能力(包括網路存取)。讀取文字不代表核准新的網路目的地。",
|
||||
"plugins.interaction.input": "輸入文字",
|
||||
"plugins.interaction.filter": "篩選選項",
|
||||
|
||||
@@ -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 音訊',
|
||||
|
||||
@@ -70,7 +70,11 @@ export function pruneInactiveScopedSessions(
|
||||
orphanedSessionIds: string[];
|
||||
} {
|
||||
const orphanedSessionIds = sessions
|
||||
.filter((session) => session.scope.targetId && !activeTargetIds.has(session.scope.targetId))
|
||||
.filter((session) => (
|
||||
(session.scope.type === "terminal" || session.scope.type === "workspace")
|
||||
&& session.scope.targetId
|
||||
&& !activeTargetIds.has(session.scope.targetId)
|
||||
))
|
||||
.filter((session) => !activeSessionIds.has(session.id))
|
||||
.map((session) => session.id);
|
||||
|
||||
|
||||
@@ -116,6 +116,9 @@ function isScopeKeyActive(scopeKey: string, activeTargetIds: Set<string>) {
|
||||
const separatorIndex = scopeKey.indexOf(':');
|
||||
if (separatorIndex === -1) return true;
|
||||
|
||||
const scopeType = scopeKey.slice(0, separatorIndex);
|
||||
if (scopeType === 'global') return true;
|
||||
|
||||
const targetId = scopeKey.slice(separatorIndex + 1);
|
||||
if (!targetId) return true;
|
||||
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -24,11 +24,22 @@ export class PluginHostActionResources {
|
||||
const entry = this.entries.get(id);
|
||||
if (!entry) throw new Error('Selected host is unavailable');
|
||||
const host = entry.host;
|
||||
const osValue = typeof host.os === 'string'
|
||||
? Array.from(host.os).filter((ch) => {
|
||||
const code = ch.charCodeAt(0);
|
||||
return code >= 0x20 && code !== 0x7f;
|
||||
}).join('').slice(0, 128)
|
||||
: '';
|
||||
const notesValue = typeof host.notes === 'string'
|
||||
? host.notes.split('\0').join('').slice(0, 4096)
|
||||
: '';
|
||||
return {
|
||||
resourceId: host.id, revision: entry.revision,
|
||||
label: host.label, hostname: host.hostname, username: host.username,
|
||||
...(host.port === undefined ? {} : { port: host.port }), protocol: host.protocol ?? 'ssh',
|
||||
group: host.group ?? '', tags: [...host.tags],
|
||||
...(osValue ? { os: osValue } : {}),
|
||||
...(notesValue ? { notes: notesValue } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,17 @@ type WireNode = { id: string; type: 3 | 8; data: string } | {
|
||||
};
|
||||
type WireTree = { children: WireNode[] };
|
||||
|
||||
const validatedTrees = new WeakSet<object>();
|
||||
|
||||
export function isValidatedPluginRemoteTree(tree: unknown): boolean {
|
||||
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
|
||||
}
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
let current: WireTree = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
let failed = false;
|
||||
const project = (node: unknown): WireNode => {
|
||||
const value = node as { id: string; type: number; data?: string; element?: string; attributes?: Record<string, string>; children?: unknown[] };
|
||||
@@ -27,11 +34,13 @@ export function createPluginRemoteTree() {
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
import type { Host, PortForwardingRule, Snippet } from '../../domain/models';
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from '../../domain/groupConfig';
|
||||
import { materializeHostProxyProfile } from '../../domain/proxyProfiles';
|
||||
import { resolveEffectiveTerminalProtocol } from '../../domain/terminalProtocol';
|
||||
import {
|
||||
migratePortForwardingRulesFromStorage,
|
||||
toPersistedPortForwardingRules,
|
||||
} from '../../domain/portForwardingPersistence';
|
||||
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { preparePluginHostStream } from '../../infrastructure/services/pluginHostStreamService';
|
||||
import { startPortForward, stopAndCleanupRule } from '../../infrastructure/services/portForwardingService';
|
||||
import { captureScreenSnapshot } from '../../infrastructure/scripts/screenSnapshotRegistry';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import {
|
||||
getAppSessionRuntime,
|
||||
getAppSettingsRuntime,
|
||||
type AppVaultRuntime,
|
||||
} from './appRuntimeBridge';
|
||||
import type { PluginHostActionResources } from './pluginHostActionResources';
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
};
|
||||
|
||||
function readPortForwardRules(): PortForwardingRule[] {
|
||||
const raw = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
|
||||
return migratePortForwardingRulesFromStorage(Array.isArray(raw) ? raw : []);
|
||||
}
|
||||
|
||||
function writePortForwardRules(rules: PortForwardingRule[]): void {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, toPersistedPortForwardingRules(rules));
|
||||
}
|
||||
|
||||
function summarizePortForwardRule(rule: PortForwardingRule, hosts: readonly Host[]) {
|
||||
const host = rule.hostId ? hosts.find((candidate) => candidate.id === rule.hostId) : undefined;
|
||||
return {
|
||||
id: rule.id,
|
||||
label: rule.label,
|
||||
type: rule.type,
|
||||
localPort: rule.localPort,
|
||||
bindAddress: rule.bindAddress || '127.0.0.1',
|
||||
...(rule.remoteHost ? { remoteHost: rule.remoteHost } : {}),
|
||||
...(typeof rule.remotePort === 'number' && rule.remotePort >= 1 ? { remotePort: rule.remotePort } : {}),
|
||||
...(host?.label ? { hostLabel: host.label } : {}),
|
||||
...(host?.hostname ? { hostname: host.hostname } : {}),
|
||||
status: rule.status ?? 'inactive',
|
||||
...(rule.error ? { error: rule.error.slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function summarizeSnippet(snippet: Snippet) {
|
||||
return {
|
||||
id: snippet.id,
|
||||
label: snippet.label,
|
||||
command: snippet.command,
|
||||
...(snippet.package ? { package: snippet.package } : {}),
|
||||
...(Array.isArray(snippet.tags) && snippet.tags.length > 0 ? { tags: [...snippet.tags] } : {}),
|
||||
...(snippet.shortcut ? { shortcut: snippet.shortcut } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function effectiveHost(
|
||||
host: Host,
|
||||
vault: Pick<AppVaultRuntime, 'groupConfigs' | 'proxyProfiles'>,
|
||||
): Host {
|
||||
const validProxyProfileIds = new Set(vault.proxyProfiles.map((p) => p.id));
|
||||
const defaults = host.group
|
||||
? resolveGroupDefaults(host.group, vault.groupConfigs, { validProxyProfileIds })
|
||||
: {};
|
||||
return materializeHostProxyProfile(
|
||||
applyGroupDefaults(host, defaults, { validProxyProfileIds }),
|
||||
vault.proxyProfiles,
|
||||
);
|
||||
}
|
||||
|
||||
export async function handlePluginVaultDataRequest(
|
||||
kind: string,
|
||||
payload: Record<string, unknown>,
|
||||
ctx: PluginVaultDataContext,
|
||||
): Promise<unknown> {
|
||||
const vault = ctx.getVault();
|
||||
|
||||
switch (kind) {
|
||||
case 'resolveMetadata': {
|
||||
const hostIds = Array.isArray(payload.hostIds) ? payload.hostIds : [];
|
||||
const hosts: Record<string, Record<string, unknown>> = {};
|
||||
for (const hostId of hostIds) {
|
||||
if (typeof hostId !== 'string') continue;
|
||||
const found = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!found) continue;
|
||||
const { resourceId: _resourceId, revision: _revision, ...meta } = ctx.resources.metadata(found.id);
|
||||
hosts[hostId] = meta;
|
||||
}
|
||||
return { hosts };
|
||||
}
|
||||
|
||||
case 'prepareConnection': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved SSH host no longer exists');
|
||||
const settings = getAppSettingsRuntime();
|
||||
if (!settings) throw new Error('Terminal settings unavailable');
|
||||
const connectionOptions = await preparePluginHostStream(host, vault, settings.terminalSettings);
|
||||
return { connectionOptions };
|
||||
}
|
||||
|
||||
case 'prepareProbeTarget': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const rawHost = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!rawHost) throw new Error('Saved host no longer exists');
|
||||
const host = effectiveHost(rawHost, vault);
|
||||
const defaultProtocol = resolveEffectiveTerminalProtocol(host);
|
||||
const rdpPort = host.rdpConfig?.port ?? (defaultProtocol === 'rdp' ? (host.port || 3389) : undefined);
|
||||
const vncPort = host.vncConfig?.port ?? (defaultProtocol === 'vnc' ? (host.port || 5900) : undefined);
|
||||
const isRemoteDesktopOnly = defaultProtocol === 'rdp' || defaultProtocol === 'vnc';
|
||||
return {
|
||||
hostname: host.hostname,
|
||||
...(!isRemoteDesktopOnly ? { sshPort: host.port || 22 } : {}),
|
||||
...(rdpPort ? { rdpPort } : {}),
|
||||
...(vncPort ? { vncPort } : {}),
|
||||
defaultProtocol,
|
||||
...(host.rdpConfig?.securityMode ? { rdpSecurityMode: host.rdpConfig.securityMode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
case 'listGroups': {
|
||||
const counts = new Map<string, number>();
|
||||
for (const groupPath of vault.customGroups) {
|
||||
if (groupPath) counts.set(groupPath, counts.get(groupPath) ?? 0);
|
||||
}
|
||||
for (const host of vault.hosts) {
|
||||
if (host.group) counts.set(host.group, (counts.get(host.group) ?? 0) + 1);
|
||||
}
|
||||
const groups = [...counts.entries()]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.slice(0, 1000)
|
||||
.map(([path, hostCount]) => ({ path, hostCount }));
|
||||
return { groups };
|
||||
}
|
||||
|
||||
case 'updateHostNotes': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const notes = typeof payload.notes === 'string' ? payload.notes.slice(0, 4096) : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved host no longer exists');
|
||||
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
|
||||
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, notes } : item)));
|
||||
return { updated: true };
|
||||
}
|
||||
|
||||
case 'updateHostTags': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const tags = Array.isArray(payload.tags)
|
||||
? payload.tags.filter((t): t is string => typeof t === 'string' && t.length > 0).slice(0, 128)
|
||||
: [];
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Saved host no longer exists');
|
||||
if (host.managedSourceId) throw new Error('Managed SSH config hosts cannot be edited directly');
|
||||
vault.updateHosts((prev) => prev.map((item) => (item.id === hostId ? { ...item, tags } : item)));
|
||||
return { updated: true };
|
||||
}
|
||||
|
||||
case 'portForward.list': {
|
||||
const rules = readPortForwardRules().slice(0, 500);
|
||||
return { rules: rules.map((rule) => summarizePortForwardRule(rule, vault.hosts)) };
|
||||
}
|
||||
|
||||
case 'portForward.create': {
|
||||
const hostId = typeof payload.hostId === 'string' ? payload.hostId : '';
|
||||
const host = vault.hosts.find((candidate) => candidate.id === hostId);
|
||||
if (!host) throw new Error('Bound host no longer exists');
|
||||
const rule: PortForwardingRule = {
|
||||
id: crypto.randomUUID(),
|
||||
label: String(payload.label ?? '').slice(0, 256),
|
||||
type: (payload.type === 'remote' || payload.type === 'dynamic' ? payload.type : 'local'),
|
||||
localPort: Number(payload.localPort),
|
||||
bindAddress: typeof payload.bindAddress === 'string' && payload.bindAddress ? payload.bindAddress : '127.0.0.1',
|
||||
...(typeof payload.remoteHost === 'string' ? { remoteHost: payload.remoteHost } : {}),
|
||||
...(typeof payload.remotePort === 'number' ? { remotePort: payload.remotePort } : {}),
|
||||
hostId: host.id,
|
||||
status: 'inactive',
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const existing = readPortForwardRules();
|
||||
writePortForwardRules([...existing, rule]);
|
||||
return { ok: true, rule: summarizePortForwardRule(rule, vault.hosts) };
|
||||
}
|
||||
|
||||
case 'portForward.start': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
const rawHost = rule.hostId ? vault.hosts.find((h) => h.id === rule.hostId) : undefined;
|
||||
if (!rawHost) return { ok: false, error: 'Target host for port forwarding rule not found' };
|
||||
const settings = getAppSettingsRuntime();
|
||||
const resolvedHost = effectiveHost(rawHost, vault);
|
||||
const resolvedHosts = vault.hosts.map((h) => effectiveHost(h, vault));
|
||||
const res = await startPortForward(
|
||||
rule,
|
||||
resolvedHost,
|
||||
resolvedHosts,
|
||||
vault.keys,
|
||||
vault.identities,
|
||||
(status, error) => {
|
||||
const latest = readPortForwardRules();
|
||||
writePortForwardRules(latest.map((item) => (item.id === ruleId ? { ...item, status, error } : item)));
|
||||
},
|
||||
false,
|
||||
settings?.terminalSettings,
|
||||
vault.knownHosts,
|
||||
);
|
||||
const updated = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
return {
|
||||
ok: Boolean(res.success),
|
||||
rule: summarizePortForwardRule(updated, vault.hosts),
|
||||
...(res.error ? { error: String(res.error).slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
case 'portForward.stop': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
await stopAndCleanupRule(ruleId);
|
||||
const latestRules = readPortForwardRules();
|
||||
const nextRules = latestRules.map((item) => (item.id === ruleId ? { ...item, status: 'inactive' as const, error: undefined } : item));
|
||||
writePortForwardRules(nextRules);
|
||||
const updated = nextRules.find((item) => item.id === ruleId) ?? rule;
|
||||
return { ok: true, rule: summarizePortForwardRule(updated, vault.hosts) };
|
||||
}
|
||||
|
||||
case 'portForward.delete': {
|
||||
const ruleId = typeof payload.ruleId === 'string' ? payload.ruleId : '';
|
||||
const rules = readPortForwardRules();
|
||||
if (!rules.some((item) => item.id === ruleId)) {
|
||||
return { ok: false, error: 'Port forwarding rule not found' };
|
||||
}
|
||||
await stopAndCleanupRule(ruleId).catch(() => {});
|
||||
const latestRules = readPortForwardRules();
|
||||
writePortForwardRules(latestRules.filter((item) => item.id !== ruleId));
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
case 'snippets.list': {
|
||||
const query = typeof payload.query === 'string' ? payload.query.trim().toLowerCase() : '';
|
||||
const tag = typeof payload.tag === 'string' ? payload.tag : '';
|
||||
const pkg = typeof payload.package === 'string' ? payload.package : '';
|
||||
const filtered = vault.snippets.filter((snippet) => {
|
||||
if (pkg && snippet.package !== pkg) return false;
|
||||
if (tag && !(snippet.tags ?? []).includes(tag)) return false;
|
||||
if (query) {
|
||||
const hay = `${snippet.label} ${snippet.command} ${(snippet.tags ?? []).join(' ')}`.toLowerCase();
|
||||
if (!hay.includes(query)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return { snippets: filtered.slice(0, 1000).map(summarizeSnippet) };
|
||||
}
|
||||
|
||||
case 'snippets.get': {
|
||||
const id = typeof payload.id === 'string' ? payload.id : '';
|
||||
const found = vault.snippets.find((item) => item.id === id);
|
||||
return found ? { found: true, snippet: summarizeSnippet(found) } : { found: false };
|
||||
}
|
||||
|
||||
case 'snippets.save': {
|
||||
const id = typeof payload.id === 'string' && payload.id ? payload.id : crypto.randomUUID();
|
||||
const existing = vault.snippets.find((item) => item.id === id);
|
||||
const nextSnippet: Snippet = {
|
||||
...(existing ?? {}),
|
||||
id,
|
||||
label: String(payload.label ?? '').slice(0, 256),
|
||||
command: String(payload.command ?? '').slice(0, 65536),
|
||||
...(typeof payload.package === 'string' ? { package: payload.package } : {}),
|
||||
...(Array.isArray(payload.tags) ? { tags: payload.tags.filter((t): t is string => typeof t === 'string') } : {}),
|
||||
...(typeof payload.shortcut === 'string' ? { shortcut: payload.shortcut } : {}),
|
||||
};
|
||||
const nextList = existing
|
||||
? vault.snippets.map((item) => (item.id === id ? nextSnippet : item))
|
||||
: [...vault.snippets, nextSnippet];
|
||||
vault.updateSnippets(nextList);
|
||||
return { snippet: summarizeSnippet(nextSnippet) };
|
||||
}
|
||||
|
||||
case 'snippets.delete': {
|
||||
const id = typeof payload.id === 'string' ? payload.id : '';
|
||||
const exists = vault.snippets.some((item) => item.id === id);
|
||||
if (exists) {
|
||||
vault.updateSnippets(vault.snippets.filter((item) => item.id !== id));
|
||||
}
|
||||
return { deleted: exists };
|
||||
}
|
||||
|
||||
case 'terminals.listSessions': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeId = activeTabStore.getActiveTabId();
|
||||
const sessions = (sessionRuntime?.sessions ?? []).slice(0, 200).map((session) => ({
|
||||
sessionId: session.id,
|
||||
label: session.hostLabel || session.hostname || session.id,
|
||||
hostname: session.hostname || '',
|
||||
...(session.username ? { username: session.username } : {}),
|
||||
protocol: session.protocol || 'ssh',
|
||||
status: session.status || 'connecting',
|
||||
...(session.workspaceId ? { workspaceId: session.workspaceId } : {}),
|
||||
active: session.id === activeId || (Boolean(session.workspaceId) && session.workspaceId === activeId),
|
||||
}));
|
||||
return { sessions };
|
||||
}
|
||||
|
||||
case 'terminals.readScreen': {
|
||||
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
|
||||
const maxRows = typeof payload.maxRows === 'number' ? Math.max(1, Math.min(300, payload.maxRows)) : 80;
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
|
||||
throw new Error('Terminal session not found');
|
||||
}
|
||||
const snapshot = captureScreenSnapshot(sessionId);
|
||||
const lines = (snapshot.lines ?? []).slice(-maxRows);
|
||||
return {
|
||||
sessionId,
|
||||
rows: snapshot.rows ?? lines.length,
|
||||
cols: snapshot.cols ?? 80,
|
||||
lines,
|
||||
};
|
||||
}
|
||||
|
||||
case 'terminals.sendInput': {
|
||||
const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : '';
|
||||
const data = typeof payload.data === 'string' ? payload.data : '';
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.sessions.some((s) => s.id === sessionId)) {
|
||||
throw new Error('Terminal session not found');
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.writeToSession) throw new Error('Terminal input bridge is unavailable');
|
||||
bridge.writeToSession(sessionId, data);
|
||||
return { sent: true };
|
||||
}
|
||||
|
||||
case 'terminals.openLocal': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
if (!sessionRuntime?.createLocalTerminal) throw new Error('Local terminal is unavailable');
|
||||
const sessionId = sessionRuntime.createLocalTerminal();
|
||||
return { opened: true, ...(typeof sessionId === 'string' ? { sessionId } : {}) };
|
||||
}
|
||||
|
||||
case 'workspace.listTabs': {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const tabs: Array<{ id: string; kind: 'vault' | 'sftp' | 'session' | 'workspace' | 'log'; title: string; active: boolean }> = [
|
||||
{ id: 'vault', kind: 'vault', title: 'Vault', active: activeTabId === 'vault' },
|
||||
{ id: 'sftp', kind: 'sftp', title: 'SFTP', active: activeTabId === 'sftp' },
|
||||
];
|
||||
for (const workspace of sessionRuntime?.workspaces ?? []) {
|
||||
tabs.push({ id: workspace.id, kind: 'workspace', title: workspace.title || 'Workspace', active: activeTabId === workspace.id });
|
||||
}
|
||||
for (const session of sessionRuntime?.sessions ?? []) {
|
||||
if (session.workspaceId) continue;
|
||||
tabs.push({ id: session.id, kind: 'session', title: session.hostLabel || session.hostname || 'Terminal', active: activeTabId === session.id });
|
||||
}
|
||||
for (const logView of sessionRuntime?.logViews ?? []) {
|
||||
tabs.push({ id: logView.id, kind: 'log', title: logView.title || 'Log', active: activeTabId === logView.id });
|
||||
}
|
||||
return { activeTabId, tabs: tabs.slice(0, 200) };
|
||||
}
|
||||
|
||||
case 'workspace.focusTab': {
|
||||
const tabId = typeof payload.tabId === 'string' ? payload.tabId : '';
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const known = new Set<string>(['vault', 'sftp']);
|
||||
for (const workspace of sessionRuntime?.workspaces ?? []) known.add(workspace.id);
|
||||
for (const session of sessionRuntime?.sessions ?? []) {
|
||||
if (!session.workspaceId) known.add(session.id);
|
||||
}
|
||||
for (const logView of sessionRuntime?.logViews ?? []) known.add(logView.id);
|
||||
let resolvedTabId = known.has(tabId) ? tabId : null;
|
||||
if (!resolvedTabId) {
|
||||
const memberSession = (sessionRuntime?.sessions ?? []).find((s) => s.id === tabId && s.workspaceId);
|
||||
if (memberSession?.workspaceId && known.has(memberSession.workspaceId)) {
|
||||
resolvedTabId = memberSession.workspaceId;
|
||||
}
|
||||
}
|
||||
if (!resolvedTabId) return { focused: false };
|
||||
if (sessionRuntime?.setActiveTabId) sessionRuntime.setActiveTabId(resolvedTabId);
|
||||
else activeTabStore.setActiveTabId(resolvedTabId);
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
}
|
||||
@@ -39,3 +39,24 @@ test('idle instances are evicted while active instances are never silently repla
|
||||
assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release();
|
||||
const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose();
|
||||
});
|
||||
test('cssUnchanged updates retain previously validated stylesheet and peek returns live session synchronously', () => {
|
||||
const f = fixture(); const store = new PluginViewSessions();
|
||||
assert.equal(store.peek('view'), null);
|
||||
const view = store.acquire('view', f.bridge, request); const id = f.opened[0].instanceId;
|
||||
assert.equal(store.peek('view'), view);
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.a{display:flex}', mutations: [] });
|
||||
assert.equal(view.getSnapshot().css, '.a{display:flex}');
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, css: '', cssUnchanged: true, mutations: [[0, '~', { id: 't', type: 3, data: 'hi' }, 0]] } as Update);
|
||||
assert.equal(view.getSnapshot().css, '.a{display:flex}');
|
||||
assert.deepEqual(view.getSnapshot().tree.children[0], { id: 't', type: 3, data: 'hi' });
|
||||
store.dispose();
|
||||
});
|
||||
test('empty first update holds loading briefly to prevent blank-frame flash then completes cleanly', async () => {
|
||||
const f = fixture(); const store = new PluginViewSessions();
|
||||
const view = store.acquire('empty-grace', f.bridge, request); const id = f.opened[0].instanceId;
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '', mutations: [] });
|
||||
assert.equal(view.getSnapshot().loading, true, 'empty first update holds loading briefly');
|
||||
await new Promise((resolve) => setTimeout(resolve, 90));
|
||||
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
|
||||
store.dispose();
|
||||
});
|
||||
@@ -6,6 +6,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
|
||||
|
||||
function hasRenderableTreeContent(tree: PluginViewSnapshot['tree']): boolean {
|
||||
for (const child of tree.children) {
|
||||
if (child.type === 3 && child.data.trim().length > 0) return true;
|
||||
if (child.type === 1) {
|
||||
if (child.element !== 'div' || child.children.length > 0) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Owns a window's bounded, retained UI instances independently of React mounts. */
|
||||
export class PluginViewSessions {
|
||||
@@ -15,13 +26,15 @@ export class PluginViewSessions {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let lastRawCss: string | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
const publish = (next: PluginViewSnapshot) => { state = next; for (const listener of listeners) listener(); };
|
||||
const cleanup: Array<() => void> = [];
|
||||
const dispose = (failed = false) => {
|
||||
if (disposed) return;
|
||||
disposed = true; clearTimeout(timer); cleanup.forEach((stop) => stop());
|
||||
disposed = true; clearTimeout(timer); clearTimeout(emptyFrameTimer); cleanup.forEach((stop) => stop());
|
||||
this.sessions.delete(key);
|
||||
publish({ ...empty(), loading: false, error: failed });
|
||||
void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
@@ -31,7 +44,30 @@ export class PluginViewSessions {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId });
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
const nextTree = tree.apply(update.mutations);
|
||||
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
|
||||
if (state.loading && !hasRenderableTreeContent(nextTree)) {
|
||||
// Hold the host loading surface briefly while an older SDK flushes its
|
||||
// initial React commit so users never see an empty blank frame flash.
|
||||
publish({ tree: nextTree, css: nextCss, loading: true, error: false, settled });
|
||||
if (emptyFrameTimer === undefined) {
|
||||
emptyFrameTimer = setTimeout(() => {
|
||||
emptyFrameTimer = undefined;
|
||||
if (!disposed && state.loading) publish({ ...state, loading: false });
|
||||
}, EMPTY_FIRST_FRAME_GRACE_MS);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (emptyFrameTimer !== undefined) {
|
||||
clearTimeout(emptyFrameTimer);
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch { dispose(true); }
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
@@ -69,6 +105,9 @@ export class PluginViewSessions {
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
peek(key: string) {
|
||||
return this.sessions.get(key) ?? null;
|
||||
}
|
||||
acquire(key: string, bridge: Bridge, request: Omit<import('@netcatty/plugin-contract').HostDrawnViewOpenRequest, 'instanceId'>) {
|
||||
let session = this.sessions.get(key);
|
||||
if (!session) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
type CloseablePluginViewSessions = {
|
||||
closeView(viewId: string): void;
|
||||
};
|
||||
@@ -16,3 +18,7 @@ export function registerLoadedPluginViewSessions(sessions: CloseablePluginViewSe
|
||||
export function closePluginViewSessionIfLoaded(viewId: string): void {
|
||||
loadedSessions?.closeView(viewId);
|
||||
}
|
||||
|
||||
export function prewarmHostDrawnPluginView(viewId: string): void {
|
||||
void netcattyBridge.get()?.prewarmHostDrawnPluginView?.(viewId)?.catch?.(() => {});
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -109,7 +109,8 @@ export interface UseAIChatStreamingReturn {
|
||||
export interface SendToCattyContext {
|
||||
activeProvider: ProviderConfig | undefined;
|
||||
activeModelId: string;
|
||||
scopeType: 'terminal' | 'workspace';
|
||||
reasoningEffort?: string;
|
||||
scopeType: 'terminal' | 'workspace' | 'global';
|
||||
scopeTargetId?: string;
|
||||
scopeLabel?: string;
|
||||
globalPermissionMode: AIPermissionMode;
|
||||
@@ -125,6 +126,7 @@ export interface SendToCattyContext {
|
||||
selectedUserSkillSlugs?: string[];
|
||||
permissionMode?: AIPermissionMode;
|
||||
forceCompaction?: boolean;
|
||||
pluginContext?: import('../../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
|
||||
}
|
||||
|
||||
export interface SendToExternalContext {
|
||||
|
||||
@@ -11,21 +11,33 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
}) {
|
||||
const contextKey = JSON.stringify(context);
|
||||
const key = JSON.stringify([viewId, version, slot, contextKey]);
|
||||
const scopeId = typeof window !== 'undefined'
|
||||
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
|
||||
: '';
|
||||
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
|
||||
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const [state, setState] = useState<{
|
||||
key: string;
|
||||
snapshot: PluginViewSnapshot;
|
||||
image?: (path: string) => Promise<string>;
|
||||
}>({ key: '', snapshot: initial() });
|
||||
}>(() => (
|
||||
cachedSession
|
||||
? { key, snapshot: cachedSession.getSnapshot(), image: cachedSession.image }
|
||||
: { key: '', snapshot: initial() }
|
||||
));
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
|
||||
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
if (!active) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge) { unavailableRef.current(); return; }
|
||||
const scopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([scopeId, key]), bridge, { viewId, scopeId, context: JSON.parse(contextKey) });
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
@@ -37,11 +49,19 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const loadImage = active && state.key === key && state.image ? state.image : fallbackLoadImage;
|
||||
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
? cachedSession.getSnapshot()
|
||||
: initial();
|
||||
const loadImage = hasCurrentState && state.image
|
||||
? state.image
|
||||
: (cachedSession?.image ?? fallbackLoadImage);
|
||||
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
|
||||
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
|
||||
}, [active, key]);
|
||||
// A newly selected plugin must never receive values from the previous tree,
|
||||
// even during the render before effect cleanup and the next activation.
|
||||
return { ...(state.key === key ? state.snapshot : initial()), visible: active && !hidden, loadImage, sendEvent };
|
||||
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import type {
|
||||
PluginAISidebarContextSnapshot,
|
||||
PluginAISidebarToolSpec,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../../infrastructure/ai/pluginAiSidebarTypes';
|
||||
|
||||
const WIDTH_STORAGE_KEY = 'netcatty:plugin-ai-sidebar-width';
|
||||
export const DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH = 400;
|
||||
export const MIN_PLUGIN_AI_SIDEBAR_WIDTH = 320;
|
||||
export const MAX_PLUGIN_AI_SIDEBAR_WIDTH = 680;
|
||||
|
||||
export function readPluginAiSidebarWidth(): number {
|
||||
const parsed = localStorageAdapter.readNumber(WIDTH_STORAGE_KEY);
|
||||
if (
|
||||
typeof parsed === 'number'
|
||||
&& Number.isFinite(parsed)
|
||||
&& parsed >= MIN_PLUGIN_AI_SIDEBAR_WIDTH
|
||||
&& parsed <= MAX_PLUGIN_AI_SIDEBAR_WIDTH
|
||||
) {
|
||||
return Math.round(parsed);
|
||||
}
|
||||
return DEFAULT_PLUGIN_AI_SIDEBAR_WIDTH;
|
||||
}
|
||||
|
||||
export function writePluginAiSidebarWidth(width: number): void {
|
||||
const clamped = Math.max(
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
Math.min(MAX_PLUGIN_AI_SIDEBAR_WIDTH, Math.round(width)),
|
||||
);
|
||||
localStorageAdapter.writeNumber(WIDTH_STORAGE_KEY, clamped);
|
||||
}
|
||||
|
||||
const EMPTY_STATE: NetcattyPluginAiSidebarState = Object.freeze({
|
||||
contexts: Object.freeze([]),
|
||||
tools: Object.freeze([]),
|
||||
});
|
||||
|
||||
export interface PendingPluginSidebarPrompt {
|
||||
readonly id: number;
|
||||
readonly prompt: string;
|
||||
readonly autoSend?: boolean;
|
||||
}
|
||||
|
||||
let nextPromptSeq = 1;
|
||||
|
||||
export function usePluginAiSidebarForView(options: {
|
||||
pluginId: string;
|
||||
pluginName: string;
|
||||
viewId: string;
|
||||
enabled?: boolean;
|
||||
onCommand?: (command: NetcattyPluginAiSidebarCommand) => void;
|
||||
}) {
|
||||
const { pluginId, pluginName, viewId, enabled = true, onCommand } = options;
|
||||
const [state, setState] = useState<NetcattyPluginAiSidebarState>(EMPTY_STATE);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setState(EMPTY_STATE);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.getPluginAiSidebarState && !bridge?.onPluginAiSidebarStateChanged) {
|
||||
setState(EMPTY_STATE);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
let receivedPush = false;
|
||||
const unsubscribeState = bridge.onPluginAiSidebarStateChanged?.((next) => {
|
||||
if (!active) return;
|
||||
receivedPush = true;
|
||||
setState(next ?? EMPTY_STATE);
|
||||
});
|
||||
void bridge.getPluginAiSidebarState?.().then((next) => {
|
||||
if (!active || receivedPush) return;
|
||||
setState(next ?? EMPTY_STATE);
|
||||
}).catch(() => {
|
||||
if (!active || receivedPush) return;
|
||||
setState(EMPTY_STATE);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribeState?.();
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !onCommand) return;
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.onPluginAiSidebarCommand) return;
|
||||
return bridge.onPluginAiSidebarCommand((command) => {
|
||||
if (!command || command.pluginId !== pluginId) return;
|
||||
if (command.viewId && command.viewId !== viewId) return;
|
||||
onCommand(command);
|
||||
});
|
||||
}, [enabled, onCommand, pluginId, viewId]);
|
||||
|
||||
const contextSnapshot: PluginAISidebarContextSnapshot | null = useMemo(() => {
|
||||
const match = state.contexts.find(
|
||||
(entry) => entry.pluginId === pluginId && entry.viewId === viewId,
|
||||
);
|
||||
return match ?? null;
|
||||
}, [pluginId, state.contexts, viewId]);
|
||||
|
||||
const tools: readonly PluginAISidebarToolSpec[] = useMemo(() => (
|
||||
state.tools.filter(
|
||||
(tool) => tool.pluginId === pluginId && (!tool.viewId || tool.viewId === viewId),
|
||||
)
|
||||
), [pluginId, state.tools, viewId]);
|
||||
|
||||
const turnContext: PluginAISidebarTurnContext | null = useMemo(() => {
|
||||
if (!contextSnapshot && tools.length === 0) return null;
|
||||
return {
|
||||
pluginId,
|
||||
pluginName: contextSnapshot?.pluginName || pluginName,
|
||||
viewId,
|
||||
...(contextSnapshot?.title ? { title: contextSnapshot.title } : {}),
|
||||
...(contextSnapshot?.subtitle ? { subtitle: contextSnapshot.subtitle } : {}),
|
||||
...(contextSnapshot?.summary ? { summary: contextSnapshot.summary } : {}),
|
||||
tools,
|
||||
};
|
||||
}, [contextSnapshot, pluginId, pluginName, tools, viewId]);
|
||||
|
||||
const suggestedPrompts = contextSnapshot?.suggestedPrompts;
|
||||
|
||||
const createPendingPrompt = useCallback(
|
||||
(prompt: string, autoSend?: boolean): PendingPluginSidebarPrompt => ({
|
||||
id: nextPromptSeq++,
|
||||
prompt,
|
||||
autoSend,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return {
|
||||
contextSnapshot,
|
||||
tools,
|
||||
turnContext,
|
||||
suggestedPrompts,
|
||||
createPendingPrompt,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { getAppHandlers } from '../app/appHandlersBridge';
|
||||
import { getAppAppLockRuntime, getAppVaultRuntime, getAppSettingsRuntime } from './appRuntimeBridge';
|
||||
import { PluginHostActionResources } from './pluginHostActionResources';
|
||||
import { executePluginHostAction, type PluginHostAction } from './pluginHostActionExecution';
|
||||
import { handlePluginVaultDataRequest } from './pluginVaultDataHandlers';
|
||||
import { requestOpenDualPaneSftp } from './sftp/sftpDualPaneOpenStore';
|
||||
import { pluginHostRunsSavedScripts, type PluginHostDraftFields } from '../../domain/pluginHostActions';
|
||||
import type { Host, GroupConfig, ManagedSource, Snippet } from '../../domain/models';
|
||||
|
||||
@@ -120,6 +122,27 @@ export function usePluginHostActions() {
|
||||
});
|
||||
return;
|
||||
}
|
||||
const openHostSession = (host: Host) => {
|
||||
const mode = request.kind === 'vault.requestConnect' ? (request.mode ?? 'terminal') : 'terminal';
|
||||
if (mode === 'sftp') {
|
||||
requestOpenDualPaneSftp(host.id);
|
||||
return;
|
||||
}
|
||||
const connect = getAppHandlers()?.handleConnectToHost;
|
||||
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
|
||||
return connect(host);
|
||||
};
|
||||
if (request.kind === 'vault.requestConnect' && entry.prompt.durableHostId && entry.host) {
|
||||
assertCurrent(entry);
|
||||
const receipt = await bridge.respondPluginInteraction!({ requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' });
|
||||
if (!receipt || typeof receipt !== 'object' || !receipt.completionToken) throw new Error('Host action was revoked');
|
||||
entry.completionToken = receipt.completionToken;
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
await openHostSession(entry.host);
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
return;
|
||||
}
|
||||
let action: PluginHostAction;
|
||||
if (request.kind === 'vault.requestConnect' && target) action = { kind: 'connect', target };
|
||||
else if (request.kind === 'vault.requestHostDraft' && entry.prompt.reviewedDraft) {
|
||||
@@ -136,11 +159,7 @@ export function usePluginHostActions() {
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
},
|
||||
connect: (host) => {
|
||||
const connect = getAppHandlers()?.handleConnectToHost;
|
||||
if (typeof connect !== 'function') throw new Error('Host connection flow unavailable');
|
||||
return connect(host);
|
||||
},
|
||||
connect: openHostSession,
|
||||
});
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
} catch { await fail(entry); }
|
||||
@@ -191,7 +210,12 @@ export function usePluginHostActions() {
|
||||
}
|
||||
const vault = getVault();
|
||||
const candidates = [...vault.hosts];
|
||||
const host = prompt.vaultTarget ? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision) : undefined;
|
||||
const host = prompt.durableHostId
|
||||
? vault.hosts.find((candidate) => candidate.id === prompt.durableHostId)
|
||||
: prompt.vaultTarget
|
||||
? resources.current.resolve(prompt.vaultTarget.resourceId, prompt.vaultTarget.revision)
|
||||
: undefined;
|
||||
if (prompt.durableHostId && !host) throw new Error('Saved SSH host no longer exists');
|
||||
const entry: Review = {
|
||||
prompt, candidates, candidateRevisions: new Map(candidates.map((candidate) => [candidate.id, resources.current.metadata(candidate.id).revision])),
|
||||
customGroups: vault.customGroups, host, groups: vault.groupConfigs, snippets: vault.snippets,
|
||||
@@ -220,6 +244,39 @@ export function usePluginHostActions() {
|
||||
};
|
||||
}, [execute, fail, getVault]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.onPluginVaultDataRequest || !bridge.respondPluginVaultData || !bridge.setPluginVaultDataReady) return;
|
||||
const unsubscribe = bridge.onPluginVaultDataRequest((request) => {
|
||||
void (async () => {
|
||||
try {
|
||||
const data = await handlePluginVaultDataRequest(request.kind, request.payload ?? {}, {
|
||||
getVault,
|
||||
resources: resources.current,
|
||||
});
|
||||
await bridge.respondPluginVaultData!({
|
||||
requestId: request.requestId,
|
||||
actionToken: request.actionToken,
|
||||
ok: true,
|
||||
data,
|
||||
});
|
||||
} catch (err) {
|
||||
await bridge.respondPluginVaultData!({
|
||||
requestId: request.requestId,
|
||||
actionToken: request.actionToken,
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : 'Vault data request failed',
|
||||
}).catch(() => {});
|
||||
}
|
||||
})();
|
||||
});
|
||||
void bridge.setPluginVaultDataReady(true).catch(() => {});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
void bridge.setPluginVaultDataReady?.(false).catch(() => {});
|
||||
};
|
||||
}, [getVault]);
|
||||
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
|
||||
const entry = current.current;
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
const EMPTY_BADGES: ReadonlyMap<string, NetcattyPluginViewBadge> = new Map();
|
||||
|
||||
function buildBadgeMap(
|
||||
badges: ReadonlyArray<NetcattyPluginViewBadge> | null | undefined,
|
||||
): ReadonlyMap<string, NetcattyPluginViewBadge> {
|
||||
if (!Array.isArray(badges) || badges.length === 0) return EMPTY_BADGES;
|
||||
const map = new Map<string, NetcattyPluginViewBadge>();
|
||||
for (const badge of badges) {
|
||||
if (badge && typeof badge.viewId === 'string' && badge.viewId.length > 0) {
|
||||
map.set(badge.viewId, badge);
|
||||
}
|
||||
}
|
||||
return map.size > 0 ? map : EMPTY_BADGES;
|
||||
}
|
||||
|
||||
export function usePluginViewBadges(enabled = true): ReadonlyMap<string, NetcattyPluginViewBadge> {
|
||||
const [badgesByViewId, setBadgesByViewId] = useState<ReadonlyMap<string, NetcattyPluginViewBadge>>(EMPTY_BADGES);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
return;
|
||||
}
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.listPluginViewBadges && !bridge?.onPluginViewBadgesChanged) {
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
let receivedPush = false;
|
||||
const unsubscribe = bridge.onPluginViewBadgesChanged?.((badges) => {
|
||||
if (!active) return;
|
||||
receivedPush = true;
|
||||
setBadgesByViewId(buildBadgeMap(badges));
|
||||
});
|
||||
void bridge.listPluginViewBadges?.().then((badges) => {
|
||||
if (!active || receivedPush) return;
|
||||
setBadgesByViewId(buildBadgeMap(badges));
|
||||
}).catch(() => {
|
||||
if (!active || receivedPush) return;
|
||||
setBadgesByViewId(EMPTY_BADGES);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe?.();
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
return badgesByViewId;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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((
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let pluginsLoading = false;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const render = async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await render();
|
||||
assert.equal(model.isCustomized, false);
|
||||
assert.ok(model.visibleIds.includes(DB_PLUGIN));
|
||||
assert.ok(model.visibleIds.includes(MONITOR_PLUGIN));
|
||||
|
||||
// Back-to-back mutations in the same act batch under StrictMode return fresh
|
||||
// synchronous configs and preserve both mutations without updater side effects.
|
||||
let afterReorder!: ReturnType<typeof model.reorder>;
|
||||
let afterHide!: ReturnType<typeof model.setVisible>;
|
||||
await act(async () => {
|
||||
afterReorder = model.reorder(MONITOR_PLUGIN, 'hosts', 'after');
|
||||
afterHide = model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(afterReorder.order[1], MONITOR_PLUGIN);
|
||||
assert.equal(afterHide.order[1], MONITOR_PLUGIN);
|
||||
assert.deepEqual(afterHide.hidden, ['logs']);
|
||||
|
||||
assert.equal(model.visibleIds[1], MONITOR_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
assert.equal(model.visibleIds.includes('logs'), false);
|
||||
assert.equal(model.isCustomized, true);
|
||||
|
||||
// Locked 'hosts' cannot be hidden.
|
||||
await act(async () => {
|
||||
model.setVisible('hosts', false);
|
||||
});
|
||||
assert.equal(model.isHidden('hosts'), false);
|
||||
|
||||
// Simulate cold start: unmount, remount with pluginsLoading = true & activePluginIds = [].
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = true;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
// Plugin preferences stay preserved in config while loading, but don't show in visibleIds yet.
|
||||
assert.equal(model.visibleIds.includes(MONITOR_PLUGIN), false);
|
||||
assert.ok(model.config.order.includes(MONITOR_PLUGIN));
|
||||
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], MONITOR_PLUGIN, 'custom slot of remaining plugin survives cold start');
|
||||
assert.equal(model.config.order.includes(DB_PLUGIN), false, 'uninstalled plugin is pruned cleanly');
|
||||
const persisted = JSON.parse(dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}');
|
||||
assert.equal(persisted.order.includes(DB_PLUGIN), false, 'pruned plugin is also removed from storage');
|
||||
assert.deepEqual(persisted.hidden, ['logs']);
|
||||
|
||||
// Reset restores defaults.
|
||||
await act(async () => {
|
||||
model.reset();
|
||||
});
|
||||
assert.equal(model.isCustomized, false);
|
||||
assert.equal(model.isHidden('logs'), false);
|
||||
assert.equal(model.visibleIds.at(-1), MONITOR_PLUGIN);
|
||||
|
||||
await act(async () => {
|
||||
coldRoot.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
areVaultNavConfigsEqual,
|
||||
canHideVaultNavItem,
|
||||
getManageableVaultNavIds,
|
||||
getVisibleVaultNavIds,
|
||||
isCustomVaultNavConfig,
|
||||
moveVaultNavItem,
|
||||
normalizeVaultNavConfig,
|
||||
reconcileVaultNavConfig,
|
||||
reorderVaultNavItems,
|
||||
resetVaultNavConfig,
|
||||
setVaultNavItemVisibility,
|
||||
toggleVaultNavItemVisibility,
|
||||
type PluginVaultNavId,
|
||||
type VaultNavConfig,
|
||||
type VaultNavDropPosition,
|
||||
type VaultNavItemId,
|
||||
} from '../../domain/vaultNavConfig';
|
||||
import { STORAGE_KEY_VAULT_NAV_CONFIG } from '../../infrastructure/config/storageKeys';
|
||||
import {
|
||||
LOCAL_STORAGE_ADAPTER_CHANGED_EVENT,
|
||||
localStorageAdapter,
|
||||
} from '../../infrastructure/persistence/localStorageAdapter';
|
||||
|
||||
export interface UseVaultNavConfigOptions {
|
||||
activePluginIds: readonly PluginVaultNavId[];
|
||||
/** Pass true while plugin contributions are still loading on cold start. */
|
||||
pluginsLoading?: boolean;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
config: VaultNavConfig;
|
||||
visibleIds: VaultNavItemId[];
|
||||
manageableIds: VaultNavItemId[];
|
||||
hiddenSet: ReadonlySet<VaultNavItemId>;
|
||||
isCustomized: boolean;
|
||||
isHidden: (id: VaultNavItemId) => boolean;
|
||||
canHide: (id: VaultNavItemId) => boolean;
|
||||
setVisible: (id: VaultNavItemId, visible: boolean) => VaultNavConfig;
|
||||
toggleVisible: (id: VaultNavItemId) => VaultNavConfig;
|
||||
reorder: (
|
||||
draggedId: VaultNavItemId,
|
||||
targetId: VaultNavItemId,
|
||||
position?: VaultNavDropPosition,
|
||||
) => VaultNavConfig;
|
||||
move: (
|
||||
id: VaultNavItemId,
|
||||
direction: 'up' | 'down',
|
||||
scopeIds?: readonly VaultNavItemId[],
|
||||
) => VaultNavConfig;
|
||||
reset: () => VaultNavConfig;
|
||||
}
|
||||
|
||||
function readStoredVaultNavConfig(
|
||||
activePluginIds: readonly PluginVaultNavId[],
|
||||
pruneMissingPlugins: boolean,
|
||||
): VaultNavConfig {
|
||||
try {
|
||||
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
|
||||
} catch {
|
||||
return resetVaultNavConfig(activePluginIds);
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredVaultNavConfig(config: VaultNavConfig): void {
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_VAULT_NAV_CONFIG, config);
|
||||
} catch {
|
||||
// Best effort; in-memory state still applies for the current session.
|
||||
}
|
||||
}
|
||||
|
||||
export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
);
|
||||
const configRef = useRef<VaultNavConfig>(config);
|
||||
configRef.current = config;
|
||||
|
||||
// Reconcile when active plugin list changes or cold-start loading finishes.
|
||||
// Kept strictly outside React state updaters so storage writes and sync events
|
||||
// never execute re-entrantly during rendering or StrictMode double-invocations.
|
||||
useEffect(() => {
|
||||
const current = configRef.current;
|
||||
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(current, reconciled)) {
|
||||
configRef.current = reconciled;
|
||||
setConfig(reconciled);
|
||||
}
|
||||
if (pruneMissingPlugins) {
|
||||
try {
|
||||
const rawStored = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
if (rawStored != null) {
|
||||
const normalizedStored = normalizeVaultNavConfig(rawStored, stablePluginIds, {
|
||||
pruneMissingPlugins: false,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(normalizedStored, reconciled)) {
|
||||
writeStoredVaultNavConfig(reconciled);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
}
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
|
||||
// Cross-window and adapter sync.
|
||||
useEffect(() => {
|
||||
const sync = (event: Event) => {
|
||||
if (event instanceof StorageEvent && event.key !== STORAGE_KEY_VAULT_NAV_CONFIG) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event instanceof CustomEvent
|
||||
&& event.detail?.key !== STORAGE_KEY_VAULT_NAV_CONFIG
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
|
||||
if (!areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
}
|
||||
};
|
||||
window.addEventListener('storage', sync);
|
||||
window.addEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
return () => {
|
||||
window.removeEventListener('storage', sync);
|
||||
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
};
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
|
||||
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
|
||||
if (areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
return configRef.current;
|
||||
}
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
writeStoredVaultNavConfig(next);
|
||||
return next;
|
||||
}, []);
|
||||
|
||||
const setVisible = useCallback(
|
||||
(id: VaultNavItemId, visible: boolean): VaultNavConfig =>
|
||||
commit(setVaultNavItemVisibility(configRef.current, id, visible, stablePluginIds)),
|
||||
[commit, stablePluginIds],
|
||||
);
|
||||
|
||||
const toggleVisible = useCallback(
|
||||
(id: VaultNavItemId): VaultNavConfig =>
|
||||
commit(toggleVaultNavItemVisibility(configRef.current, id, stablePluginIds)),
|
||||
[commit, stablePluginIds],
|
||||
);
|
||||
|
||||
const reorder = useCallback(
|
||||
(
|
||||
draggedId: VaultNavItemId,
|
||||
targetId: VaultNavItemId,
|
||||
position: VaultNavDropPosition = 'before',
|
||||
): VaultNavConfig =>
|
||||
commit(reorderVaultNavItems(configRef.current, draggedId, targetId, position)),
|
||||
[commit],
|
||||
);
|
||||
|
||||
const move = useCallback(
|
||||
(
|
||||
id: VaultNavItemId,
|
||||
direction: 'up' | 'down',
|
||||
scopeIds?: readonly VaultNavItemId[],
|
||||
): VaultNavConfig =>
|
||||
commit(moveVaultNavItem(configRef.current, id, direction, scopeIds)),
|
||||
[commit],
|
||||
);
|
||||
|
||||
const reset = useCallback((): VaultNavConfig => {
|
||||
const next = resetVaultNavConfig(stablePluginIds);
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
writeStoredVaultNavConfig(next);
|
||||
return next;
|
||||
}, [stablePluginIds]);
|
||||
|
||||
const visibleIds = useMemo(
|
||||
() => getVisibleVaultNavIds(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
const manageableIds = useMemo(
|
||||
() => getManageableVaultNavIds(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
const hiddenSet = useMemo(
|
||||
() => new Set<VaultNavItemId>(config.hidden),
|
||||
[config.hidden],
|
||||
);
|
||||
const isCustomized = useMemo(
|
||||
() => isCustomVaultNavConfig(config, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
|
||||
const isHidden = useCallback(
|
||||
(id: VaultNavItemId) => hiddenSet.has(id),
|
||||
[hiddenSet],
|
||||
);
|
||||
const canHide = useCallback(
|
||||
(id: VaultNavItemId) => canHideVaultNavItem(config, id, stablePluginIds),
|
||||
[config, stablePluginIds],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
config,
|
||||
visibleIds,
|
||||
manageableIds,
|
||||
hiddenSet,
|
||||
isCustomized,
|
||||
isHidden,
|
||||
canHide,
|
||||
setVisible,
|
||||
toggleVisible,
|
||||
reorder,
|
||||
move,
|
||||
reset,
|
||||
}),
|
||||
[
|
||||
canHide,
|
||||
config,
|
||||
hiddenSet,
|
||||
isCustomized,
|
||||
isHidden,
|
||||
manageableIds,
|
||||
move,
|
||||
reorder,
|
||||
reset,
|
||||
setVisible,
|
||||
toggleVisible,
|
||||
visibleIds,
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import React, { type Dispatch, type SetStateAction } from 'react';
|
||||
import { History, Plus, Undo2, X } from 'lucide-react';
|
||||
import React, { useState, type Dispatch, type SetStateAction } from 'react';
|
||||
import { History, Plus, Sparkles, Undo2, Wrench, X } from 'lucide-react';
|
||||
import type { AIPermissionMode, AISession, ChatMessage, DiscoveredAgent, ExternalAgentConfig, AgentModelPreset, ProviderConfig, UploadedFile } from '../infrastructure/ai/types';
|
||||
import type {
|
||||
PluginAISidebarPrompt,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../infrastructure/ai/pluginAiSidebarTypes';
|
||||
import type { Host, VaultNote } from '../types';
|
||||
import type { UserSkillOption } from './ai/userSkillsState';
|
||||
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
|
||||
@@ -135,6 +139,11 @@ interface AIChatPanelContentProps {
|
||||
parked?: boolean;
|
||||
/** Disable header transitions while send preflight is in flight. */
|
||||
sending?: boolean;
|
||||
/** Contextual plugin view metadata & registered tools injected into Catty Agent. */
|
||||
pluginContext?: PluginAISidebarTurnContext | null;
|
||||
pluginSuggestedPrompts?: readonly PluginAISidebarPrompt[];
|
||||
onClosePanel?: () => void;
|
||||
borderlessChrome?: boolean;
|
||||
}
|
||||
|
||||
export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
@@ -224,7 +233,12 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onOpenVaultSection,
|
||||
parked = false,
|
||||
sending = false,
|
||||
pluginContext = null,
|
||||
pluginSuggestedPrompts,
|
||||
onClosePanel,
|
||||
borderlessChrome = false,
|
||||
}) => {
|
||||
const [showPluginTools, setShowPluginTools] = useState(false);
|
||||
const handleContinue = React.useCallback(() => handleSend(t('ai.chat.continue')), [handleSend, t]);
|
||||
const mentionHosts = React.useMemo(
|
||||
() => terminalSessions.map((session) => ({
|
||||
@@ -269,7 +283,9 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Header')}>
|
||||
<div className={cn(
|
||||
TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS,
|
||||
'px-2 flex items-center justify-between border-b border-border/50',
|
||||
borderlessChrome
|
||||
? 'px-2.5 flex items-center justify-between'
|
||||
: 'px-2 flex items-center justify-between border-b border-border/50',
|
||||
)}>
|
||||
<AgentSelector
|
||||
currentAgentId={currentAgentId}
|
||||
@@ -334,11 +350,79 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('ai.chat.newChat')}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onClosePanel && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-6 w-6 rounded-md text-muted-foreground/62 hover:bg-white/[0.05] hover:text-foreground"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClosePanel}
|
||||
>
|
||||
<X size={13} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('common.close')}</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</React.Profiler>
|
||||
)}
|
||||
|
||||
{/* ── Borderless Plugin Context Strip ── */}
|
||||
{!parked && pluginContext && !showHistory && (
|
||||
<div
|
||||
data-section="plugin-ai-context-strip"
|
||||
className="shrink-0 px-3 pt-2 pb-1"
|
||||
>
|
||||
<div className="rounded-xl bg-muted/30 dark:bg-white/[0.035] px-2.5 py-2">
|
||||
<div className="flex items-center justify-between gap-2 min-w-0">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<Sparkles size={12} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground/90">
|
||||
{pluginContext.title || pluginContext.pluginName}
|
||||
</span>
|
||||
</div>
|
||||
{pluginContext.tools.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPluginTools((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-[10.5px] font-medium transition-colors cursor-pointer',
|
||||
showPluginTools
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Wrench size={10} />
|
||||
<span>{pluginContext.tools.length} tools</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{pluginContext.subtitle && (
|
||||
<p className="mt-0.5 truncate text-[11px] text-muted-foreground/75">
|
||||
{pluginContext.subtitle}
|
||||
</p>
|
||||
)}
|
||||
{showPluginTools && pluginContext.tools.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-1 pt-1.5 border-t border-border/20">
|
||||
{pluginContext.tools.map((tool) => (
|
||||
<span
|
||||
key={tool.qualifiedName}
|
||||
title={tool.description}
|
||||
className="inline-flex items-center gap-1 rounded-md bg-background/65 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground"
|
||||
>
|
||||
<span>{tool.name}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Main content ── */}
|
||||
{!parked && showHistory && !hideHistory ? (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.History')}>
|
||||
@@ -376,6 +460,28 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
</React.Profiler>
|
||||
)}
|
||||
|
||||
{/* Borderless Plugin Starter Prompt Chips (when chat is empty) */}
|
||||
{!parked && messages.length === 0 && pluginSuggestedPrompts && pluginSuggestedPrompts.length > 0 && (
|
||||
<div
|
||||
data-section="plugin-ai-suggested-prompts"
|
||||
className="shrink-0 px-3 pb-2"
|
||||
>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{pluginSuggestedPrompts.map((item, idx) => (
|
||||
<button
|
||||
key={`${item.label}-${idx}`}
|
||||
type="button"
|
||||
disabled={sending || isStreaming || !canSendCurrentAgent}
|
||||
onClick={() => handleSend(item.prompt)}
|
||||
className="rounded-lg bg-muted/35 dark:bg-white/[0.045] hover:bg-muted/65 dark:hover:bg-white/[0.09] px-2.5 py-1.5 text-left text-[11.5px] leading-snug text-foreground/80 hover:text-foreground transition-colors cursor-pointer disabled:pointer-events-none disabled:opacity-45"
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent sessions (Zed-style, shown when no messages) */}
|
||||
{!parked && messages.length === 0 && historySessions.length > 0 && !hideRecent && (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Recent')}>
|
||||
|
||||
@@ -346,6 +346,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onOpenVaultHost,
|
||||
onOpenVaultSnippet,
|
||||
onOpenVaultSection,
|
||||
pluginContext = null,
|
||||
pluginSuggestedPrompts,
|
||||
pendingPluginPrompt = null,
|
||||
onPendingPluginPromptConsumed,
|
||||
onClosePanel,
|
||||
borderlessChrome = false,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const scopeKey = `${scopeType}:${scopeTargetId ?? ''}`;
|
||||
@@ -622,7 +628,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
const liveTargets = new Set(liveScopeTargetIds ?? workspaceMemberTerminalIds ?? []);
|
||||
for (const workspace of workspaces) liveTargets.add(workspace.id);
|
||||
liveTargets.add(scopeTargetId);
|
||||
if (canRebindChat(session, liveTargets)) {
|
||||
if (canRebindChat(session, liveTargets) && (scopeType === 'terminal' || scopeType === 'workspace')) {
|
||||
// Same race as the manager rebind: stop any in-flight turn first so the
|
||||
// scope rewrite never happens under a live stream.
|
||||
await stopActiveTurnBeforeScopeRebind(target.sessionId, {
|
||||
@@ -1687,7 +1693,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [updateSessionTitle]);
|
||||
|
||||
const buildExecutorContextForScope = useCallback((scope: {
|
||||
type: 'terminal' | 'workspace';
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
label?: string;
|
||||
}): ExecutorContext => {
|
||||
@@ -2002,6 +2008,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
autoTitleSession,
|
||||
selectedUserSkillSlugs: selectedSkillSlugs,
|
||||
titleText,
|
||||
pluginContext,
|
||||
}, modelAttachments.length > 0 ? modelAttachments : undefined);
|
||||
}
|
||||
} finally {
|
||||
@@ -2024,6 +2031,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
clearScopeDraft, showScopeSessionView, setActiveSessionId,
|
||||
flushDraftText, currentAgentConfig, buildExternalAgentRuntimeModelTarget,
|
||||
loadSdkRuntimeModelCatalog, applySdkRuntimeModelCatalog, collectCustomModelIds,
|
||||
pluginContext,
|
||||
]);
|
||||
|
||||
const handleCompact = useCallback(async () => {
|
||||
@@ -2074,6 +2082,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
autoTitleSession: () => {},
|
||||
selectedUserSkillSlugs: [],
|
||||
forceCompaction: true,
|
||||
pluginContext,
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
@@ -2096,6 +2105,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
selectedCattyThinking,
|
||||
globalPermissionMode,
|
||||
isStreaming,
|
||||
pluginContext,
|
||||
scopeKey,
|
||||
scopeLabel,
|
||||
scopeTargetId,
|
||||
@@ -2318,7 +2328,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
&& session.scope.type === scopeType
|
||||
&& session.scope.targetId === scopeTargetId,
|
||||
);
|
||||
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope) {
|
||||
if (isAlreadyInScope || !scopeTargetId || !rebindSessionScope || scopeType === 'global') {
|
||||
handleSelectSession(sessionId);
|
||||
return;
|
||||
}
|
||||
@@ -2435,24 +2445,28 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [exportSessionsBackup, t]);
|
||||
|
||||
const globalManagerNode = useMemo(() => (
|
||||
<GlobalAIChatSessionManager
|
||||
sessions={sessions}
|
||||
activeSessionIdMap={activeSessionIdMap}
|
||||
currentScopeType={scopeType}
|
||||
currentScopeTargetId={scopeTargetId}
|
||||
currentScopeHostIds={scopeHostIds}
|
||||
workspaces={workspaces}
|
||||
terminalInfos={managerTerminalInfos}
|
||||
hosts={hosts}
|
||||
externalAgents={externalAgents}
|
||||
rebindTargets={managerRebindTargets}
|
||||
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
|
||||
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
scopeType === 'global'
|
||||
? undefined
|
||||
: (
|
||||
<GlobalAIChatSessionManager
|
||||
sessions={sessions}
|
||||
activeSessionIdMap={activeSessionIdMap}
|
||||
currentScopeType={scopeType}
|
||||
currentScopeTargetId={scopeTargetId}
|
||||
currentScopeHostIds={scopeHostIds}
|
||||
workspaces={workspaces}
|
||||
terminalInfos={managerTerminalInfos}
|
||||
hosts={hosts}
|
||||
externalAgents={externalAgents}
|
||||
rebindTargets={managerRebindTargets}
|
||||
onSelect={(sessionId) => { void handleManagerActivate(sessionId); }}
|
||||
onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined}
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
)
|
||||
), [
|
||||
sessions,
|
||||
activeSessionIdMap,
|
||||
@@ -2486,6 +2500,22 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setShowHistory(false);
|
||||
}, [ensureScopeDraft, showScopeDraftView, updateScopeDraft]);
|
||||
|
||||
const consumedPluginPromptIdRef = useRef<number | null>(null);
|
||||
useEffect(() => {
|
||||
if (!pendingPluginPrompt) return;
|
||||
if (consumedPluginPromptIdRef.current === pendingPluginPrompt.id) return;
|
||||
consumedPluginPromptIdRef.current = pendingPluginPrompt.id;
|
||||
onPendingPluginPromptConsumed?.(pendingPluginPrompt.id);
|
||||
const trimmedPrompt = pendingPluginPrompt.prompt.trim();
|
||||
if (!trimmedPrompt) return;
|
||||
setShowHistory(false);
|
||||
if (pendingPluginPrompt.autoSend && !isStreaming) {
|
||||
void handleSend(trimmedPrompt);
|
||||
} else {
|
||||
setInputValue(trimmedPrompt);
|
||||
}
|
||||
}, [handleSend, isStreaming, onPendingPluginPromptConsumed, pendingPluginPrompt, setInputValue]);
|
||||
|
||||
// Hidden retained panels keep the composer mounted (parent is `hidden` +
|
||||
// inert) so reopen does not remount ChatInput. Skip the message list.
|
||||
return (
|
||||
@@ -2609,6 +2639,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onOpenVaultHost={onOpenVaultHost}
|
||||
onOpenVaultSnippet={onOpenVaultSnippet}
|
||||
onOpenVaultSection={onOpenVaultSection}
|
||||
pluginContext={pluginContext}
|
||||
pluginSuggestedPrompts={pluginSuggestedPrompts}
|
||||
onClosePanel={onClosePanel}
|
||||
borderlessChrome={borderlessChrome}
|
||||
/>
|
||||
</div>
|
||||
</React.Profiler>
|
||||
@@ -2698,6 +2732,12 @@ export function aiChatSidePanelPropsAreEqual(
|
||||
if (prev.onOpenVaultSnippet !== next.onOpenVaultSnippet) return false;
|
||||
if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false;
|
||||
if (prev.onFocusAIScopeTarget !== next.onFocusAIScopeTarget) return false;
|
||||
if (prev.pluginContext !== next.pluginContext) return false;
|
||||
if (prev.pluginSuggestedPrompts !== next.pluginSuggestedPrompts) return false;
|
||||
if (prev.pendingPluginPrompt !== next.pendingPluginPrompt) return false;
|
||||
if (prev.onPendingPluginPromptConsumed !== next.onPendingPluginPromptConsumed) return false;
|
||||
if (prev.onClosePanel !== next.onClosePanel) return false;
|
||||
if (prev.borderlessChrome !== next.borderlessChrome) return false;
|
||||
|
||||
const scopeKey = `${prev.scopeType}:${prev.scopeTargetId ?? ''}`;
|
||||
if (
|
||||
|
||||
@@ -104,7 +104,7 @@ export interface AIChatSidePanelProps {
|
||||
quickMessages?: AIQuickMessage[];
|
||||
|
||||
// Context
|
||||
scopeType: 'terminal' | 'workspace';
|
||||
scopeType: 'terminal' | 'workspace' | 'global';
|
||||
scopeTargetId?: string;
|
||||
scopeHostIds?: string[];
|
||||
scopeLabel?: string;
|
||||
@@ -143,7 +143,7 @@ export interface AIChatSidePanelProps {
|
||||
connected: boolean;
|
||||
}>;
|
||||
resolveExecutorContext?: (scope: {
|
||||
type: 'terminal' | 'workspace';
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
label?: string;
|
||||
}) => ExecutorContext;
|
||||
@@ -151,6 +151,14 @@ export interface AIChatSidePanelProps {
|
||||
// Visibility
|
||||
isVisible?: boolean;
|
||||
|
||||
// Plugin contextual sidebar integration (native Catty Agent + plugin tools)
|
||||
pluginContext?: import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarTurnContext | null;
|
||||
pluginSuggestedPrompts?: readonly import('../infrastructure/ai/pluginAiSidebarTypes').PluginAISidebarPrompt[];
|
||||
pendingPluginPrompt?: { id: number; prompt: string; autoSend?: boolean } | null;
|
||||
onPendingPluginPromptConsumed?: (id: number) => void;
|
||||
onClosePanel?: () => void;
|
||||
borderlessChrome?: boolean;
|
||||
|
||||
// Vault artifact navigation (from AI chat tool results)
|
||||
notes?: VaultNote[];
|
||||
hosts?: Host[];
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -262,3 +262,90 @@ test('usePluginTerminalSidebar skips tab/focus subscriptions when zero pages exi
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginTerminalSidebarLauncher renders live view badges and clears them on updates', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true, url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'SVGElement', 'Node', 'NodeFilter', 'MutationObserver', 'CustomEvent', 'Event', 'MouseEvent']) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('PointerEvent', dom.window.MouseEvent);
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('requestAnimationFrame', (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0));
|
||||
install('cancelAnimationFrame', (id: number) => clearTimeout(id));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const { TooltipProvider } = await import('./ui/tooltip');
|
||||
const { PluginTerminalSidebarLauncher } = await import('./plugins/PluginTerminalSidebar');
|
||||
|
||||
const viewA = { id: 'com.example.sidebar.alerts', title: 'Alerts', location: 'terminal-sidebar', visible: true };
|
||||
const snapshot = {
|
||||
locale: 'en',
|
||||
plugins: [{ id: 'com.example.sidebar', displayName: 'Synthetic Monitor', version: '1.0.0', commands: [], keybindings: [], menus: [], settings: [], views: [viewA] }],
|
||||
};
|
||||
let badges: ReadonlyArray<NetcattyPluginViewBadge> = [
|
||||
{ pluginId: 'com.example.sidebar', viewId: viewA.id, count: 5, tone: 'danger', tooltip: '5 active alerts' },
|
||||
];
|
||||
const badgeListeners = new Set<(next: ReadonlyArray<NetcattyPluginViewBadge>) => void>();
|
||||
|
||||
Object.assign(dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return snapshot; },
|
||||
onPluginContributionsChanged() { return () => {}; },
|
||||
async listPluginViewBadges() { return badges; },
|
||||
onPluginViewBadgesChanged(cb: (next: ReadonlyArray<NetcattyPluginViewBadge>) => void) {
|
||||
badgeListeners.add(cb);
|
||||
return () => badgeListeners.delete(cb);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider delayDuration={0}>
|
||||
<PluginTerminalSidebarLauncher sessionId="session-1" />
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
await settle();
|
||||
});
|
||||
|
||||
const btn = document.querySelector<HTMLButtonElement>('button[aria-label="Alerts — Synthetic Monitor (5 active alerts)"]')!;
|
||||
assert.ok(btn, 'terminal sidebar launcher includes badge tooltip in aria-label');
|
||||
const badgeEl = btn.querySelector<HTMLElement>('[data-plugin-view-badge]')!;
|
||||
assert.equal(badgeEl.textContent, '5');
|
||||
assert.equal(badgeEl.getAttribute('data-plugin-view-badge-tone'), 'danger');
|
||||
|
||||
// Clear badge via push event
|
||||
badges = [];
|
||||
await act(async () => {
|
||||
for (const listener of badgeListeners) listener(badges);
|
||||
await settle();
|
||||
});
|
||||
assert.equal(document.querySelector('[data-plugin-view-badge]'), null);
|
||||
assert.ok(document.querySelector('button[aria-label="Alerts — Synthetic Monitor"]'));
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
await settle();
|
||||
});
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -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 });
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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],
|
||||
);
|
||||
@@ -2346,7 +2348,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
// here dismisses the panel.
|
||||
const handleToggleAiFromTopBar = useCallback(() => {
|
||||
const tabId = activeTabIdRef.current;
|
||||
if (!tabId) return;
|
||||
if (!tabId || tabId === 'vault') return;
|
||||
|
||||
const intent = resolveAiSidePanelToggleIntent(
|
||||
sidePanelOpenTabsRef.current.get(tabId) ?? null,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -1294,7 +1294,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
size="icon"
|
||||
className="h-7 w-7 shrink-0 app-no-drag top-tab-utility-btn"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('netcatty:toggle-ai-panel'))}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('netcatty:toggle-ai-panel', { cancelable: true }))}
|
||||
>
|
||||
<Sparkles size={16} />
|
||||
</Button>
|
||||
|
||||
+76
-14
@@ -16,7 +16,6 @@ import {
|
||||
Key,
|
||||
LayoutGrid,
|
||||
List,
|
||||
Monitor,
|
||||
Network,
|
||||
NotebookText,
|
||||
Pin,
|
||||
@@ -61,7 +60,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 +79,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,25 +114,18 @@ 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";
|
||||
import { useRegisterVaultHostTreeActions } from "./vault/useRegisterVaultHostTreeActions";
|
||||
import { Button } from "./ui/button";
|
||||
import { RippleButton } from "./ui/ripple";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
@@ -169,7 +159,21 @@ import { useVaultHostCollections } from "./vault/useVaultHostCollections";
|
||||
import { useVaultImportHandlers } from "../application/state/useVaultImportHandlers";
|
||||
import { useVaultGroupDragHandlers } from "./vault/useVaultGroupDragHandlers";
|
||||
import { usePluginVaultPages } from "../application/state/usePluginVaultPages";
|
||||
import { useVaultNavConfig } from "../application/state/useVaultNavConfig";
|
||||
import {
|
||||
getVisibleVaultNavIds,
|
||||
resolveFallbackVaultSection,
|
||||
type VaultNavItemId,
|
||||
} from "../domain/vaultNavConfig";
|
||||
|
||||
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"));
|
||||
@@ -179,7 +183,6 @@ const SnippetsManager = lazy(() => import("./SnippetsManager"));
|
||||
|
||||
export type VaultSection =
|
||||
| "hosts"
|
||||
| "monitor"
|
||||
| "keys"
|
||||
| "proxies"
|
||||
| "snippets"
|
||||
@@ -384,6 +387,59 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
hostsRef.current = hosts;
|
||||
const [currentSection, setCurrentSection] = useState<VaultSection>("hosts");
|
||||
const pluginVault = usePluginVaultPages({ locale, section: currentSection, select: setCurrentSection });
|
||||
const activePluginNavIds = useMemo(
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
const previousHidden = previousHiddenNavRef.current;
|
||||
previousHiddenNavRef.current = vaultNavConfig.hiddenSet;
|
||||
if (
|
||||
!previousHidden.has(currentSection)
|
||||
&& vaultNavConfig.hiddenSet.has(currentSection)
|
||||
) {
|
||||
setCurrentSection(
|
||||
resolveFallbackVaultSection(currentSection, vaultNavConfig.visibleIds),
|
||||
);
|
||||
}
|
||||
}, [currentSection, vaultNavConfig.hiddenSet, vaultNavConfig.visibleIds]);
|
||||
|
||||
const handleSelectVaultNavItem = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
setCurrentSection(id);
|
||||
if (id === "hosts") {
|
||||
setSelectedGroupPath(null);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleHideVaultNavItem = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
const next = vaultNavConfig.setVisible(id, false);
|
||||
if (currentSection === id) {
|
||||
const nextVisible = getVisibleVaultNavIds(next, activePluginNavIds);
|
||||
setCurrentSection(resolveFallbackVaultSection(currentSection, nextVisible));
|
||||
}
|
||||
},
|
||||
[activePluginNavIds, currentSection, vaultNavConfig],
|
||||
);
|
||||
|
||||
const handleToggleVaultNavItemVisible = useCallback(
|
||||
(id: VaultNavItemId) => {
|
||||
const next = vaultNavConfig.toggleVisible(id);
|
||||
if (currentSection === id && next.hidden.includes(id)) {
|
||||
const nextVisible = getVisibleVaultNavIds(next, activePluginNavIds);
|
||||
setCurrentSection(resolveFallbackVaultSection(currentSection, nextVisible));
|
||||
}
|
||||
},
|
||||
[activePluginNavIds, currentSection, vaultNavConfig],
|
||||
);
|
||||
const [search, setSearch] = useState("");
|
||||
const [selectedGroupPath, setSelectedGroupPath] = useState<string | null>(
|
||||
null,
|
||||
@@ -839,6 +895,10 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
const [{ buildVaultCsvCredentialOptions }, { exportHostsToCsvWithStats }] = await Promise.all([
|
||||
import("../application/vaultCsvExportCredentials"),
|
||||
import("../domain/vaultImport"),
|
||||
]);
|
||||
const {
|
||||
keyPathsById,
|
||||
keyPassphrasesById,
|
||||
@@ -1573,6 +1633,10 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
Copy,
|
||||
currentSection,
|
||||
pluginVault,
|
||||
vaultNavConfig,
|
||||
handleSelectVaultNavItem,
|
||||
handleHideVaultNavItem,
|
||||
handleToggleVaultNavItemVisible,
|
||||
customGroups,
|
||||
deleteGroupPath,
|
||||
deleteGroupPaths,
|
||||
@@ -1667,7 +1731,6 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
List,
|
||||
managedGroupPaths,
|
||||
managedSources,
|
||||
Monitor,
|
||||
moveGroup,
|
||||
moveHostToGroup,
|
||||
moveHostsToGroup,
|
||||
@@ -1720,7 +1783,6 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
reorderGroup,
|
||||
reorderHost,
|
||||
resetImportProgress,
|
||||
RippleButton,
|
||||
rootRef,
|
||||
sanitizeHost,
|
||||
ScreenShare,
|
||||
|
||||
@@ -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\(\)/);
|
||||
});
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ import {
|
||||
} from './toolArtifacts/toolArtifactNames';
|
||||
import { parseVaultToolArtifact } from './toolArtifacts/vaultToolArtifact';
|
||||
import { VaultArtifactToolResult } from './toolArtifacts/VaultArtifactToolResult';
|
||||
import { parsePluginToolArtifact } from './toolArtifacts/pluginToolArtifact';
|
||||
import { PluginArtifactToolResult } from './toolArtifacts/PluginArtifactToolResult';
|
||||
import type { Host, Snippet, VaultNote } from '../../types';
|
||||
import {
|
||||
onApprovalRequest,
|
||||
@@ -620,6 +622,15 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
&& displayedMessages[end].role === "assistant";
|
||||
|
||||
const renderToolResultItem = (item: typeof toolResults[number]) => {
|
||||
const pluginArtifact = parsePluginToolArtifact(item.name, item.content, item.isError);
|
||||
if (pluginArtifact) {
|
||||
return (
|
||||
<PluginArtifactToolResult
|
||||
key={item.toolCallId}
|
||||
artifact={pluginArtifact}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const artifactToolName = item.artifactToolName ?? item.name;
|
||||
const remoteDesktopArtifact = parseRemoteDesktopToolArtifact(
|
||||
artifactToolName,
|
||||
@@ -688,6 +699,31 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
);
|
||||
}
|
||||
|
||||
const pluginArtifactItems = toolResults
|
||||
.map((item) => ({ item, artifact: parsePluginToolArtifact(item.name, item.content, item.isError) }))
|
||||
.filter((entry): entry is { item: typeof toolResults[number]; artifact: NonNullable<ReturnType<typeof parsePluginToolArtifact>> } => entry.artifact !== null);
|
||||
const nonPluginItems = toolResults.filter(
|
||||
(item) => parsePluginToolArtifact(item.name, item.content, item.isError) === null,
|
||||
);
|
||||
|
||||
if (pluginArtifactItems.length > 0) {
|
||||
return (
|
||||
<div key={`tool-group-${message.id}`} className="space-y-2 py-0.5">
|
||||
{nonPluginItems.length > 0 && (
|
||||
<ToolCallGroup
|
||||
count={nonPluginItems.length}
|
||||
defaultExpanded={!hasAssistantAfter}
|
||||
>
|
||||
{nonPluginItems.map(renderToolResultItem)}
|
||||
</ToolCallGroup>
|
||||
)}
|
||||
{pluginArtifactItems.map(({ item, artifact }) => (
|
||||
<PluginArtifactToolResult key={item.toolCallId} artifact={artifact} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ToolCallGroup
|
||||
key={`tool-group-${message.id}`}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -38,7 +38,7 @@ export function resolveDisplayedPanelView(
|
||||
hasDraft: boolean,
|
||||
sessions: AISession[],
|
||||
persistedSessionId?: string | null,
|
||||
scopeType: "terminal" | "workspace" = "workspace",
|
||||
scopeType: "terminal" | "workspace" | "global" = "workspace",
|
||||
anchorChatId?: string | null,
|
||||
preferredHistorySessionId?: string | null,
|
||||
): AIPanelView {
|
||||
|
||||
@@ -6,7 +6,7 @@ const MAX_HISTORY_CACHE_ENTRIES_PER_SESSION_LIST = 64;
|
||||
const historyCache = new WeakMap<AISession[], Map<HistoryCacheKey, AISession[]>>();
|
||||
|
||||
function buildHistoryCacheKey(
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
@@ -26,7 +26,7 @@ function buildHistoryCacheKey(
|
||||
|
||||
export function getScopedHistorySessions(
|
||||
sessions: AISession[],
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
@@ -103,7 +103,7 @@ export function _getScopedHistoryCacheSizeForTests(sessions: AISession[]): numbe
|
||||
*/
|
||||
export function getPreferredAutoResumeSessionId(
|
||||
historySessions: readonly AISession[],
|
||||
scopeType: 'terminal' | 'workspace',
|
||||
scopeType: 'terminal' | 'workspace' | 'global',
|
||||
scopeTargetId: string | undefined,
|
||||
scopeHostIds: string[] | undefined,
|
||||
activeTerminalSessionIds: Set<string>,
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { AISession } from "../../infrastructure/ai/types";
|
||||
|
||||
export function getSessionScopeMatchRank(
|
||||
session: AISession,
|
||||
scopeType: "terminal" | "workspace",
|
||||
scopeType: "terminal" | "workspace" | "global",
|
||||
scopeTargetId?: string,
|
||||
scopeHostIds?: string[],
|
||||
/**
|
||||
@@ -37,6 +37,7 @@ export function getSessionScopeMatchRank(
|
||||
|
||||
if (session.scope.type !== scopeType) return 0;
|
||||
if (session.scope.targetId === scopeTargetId) return 3;
|
||||
if (scopeType === "global") return 0;
|
||||
|
||||
if (scopeType === "terminal" && activeTerminalSessionIds?.has(session.id)) {
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import { BarChart3, Check, Code2, ExternalLink, Loader2, Pin, Table2 } from 'lucide-react';
|
||||
import { cn } from '../../../lib/utils';
|
||||
import { netcattyBridge } from '../../../infrastructure/services/netcattyBridge';
|
||||
import { toast } from '../../ui/toast';
|
||||
import { PluginBiChart } from '../../plugins/primitives/PluginBiChart';
|
||||
import type {
|
||||
PluginArtifactActionSpec,
|
||||
PluginBiChartRenderedArtifact,
|
||||
PluginRenderedToolArtifact,
|
||||
PluginSqlResultRenderedArtifact,
|
||||
} from './pluginToolArtifact';
|
||||
|
||||
const MAX_PREVIEW_ROWS = 10;
|
||||
const MAX_PREVIEW_COLS = 8;
|
||||
|
||||
function formatCellValue(value: unknown): string {
|
||||
if (value === null || value === undefined) return 'NULL';
|
||||
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
||||
if (typeof value === 'number') {
|
||||
return Number.isFinite(value) ? String(value) : '—';
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return value.length > 64 ? `${value.slice(0, 61)}...` : value;
|
||||
}
|
||||
try {
|
||||
const serialized = JSON.stringify(value);
|
||||
return serialized.length > 64 ? `${serialized.slice(0, 61)}...` : serialized;
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function usePluginArtifactAction(
|
||||
pluginId: string | undefined,
|
||||
viewId: string | undefined,
|
||||
) {
|
||||
const [busyKey, setBusyKey] = useState<string | null>(null);
|
||||
const [doneKeys, setDoneKeys] = useState<Record<string, boolean>>({});
|
||||
|
||||
const runAction = useCallback(async (
|
||||
key: string,
|
||||
action: PluginArtifactActionSpec,
|
||||
successToast: string,
|
||||
) => {
|
||||
if (!pluginId) return;
|
||||
const invoke = netcattyBridge.get()?.invokePluginAiTool;
|
||||
if (typeof invoke !== 'function') {
|
||||
toast.error('Plugin action bridge is unavailable.');
|
||||
return;
|
||||
}
|
||||
setBusyKey(key);
|
||||
try {
|
||||
await invoke({
|
||||
pluginId,
|
||||
toolName: action.toolName,
|
||||
args: action.args,
|
||||
...(viewId ? { viewId } : {}),
|
||||
});
|
||||
setDoneKeys((prev) => ({ ...prev, [key]: true }));
|
||||
toast.success(successToast);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
toast.error(message || 'Action failed.');
|
||||
} finally {
|
||||
setBusyKey((prev) => (prev === key ? null : prev));
|
||||
}
|
||||
}, [pluginId, viewId]);
|
||||
|
||||
return { busyKey, doneKeys, runAction };
|
||||
}
|
||||
|
||||
const BiChartArtifactView: React.FC<{ artifact: PluginBiChartRenderedArtifact }> = ({ artifact }) => {
|
||||
const [showSql, setShowSql] = useState(false);
|
||||
const { busyKey, doneKeys, runAction } = usePluginArtifactAction(artifact.pluginId, artifact.viewId);
|
||||
const canInvoke = Boolean(artifact.pluginId);
|
||||
|
||||
const chartProps = {
|
||||
...artifact.chartSpec,
|
||||
// Render header in our quiet artifact frame instead of duplicating titles.
|
||||
title: undefined,
|
||||
subtitle: undefined,
|
||||
height: artifact.chartSpec.height ?? 215,
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-plugin-ai-artifact="bi-chart"
|
||||
className="min-w-0 rounded-xl bg-muted/30 dark:bg-white/[0.035] px-3 py-2.5 space-y-2.5"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<BarChart3 size={13} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground">
|
||||
{artifact.title || 'BI Chart'}
|
||||
</span>
|
||||
</div>
|
||||
{artifact.subtitle && (
|
||||
<p className="mt-0.5 truncate text-[11px] text-muted-foreground/75">
|
||||
{artifact.subtitle}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
{artifact.sql && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSql((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer',
|
||||
showSql
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Code2 size={11} />
|
||||
<span>SQL</span>
|
||||
</button>
|
||||
)}
|
||||
{canInvoke && artifact.openAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'open'}
|
||||
onClick={() => void runAction('open', artifact.openAction!, 'Opened in SQL Editor')}
|
||||
className="inline-flex items-center gap-1 rounded-md bg-background/60 px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-background hover:text-foreground cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{busyKey === 'open' ? <Loader2 size={11} className="animate-spin" /> : <ExternalLink size={11} />}
|
||||
<span>{artifact.openAction.label || 'Open SQL'}</span>
|
||||
</button>
|
||||
)}
|
||||
{canInvoke && artifact.pinAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'pin'}
|
||||
onClick={() => void runAction('pin', artifact.pinAction!, 'Pinned to BI Dashboard')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-50',
|
||||
doneKeys.pin
|
||||
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-primary/12 text-primary hover:bg-primary/20',
|
||||
)}
|
||||
>
|
||||
{busyKey === 'pin'
|
||||
? <Loader2 size={11} className="animate-spin" />
|
||||
: doneKeys.pin
|
||||
? <Check size={11} />
|
||||
: <Pin size={11} />}
|
||||
<span>{doneKeys.pin ? 'Pinned' : (artifact.pinAction.label || 'Pin to BI Dashboard')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Optional compact KPI strip */}
|
||||
{artifact.kpis && artifact.kpis.length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-1.5 sm:grid-cols-3">
|
||||
{artifact.kpis.map((kpi, index) => (
|
||||
<div
|
||||
key={`${kpi.label}-${index}`}
|
||||
className="min-w-0 rounded-lg bg-background/55 dark:bg-white/[0.03] px-2.5 py-1.5"
|
||||
>
|
||||
<div className="truncate text-[10px] text-muted-foreground/75">{kpi.label}</div>
|
||||
<div className="mt-0.5 flex items-baseline gap-1.5 min-w-0">
|
||||
<span className="truncate text-[13px] font-semibold tabular-nums text-foreground">
|
||||
{kpi.value}
|
||||
</span>
|
||||
{kpi.delta && (
|
||||
<span
|
||||
className={cn(
|
||||
'truncate text-[10px] font-medium tabular-nums',
|
||||
kpi.tone === 'positive'
|
||||
? 'text-emerald-600 dark:text-emerald-400'
|
||||
: kpi.tone === 'negative'
|
||||
? 'text-rose-600 dark:text-rose-400'
|
||||
: kpi.tone === 'warning'
|
||||
? 'text-amber-600 dark:text-amber-400'
|
||||
: 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{kpi.delta}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Host-rendered interactive PluginBiChart */}
|
||||
<div className="min-w-0 rounded-lg bg-background/70 dark:bg-black/20 p-1.5">
|
||||
<PluginBiChart {...chartProps} />
|
||||
</div>
|
||||
|
||||
{/* Optional collapsible SQL inspector */}
|
||||
{showSql && artifact.sql && (
|
||||
<pre className="overflow-x-auto rounded-lg bg-background/75 dark:bg-black/25 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-foreground/85 whitespace-pre-wrap break-words">
|
||||
{artifact.sql}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const SqlResultArtifactView: React.FC<{ artifact: PluginSqlResultRenderedArtifact }> = ({ artifact }) => {
|
||||
const [showSql, setShowSql] = useState(false);
|
||||
const { busyKey, doneKeys, runAction } = usePluginArtifactAction(artifact.pluginId, artifact.viewId);
|
||||
const canInvoke = Boolean(artifact.pluginId);
|
||||
|
||||
const visibleColumns = artifact.columns.slice(0, MAX_PREVIEW_COLS);
|
||||
const hiddenColumnCount = Math.max(0, artifact.columns.length - visibleColumns.length);
|
||||
const visibleRows = artifact.rows.slice(0, MAX_PREVIEW_ROWS);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-plugin-ai-artifact="sql-result"
|
||||
className="min-w-0 rounded-xl bg-muted/30 dark:bg-white/[0.035] px-3 py-2.5 space-y-2"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<Table2 size={13} className="shrink-0 text-primary/80" />
|
||||
<span className="truncate text-[12px] font-medium text-foreground">
|
||||
{artifact.title || 'Query Result'}
|
||||
</span>
|
||||
<span className="shrink-0 rounded-md bg-background/60 px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
|
||||
{artifact.rowCount} {artifact.rowCount === 1 ? 'row' : 'rows'}
|
||||
{artifact.durationMs != null ? ` · ${artifact.durationMs} ms` : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowSql((prev) => !prev)}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer',
|
||||
showSql
|
||||
? 'bg-primary/15 text-primary'
|
||||
: 'bg-background/60 text-muted-foreground hover:bg-background hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<Code2 size={11} />
|
||||
<span>SQL</span>
|
||||
</button>
|
||||
{canInvoke && artifact.openAction && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busyKey === 'open'}
|
||||
onClick={() => void runAction('open', artifact.openAction!, 'Opened in SQL Editor')}
|
||||
className={cn(
|
||||
'inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-50',
|
||||
doneKeys.open
|
||||
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-primary/12 text-primary hover:bg-primary/20',
|
||||
)}
|
||||
>
|
||||
{busyKey === 'open'
|
||||
? <Loader2 size={11} className="animate-spin" />
|
||||
: doneKeys.open
|
||||
? <Check size={11} />
|
||||
: <ExternalLink size={11} />}
|
||||
<span>{doneKeys.open ? 'Opened' : (artifact.openAction.label || 'Open in SQL Editor')}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showSql && (
|
||||
<pre className="overflow-x-auto rounded-lg bg-background/75 dark:bg-black/25 px-2.5 py-2 font-mono text-[11px] leading-relaxed text-foreground/85 whitespace-pre-wrap break-words">
|
||||
{artifact.sql}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{visibleColumns.length > 0 && visibleRows.length > 0 ? (
|
||||
<div className="overflow-x-auto rounded-lg bg-background/65 dark:bg-black/20">
|
||||
<table className="w-full border-collapse text-left text-[11px]">
|
||||
<thead>
|
||||
<tr className="border-b border-border/25 text-muted-foreground/80">
|
||||
{visibleColumns.map((col, idx) => (
|
||||
<th
|
||||
key={`${col}-${idx}`}
|
||||
className="px-2.5 py-1.5 font-medium whitespace-nowrap"
|
||||
>
|
||||
{col}
|
||||
</th>
|
||||
))}
|
||||
{hiddenColumnCount > 0 && (
|
||||
<th className="px-2 py-1.5 font-normal text-muted-foreground/60 whitespace-nowrap">
|
||||
+{hiddenColumnCount}
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border/15">
|
||||
{visibleRows.map((row, rowIdx) => (
|
||||
<tr key={rowIdx} className="hover:bg-muted/25">
|
||||
{visibleColumns.map((_, colIdx) => {
|
||||
const cell = row[colIdx];
|
||||
const isNull = cell === null || cell === undefined;
|
||||
return (
|
||||
<td
|
||||
key={colIdx}
|
||||
className={cn(
|
||||
'px-2.5 py-1 font-mono whitespace-nowrap tabular-nums',
|
||||
isNull ? 'text-muted-foreground/45 italic' : 'text-foreground/85',
|
||||
)}
|
||||
>
|
||||
{formatCellValue(cell)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
{hiddenColumnCount > 0 && (
|
||||
<td className="px-2 py-1 text-muted-foreground/45">…</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{(artifact.rowCount > visibleRows.length || artifact.truncated) && (
|
||||
<div className="px-2.5 py-1 text-[10px] text-muted-foreground/65">
|
||||
Showing {visibleRows.length} of {artifact.totalRows ?? artifact.rowCount} rows
|
||||
{artifact.truncated ? ' (capped)' : ''}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg bg-background/50 px-2.5 py-2 text-[11px] text-muted-foreground">
|
||||
Query returned 0 rows.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const PluginArtifactToolResult: React.FC<{
|
||||
artifact: PluginRenderedToolArtifact;
|
||||
}> = ({ artifact }) => {
|
||||
if (artifact.kind === 'bi-chart') {
|
||||
return <BiChartArtifactView artifact={artifact} />;
|
||||
}
|
||||
return <SqlResultArtifactView artifact={artifact} />;
|
||||
};
|
||||
@@ -0,0 +1,155 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import React from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { act } from 'react';
|
||||
import { parsePluginToolArtifact } from './pluginToolArtifact';
|
||||
import { PluginArtifactToolResult } from './PluginArtifactToolResult';
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
url: 'https://netcatty.local/',
|
||||
});
|
||||
const prev = {
|
||||
window: globalThis.window,
|
||||
document: globalThis.document,
|
||||
navigator: globalThis.navigator,
|
||||
HTMLElement: globalThis.HTMLElement,
|
||||
SVGElement: globalThis.SVGElement,
|
||||
IS_REACT_ACT_ENVIRONMENT: (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT,
|
||||
};
|
||||
Object.defineProperty(globalThis, 'window', { value: dom.window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: dom.window.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', { value: dom.window.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, 'SVGElement', { value: dom.window.SVGElement, configurable: true });
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'window', { value: prev.window, configurable: true });
|
||||
Object.defineProperty(globalThis, 'document', { value: prev.document, configurable: true });
|
||||
Object.defineProperty(globalThis, 'navigator', { value: prev.navigator, configurable: true });
|
||||
Object.defineProperty(globalThis, 'HTMLElement', { value: prev.HTMLElement, configurable: true });
|
||||
Object.defineProperty(globalThis, 'SVGElement', { value: prev.SVGElement, configurable: true });
|
||||
(globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prev.IS_REACT_ACT_ENVIRONMENT;
|
||||
dom.window.close();
|
||||
};
|
||||
}
|
||||
|
||||
test('parsePluginToolArtifact parses bi-chart and sql-result payloads and rejects spoofed or invalid ones', () => {
|
||||
const chartPayload = JSON.stringify({
|
||||
ok: true,
|
||||
_netcattyArtifact: {
|
||||
kind: 'bi-chart',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyViewId: 'com.binaricat.netcatty-database.workbench',
|
||||
_netcattyToolName: 'db_create_bi_chart',
|
||||
title: 'Revenue by Region',
|
||||
chartSpec: {
|
||||
type: 'bar',
|
||||
categories: ['NA', 'EU'],
|
||||
series: [{ id: 'rev', name: 'Revenue', values: [120, 95] }],
|
||||
},
|
||||
kpis: [{ label: 'Total', value: '$215', tone: 'positive' }],
|
||||
sql: 'SELECT region, SUM(revenue) FROM sales GROUP BY region',
|
||||
pinAction: { toolName: 'db_pin_chart_to_dashboard', args: { title: 'Revenue by Region' } },
|
||||
},
|
||||
});
|
||||
const chart = parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', chartPayload);
|
||||
assert.equal(chart?.kind, 'bi-chart');
|
||||
assert.equal(chart?.pluginId, 'com.binaricat.netcatty-database');
|
||||
assert.equal(chart?.kpis?.length, 1);
|
||||
assert.equal(chart?.pinAction?.toolName, 'db_pin_chart_to_dashboard');
|
||||
|
||||
// Non-plugin tools (e.g. terminal_execute, sftp_read) cannot spoof _netcattyArtifact
|
||||
assert.equal(parsePluginToolArtifact('terminal_execute', chartPayload), null);
|
||||
assert.equal(parsePluginToolArtifact('web_search', chartPayload), null);
|
||||
// Mismatched _netcattyToolName vs qualified tool suffix is rejected
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_other_tool', chartPayload), null);
|
||||
|
||||
const sql = parsePluginToolArtifact('plugin_abc123_db_run_readonly_sql', {
|
||||
_netcattyArtifact: {
|
||||
kind: 'sql-result',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyToolName: 'db_run_readonly_sql',
|
||||
sql: 'SELECT id, name FROM users LIMIT 2',
|
||||
columns: ['id', 'name'],
|
||||
rows: [[1, 'Alice'], [2, 'Bob']],
|
||||
rowCount: 2,
|
||||
durationMs: 4,
|
||||
openAction: { toolName: 'db_open_sql_tab', args: { sql: 'SELECT id, name FROM users' } },
|
||||
},
|
||||
});
|
||||
assert.equal(sql?.kind, 'sql-result');
|
||||
assert.equal(sql?.rows.length, 2);
|
||||
assert.equal(sql?.openAction?.toolName, 'db_open_sql_tab');
|
||||
|
||||
// Error results and unknown chart types are rejected
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', { _netcattyArtifact: { kind: 'bi-chart', _netcattyPluginId: 'com.a.b', _netcattyToolName: 'db_create_bi_chart', chartSpec: { type: 'bar', series: [{ id: 'a', name: 'A', values: [1] }] } } }, true), null);
|
||||
assert.equal(parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', { _netcattyArtifact: { kind: 'bi-chart', _netcattyPluginId: 'com.a.b', _netcattyToolName: 'db_create_bi_chart', chartSpec: { type: 'invalid', series: [{ id: 'a', name: 'A', values: [1] }] } } }), null);
|
||||
});
|
||||
|
||||
test('PluginArtifactToolResult renders inline PluginBiChart and invokes pinAction via netcatty bridge', async () => {
|
||||
const cleanup = installDom();
|
||||
const invoked: Array<Record<string, unknown>> = [];
|
||||
(window as unknown as { netcatty?: Record<string, unknown> }).netcatty = {
|
||||
invokePluginAiTool: async (payload: Record<string, unknown>) => {
|
||||
invoked.push(payload);
|
||||
return { ok: true };
|
||||
},
|
||||
};
|
||||
|
||||
const artifact = parsePluginToolArtifact('plugin_abc123_db_create_bi_chart', {
|
||||
_netcattyArtifact: {
|
||||
kind: 'bi-chart',
|
||||
_netcattyPluginId: 'com.binaricat.netcatty-database',
|
||||
_netcattyViewId: 'com.binaricat.netcatty-database.workbench',
|
||||
_netcattyToolName: 'db_create_bi_chart',
|
||||
title: 'Top Products',
|
||||
chartSpec: {
|
||||
type: 'bar',
|
||||
categories: ['Pro', 'Air'],
|
||||
series: [{ id: 'rev', name: 'Revenue', values: [4200, 3100] }],
|
||||
},
|
||||
kpis: [{ label: 'Total Revenue', value: '$7.3K', tone: 'positive' }],
|
||||
sql: 'SELECT product, SUM(revenue) FROM orders GROUP BY product',
|
||||
pinAction: {
|
||||
toolName: 'db_pin_chart_to_dashboard',
|
||||
args: { title: 'Top Products' },
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.ok(artifact);
|
||||
|
||||
const container = document.getElementById('root')!;
|
||||
const root = createRoot(container);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(React.createElement(PluginArtifactToolResult, { artifact }));
|
||||
});
|
||||
assert.ok(container.querySelector('[data-plugin-ai-artifact="bi-chart"]'));
|
||||
assert.ok(container.querySelector('svg'), 'PluginBiChart SVG should render inline');
|
||||
assert.ok(container.textContent?.includes('$7.3K'));
|
||||
|
||||
const pinButton = Array.from(container.querySelectorAll('button')).find(
|
||||
(btn) => btn.textContent?.includes('Pin to BI Dashboard'),
|
||||
);
|
||||
assert.ok(pinButton, 'Pin to BI Dashboard button should render');
|
||||
await act(async () => {
|
||||
pinButton.click();
|
||||
});
|
||||
assert.equal(invoked.length, 1);
|
||||
assert.deepEqual(invoked[0], {
|
||||
pluginId: 'com.binaricat.netcatty-database',
|
||||
toolName: 'db_pin_chart_to_dashboard',
|
||||
args: { title: 'Top Products' },
|
||||
viewId: 'com.binaricat.netcatty-database.workbench',
|
||||
});
|
||||
assert.ok(container.textContent?.includes('Pinned'));
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
cleanup();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import type { PluginBiChartWidgetProps } from '../../plugins/primitives/types';
|
||||
import { parseResultPayload } from './toolArtifactResultPayload';
|
||||
|
||||
const VALID_BI_CHART_TYPES = new Set([
|
||||
'bar',
|
||||
'horizontal-bar',
|
||||
'stacked-bar',
|
||||
'line',
|
||||
'area',
|
||||
'pie',
|
||||
'donut',
|
||||
'scatter',
|
||||
'funnel',
|
||||
'combo',
|
||||
]);
|
||||
|
||||
const VALID_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,47}$/;
|
||||
const QUALIFIED_PLUGIN_TOOL_RE = /^plugin_[0-9a-f]{6}_([a-z][a-z0-9_]{0,47})$/;
|
||||
|
||||
export interface PluginArtifactActionSpec {
|
||||
readonly toolName: string;
|
||||
readonly label?: string;
|
||||
readonly args: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PluginBiChartArtifactKpi {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly delta?: string;
|
||||
readonly tone?: 'default' | 'positive' | 'negative' | 'warning';
|
||||
}
|
||||
|
||||
export interface PluginBiChartRenderedArtifact {
|
||||
readonly kind: 'bi-chart';
|
||||
readonly pluginId?: string;
|
||||
readonly pluginName?: string;
|
||||
readonly viewId?: string;
|
||||
readonly sourceToolName?: string;
|
||||
readonly title?: string;
|
||||
readonly subtitle?: string;
|
||||
readonly chartSpec: PluginBiChartWidgetProps;
|
||||
readonly kpis?: readonly PluginBiChartArtifactKpi[];
|
||||
readonly sql?: string;
|
||||
readonly pinAction?: PluginArtifactActionSpec;
|
||||
readonly openAction?: PluginArtifactActionSpec;
|
||||
}
|
||||
|
||||
export interface PluginSqlResultRenderedArtifact {
|
||||
readonly kind: 'sql-result';
|
||||
readonly pluginId?: string;
|
||||
readonly pluginName?: string;
|
||||
readonly viewId?: string;
|
||||
readonly sourceToolName?: string;
|
||||
readonly title?: string;
|
||||
readonly sql: string;
|
||||
readonly columns: readonly string[];
|
||||
readonly rows: readonly (readonly unknown[])[];
|
||||
readonly rowCount: number;
|
||||
readonly totalRows?: number;
|
||||
readonly durationMs?: number;
|
||||
readonly truncated?: boolean;
|
||||
readonly openAction?: PluginArtifactActionSpec;
|
||||
readonly chartAction?: PluginArtifactActionSpec;
|
||||
}
|
||||
|
||||
export type PluginRenderedToolArtifact =
|
||||
| PluginBiChartRenderedArtifact
|
||||
| PluginSqlResultRenderedArtifact;
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
function asNonEmptyString(value: unknown, maxLength = 240): string | undefined {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return undefined;
|
||||
return trimmed.slice(0, maxLength);
|
||||
}
|
||||
|
||||
function parseArtifactAction(value: unknown): PluginArtifactActionSpec | undefined {
|
||||
const record = asRecord(value);
|
||||
if (!record) return undefined;
|
||||
const toolName = typeof record.toolName === 'string' ? record.toolName.trim() : '';
|
||||
if (!VALID_TOOL_NAME_RE.test(toolName)) return undefined;
|
||||
const args = asRecord(record.args) ?? {};
|
||||
const label = asNonEmptyString(record.label, 64);
|
||||
return {
|
||||
toolName,
|
||||
...(label ? { label } : {}),
|
||||
args,
|
||||
};
|
||||
}
|
||||
|
||||
function parseKpis(value: unknown): PluginBiChartArtifactKpi[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const items: PluginBiChartArtifactKpi[] = [];
|
||||
for (const raw of value.slice(0, 4)) {
|
||||
const record = asRecord(raw);
|
||||
if (!record) continue;
|
||||
const label = asNonEmptyString(record.label, 64);
|
||||
const val = asNonEmptyString(record.value, 64);
|
||||
if (!label || !val) continue;
|
||||
const delta = asNonEmptyString(record.delta, 32);
|
||||
const tone = record.tone === 'positive' || record.tone === 'negative' || record.tone === 'warning'
|
||||
? record.tone
|
||||
: 'default';
|
||||
items.push({
|
||||
label,
|
||||
value: val,
|
||||
...(delta ? { delta } : {}),
|
||||
tone,
|
||||
});
|
||||
}
|
||||
return items.length > 0 ? items : undefined;
|
||||
}
|
||||
|
||||
export function parsePluginToolArtifact(
|
||||
toolName: string | undefined,
|
||||
result: unknown,
|
||||
isError?: boolean,
|
||||
): PluginRenderedToolArtifact | null {
|
||||
if (isError) return null;
|
||||
if (typeof toolName !== 'string') return null;
|
||||
const qualifiedMatch = QUALIFIED_PLUGIN_TOOL_RE.exec(toolName.trim());
|
||||
if (!qualifiedMatch) return null;
|
||||
const expectedToolSuffix = qualifiedMatch[1];
|
||||
|
||||
const payload = parseResultPayload(result);
|
||||
if (!payload) return null;
|
||||
const artifact = asRecord(payload._netcattyArtifact);
|
||||
if (!artifact) return null;
|
||||
|
||||
const pluginId = asNonEmptyString(artifact._netcattyPluginId, 160);
|
||||
const pluginName = asNonEmptyString(artifact._netcattyPluginName, 120);
|
||||
const viewId = asNonEmptyString(artifact._netcattyViewId, 256);
|
||||
const sourceToolName = asNonEmptyString(artifact._netcattyToolName, 64);
|
||||
if (!pluginId || sourceToolName !== expectedToolSuffix) return null;
|
||||
|
||||
if (artifact.kind === 'bi-chart') {
|
||||
const rawChartSpec = asRecord(artifact.chartSpec);
|
||||
if (!rawChartSpec) return null;
|
||||
const chartType = typeof rawChartSpec.type === 'string' ? rawChartSpec.type : '';
|
||||
if (!VALID_BI_CHART_TYPES.has(chartType)) return null;
|
||||
const hasSeries = Array.isArray(rawChartSpec.series) && rawChartSpec.series.length > 0;
|
||||
const hasPoints = Array.isArray(rawChartSpec.points) && rawChartSpec.points.length > 0;
|
||||
if (!hasSeries && !hasPoints) return null;
|
||||
|
||||
return {
|
||||
kind: 'bi-chart',
|
||||
pluginId,
|
||||
pluginName,
|
||||
viewId,
|
||||
sourceToolName,
|
||||
title: asNonEmptyString(artifact.title, 140) ?? asNonEmptyString(rawChartSpec.title, 140),
|
||||
subtitle: asNonEmptyString(artifact.subtitle, 180) ?? asNonEmptyString(rawChartSpec.subtitle, 180),
|
||||
chartSpec: rawChartSpec as unknown as PluginBiChartWidgetProps,
|
||||
kpis: parseKpis(artifact.kpis),
|
||||
sql: asNonEmptyString(artifact.sql, 8000),
|
||||
pinAction: parseArtifactAction(artifact.pinAction),
|
||||
openAction: parseArtifactAction(artifact.openAction),
|
||||
};
|
||||
}
|
||||
|
||||
if (artifact.kind === 'sql-result') {
|
||||
const sql = asNonEmptyString(artifact.sql, 8000);
|
||||
if (!sql) return null;
|
||||
const columns = Array.isArray(artifact.columns)
|
||||
? artifact.columns.slice(0, 32).map((col) => String(col ?? ''))
|
||||
: [];
|
||||
const rows = Array.isArray(artifact.rows)
|
||||
? artifact.rows.slice(0, 50).map((row) => (Array.isArray(row) ? row.slice(0, 32) : [row]))
|
||||
: [];
|
||||
const rowCount = typeof artifact.rowCount === 'number' && Number.isFinite(artifact.rowCount)
|
||||
? Math.max(0, Math.floor(artifact.rowCount))
|
||||
: rows.length;
|
||||
const totalRows = typeof artifact.totalRows === 'number' && Number.isFinite(artifact.totalRows)
|
||||
? Math.max(rowCount, Math.floor(artifact.totalRows))
|
||||
: undefined;
|
||||
const durationMs = typeof artifact.durationMs === 'number' && Number.isFinite(artifact.durationMs)
|
||||
? Math.max(0, Math.round(artifact.durationMs))
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
kind: 'sql-result',
|
||||
pluginId,
|
||||
pluginName,
|
||||
viewId,
|
||||
sourceToolName,
|
||||
title: asNonEmptyString(artifact.title, 140),
|
||||
sql,
|
||||
columns,
|
||||
rows,
|
||||
rowCount,
|
||||
totalRows,
|
||||
durationMs,
|
||||
truncated: artifact.truncated === true,
|
||||
openAction: parseArtifactAction(artifact.openAction),
|
||||
chartAction: parseArtifactAction(artifact.chartAction),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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\) =>/);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { Suspense } from 'react';
|
||||
import { prewarmHostDrawnPluginView } from '../../application/state/pluginViewSessionRegistry';
|
||||
import type { PluginHostDrawnPageProps } from './PluginHostDrawnPage';
|
||||
|
||||
let preloadPromise: Promise<unknown> | null = null;
|
||||
@@ -11,8 +12,41 @@ export function preloadPluginHostDrawnPage(): void {
|
||||
void loadPluginHostDrawnPage().catch(() => { preloadPromise = null; });
|
||||
}
|
||||
|
||||
export function prewarmPluginView(viewId?: string): void {
|
||||
preloadPluginHostDrawnPage();
|
||||
if (viewId) prewarmHostDrawnPluginView(viewId);
|
||||
}
|
||||
|
||||
const PluginHostDrawnPageImpl = React.lazy(loadPluginHostDrawnPage);
|
||||
|
||||
export function PluginViewLoadingSurface({ slot, loadingLabel }: { slot: string; loadingLabel: string }) {
|
||||
return (
|
||||
<div
|
||||
data-plugin-view-slot={slot}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="flex h-full min-h-0 w-full flex-1 flex-col gap-3 bg-background p-4 text-sm text-muted-foreground"
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-muted-foreground/30 border-t-foreground/70" aria-hidden="true" />
|
||||
<span className="text-xs font-medium text-muted-foreground">{loadingLabel}</span>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 gap-3 opacity-60" aria-hidden="true">
|
||||
<div className="hidden w-52 shrink-0 flex-col gap-2 rounded-lg border border-border/40 bg-muted/20 p-3 sm:flex">
|
||||
<div className="h-3 w-2/3 animate-pulse rounded bg-muted/60" />
|
||||
<div className="h-3 w-4/5 animate-pulse rounded bg-muted/40" />
|
||||
<div className="h-3 w-1/2 animate-pulse rounded bg-muted/40" />
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-2.5 rounded-lg border border-border/40 bg-muted/10 p-3">
|
||||
<div className="h-3.5 w-1/3 animate-pulse rounded bg-muted/50" />
|
||||
<div className="h-24 w-full animate-pulse rounded bg-muted/30" />
|
||||
<div className="min-h-0 flex-1 animate-pulse rounded bg-muted/20" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy boundary for host-drawn plugin views so css-tree, mdn-data, and
|
||||
* @remote-dom/core stay out of the startup entry bundle until a plugin view
|
||||
@@ -24,9 +58,7 @@ export function LazyPluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
<Suspense
|
||||
fallback={
|
||||
props.active ? (
|
||||
<p data-plugin-view-slot={slot} role="status" className="p-4 text-sm text-muted-foreground">
|
||||
{props.loadingLabel}
|
||||
</p>
|
||||
<PluginViewLoadingSurface slot={slot} loadingLabel={props.loadingLabel} />
|
||||
) : null
|
||||
}
|
||||
>
|
||||
|
||||
@@ -14,10 +14,12 @@ export function PluginHostActionHost() {
|
||||
if (!entry) return null;
|
||||
const request = entry.prompt.request;
|
||||
const selection = request.kind === 'vault.selectHosts';
|
||||
const durableSelection = selection && request.durable === true;
|
||||
const stream = request.kind === 'network.stream.connectViaHost';
|
||||
const directStreamConfirm = request.kind === 'network.stream.confirm';
|
||||
const tlsConfirm = request.kind === 'network.stream.tlsConfirm';
|
||||
const connection = request.kind === 'vault.requestConnect' || stream;
|
||||
const isSftpConnect = request.kind === 'vault.requestConnect' && request.mode === 'sftp';
|
||||
const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined;
|
||||
const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined;
|
||||
const dialogTitle = selection
|
||||
@@ -26,11 +28,13 @@ export function PluginHostActionHost() {
|
||||
? 'Confirm Network Connection'
|
||||
: tlsConfirm
|
||||
? 'Verify TLS Certificate'
|
||||
: connection
|
||||
? t('plugins.hostActions.connect')
|
||||
: entry.host
|
||||
? t('plugins.hostActions.edit')
|
||||
: t('plugins.hostActions.create');
|
||||
: isSftpConnect
|
||||
? t('vault.hosts.openSftp')
|
||||
: connection
|
||||
? t('plugins.hostActions.connect')
|
||||
: entry.host
|
||||
? t('plugins.hostActions.edit')
|
||||
: t('plugins.hostActions.create');
|
||||
|
||||
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
|
||||
<DialogContent className={selection ? 'max-w-md h-[min(85vh,640px)] flex flex-col p-0 gap-0 overflow-hidden' : 'sm:max-w-[560px] max-h-[85vh] overflow-y-auto'} hideCloseButton>
|
||||
@@ -40,6 +44,11 @@ export function PluginHostActionHost() {
|
||||
</DialogHeader>
|
||||
{selection ? <>
|
||||
<p className="px-4 pt-3 text-xs text-muted-foreground">{t('plugins.hostActions.selectionNote')}</p>
|
||||
{durableSelection && (
|
||||
<p className="px-4 pt-1 text-xs text-amber-600 dark:text-amber-400">
|
||||
Selected hosts will remain bound to this plugin across sessions until revoked. SSH passwords and private keys are never shared.
|
||||
</p>
|
||||
)}
|
||||
<p className="px-4 pt-2 text-sm font-medium break-words">{request.title}</p>
|
||||
{state.selectedIds.length > 50 && <p role="alert" className="px-4 text-sm text-destructive">{t('plugins.hostActions.selectionLimit')}</p>}
|
||||
<SelectHostPanelContent hosts={entry.candidates} customGroups={entry.customGroups} selectedHostIds={state.selectedIds} multiSelect className="flex-1 min-h-0" confirmDisabled={state.busy || state.selectedIds.length > 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPluginView';
|
||||
import { PluginViewLoadingSurface } from './LazyPluginHostDrawnPage';
|
||||
import { PluginSettingsEntry } from './PluginSettingsEntry';
|
||||
import { PluginRemoteSurface } from './PluginRemoteSurface';
|
||||
|
||||
@@ -32,7 +33,7 @@ function hasFullBleedChrome(tree: unknown): boolean {
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
const view = useHostDrawnPluginView(props);
|
||||
if (!view.visible) return null;
|
||||
if (view.loading) return <p data-plugin-view-slot={props.slot.split(':')[0]} role="status" className="p-4 text-sm text-muted-foreground">{props.loadingLabel}</p>;
|
||||
if (view.loading) return <PluginViewLoadingSurface slot={props.slot.split(':')[0]} loadingLabel={props.loadingLabel} />;
|
||||
const fullBleed = hasFullBleedChrome(view.tree);
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
|
||||
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
|
||||
|
||||
@@ -21,18 +21,30 @@ function HostInteractionDialog({ state, prompt }: {
|
||||
const request = prompt.request;
|
||||
const terminalShare = request.kind === 'terminal.selection.read';
|
||||
const inputDraft = request.kind === 'terminal.input.propose';
|
||||
const isConfirm = request.kind === 'confirm';
|
||||
const isOpenExternalUrl = request.kind === 'openExternalUrl';
|
||||
const previewClipboard = request.kind === 'clipboard.read' && prompt.phase === 'request';
|
||||
const needsPreview = previewClipboard || (terminalShare && prompt.phase === 'request');
|
||||
const textBytes = new TextEncoder().encode(state.value).length;
|
||||
const canSubmit = request.kind === 'quickPick' ? request.items.some((item) => item.id === state.value) : textBytes <= PLUGIN_HOST_INTERACTION_LIMITS.textBytes;
|
||||
const canSubmit = request.kind === 'quickPick'
|
||||
? request.items.some((item) => item.id === state.value)
|
||||
: (isConfirm || isOpenExternalUrl || textBytes <= PLUGIN_HOST_INTERACTION_LIMITS.textBytes);
|
||||
const displayTitle = isOpenExternalUrl
|
||||
? (request.title ?? t('plugins.interaction.openUrlTitle'))
|
||||
: request.title;
|
||||
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-[520px]" hideCloseButton>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('plugins.interaction.title')}</DialogTitle>
|
||||
<DialogDescription className="break-all">{prompt.pluginId} · {prompt.pluginVersion}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<p className="break-words text-sm font-medium">{request.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{t(inputDraft ? 'plugins.interaction.draftNote' : terminalShare ? 'plugins.interaction.terminalDisclosure' : 'plugins.interaction.sharing')}</p>
|
||||
<p className="break-words text-sm font-medium">{displayTitle}</p>
|
||||
{isConfirm && request.message && <p className="break-words text-sm text-muted-foreground whitespace-pre-wrap">{request.message}</p>}
|
||||
{isOpenExternalUrl && <>
|
||||
<p className="text-xs text-muted-foreground">{t('plugins.interaction.openUrlNote')}</p>
|
||||
<code className="block rounded-md border bg-muted/40 p-2.5 font-mono text-xs break-all">{request.url}</code>
|
||||
</>}
|
||||
{!isConfirm && !isOpenExternalUrl && <p className="text-xs text-muted-foreground">{t(inputDraft ? 'plugins.interaction.draftNote' : terminalShare ? 'plugins.interaction.terminalDisclosure' : 'plugins.interaction.sharing')}</p>}
|
||||
{(terminalShare || inputDraft) && <p className="break-all text-sm">{t('plugins.interaction.terminalTarget')}: {prompt.terminalLabel} ({prompt.terminalSessionId})</p>}
|
||||
{inputDraft && <textarea aria-label={t('plugins.interaction.draft')} className="min-h-28 max-h-64 w-full rounded-md border bg-muted/30 p-3 font-mono text-xs" value={state.value} maxLength={PLUGIN_HOST_INTERACTION_LIMITS.textBytes} disabled={state.busy} onChange={(event) => state.setValue(event.target.value)} />}
|
||||
{(inputDraft || (terminalShare && prompt.phase === 'preview')) && <pre aria-label={t('plugins.interaction.exactText')} className="max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-md border p-2 font-mono text-xs">{JSON.stringify(inputDraft ? state.value : prompt.previewText)}</pre>}
|
||||
@@ -50,9 +62,19 @@ function HostInteractionDialog({ state, prompt }: {
|
||||
{(request.kind === 'clipboard.write' || prompt.phase === 'preview') && <textarea aria-label={t('plugins.interaction.preview')} readOnly className="min-h-28 max-h-64 w-full resize-none rounded-md border bg-muted/30 p-3 font-mono text-xs" value={request.kind === 'clipboard.write' ? request.text : prompt.previewText ?? ''} />}
|
||||
{state.error && <p role="alert" className="text-sm text-destructive">{t('plugins.interaction.failed')}</p>}
|
||||
<DialogFooter>
|
||||
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>{t('common.cancel')}</Button>
|
||||
<Button disabled={state.busy || !canSubmit} onClick={() => void state.respond(needsPreview ? 'preview' : 'submit')}>
|
||||
{t(needsPreview ? terminalShare ? 'plugins.interaction.terminalPreview' : 'plugins.interaction.previewAction' : inputDraft ? 'plugins.interaction.closeDraft' : request.kind === 'clipboard.read' || terminalShare ? 'plugins.interaction.share' : request.kind === 'clipboard.write' ? 'plugins.interaction.copy' : 'common.continue')}
|
||||
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>
|
||||
{isConfirm && request.cancelLabel ? request.cancelLabel : t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={isConfirm && request.destructive ? 'destructive' : 'default'}
|
||||
disabled={state.busy || !canSubmit}
|
||||
onClick={() => void state.respond(needsPreview ? 'preview' : 'submit')}
|
||||
>
|
||||
{isConfirm && request.confirmLabel
|
||||
? request.confirmLabel
|
||||
: isOpenExternalUrl
|
||||
? t('plugins.interaction.openUrlAction')
|
||||
: t(needsPreview ? terminalShare ? 'plugins.interaction.terminalPreview' : 'plugins.interaction.previewAction' : inputDraft ? 'plugins.interaction.closeDraft' : request.kind === 'clipboard.read' || terminalShare ? 'plugins.interaction.share' : request.kind === 'clipboard.write' ? 'plugins.interaction.copy' : 'common.continue')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -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]">
|
||||
|
||||
@@ -6,6 +6,7 @@ import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } fro
|
||||
import { matchWorkbenchShortcut } from './primitives/shortcuts';
|
||||
import type { PluginSplitPaneWidgetProps } from './primitives/types';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { isValidatedPluginRemoteTree } from '../../application/state/pluginRemoteTree';
|
||||
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
|
||||
@@ -28,7 +29,7 @@ const SURFACE_EVENTS = [
|
||||
'scroll',
|
||||
] as const;
|
||||
const SURFACE_EVENT_SET = new Set<string>(SURFACE_EVENTS);
|
||||
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas']);
|
||||
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas', 'metric-chart', 'bi-chart']);
|
||||
|
||||
const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
|
||||
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
|
||||
@@ -339,6 +340,7 @@ function readSelectionRange(
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const checkedTree = useMemo(() => {
|
||||
if (isValidatedPluginRemoteTree(tree)) return tree as { children: RemoteNode[] };
|
||||
try {
|
||||
validatePluginRemoteTree(tree);
|
||||
return tree as { children: RemoteNode[] };
|
||||
@@ -537,11 +539,14 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
};
|
||||
}, [shadow, depth]);
|
||||
|
||||
const baseStyleElement = useMemo(() => <style>{SHADOW_BASE_SCROLLBAR_CSS}</style>, []);
|
||||
const pluginStyleElement = useMemo(() => <style>{css}</style>, [css]);
|
||||
|
||||
return (
|
||||
<SurfaceContext.Provider value={surfaceContextValue}>
|
||||
<div ref={surfaceRef} className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
|
||||
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/25" />
|
||||
{shadow && createPortal(<><style>{SHADOW_BASE_SCROLLBAR_CSS}</style><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
{shadow && createPortal(<>{baseStyleElement}{pluginStyleElement}{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
</div>
|
||||
</SurfaceContext.Provider>
|
||||
);
|
||||
|
||||
@@ -3,28 +3,49 @@ import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { activeTabStore } from '../../application/state/activeTabStore';
|
||||
import { subscribeSidePanelLiveSnapshot } from '../../application/state/sidePanelLiveStore';
|
||||
import { usePluginContributions } from '../../application/state/usePluginContributions';
|
||||
import { usePluginViewBadges } from '../../application/state/usePluginViewBadges';
|
||||
import { collectPluginTerminalSidebarPages, PLUGIN_TERMINAL_SIDEBAR_CONTEXT, requestOpenPluginTerminalSidebar,
|
||||
type PluginTerminalSidebarPage } from '../../application/state/usePluginTerminalSidebar';
|
||||
import { formatPluginViewBadgeAriaText, formatPluginViewBadgeLabel, isPluginViewBadgeVisible } from '../../domain/pluginViewBadge';
|
||||
import { cn } from '../../lib/utils';
|
||||
import { PluginContributionIcon } from './PluginContributionIcon';
|
||||
import { PluginViewBadge } from './PluginViewBadge';
|
||||
import { Button } from '../ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
|
||||
import { LazyPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
|
||||
import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDrawnPage';
|
||||
|
||||
export function PluginTerminalSidebarLauncher({ sessionId, buttonClassName = 'h-6 w-6' }: { sessionId: string; buttonClassName?: string }) {
|
||||
const { locale } = useI18n();
|
||||
const contributions = usePluginContributions({ locale, context: PLUGIN_TERMINAL_SIDEBAR_CONTEXT });
|
||||
const pages = collectPluginTerminalSidebarPages(contributions.snapshot.plugins);
|
||||
const badgesByViewId = usePluginViewBadges(pages.length > 0);
|
||||
if (!pages.length) return null;
|
||||
return <>{pages.map((page) => <Tooltip key={page.tool}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className={buttonClassName}
|
||||
aria-label={`${page.title} — ${page.pluginName}`}
|
||||
onClick={() => requestOpenPluginTerminalSidebar(page.viewId, sessionId)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">{page.title} — {page.pluginName}</TooltipContent>
|
||||
</Tooltip>)}</>;
|
||||
return <>{pages.map((page) => {
|
||||
const rawBadge = badgesByViewId.get(page.viewId);
|
||||
const activeBadge = isPluginViewBadgeVisible(rawBadge) ? rawBadge : null;
|
||||
const badgeLabel = formatPluginViewBadgeLabel(activeBadge);
|
||||
const badgeAria = formatPluginViewBadgeAriaText(activeBadge);
|
||||
const baseLabel = `${page.title} — ${page.pluginName}`;
|
||||
const tooltip = activeBadge?.tooltip
|
||||
? `${baseLabel} · ${activeBadge.tooltip}`
|
||||
: badgeLabel
|
||||
? `${baseLabel} (${badgeLabel})`
|
||||
: baseLabel;
|
||||
const ariaLabel = badgeAria ? `${baseLabel} (${badgeAria})` : baseLabel;
|
||||
return <Tooltip key={page.tool}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon" className={cn('relative overflow-visible', buttonClassName)}
|
||||
aria-label={ariaLabel}
|
||||
onMouseEnter={() => prewarmPluginView(page.viewId)}
|
||||
onFocus={() => prewarmPluginView(page.viewId)}
|
||||
onClick={() => requestOpenPluginTerminalSidebar(page.viewId, sessionId)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={14} />
|
||||
{activeBadge && <PluginViewBadge badge={activeBadge} variant="compact-overlay" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">{tooltip}</TooltipContent>
|
||||
</Tooltip>;
|
||||
})}</>;
|
||||
}
|
||||
|
||||
export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSession, unavailable, focused, showHeader = true }: {
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { useAIState } from '../../application/state/useAIState';
|
||||
import { useAISessionsStore } from '../../application/state/aiSessionsStore';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import type {
|
||||
PluginAISidebarPrompt,
|
||||
PluginAISidebarTurnContext,
|
||||
} from '../../infrastructure/ai/pluginAiSidebarTypes';
|
||||
import {
|
||||
MAX_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
readPluginAiSidebarWidth,
|
||||
writePluginAiSidebarWidth,
|
||||
type PendingPluginSidebarPrompt,
|
||||
} from '../../application/state/usePluginAiSidebar';
|
||||
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const LazyAIChatSidePanel = lazy(() => import('../AIChatSidePanel'));
|
||||
|
||||
const PluginAISidebarFallback: React.FC = () => {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-background text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 size={14} className="animate-spin" />
|
||||
{t('ai.chat.preparing')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export interface PluginVaultAISidebarProps {
|
||||
pluginId: string;
|
||||
pluginName: string;
|
||||
viewId: string;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
pluginContext: PluginAISidebarTurnContext | null;
|
||||
suggestedPrompts?: readonly PluginAISidebarPrompt[];
|
||||
pendingPrompt?: PendingPluginSidebarPrompt | null;
|
||||
onPendingPromptConsumed?: (id: number) => void;
|
||||
}
|
||||
|
||||
export const PluginVaultAISidebar: React.FC<PluginVaultAISidebarProps> = ({
|
||||
pluginName,
|
||||
viewId,
|
||||
open,
|
||||
onClose,
|
||||
pluginContext,
|
||||
suggestedPrompts,
|
||||
pendingPrompt,
|
||||
onPendingPromptConsumed,
|
||||
}) => {
|
||||
const aiConfig = useAIState();
|
||||
const {
|
||||
sessions,
|
||||
activeSessionIdMap,
|
||||
draftsByScope,
|
||||
panelViewByScope,
|
||||
} = useAISessionsStore();
|
||||
const [width, setWidth] = useState<number>(readPluginAiSidebarWidth);
|
||||
const [resizing, setResizing] = useState(false);
|
||||
const widthRef = useRef(width);
|
||||
widthRef.current = width;
|
||||
|
||||
useEffect(() => {
|
||||
if (!resizing) return;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
const next = Math.max(
|
||||
MIN_PLUGIN_AI_SIDEBAR_WIDTH,
|
||||
Math.min(MAX_PLUGIN_AI_SIDEBAR_WIDTH, Math.round(window.innerWidth - event.clientX - 8)),
|
||||
);
|
||||
widthRef.current = next;
|
||||
setWidth(next);
|
||||
};
|
||||
const onUp = () => {
|
||||
setResizing(false);
|
||||
document.body.style.cursor = '';
|
||||
writePluginAiSidebarWidth(widthRef.current);
|
||||
};
|
||||
document.body.style.cursor = 'col-resize';
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp, { once: true });
|
||||
return () => {
|
||||
document.body.style.cursor = '';
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
};
|
||||
}, [resizing]);
|
||||
|
||||
const handleStartResize = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
setResizing(true);
|
||||
}, []);
|
||||
|
||||
const scopeTargetId = `plugin-view:${viewId}`;
|
||||
|
||||
return (
|
||||
<aside
|
||||
data-plugin-ai-sidebar={viewId}
|
||||
data-open={open ? 'true' : 'false'}
|
||||
aria-label={`${pluginName} AI Assistant`}
|
||||
style={open ? { width } : undefined}
|
||||
className={cn(
|
||||
'relative flex h-full min-h-0 shrink-0 flex-col bg-background',
|
||||
open ? 'border-l border-border/35' : 'hidden',
|
||||
)}
|
||||
>
|
||||
{open && (
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize AI sidebar"
|
||||
onPointerDown={handleStartResize}
|
||||
className={cn(
|
||||
'absolute top-0 bottom-0 left-0 z-20 w-1.5 -translate-x-1/2 cursor-col-resize transition-colors',
|
||||
resizing ? 'bg-primary/40' : 'hover:bg-primary/25',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<div className="min-h-0 flex-1 overflow-hidden">
|
||||
<LazyLoadBoundary name="Plugin AI sidebar" resetKey={viewId}>
|
||||
<Suspense fallback={<PluginAISidebarFallback />}>
|
||||
<LazyAIChatSidePanel
|
||||
sessions={sessions as AISession[]}
|
||||
activeSessionIdMap={activeSessionIdMap as Record<string, string | null>}
|
||||
draftsByScope={draftsByScope}
|
||||
panelViewByScope={panelViewByScope}
|
||||
setActiveSessionId={aiConfig.setActiveSessionId}
|
||||
ensureDraftForScope={aiConfig.ensureDraftForScope}
|
||||
updateDraft={aiConfig.updateDraft}
|
||||
showDraftView={aiConfig.showDraftView}
|
||||
showSessionView={aiConfig.showSessionView}
|
||||
clearDraftForScope={aiConfig.clearDraftForScope}
|
||||
addDraftFiles={aiConfig.addDraftFiles}
|
||||
removeDraftFile={aiConfig.removeDraftFile}
|
||||
createSession={aiConfig.createSession}
|
||||
undoLastTurnInSession={aiConfig.undoLastTurnInSession}
|
||||
deleteSession={aiConfig.deleteSession}
|
||||
updateSessionTitle={aiConfig.updateSessionTitle}
|
||||
exportSessionsBackup={aiConfig.exportSessionsBackup}
|
||||
importSessionsBackup={aiConfig.importSessionsBackup}
|
||||
updateSessionExternalSessionId={aiConfig.updateSessionExternalSessionId}
|
||||
addMessageToSession={aiConfig.addMessageToSession}
|
||||
updateLastMessage={aiConfig.updateLastMessage}
|
||||
updateMessageById={aiConfig.updateMessageById}
|
||||
persistContextCompaction={aiConfig.persistContextCompaction}
|
||||
forkSessionFromMessage={aiConfig.forkSessionFromMessage}
|
||||
providers={aiConfig.providers}
|
||||
activeProviderId={aiConfig.activeProviderId}
|
||||
activeModelId={aiConfig.activeModelId}
|
||||
defaultAgentId="catty"
|
||||
toolIntegrationMode={aiConfig.toolIntegrationMode}
|
||||
externalAgents={aiConfig.externalAgents}
|
||||
setExternalAgents={aiConfig.setExternalAgents}
|
||||
agentModelMap={aiConfig.agentModelMap}
|
||||
setAgentModel={aiConfig.setAgentModel}
|
||||
agentProviderMap={aiConfig.agentProviderMap}
|
||||
setAgentProvider={aiConfig.setAgentProvider}
|
||||
agentThinkingMap={aiConfig.agentThinkingMap}
|
||||
setAgentThinking={aiConfig.setAgentThinking}
|
||||
updateProvider={aiConfig.updateProvider}
|
||||
globalPermissionMode={aiConfig.globalPermissionMode}
|
||||
setGlobalPermissionMode={aiConfig.setGlobalPermissionMode}
|
||||
commandBlocklist={aiConfig.commandBlocklist}
|
||||
commandTimeout={aiConfig.commandTimeout}
|
||||
responseIdleTimeout={aiConfig.responseIdleTimeout}
|
||||
maxIterations={aiConfig.maxIterations}
|
||||
toolOutputMaxChars={aiConfig.toolOutputMaxChars}
|
||||
webSearchConfig={aiConfig.webSearchConfig}
|
||||
quickMessages={aiConfig.quickMessages}
|
||||
scopeType="global"
|
||||
scopeTargetId={scopeTargetId}
|
||||
scopeLabel={pluginContext?.title || pluginName}
|
||||
terminalSessions={[]}
|
||||
isVisible={open}
|
||||
pluginContext={pluginContext}
|
||||
pluginSuggestedPrompts={suggestedPrompts}
|
||||
pendingPluginPrompt={pendingPrompt}
|
||||
onPendingPluginPromptConsumed={onPendingPromptConsumed}
|
||||
onClosePanel={onClose}
|
||||
borderlessChrome
|
||||
/>
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
@@ -1,36 +1,132 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { activeTabStore } from '../../application/state/activeTabStore';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { usePluginVaultPages } from '../../application/state/usePluginVaultPages';
|
||||
import { usePluginViewBadges } from '../../application/state/usePluginViewBadges';
|
||||
import {
|
||||
usePluginAiSidebarForView,
|
||||
type PendingPluginSidebarPrompt,
|
||||
} from '../../application/state/usePluginAiSidebar';
|
||||
import { formatPluginViewBadgeAriaText, formatPluginViewBadgeLabel, isPluginViewBadgeVisible } from '../../domain/pluginViewBadge';
|
||||
import { PluginContributionIcon } from './PluginContributionIcon';
|
||||
import { PluginViewBadge } from './PluginViewBadge';
|
||||
import { Button } from '../ui/button';
|
||||
import { LazyPluginHostDrawnPage, preloadPluginHostDrawnPage } from './LazyPluginHostDrawnPage';
|
||||
import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDrawnPage';
|
||||
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
|
||||
|
||||
type VaultPages = ReturnType<typeof usePluginVaultPages>;
|
||||
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
|
||||
let nextPluginPromptId = 1;
|
||||
|
||||
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
|
||||
const badgesByViewId = usePluginViewBadges(model.pages.length > 0);
|
||||
if (!model.pages.length) return null;
|
||||
return <>
|
||||
{model.pages.map((page) => <Button key={page.key} type="button"
|
||||
variant={model.selected?.key === page.key ? 'secondary' : 'ghost'}
|
||||
className={`w-full h-10 ${collapsed ? 'justify-center p-0' : 'justify-start gap-3'} ${model.selected?.key === page.key ? 'bg-foreground/10 text-foreground hover:bg-foreground/15 border-border/40' : ''}`}
|
||||
title={`${page.title} — ${page.pluginName}`}
|
||||
aria-label={`${page.title} — ${page.pluginName}`}
|
||||
aria-current={model.selected?.key === page.key ? 'page' : undefined}
|
||||
onMouseEnter={preloadPluginHostDrawnPage}
|
||||
onFocus={preloadPluginHostDrawnPage}
|
||||
onClick={() => model.select(page.key)}>
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={16} className="shrink-0" />
|
||||
{!collapsed && <span className="truncate">{page.title}</span>}
|
||||
</Button>)}
|
||||
{model.pages.map((page) => {
|
||||
const rawBadge = badgesByViewId.get(page.viewId);
|
||||
const activeBadge = isPluginViewBadgeVisible(rawBadge) ? rawBadge : null;
|
||||
const badgeLabel = formatPluginViewBadgeLabel(activeBadge);
|
||||
const badgeAria = formatPluginViewBadgeAriaText(activeBadge);
|
||||
const baseLabel = `${page.title} — ${page.pluginName}`;
|
||||
const title = activeBadge?.tooltip
|
||||
? `${baseLabel} · ${activeBadge.tooltip}`
|
||||
: badgeLabel
|
||||
? `${baseLabel} (${badgeLabel})`
|
||||
: baseLabel;
|
||||
const ariaLabel = badgeAria ? `${baseLabel} (${badgeAria})` : baseLabel;
|
||||
return <Button key={page.key} type="button"
|
||||
variant={model.selected?.key === page.key ? 'secondary' : 'ghost'}
|
||||
className={`w-full h-10 ${collapsed ? 'justify-center p-0' : 'justify-start gap-3'} ${model.selected?.key === page.key ? 'bg-foreground/10 text-foreground hover:bg-foreground/15 border-border/40' : ''}`}
|
||||
title={title}
|
||||
aria-label={ariaLabel}
|
||||
aria-current={model.selected?.key === page.key ? 'page' : undefined}
|
||||
onMouseEnter={() => prewarmPluginView(page.viewId)}
|
||||
onFocus={() => prewarmPluginView(page.viewId)}
|
||||
onClick={() => model.select(page.key)}>
|
||||
<span className="relative inline-flex shrink-0 items-center justify-center">
|
||||
<PluginContributionIcon pluginId={page.pluginId} icon={page.icon} size={16} className="shrink-0" />
|
||||
{collapsed && activeBadge && <PluginViewBadge badge={activeBadge} variant="overlay" />}
|
||||
</span>
|
||||
{!collapsed && <span className="min-w-0 flex-1 truncate text-left">{page.title}</span>}
|
||||
{!collapsed && activeBadge && <PluginViewBadge badge={activeBadge} variant="inline" />}
|
||||
</Button>;
|
||||
})}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function PluginVaultPage({ model }: { model: VaultPages }) {
|
||||
const { t } = useI18n();
|
||||
const page = model.selected!;
|
||||
return <section className="flex min-h-0 flex-1 flex-col" aria-label={page.title} data-plugin-vault-page={page.key}>
|
||||
<LazyPluginHostDrawnPage pluginId={page.pluginId} viewId={page.viewId} version={page.version} slot="vault-page" active={model.active} context={model.context}
|
||||
subscribeHidden={subscribeHidden} unavailable={model.fallback} loadingLabel={t('plugins.vault.loading')} />
|
||||
const [aiSidebarOpen, setAiSidebarOpen] = useState(false);
|
||||
const [aiSidebarMounted, setAiSidebarMounted] = useState(false);
|
||||
const [pendingPrompt, setPendingPrompt] = useState<PendingPluginSidebarPrompt | null>(null);
|
||||
const activeRef = useRef(model.active);
|
||||
activeRef.current = model.active;
|
||||
|
||||
const handleSidebarCommand = useCallback((command: NetcattyPluginAiSidebarCommand) => {
|
||||
if (command.action === 'close') {
|
||||
setAiSidebarOpen(false);
|
||||
return;
|
||||
}
|
||||
if (command.action === 'open') {
|
||||
if (!activeRef.current) return;
|
||||
setAiSidebarMounted(true);
|
||||
setAiSidebarOpen(true);
|
||||
if (command.prompt && command.prompt.trim()) {
|
||||
setPendingPrompt({
|
||||
id: nextPluginPromptId++,
|
||||
prompt: command.prompt.trim(),
|
||||
autoSend: command.autoSend,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const { turnContext, suggestedPrompts } = usePluginAiSidebarForView({
|
||||
pluginId: page.pluginId,
|
||||
pluginName: page.pluginName,
|
||||
viewId: page.viewId,
|
||||
enabled: true,
|
||||
onCommand: handleSidebarCommand,
|
||||
});
|
||||
|
||||
// Top-bar Sparkles AI button toggles the contextual Catty AI sidebar while this plugin page is active.
|
||||
useEffect(() => {
|
||||
if (!model.active) return;
|
||||
const handleToggleAi = (event: Event) => {
|
||||
event.preventDefault();
|
||||
setAiSidebarMounted(true);
|
||||
setAiSidebarOpen((prev) => !prev);
|
||||
};
|
||||
window.addEventListener('netcatty:toggle-ai-panel', handleToggleAi, { capture: true });
|
||||
return () => window.removeEventListener('netcatty:toggle-ai-panel', handleToggleAi, { capture: true });
|
||||
}, [model.active]);
|
||||
|
||||
const handleCloseAiSidebar = useCallback(() => {
|
||||
setAiSidebarOpen(false);
|
||||
}, []);
|
||||
|
||||
const handlePendingPromptConsumed = useCallback((id: number) => {
|
||||
setPendingPrompt((prev) => (prev?.id === id ? null : prev));
|
||||
}, []);
|
||||
|
||||
return <section className="flex min-h-0 flex-1 flex-row overflow-hidden" aria-label={page.title} data-plugin-vault-page={page.key}>
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<LazyPluginHostDrawnPage pluginId={page.pluginId} viewId={page.viewId} version={page.version} slot="vault-page" active={model.active} context={model.context}
|
||||
subscribeHidden={subscribeHidden} unavailable={model.fallback} loadingLabel={t('plugins.vault.loading')} />
|
||||
</div>
|
||||
{aiSidebarMounted && (
|
||||
<PluginVaultAISidebar
|
||||
pluginId={page.pluginId}
|
||||
pluginName={page.pluginName}
|
||||
viewId={page.viewId}
|
||||
open={aiSidebarOpen}
|
||||
onClose={handleCloseAiSidebar}
|
||||
pluginContext={turnContext}
|
||||
suggestedPrompts={suggestedPrompts}
|
||||
pendingPrompt={pendingPrompt}
|
||||
onPendingPromptConsumed={handlePendingPromptConsumed}
|
||||
/>
|
||||
)}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
formatPluginViewBadgeLabel,
|
||||
isPluginViewBadgeVisible,
|
||||
type PluginViewBadgeDisplay,
|
||||
type PluginViewBadgeTone,
|
||||
} from '../../domain/pluginViewBadge';
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
const TONE_CLASSES: Record<PluginViewBadgeTone, string> = {
|
||||
default: 'bg-primary text-primary-foreground',
|
||||
info: 'bg-sky-600 text-white dark:bg-sky-500 dark:text-white',
|
||||
warning: 'bg-amber-500 text-zinc-950',
|
||||
danger: 'bg-red-500 text-white dark:bg-red-500 dark:text-white',
|
||||
};
|
||||
|
||||
export interface PluginViewBadgeProps {
|
||||
badge: PluginViewBadgeDisplay | null | undefined;
|
||||
/**
|
||||
* - `inline`: expanded left sidebar row pill/dot aligned right
|
||||
* - `overlay`: collapsed left sidebar icon rail corner badge
|
||||
* - `compact-overlay`: compact 24px terminal sidebar launcher corner badge
|
||||
*/
|
||||
variant: 'inline' | 'overlay' | 'compact-overlay';
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const PluginViewBadge: React.FC<PluginViewBadgeProps> = ({
|
||||
badge,
|
||||
variant,
|
||||
className,
|
||||
}) => {
|
||||
if (!isPluginViewBadgeVisible(badge)) return null;
|
||||
const label = formatPluginViewBadgeLabel(badge);
|
||||
const toneClass = TONE_CLASSES[badge.tone] ?? TONE_CLASSES.default;
|
||||
|
||||
if (label === null) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-plugin-view-badge="dot"
|
||||
data-plugin-view-badge-tone={badge.tone}
|
||||
className={cn(
|
||||
'pointer-events-none shrink-0 rounded-full',
|
||||
toneClass,
|
||||
variant === 'inline' && 'ml-auto h-2 w-2',
|
||||
variant === 'overlay' && 'absolute -top-0.5 -right-0.5 h-2 w-2 ring-2 ring-secondary',
|
||||
variant === 'compact-overlay' && 'absolute -top-0.5 -right-0.5 h-1.5 w-1.5 ring-1 ring-background',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
data-plugin-view-badge={label}
|
||||
data-plugin-view-badge-tone={badge.tone}
|
||||
className={cn(
|
||||
'pointer-events-none shrink-0 inline-flex items-center justify-center rounded-full font-semibold leading-none tabular-nums select-none',
|
||||
toneClass,
|
||||
variant === 'inline' && 'ml-auto min-w-[18px] h-[18px] px-1.5 text-[10px]',
|
||||
variant === 'overlay' && 'absolute -top-1.5 -right-2 min-w-[15px] h-[15px] px-1 text-[9px] font-bold ring-2 ring-secondary',
|
||||
variant === 'compact-overlay' && 'absolute -top-1 -right-1 min-w-[13px] h-[13px] px-0.5 text-[8px] font-bold ring-1 ring-background',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,195 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
function installDom() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
|
||||
pretendToBeVisual: true,
|
||||
url: 'http://localhost',
|
||||
});
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
const install = (key: string, value: unknown) => {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
};
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'HTMLButtonElement',
|
||||
'Element',
|
||||
'SVGElement',
|
||||
'Node',
|
||||
'NodeFilter',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'KeyboardEvent',
|
||||
'MouseEvent',
|
||||
'XMLSerializer',
|
||||
]) {
|
||||
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
|
||||
}
|
||||
install('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
install('getComputedStyle', dom.window.getComputedStyle.bind(dom.window));
|
||||
install('IS_REACT_ACT_ENVIRONMENT', true);
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => new dom.window.DOMRect(0, 0, 640, 320);
|
||||
|
||||
return {
|
||||
dom,
|
||||
cleanup() {
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('PluginBiChart renders all 10 chart types, supports datumClick cross-filtering, legend toggle, activeFilter, and SVG export', async () => {
|
||||
const env = installDom();
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginBiChart, formatBiValue } = await import('./PluginBiChart');
|
||||
|
||||
assert.equal(formatBiValue(12500, 'currency', 'USD'), '$12.5K');
|
||||
assert.equal(formatBiValue(0.425, 'percent'), '42.5%');
|
||||
assert.equal(formatBiValue(2048, 'bytes'), '2.0 KiB');
|
||||
assert.equal(formatBiValue(1500, 'ms'), '1.50 s');
|
||||
assert.equal(formatBiValue(Number.NaN), '--');
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const events: Array<{ name: string; detail?: Record<string, unknown> }> = [];
|
||||
const onWidgetEvent = (name: string, detail?: Record<string, unknown>) => {
|
||||
events.push({ name, detail });
|
||||
};
|
||||
|
||||
try {
|
||||
const cartesianTypes = ['bar', 'horizontal-bar', 'stacked-bar', 'line', 'area', 'combo'] as const;
|
||||
for (const type of cartesianTypes) {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type={type}
|
||||
title={`Test ${type}`}
|
||||
categories={['APAC', 'EMEA', 'NA']}
|
||||
series={[
|
||||
{ id: 'rev', name: 'Revenue', data: [1200, 1800, 2400], renderAs: 'bar', yAxis: 'left', color: 'sky', format: 'currency', currency: 'USD' },
|
||||
{ id: 'orders', name: 'Orders', data: [42, 68, 95], renderAs: 'line', yAxis: 'right', color: 'amber', format: 'compact' },
|
||||
]}
|
||||
xAxisLabel="Region"
|
||||
yAxisLabel="Revenue"
|
||||
yAxisRightLabel="Orders"
|
||||
showDataLabels
|
||||
smooth
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
assert.ok(document.querySelector(`[data-plugin-bi-chart="${type}"] svg`), `${type} should render an SVG`);
|
||||
assert.ok(document.querySelector('[data-bi-datum="0:1"]'), `${type} should render clickable datum markers`);
|
||||
}
|
||||
|
||||
// Click datum on combo chart and verify cross-filter event payload
|
||||
events.length = 0;
|
||||
const datum = document.querySelector<SVGElement>('[data-bi-datum="0:1"]')!;
|
||||
await act(async () => {
|
||||
datum.dispatchEvent(new env.dom.window.MouseEvent('click', { bubbles: true }));
|
||||
});
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].name, 'datumClick');
|
||||
assert.deepEqual(events[0].detail, {
|
||||
seriesIndex: 0,
|
||||
seriesName: 'Revenue',
|
||||
datumIndex: 1,
|
||||
category: 'EMEA',
|
||||
value: 1800,
|
||||
});
|
||||
|
||||
// Toggle legend series locally and verify series hides
|
||||
const legendBtn = document.querySelector<HTMLButtonElement>('[data-bi-legend-series="orders"]')!;
|
||||
assert.equal(legendBtn.getAttribute('aria-pressed'), 'true');
|
||||
await act(async () => {
|
||||
legendBtn.click();
|
||||
});
|
||||
assert.equal(legendBtn.getAttribute('aria-pressed'), 'false');
|
||||
|
||||
// Pie, Donut, Funnel, Scatter + activeFilter dimming + SVG export
|
||||
for (const type of ['pie', 'donut', 'funnel'] as const) {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type={type}
|
||||
title={`Test ${type}`}
|
||||
categories={['Visited', 'Signed Up', 'Paid']}
|
||||
series={[{ id: 's', name: 'Users', data: [1000, 420, 110] }]}
|
||||
activeFilter={{ category: 'Signed Up' }}
|
||||
showDataLabels
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const matchedEl = document.querySelector<SVGElement>('[data-bi-datum="0:1"]')!;
|
||||
const dimmedEl = document.querySelector<SVGElement>('[data-bi-datum="0:0"]')!;
|
||||
assert.ok(Number(matchedEl.getAttribute('opacity')) > 0.8, `${type} matched datum stays bright`);
|
||||
assert.ok(Number(dimmedEl.getAttribute('opacity')) < 0.4, `${type} non-matched datum dims`);
|
||||
}
|
||||
|
||||
// Scatter with bubble size + NaN/Infinity filtering
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type="scatter"
|
||||
title="Latency vs Throughput"
|
||||
series={[
|
||||
{
|
||||
id: 'nodes',
|
||||
name: 'Nodes',
|
||||
points: [
|
||||
{ x: 10, y: 200, label: 'node-a', size: 8 },
|
||||
{ x: Number.NaN, y: 100, label: 'bad' },
|
||||
{ x: 25, y: 450, label: 'node-b', size: 99 },
|
||||
],
|
||||
},
|
||||
]}
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
const scatterDots = document.querySelectorAll('[data-bi-datum]');
|
||||
assert.equal(scatterDots.length, 2, 'scatter filters out non-finite points');
|
||||
assert.equal(scatterDots[1].getAttribute('r'), '14', 'bubble radius clamps at 14');
|
||||
|
||||
// Export SVG emits bounded standalone SVG string
|
||||
events.length = 0;
|
||||
const exportSvgBtn = document.querySelector<HTMLButtonElement>('[data-bi-export-svg]')!;
|
||||
await act(async () => {
|
||||
exportSvgBtn.click();
|
||||
});
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].name, 'exportSvg');
|
||||
assert.match(String(events[0].detail?.svg), /^<svg[^>]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
|
||||
assert.equal(events[0].detail?.suggestedName, 'latency-vs-throughput.svg');
|
||||
|
||||
// Empty state
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginBiChart
|
||||
type="bar"
|
||||
categories={[]}
|
||||
series={[]}
|
||||
emptyText="Nothing to chart"
|
||||
onWidgetEvent={onWidgetEvent}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
assert.match(document.body.textContent ?? '', /Nothing to chart/);
|
||||
} finally {
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,17 @@ import React, { Suspense, lazy } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import type { PluginCodeEditorWidgetProps, PluginWidgetEventCallback } from './types';
|
||||
|
||||
const LazyPluginCodeEditorInner = lazy(() => import('./PluginCodeEditorInner'));
|
||||
let preloadEditorPromise: Promise<unknown> | null = null;
|
||||
const loadPluginCodeEditorInner = () => {
|
||||
preloadEditorPromise ??= import('./PluginCodeEditorInner');
|
||||
return preloadEditorPromise as Promise<{ default: typeof import('./PluginCodeEditorInner').default }>;
|
||||
};
|
||||
|
||||
export function preloadPluginCodeEditor(): void {
|
||||
void loadPluginCodeEditorInner().catch(() => { preloadEditorPromise = null; });
|
||||
}
|
||||
|
||||
const LazyPluginCodeEditorInner = lazy(loadPluginCodeEditorInner);
|
||||
|
||||
export interface PluginCodeEditorProps extends PluginCodeEditorWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { PluginMetricChart, formatMetricValue } from './PluginMetricChart';
|
||||
|
||||
test('PluginMetricChart renders area, sparkline, bar, thresholds, and bounds extreme input safely', () => {
|
||||
const now = 1_700_000_000_000;
|
||||
const html = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'area',
|
||||
height: 160,
|
||||
rangeMs: 300_000,
|
||||
intervalMs: 5_000,
|
||||
endAt: now,
|
||||
showLegend: true,
|
||||
showAxes: true,
|
||||
thresholds: [
|
||||
{ value: 80, tone: 'warning', label: 'Warn' },
|
||||
{ value: 95, tone: 'critical', label: 'Crit' },
|
||||
],
|
||||
series: [
|
||||
{
|
||||
id: 'cpu',
|
||||
label: 'CPU',
|
||||
color: 'sky',
|
||||
unit: '%',
|
||||
points: [
|
||||
{ at: now - 15_000, value: 22.5 },
|
||||
{ at: now - 10_000, value: 48.2 },
|
||||
{ at: now - 5_000, value: null },
|
||||
{ at: now, value: 64.0 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'mem',
|
||||
label: 'Memory',
|
||||
color: 'emerald',
|
||||
unit: '%',
|
||||
points: [
|
||||
{ at: now - 15_000, value: 51 },
|
||||
{ at: now, value: 53 },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
assert.match(html, /role="img"/);
|
||||
assert.match(html, /<svg/);
|
||||
assert.match(html, /CPU/);
|
||||
assert.match(html, /64\.0%/);
|
||||
assert.match(html, /Warn/);
|
||||
assert.match(html, /Crit/);
|
||||
|
||||
const sparkHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'sparkline',
|
||||
height: 36,
|
||||
series: [{ id: 'rx', label: 'RX', unit: 'bytes/s', points: [{ at: now - 5000, value: 1024 }, { at: now, value: 4096 }] }],
|
||||
}),
|
||||
);
|
||||
assert.match(sparkHtml, /<svg/);
|
||||
assert.match(sparkHtml, /height:36px/);
|
||||
|
||||
const barHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'bar',
|
||||
series: [{ id: 'load', label: 'Load', unit: 'count', points: [{ at: now - 5000, value: 2 }, { at: now, value: 5 }] }],
|
||||
}),
|
||||
);
|
||||
assert.match(barHtml, /<rect/);
|
||||
|
||||
// Empty state
|
||||
const emptyHtml = renderToStaticMarkup(
|
||||
React.createElement(PluginMetricChart, {
|
||||
variant: 'line',
|
||||
series: [{ id: 'empty', label: 'Empty', points: [] }],
|
||||
emptyText: 'No metrics yet',
|
||||
}),
|
||||
);
|
||||
assert.match(emptyHtml, /No metrics yet/);
|
||||
});
|
||||
|
||||
test('formatMetricValue formats percent, bytes/s, ms, temp, and count cleanly', () => {
|
||||
assert.equal(formatMetricValue(null, '%'), '--');
|
||||
assert.equal(formatMetricValue(42.34, '%'), '42.3%');
|
||||
assert.equal(formatMetricValue(100, '%'), '100%');
|
||||
assert.equal(formatMetricValue(2048, 'bytes/s'), '2.0 KiB/s');
|
||||
assert.equal(formatMetricValue(3 * 1024 * 1024, 'bytes/s'), '3.0 MiB/s');
|
||||
assert.equal(formatMetricValue(42, 'ms'), '42 ms');
|
||||
assert.equal(formatMetricValue(1500, 'ms'), '1.50 s');
|
||||
assert.equal(formatMetricValue(63.4, 'temp'), '63.4 C');
|
||||
assert.equal(formatMetricValue(2500, 'count'), '2.5k');
|
||||
});
|
||||
@@ -0,0 +1,722 @@
|
||||
import React, { useId, useMemo, useRef, useState, useEffect, useCallback } from 'react';
|
||||
import type {
|
||||
PluginMetricChartColor,
|
||||
PluginMetricChartPoint,
|
||||
PluginMetricChartSeries,
|
||||
PluginMetricChartThreshold,
|
||||
PluginMetricChartUnit,
|
||||
PluginMetricChartWidgetProps,
|
||||
} from './types';
|
||||
|
||||
const MAX_SERIES = 16;
|
||||
const MAX_POINTS_PER_SERIES = 2000;
|
||||
const MAX_THRESHOLDS = 8;
|
||||
const MIN_HEIGHT = 24;
|
||||
const MAX_HEIGHT = 480;
|
||||
const DEFAULT_WIDTH = 360;
|
||||
const DOWNSAMPLE_BUCKETS = 180;
|
||||
|
||||
const COLOR_MAP: Record<PluginMetricChartColor, string> = {
|
||||
primary: 'hsl(var(--primary))',
|
||||
sky: '#0ea5e9',
|
||||
emerald: '#10b981',
|
||||
amber: '#f59e0b',
|
||||
violet: '#8b5cf6',
|
||||
rose: '#f43f5e',
|
||||
cyan: '#06b6d4',
|
||||
muted: 'hsl(var(--muted-foreground))',
|
||||
};
|
||||
|
||||
const DEFAULT_COLOR_CYCLE: PluginMetricChartColor[] = [
|
||||
'sky',
|
||||
'emerald',
|
||||
'amber',
|
||||
'violet',
|
||||
'rose',
|
||||
'cyan',
|
||||
'primary',
|
||||
'muted',
|
||||
];
|
||||
|
||||
function resolveColor(color: PluginMetricChartColor | undefined, index: number): string {
|
||||
if (color && Object.hasOwn(COLOR_MAP, color)) {
|
||||
return COLOR_MAP[color];
|
||||
}
|
||||
return COLOR_MAP[DEFAULT_COLOR_CYCLE[index % DEFAULT_COLOR_CYCLE.length]];
|
||||
}
|
||||
|
||||
export function formatMetricValue(value: number | null | undefined, unit: PluginMetricChartUnit = ''): string {
|
||||
if (value == null || !Number.isFinite(value)) return '--';
|
||||
if (unit === '%') {
|
||||
return `${value.toFixed(value >= 100 || value === 0 ? 0 : 1)}%`;
|
||||
}
|
||||
if (unit === 'ms') {
|
||||
return value >= 1000 ? `${(value / 1000).toFixed(2)} s` : `${Math.round(value)} ms`;
|
||||
}
|
||||
if (unit === 'temp') {
|
||||
return `${value.toFixed(1)} C`;
|
||||
}
|
||||
if (unit === 'bytes/s' || unit === 'bytes') {
|
||||
const suffix = unit === 'bytes/s' ? '/s' : '';
|
||||
const abs = Math.abs(value);
|
||||
if (abs >= 1024 ** 3) return `${(value / (1024 ** 3)).toFixed(2)} GiB${suffix}`;
|
||||
if (abs >= 1024 ** 2) return `${(value / (1024 ** 2)).toFixed(1)} MiB${suffix}`;
|
||||
if (abs >= 1024) return `${(value / 1024).toFixed(1)} KiB${suffix}`;
|
||||
return `${Math.round(value)} B${suffix}`;
|
||||
}
|
||||
if (unit === 'count') {
|
||||
if (Math.abs(value) >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
||||
if (Math.abs(value) >= 1_000) return `${(value / 1_000).toFixed(1)}k`;
|
||||
return Number.isInteger(value) ? String(value) : value.toFixed(1);
|
||||
}
|
||||
return Math.abs(value) >= 100 ? value.toFixed(0) : value.toFixed(1);
|
||||
}
|
||||
|
||||
function formatClockTime(epochMs: number): string {
|
||||
if (!Number.isFinite(epochMs)) return '';
|
||||
const date = new Date(epochMs);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
const ss = String(date.getSeconds()).padStart(2, '0');
|
||||
return `${hh}:${mm}:${ss}`;
|
||||
}
|
||||
|
||||
interface CleanSeries {
|
||||
id: string;
|
||||
label: string;
|
||||
color: string;
|
||||
unit: PluginMetricChartUnit;
|
||||
points: Array<{ at: number; value: number | null }>;
|
||||
latestValue: number | null;
|
||||
}
|
||||
|
||||
interface PlotSegment {
|
||||
linePath: string;
|
||||
areaPath: string;
|
||||
lastX: number;
|
||||
lastY: number;
|
||||
}
|
||||
|
||||
function sanitizeSeries(raw: PluginMetricChartSeries[] | undefined): CleanSeries[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
const limited = raw.slice(0, MAX_SERIES);
|
||||
const seenIds = new Set<string>();
|
||||
return limited
|
||||
.filter((item): item is PluginMetricChartSeries => Boolean(item && typeof item === 'object'))
|
||||
.map((item, idx) => {
|
||||
const rawPoints = Array.isArray(item.points) ? item.points.slice(-MAX_POINTS_PER_SERIES) : [];
|
||||
const points: Array<{ at: number; value: number | null }> = [];
|
||||
for (const pt of rawPoints) {
|
||||
if (!pt || typeof pt !== 'object' || typeof pt.at !== 'number' || !Number.isFinite(pt.at)) continue;
|
||||
const val = typeof pt.value === 'number' && Number.isFinite(pt.value) ? pt.value : null;
|
||||
points.push({ at: pt.at, value: val });
|
||||
}
|
||||
points.sort((a, b) => a.at - b.at);
|
||||
let latestValue: number | null = null;
|
||||
for (let i = points.length - 1; i >= 0; i -= 1) {
|
||||
if (points[i].value !== null) {
|
||||
latestValue = points[i].value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const baseId = typeof item.id === 'string' && item.id ? item.id : `series-${idx}`;
|
||||
const uniqueId = seenIds.has(baseId) ? `${baseId}-${idx}` : baseId;
|
||||
seenIds.add(uniqueId);
|
||||
return {
|
||||
id: uniqueId,
|
||||
label: typeof item.label === 'string' && item.label ? item.label : `Series ${idx + 1}`,
|
||||
color: resolveColor(item.color, idx),
|
||||
unit: item.unit ?? '',
|
||||
points,
|
||||
latestValue,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function sanitizeThresholds(raw: PluginMetricChartThreshold[] | undefined): PluginMetricChartThreshold[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw
|
||||
.slice(0, MAX_THRESHOLDS)
|
||||
.filter(
|
||||
(t): t is PluginMetricChartThreshold =>
|
||||
Boolean(t && typeof t === 'object' && typeof t.value === 'number' && Number.isFinite(t.value) && (t.tone === 'warning' || t.tone === 'critical')),
|
||||
);
|
||||
}
|
||||
|
||||
function buildSegments(
|
||||
points: PluginMetricChartPoint[],
|
||||
startAt: number,
|
||||
endAt: number,
|
||||
yMin: number,
|
||||
yMax: number,
|
||||
gapThresholdMs: number,
|
||||
plotLeft: number,
|
||||
plotTop: number,
|
||||
plotWidth: number,
|
||||
plotHeight: number,
|
||||
): PlotSegment[] {
|
||||
const spanX = Math.max(1, endAt - startAt);
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
const visible = points.filter((p) => p.at >= startAt && p.at <= endAt);
|
||||
|
||||
const runs: Array<Array<{ at: number; value: number }>> = [];
|
||||
let currentRun: Array<{ at: number; value: number }> = [];
|
||||
for (const pt of visible) {
|
||||
if (pt.value === null || !Number.isFinite(pt.value)) {
|
||||
if (currentRun.length > 0) {
|
||||
runs.push(currentRun);
|
||||
currentRun = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (currentRun.length > 0 && pt.at - currentRun[currentRun.length - 1].at > gapThresholdMs) {
|
||||
runs.push(currentRun);
|
||||
currentRun = [];
|
||||
}
|
||||
currentRun.push({ at: pt.at, value: pt.value });
|
||||
}
|
||||
if (currentRun.length > 0) runs.push(currentRun);
|
||||
|
||||
const baseY = plotTop + plotHeight;
|
||||
return runs.map((samples) => {
|
||||
const selected = new Set([samples[0], samples[samples.length - 1]]);
|
||||
if (samples.length > DOWNSAMPLE_BUCKETS) {
|
||||
const buckets = new Map<number, { min: (typeof samples)[number]; max: (typeof samples)[number] }>();
|
||||
for (const sample of samples) {
|
||||
const col = Math.min(DOWNSAMPLE_BUCKETS - 1, Math.max(0, Math.floor(((sample.at - startAt) / spanX) * DOWNSAMPLE_BUCKETS)));
|
||||
const bucket = buckets.get(col);
|
||||
if (!bucket) {
|
||||
buckets.set(col, { min: sample, max: sample });
|
||||
} else {
|
||||
if (sample.value < bucket.min.value) bucket.min = sample;
|
||||
if (sample.value > bucket.max.value) bucket.max = sample;
|
||||
}
|
||||
}
|
||||
for (const bucket of buckets.values()) {
|
||||
selected.add(bucket.min);
|
||||
selected.add(bucket.max);
|
||||
}
|
||||
} else {
|
||||
for (const sample of samples) selected.add(sample);
|
||||
}
|
||||
|
||||
const coords = samples
|
||||
.filter((sample) => selected.has(sample))
|
||||
.map((sample) => {
|
||||
const ratioX = Math.max(0, Math.min(1, (sample.at - startAt) / spanX));
|
||||
const clampedY = Math.max(yMin, Math.min(yMax, sample.value));
|
||||
const ratioY = (clampedY - yMin) / spanY;
|
||||
return {
|
||||
x: plotLeft + ratioX * plotWidth,
|
||||
y: plotTop + plotHeight - ratioY * plotHeight,
|
||||
};
|
||||
});
|
||||
|
||||
const linePath = coords
|
||||
.map((pt, i) => `${i === 0 ? 'M' : 'L'} ${pt.x.toFixed(2)} ${pt.y.toFixed(2)}`)
|
||||
.join(' ');
|
||||
const first = coords[0];
|
||||
const last = coords[coords.length - 1];
|
||||
const areaPath = coords.length > 1
|
||||
? `${linePath} L ${last.x.toFixed(2)} ${baseY.toFixed(2)} L ${first.x.toFixed(2)} ${baseY.toFixed(2)} Z`
|
||||
: '';
|
||||
return { linePath, areaPath, lastX: last.x, lastY: last.y };
|
||||
});
|
||||
}
|
||||
|
||||
export function PluginMetricChart(props: PluginMetricChartWidgetProps) {
|
||||
const uid = useId().replace(/[^a-zA-Z0-9_-]/g, '');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState<number>(DEFAULT_WIDTH);
|
||||
const [hoverX, setHoverX] = useState<number | null>(null);
|
||||
|
||||
const variant = props.variant ?? 'area';
|
||||
const isSparkline = variant === 'sparkline';
|
||||
const showAxes = props.showAxes ?? !isSparkline;
|
||||
const showGrid = props.showGrid ?? !isSparkline;
|
||||
const showLegend = props.showLegend ?? (!isSparkline && (props.series?.length ?? 0) > 1);
|
||||
const interactive = props.interactive ?? !isSparkline;
|
||||
const chartHeight = Math.max(
|
||||
MIN_HEIGHT,
|
||||
Math.min(MAX_HEIGHT, typeof props.height === 'number' && Number.isFinite(props.height) ? props.height : (isSparkline ? 40 : 160)),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
const updateWidth = () => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width > 16) setWidth(Math.round(rect.width));
|
||||
};
|
||||
updateWidth();
|
||||
if (typeof ResizeObserver === 'function') {
|
||||
const observer = new ResizeObserver(updateWidth);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}
|
||||
return undefined;
|
||||
}, []);
|
||||
|
||||
const series = useMemo(() => sanitizeSeries(props.series), [props.series]);
|
||||
const thresholds = useMemo(() => sanitizeThresholds(props.thresholds), [props.thresholds]);
|
||||
|
||||
const { startAt, endAt, yMin, yMax, hasData, primaryUnit } = useMemo(() => {
|
||||
let minAt = Infinity;
|
||||
let maxAt = -Infinity;
|
||||
let maxVal = -Infinity;
|
||||
let minVal = Infinity;
|
||||
let dataPoints = 0;
|
||||
|
||||
for (const s of series) {
|
||||
for (const p of s.points) {
|
||||
if (p.at < minAt) minAt = p.at;
|
||||
if (p.at > maxAt) maxAt = p.at;
|
||||
if (p.value !== null) {
|
||||
dataPoints += 1;
|
||||
if (p.value > maxVal) maxVal = p.value;
|
||||
if (p.value < minVal) minVal = p.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedEnd = typeof props.endAt === 'number' && Number.isFinite(props.endAt)
|
||||
? props.endAt
|
||||
: (Number.isFinite(maxAt) ? maxAt : Date.now());
|
||||
const rawDataSpan = Number.isFinite(minAt) && resolvedEnd > minAt ? resolvedEnd - minAt : NaN;
|
||||
const resolvedRange = typeof props.rangeMs === 'number' && Number.isFinite(props.rangeMs) && props.rangeMs > 0
|
||||
? props.rangeMs
|
||||
: (Number.isFinite(rawDataSpan) ? Math.max(1000, rawDataSpan) : 5 * 60_000);
|
||||
const candidateStart = resolvedEnd - resolvedRange;
|
||||
const resolvedStart = Number.isFinite(candidateStart) && Number.isFinite(resolvedEnd - candidateStart)
|
||||
? candidateStart
|
||||
: resolvedEnd - 5 * 60_000;
|
||||
|
||||
const unit = series[0]?.unit ?? '';
|
||||
const rawMin = typeof props.min === 'number' && Number.isFinite(props.min)
|
||||
? props.min
|
||||
: (Number.isFinite(minVal) && minVal < 0 ? (Number.isFinite(minVal * 1.1) ? minVal * 1.1 : minVal) : 0);
|
||||
let resolvedMin = Number.isFinite(rawMin) ? rawMin : 0;
|
||||
|
||||
let resolvedMax: number;
|
||||
if (typeof props.max === 'number' && Number.isFinite(props.max)) {
|
||||
resolvedMax = props.max;
|
||||
} else if (unit === '%' && (!Number.isFinite(maxVal) || maxVal <= 100)) {
|
||||
resolvedMax = 100;
|
||||
} else {
|
||||
let peak = Number.isFinite(maxVal) ? maxVal : 1;
|
||||
for (const t of thresholds) {
|
||||
if (t.value > peak) peak = t.value;
|
||||
}
|
||||
if (peak <= resolvedMin) {
|
||||
const padded = resolvedMin + (unit === 'ms' ? 10 : 1);
|
||||
resolvedMax = Number.isFinite(padded) ? padded : resolvedMin;
|
||||
} else {
|
||||
const paddedPeak = peak * 1.1;
|
||||
resolvedMax = Number.isFinite(paddedPeak) ? paddedPeak : peak;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isFinite(resolvedMax - resolvedMin) || resolvedMax <= resolvedMin) {
|
||||
resolvedMin = 0;
|
||||
resolvedMax = 100;
|
||||
}
|
||||
|
||||
return {
|
||||
startAt: resolvedStart,
|
||||
endAt: resolvedEnd,
|
||||
yMin: resolvedMin,
|
||||
yMax: resolvedMax,
|
||||
hasData: dataPoints > 0,
|
||||
primaryUnit: unit,
|
||||
};
|
||||
}, [series, thresholds, props.endAt, props.rangeMs, props.min, props.max]);
|
||||
|
||||
const gapThresholdMs = useMemo(() => {
|
||||
const interval = typeof props.intervalMs === 'number' && Number.isFinite(props.intervalMs) && props.intervalMs > 0
|
||||
? props.intervalMs
|
||||
: 5000;
|
||||
return Math.max(5000, interval * 2.5);
|
||||
}, [props.intervalMs]);
|
||||
|
||||
const padLeft = showAxes ? 52 : (isSparkline ? 2 : 8);
|
||||
const padRight = showAxes ? 12 : (isSparkline ? 2 : 8);
|
||||
const padTop = isSparkline ? 3 : 10;
|
||||
const padBottom = showAxes ? 22 : (isSparkline ? 3 : 8);
|
||||
const svgHeight = Math.max(20, chartHeight - (showLegend ? 24 : 0));
|
||||
const plotWidth = Math.max(20, width - padLeft - padRight);
|
||||
const plotHeight = Math.max(12, svgHeight - padTop - padBottom);
|
||||
|
||||
const seriesSegments = useMemo(() => (
|
||||
series.map((s) => ({
|
||||
series: s,
|
||||
segments: buildSegments(
|
||||
s.points,
|
||||
startAt,
|
||||
endAt,
|
||||
yMin,
|
||||
yMax,
|
||||
gapThresholdMs,
|
||||
padLeft,
|
||||
padTop,
|
||||
plotWidth,
|
||||
plotHeight,
|
||||
),
|
||||
}))
|
||||
), [series, startAt, endAt, yMin, yMax, gapThresholdMs, padLeft, padTop, plotWidth, plotHeight]);
|
||||
|
||||
const hoverSnapshot = useMemo(() => {
|
||||
if (!interactive || hoverX === null || !hasData) return null;
|
||||
const ratio = Math.max(0, Math.min(1, (hoverX - padLeft) / plotWidth));
|
||||
const targetAt = startAt + ratio * (endAt - startAt);
|
||||
const tolerance = Math.max(gapThresholdMs, (endAt - startAt) * 0.04);
|
||||
|
||||
let snappedAt: number | null = null;
|
||||
const values: Array<{ id: string; label: string; color: string; value: number | null; unit: PluginMetricChartUnit; x: number; y: number | null }> = [];
|
||||
const spanX = Math.max(1, endAt - startAt);
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
|
||||
for (const s of series) {
|
||||
let closest: PluginMetricChartPoint | null = null;
|
||||
let bestDelta = tolerance;
|
||||
for (const pt of s.points) {
|
||||
if (pt.value === null || pt.at < startAt || pt.at > endAt) continue;
|
||||
const delta = Math.abs(pt.at - targetAt);
|
||||
if (delta <= bestDelta) {
|
||||
bestDelta = delta;
|
||||
closest = pt;
|
||||
}
|
||||
}
|
||||
if (closest && closest.value !== null) {
|
||||
if (snappedAt === null) snappedAt = closest.at;
|
||||
const rx = Math.max(0, Math.min(1, (closest.at - startAt) / spanX));
|
||||
const ry = (Math.max(yMin, Math.min(yMax, closest.value)) - yMin) / spanY;
|
||||
values.push({
|
||||
id: s.id,
|
||||
label: s.label,
|
||||
color: s.color,
|
||||
value: closest.value,
|
||||
unit: s.unit,
|
||||
x: padLeft + rx * plotWidth,
|
||||
y: padTop + plotHeight - ry * plotHeight,
|
||||
});
|
||||
} else {
|
||||
values.push({
|
||||
id: s.id,
|
||||
label: s.label,
|
||||
color: s.color,
|
||||
value: null,
|
||||
unit: s.unit,
|
||||
x: hoverX,
|
||||
y: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (snappedAt === null) return null;
|
||||
const snappedX = padLeft + Math.max(0, Math.min(1, (snappedAt - startAt) / spanX)) * plotWidth;
|
||||
return { at: snappedAt, x: snappedX, values };
|
||||
}, [interactive, hoverX, hasData, padLeft, padTop, plotWidth, plotHeight, startAt, endAt, yMin, yMax, gapThresholdMs, series]);
|
||||
|
||||
const handlePointerMove = useCallback((event: React.PointerEvent<SVGSVGElement>) => {
|
||||
if (!interactive) return;
|
||||
const rect = event.currentTarget.getBoundingClientRect();
|
||||
const x = event.clientX - rect.left;
|
||||
if (x >= padLeft && x <= padLeft + plotWidth) {
|
||||
setHoverX(x);
|
||||
} else {
|
||||
setHoverX(null);
|
||||
}
|
||||
}, [interactive, padLeft, plotWidth]);
|
||||
|
||||
const handlePointerLeave = useCallback(() => {
|
||||
setHoverX(null);
|
||||
}, []);
|
||||
|
||||
const yTicks = useMemo(() => {
|
||||
if (!showAxes) return [];
|
||||
const mid = yMin + (yMax - yMin) / 2;
|
||||
return [
|
||||
{ value: yMax, y: padTop },
|
||||
{ value: mid, y: padTop + plotHeight / 2 },
|
||||
{ value: yMin, y: padTop + plotHeight },
|
||||
];
|
||||
}, [showAxes, yMin, yMax, padTop, plotHeight]);
|
||||
|
||||
const xTicks = useMemo(() => {
|
||||
if (!showAxes) return [];
|
||||
const mid = startAt + (endAt - startAt) / 2;
|
||||
return [
|
||||
{ at: startAt, x: padLeft, anchor: 'start' as const },
|
||||
{ at: mid, x: padLeft + plotWidth / 2, anchor: 'middle' as const },
|
||||
{ at: endAt, x: padLeft + plotWidth, anchor: 'end' as const },
|
||||
];
|
||||
}, [showAxes, startAt, endAt, padLeft, plotWidth]);
|
||||
|
||||
const barItems = useMemo(() => {
|
||||
if (variant !== 'bar' || !hasData) return [];
|
||||
const timestamps = Array.from(
|
||||
new Set(
|
||||
series.flatMap((s) =>
|
||||
s.points
|
||||
.filter((p) => p.at >= startAt && p.at <= endAt && p.value !== null)
|
||||
.map((p) => p.at),
|
||||
),
|
||||
),
|
||||
).sort((a, b) => a - b);
|
||||
const maxGroups = Math.min(timestamps.length, 48);
|
||||
const step = timestamps.length > maxGroups ? Math.ceil(timestamps.length / maxGroups) : 1;
|
||||
const sampledTs = timestamps.filter((_ts, i) => i % step === 0);
|
||||
if (sampledTs.length === 0) return [];
|
||||
const groupWidth = Math.max(4, plotWidth / sampledTs.length);
|
||||
const innerWidth = Math.max(2, (groupWidth * 0.78) / Math.max(1, series.length));
|
||||
const spanY = Math.max(1e-9, yMax - yMin);
|
||||
const bars: Array<{ key: string; x: number; y: number; w: number; h: number; color: string }> = [];
|
||||
|
||||
sampledTs.forEach((ts, groupIdx) => {
|
||||
const groupStart = padLeft + groupIdx * groupWidth + groupWidth * 0.11;
|
||||
series.forEach((s, seriesIdx) => {
|
||||
const pt = s.points.find((candidate) => candidate.at === ts);
|
||||
if (!pt || pt.value === null) return;
|
||||
const clamped = Math.max(yMin, Math.min(yMax, pt.value));
|
||||
const barH = Math.max(1, ((clamped - yMin) / spanY) * plotHeight);
|
||||
bars.push({
|
||||
key: `${s.id}-${ts}`,
|
||||
x: groupStart + seriesIdx * innerWidth,
|
||||
y: padTop + plotHeight - barH,
|
||||
w: Math.max(1.5, innerWidth - 1),
|
||||
h: barH,
|
||||
color: s.color,
|
||||
});
|
||||
});
|
||||
});
|
||||
return bars;
|
||||
}, [variant, hasData, series, startAt, endAt, yMin, yMax, padLeft, padTop, plotWidth, plotHeight]);
|
||||
|
||||
const tooltipLeft = hoverSnapshot
|
||||
? (hoverSnapshot.x > width * 0.62 ? Math.max(4, hoverSnapshot.x - 168) : Math.max(4, Math.min(width - 164, hoverSnapshot.x + 10)))
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative flex w-full flex-col select-none overflow-hidden text-foreground"
|
||||
style={{ height: `${chartHeight}px` }}
|
||||
role="img"
|
||||
aria-label={props.ariaLabel ?? series.map((s) => s.label).join(', ')}
|
||||
>
|
||||
{showLegend && (
|
||||
<div className="flex h-6 shrink-0 items-center justify-between gap-2 px-1 text-[11px] text-muted-foreground">
|
||||
<div className="flex min-w-0 items-center gap-3 overflow-hidden">
|
||||
{series.map((s) => (
|
||||
<span key={s.id} className="inline-flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: s.color }} />
|
||||
<span className="truncate">{s.label}</span>
|
||||
<span className="font-mono text-foreground">{formatMetricValue(s.latestValue, s.unit)}</span>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<svg
|
||||
width={width}
|
||||
height={svgHeight}
|
||||
viewBox={`0 0 ${width} ${svgHeight}`}
|
||||
className="block h-full w-full overflow-visible"
|
||||
onPointerMove={interactive ? handlePointerMove : undefined}
|
||||
onPointerLeave={interactive ? handlePointerLeave : undefined}
|
||||
>
|
||||
<defs>
|
||||
{series.map((s, idx) => (
|
||||
<linearGradient key={s.id} id={`nc-mc-grad-${uid}-${idx}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={s.color} stopOpacity={isSparkline ? 0.28 : 0.24} />
|
||||
<stop offset="100%" stopColor={s.color} stopOpacity={0.01} />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
|
||||
{showGrid && yTicks.map((tick, idx) => (
|
||||
<line
|
||||
key={`grid-${idx}`}
|
||||
x1={padLeft}
|
||||
y1={tick.y}
|
||||
x2={padLeft + plotWidth}
|
||||
y2={tick.y}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeOpacity={0.55}
|
||||
strokeWidth={1}
|
||||
strokeDasharray={idx === yTicks.length - 1 ? undefined : '2 3'}
|
||||
/>
|
||||
))}
|
||||
|
||||
{thresholds.map((t, idx) => {
|
||||
if (t.value < yMin || t.value > yMax) return null;
|
||||
const y = padTop + plotHeight - ((t.value - yMin) / Math.max(1e-9, yMax - yMin)) * plotHeight;
|
||||
const stroke = t.tone === 'critical' ? '#f43f5e' : '#f59e0b';
|
||||
return (
|
||||
<g key={`thr-${idx}`}>
|
||||
<line
|
||||
x1={padLeft}
|
||||
y1={y}
|
||||
x2={padLeft + plotWidth}
|
||||
y2={y}
|
||||
stroke={stroke}
|
||||
strokeOpacity={0.75}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="4 3"
|
||||
/>
|
||||
{t.label && !isSparkline && (
|
||||
<text
|
||||
x={padLeft + plotWidth - 2}
|
||||
y={Math.max(padTop + 9, y - 3)}
|
||||
textAnchor="end"
|
||||
fontSize={9}
|
||||
fill={stroke}
|
||||
>
|
||||
{t.label}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{variant === 'bar' ? (
|
||||
barItems.map((bar) => (
|
||||
<rect
|
||||
key={bar.key}
|
||||
x={bar.x}
|
||||
y={bar.y}
|
||||
width={bar.w}
|
||||
height={bar.h}
|
||||
rx={1.5}
|
||||
fill={bar.color}
|
||||
fillOpacity={0.85}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
seriesSegments.map(({ series: s, segments }, idx) => (
|
||||
<g key={s.id}>
|
||||
{(variant === 'area' || isSparkline) && segments.map((seg, segIdx) => (
|
||||
seg.areaPath ? (
|
||||
<path
|
||||
key={`area-${segIdx}`}
|
||||
d={seg.areaPath}
|
||||
fill={`url(#nc-mc-grad-${uid}-${idx})`}
|
||||
/>
|
||||
) : null
|
||||
))}
|
||||
{segments.map((seg, segIdx) => (
|
||||
<path
|
||||
key={`line-${segIdx}`}
|
||||
d={seg.linePath}
|
||||
fill="none"
|
||||
stroke={s.color}
|
||||
strokeWidth={isSparkline ? 1.5 : 1.75}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
))}
|
||||
{segments.length > 0 && !hoverSnapshot && (
|
||||
<circle
|
||||
cx={segments[segments.length - 1].lastX}
|
||||
cy={segments[segments.length - 1].lastY}
|
||||
r={isSparkline ? 2 : 2.5}
|
||||
fill={s.color}
|
||||
/>
|
||||
)}
|
||||
</g>
|
||||
))
|
||||
)}
|
||||
|
||||
{showAxes && yTicks.map((tick, idx) => (
|
||||
<text
|
||||
key={`ytick-${idx}`}
|
||||
x={padLeft - 6}
|
||||
y={tick.y + 3}
|
||||
textAnchor="end"
|
||||
fontSize={10}
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
className="font-mono"
|
||||
>
|
||||
{formatMetricValue(tick.value, primaryUnit)}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{showAxes && xTicks.map((tick, idx) => (
|
||||
<text
|
||||
key={`xtick-${idx}`}
|
||||
x={tick.x}
|
||||
y={svgHeight - 5}
|
||||
textAnchor={tick.anchor}
|
||||
fontSize={10}
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
className="font-mono"
|
||||
>
|
||||
{formatClockTime(tick.at)}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{hoverSnapshot && (
|
||||
<g>
|
||||
<line
|
||||
x1={hoverSnapshot.x}
|
||||
y1={padTop}
|
||||
x2={hoverSnapshot.x}
|
||||
y2={padTop + plotHeight}
|
||||
stroke="hsl(var(--muted-foreground))"
|
||||
strokeOpacity={0.55}
|
||||
strokeWidth={1}
|
||||
strokeDasharray="2 2"
|
||||
/>
|
||||
{hoverSnapshot.values.map((item) => (
|
||||
item.y !== null ? (
|
||||
<circle
|
||||
key={`dot-${item.id}`}
|
||||
cx={item.x}
|
||||
cy={item.y}
|
||||
r={3.5}
|
||||
fill={item.color}
|
||||
stroke="hsl(var(--background))"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
) : null
|
||||
))}
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{!hasData && !isSparkline && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center text-xs text-muted-foreground">
|
||||
{props.emptyText ?? 'Waiting for samples...'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{hoverSnapshot && (
|
||||
<div
|
||||
className="pointer-events-none absolute top-1 z-10 min-w-[140px] max-w-[200px] rounded-md border border-border/80 bg-popover/95 px-2.5 py-1.5 text-[11px] text-popover-foreground shadow-md backdrop-blur-sm"
|
||||
style={{ left: `${tooltipLeft}px` }}
|
||||
>
|
||||
<div className="mb-1 font-mono text-[10px] text-muted-foreground">
|
||||
{formatClockTime(hoverSnapshot.at)}
|
||||
</div>
|
||||
<div className="space-y-0.5">
|
||||
{hoverSnapshot.values.map((item) => (
|
||||
<div key={item.id} className="flex items-center justify-between gap-2">
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="h-2 w-2 shrink-0 rounded-full" style={{ backgroundColor: item.color }} />
|
||||
<span className="truncate text-muted-foreground">{item.label}</span>
|
||||
</span>
|
||||
<span className="font-mono font-medium text-foreground">
|
||||
{formatMetricValue(item.value, item.unit)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import { PluginBiChart } from './PluginBiChart';
|
||||
import { PluginCodeEditor } from './PluginCodeEditor';
|
||||
import { PluginDataGrid } from './PluginDataGrid';
|
||||
import { PluginErCanvas } from './PluginErCanvas';
|
||||
import { PluginMetricChart } from './PluginMetricChart';
|
||||
import type {
|
||||
PluginBiChartWidgetProps,
|
||||
PluginCodeEditorWidgetProps,
|
||||
PluginDataGridWidgetProps,
|
||||
PluginErCanvasWidgetProps,
|
||||
PluginMetricChartWidgetProps,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas';
|
||||
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas' | 'metric-chart' | 'bi-chart';
|
||||
|
||||
export function parseWidgetPropsJson<T extends object>(raw: string | undefined): T {
|
||||
if (!raw) return {} as T;
|
||||
@@ -50,6 +54,12 @@ export function PluginSlottedWidget({
|
||||
{kind === 'er-canvas' && (
|
||||
<PluginErCanvas {...(parsedProps as PluginErCanvasWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
{kind === 'metric-chart' && (
|
||||
<PluginMetricChart {...(parsedProps as PluginMetricChartWidgetProps)} />
|
||||
)}
|
||||
{kind === 'bi-chart' && (
|
||||
<PluginBiChart {...(parsedProps as PluginBiChartWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
}
|
||||
@@ -134,3 +134,131 @@ export interface PluginErCanvasWidgetProps {
|
||||
tables?: PluginErTable[];
|
||||
relations?: PluginErRelation[];
|
||||
}
|
||||
|
||||
export type PluginMetricChartColor =
|
||||
| 'primary'
|
||||
| 'sky'
|
||||
| 'emerald'
|
||||
| 'amber'
|
||||
| 'violet'
|
||||
| 'rose'
|
||||
| 'cyan'
|
||||
| 'muted';
|
||||
|
||||
export type PluginMetricChartUnit = '%' | 'bytes/s' | 'ms' | 'count' | 'temp' | 'bytes' | '';
|
||||
|
||||
export interface PluginMetricChartPoint {
|
||||
at: number;
|
||||
value: number | null;
|
||||
}
|
||||
|
||||
export interface PluginMetricChartSeries {
|
||||
id: string;
|
||||
label: string;
|
||||
color?: PluginMetricChartColor;
|
||||
unit?: PluginMetricChartUnit;
|
||||
points: PluginMetricChartPoint[];
|
||||
}
|
||||
|
||||
export interface PluginMetricChartThreshold {
|
||||
value: number;
|
||||
tone: 'warning' | 'critical';
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface PluginMetricChartWidgetProps {
|
||||
variant?: 'area' | 'line' | 'sparkline' | 'bar';
|
||||
series?: PluginMetricChartSeries[];
|
||||
rangeMs?: number;
|
||||
intervalMs?: number;
|
||||
endAt?: number;
|
||||
min?: number;
|
||||
max?: number | 'auto';
|
||||
height?: number;
|
||||
thresholds?: PluginMetricChartThreshold[];
|
||||
showGrid?: boolean;
|
||||
showLegend?: boolean;
|
||||
showAxes?: boolean;
|
||||
interactive?: boolean;
|
||||
emptyText?: string;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
export type PluginBiChartType =
|
||||
| 'bar'
|
||||
| 'horizontal-bar'
|
||||
| 'stacked-bar'
|
||||
| 'line'
|
||||
| 'area'
|
||||
| 'pie'
|
||||
| 'donut'
|
||||
| 'scatter'
|
||||
| 'funnel'
|
||||
| 'combo';
|
||||
|
||||
export type PluginBiChartColor =
|
||||
| 'primary'
|
||||
| 'sky'
|
||||
| 'emerald'
|
||||
| 'amber'
|
||||
| 'violet'
|
||||
| 'rose'
|
||||
| 'cyan'
|
||||
| 'indigo'
|
||||
| 'teal'
|
||||
| 'orange'
|
||||
| 'slate'
|
||||
| 'muted';
|
||||
|
||||
export type PluginBiChartPalette = 'default' | 'categorical' | 'cool' | 'warm' | 'monochrome';
|
||||
|
||||
export type PluginBiChartValueFormat = 'number' | 'compact' | 'currency' | 'percent' | 'bytes' | 'ms';
|
||||
|
||||
export interface PluginBiChartScatterPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
label?: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export interface PluginBiChartSeries {
|
||||
id: string;
|
||||
name: string;
|
||||
data?: Array<number | null>;
|
||||
points?: PluginBiChartScatterPoint[];
|
||||
renderAs?: 'bar' | 'line' | 'area';
|
||||
yAxis?: 'left' | 'right';
|
||||
color?: PluginBiChartColor;
|
||||
format?: PluginBiChartValueFormat;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export interface PluginBiChartActiveFilter {
|
||||
seriesIndex?: number;
|
||||
datumIndex?: number;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
export interface PluginBiChartWidgetProps {
|
||||
type?: PluginBiChartType;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
categories?: string[];
|
||||
series?: PluginBiChartSeries[];
|
||||
palette?: PluginBiChartPalette;
|
||||
xAxisLabel?: string;
|
||||
yAxisLabel?: string;
|
||||
yAxisRightLabel?: string;
|
||||
valueFormat?: PluginBiChartValueFormat;
|
||||
currency?: string;
|
||||
height?: number;
|
||||
showGrid?: boolean;
|
||||
showLegend?: boolean;
|
||||
showDataLabels?: boolean;
|
||||
smooth?: boolean;
|
||||
donutInnerRatio?: number;
|
||||
exportable?: boolean;
|
||||
activeFilter?: PluginBiChartActiveFilter | null;
|
||||
emptyText?: string;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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}
|
||||
|
||||
Loaded 100 of 354 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user