Compare commits

..
Author SHA1 Message Date
陈大猫 82e64a60d8 docs: note that the plugin system and official plugins are still unstable
Tell users the plugin system and current official plugins are still
in an unstable stage, and that issues are welcome and will be fixed
promptly. Linked from all four README locales to the announcement
in Discussions #4554.
2026-11-29 17:29:51 +08:00
陈大猫 3c4f561beb fix(rdp): send local clipboard images to the remote desktop (#4552)
* fix(rdp): send local clipboard images to the remote desktop

Fixes #4551

* fix(rdp): invalidate clipboard echo guards on format replacement

Fixes the Codex P2 on PR #4552: a later text-only or image-only clipboard must replace the remote clipboard even when one format matches a stale guard from the previous snapshot.

* fix(rdp): write mixed remote clipboard text and PNG locally

Addresses the Codex P2 on PR #4552: write mixed remote snapshots locally as both text/plain and image/png so the echo guard does not wipe remote text on refocus. Fall back to PNG, then text, if the mixed write fails.
2026-11-29 17:25:37 +08:00
陈大猫 d04bf9ce72 fix(terminal): clear full snippet label on autocomplete accept when the name has spaces (#4550)
Fixes #4549
2026-11-29 16:49:21 +08:00
陈大猫 bfe63719d8 feat(terminal): unify 1px focus and magnification borders with deterministic state (#4543) (#4545)
* feat(terminal): unify 1px focus and magnification borders with deterministic state

* fix(terminal): preserve zoom entry animation on unchanged initial ResizeObserver callback

* test(terminal): update browserPanelLifecycle vm stub for setMagnifiedPanesByTab
2026-11-29 14:45:56 +08:00
陈大猫 08f22349c1 fix(plugins): clear stale PluginDataGrid editingCell and blur timer on row removal (#4547) 2026-11-29 14:41:35 +08:00
陈大猫 c846cd6fd8 feat(vault): allow Direct (no proxy) on groups (#4442) (#4546) 2026-11-29 14:34:10 +08:00
Netcatty-Bot 2506b5d1bc Update Nix release metadata for v1.1.95 (#4536) 2026-11-29 12:50:41 +08:00
陈大猫 a24be98a6b fix(rdp): reuse MCS server public key when license request has no cert (#4542)
Related #4540
2026-11-29 12:23:04 +08:00
陈大猫 b08a1398e3 test(plugins): sync Database 0.3.2 brand fixture and list avatar assertions (#4537) 2026-11-29 09:18:47 +08:00
陈大猫 bc849a3aa2 docs(readme): add WeChat group badge linking to QR code across all READMEs (#4535) 2026-11-29 08:34:21 +08:00
陈大猫 2a48e30278 docs(readme): add official WeChat user group QR code to READMEs (#4534) 2026-11-29 08:33:05 +08:00
陈大猫 bf14ef9d8f docs(readme): add Plugin System section with marketplace, dev, and submission links across all READMEs (#4533) 2026-11-29 08:28:07 +08:00
陈大猫 0f1177a43b feat(plugins): automatically check for updates on plugin views and detail pages (#4532) 2026-11-29 08:21:19 +08:00
陈大猫 8c813a6fbd feat(plugins): unify installed and marketplace detail views with README first and permissions below (#4531) 2026-11-29 08:15:58 +08:00
陈大猫 775bd12443 feat(plugins): auto-recognize official binaricat plugins from official marketplace without hardcoded ID list (#4530) 2026-11-29 08:07:56 +08:00
陈大猫 4e161b3a5b feat(vault): remove standalone Customize Sidebar rail button and trigger via item context menu (#4529) 2026-11-29 06:21:25 +08:00
陈大猫 55906e1f46 fix(ai): recognize bracket [host path]$ prompts without a time field (#4527) (#4528)
Fixes #4527
2026-11-29 06:15:13 +08:00
陈大猫 8fd8983b4d chore(plugins): sync fallback catalog to Netcatty Database 0.3.2 (#4525) 2026-11-29 00:48:20 +08:00
陈大猫 a62c0f7f7f feat(plugins): open plugin detail directly when clicking plugin avatar or name (#4524) 2026-11-29 00:26:50 +08:00
陈大猫 92db9371e6 chore(plugins): omit verbose description from Settings installed plugins list (#4523) 2026-11-29 00:21:21 +08:00
陈大猫 0189ae996a feat(plugins): add one-click emerald Update button across installed list, cards, and detail header (#4522) 2026-11-29 00:18:18 +08:00
陈大猫 61ca623a08 fix(plugins): use Update label and emerald button style when upgrading installed plugin (#4521) 2026-11-29 00:11:03 +08:00
陈大猫 b4015f8719 feat(plugins): support theme-aware README pictures and sync Database 0.3.1 / Monitor 0.2.2 (#4520) 2026-11-28 23:50:00 +08:00
陈大猫 880e11eff5 fix(rdp): emit use redirection server name in system-client .rdp files
Related #4514

Add use redirection server name:i:1 to default system-client .rdp writers.

This is only a partial step for #4514 and should leave that issue open.
2026-11-28 23:49:46 +08:00
陈大猫 dc044961b5 fix(plugins): add install spinner, hide Install once installed, toggle Enable/Enabled (#4519) 2026-11-28 23:44:23 +08:00
陈大猫 873c8cfb52 feat(plugins): align official badge, render HTML/table READMEs, add gauge icon, streamline install UX (#4517) 2026-11-28 23:32:27 +08:00
bincxz cd0c24f3a4 feat(plugins): support verified remote catalog brand icons and sync official catalog 2026-11-28 23:06:51 +08:00
bincxz 93a3a37987 chore(plugins): remove duplicate in-tree plugins/netcatty-monitor directory 2026-11-28 21:41:47 +08:00
bincxz 2df6aad44b fix(lint): fix netcatty-monitor ESLint errors and configure Node globals for plugin scripts 2026-11-28 21:35:45 +08:00
bincxz 5b669539c7 build(packaging): prune unused bare-*, claude-agent-sdk, native source, and preload source payloads from release bundles 2026-11-28 21:35:45 +08:00
Joseph Hau a4cacc4bc5 fix: keep WSL directory navigation working across windows 2026-11-28 21:35:29 +08:00
Joseph Hau f491676ff9 feat: support directory picker in WSL Bash 2026-11-28 21:35:29 +08:00
192 changed files with 4443 additions and 12817 deletions

No files matched your search

-2
View File
@@ -75,8 +75,6 @@
!packages/**
!patches/
!patches/**
!plugins/
!plugins/**
!public/
!public/**
!resources/
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
Electron、React、xterm.js で構築された機能豊富な SSH ワークスペース。<br/>
🔥 内蔵 AI Agent · 分割ターミナル · Vault ビュー · SFTP ワークフロー · カスタムテーマ — すべてが一つに。
🔥 内蔵 AI Agent · 🧩 プラグインシステム · 分割ターミナル · Vault ビュー · SFTP ワークフロー · カスタムテーマ — すべてが一つに。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="GitHub でスポンサーになる"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Ko-fi でサポート"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/WeChat-Official%20Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="公式 WeChat グループに参加"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
---
<a name="plugin-system"></a>
# 🧩 プラグインシステム — Netcatty を安全に拡張
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
- 🔒 **オフラインサンドボックス & 最小権限モデル** — プラグインは SSH パスワードや秘密鍵に直接アクセスできず、すべての機能はホスト管理の **許可 / 毎回確認 / 拒否** ポリシーを経由します。
- 🖥️ **ホストネイティブ IDE コンポーネント** — `@netcatty/plugin-sdk` を使い、React または DOM で Vault ページ、ターミナルサイドバー、モーダルを構築できます。
- 🗄️ **公式プラグインをすぐ導入** — **設定 → プラグイン** から [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database)(113 エンジン対応 SQL IDE・Catty Agent・BI ダッシュボード)や [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor)(エージェントレス SSH サーバー監視・Monaco ライブ可視化ログ)をワンクリック導入できます。
- 🚀 **柔軟な配布と自動更新チェック** — 内蔵の**公式マーケットプレイス**(`plugins.netcatty.app`)、GitHub Release からの直接インストール、ローカル `.ncpkg` インポート、自社ホスト静的ソースに対応します。
### 🔗 関連リンク & ガイド
- 🛒 [**公式プラグインマーケットプレイス**](https://netcatty.app/en/plugins) — 公式・コミュニティプラグインを閲覧
- 📖 [**プラグイン基盤概要**](https://netcatty.app/en/docs/plugins-overview) — サンドボックス設計・ホストレンダリング UI・権限モデル
- 🛠️ [**プラグイン開発ガイド**](https://netcatty.app/en/docs/plugins-development) — プロジェクト作成・UI 実装・権限宣言・`.ncpkg` パッケージング
- 📤 [**マーケットプレイス公開・提出ガイド**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release 規約と公式カタログ PR 手順([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目次 <!-- omit in toc -->
- [🔥 Catty Agent — AI パートナー](#catty-agent)
- [🧩 プラグインシステム](#plugin-system)
- [Netcatty とは](#netcatty-とは)
- [なぜ Netcatty](#なぜ-netcatty)
- [機能](#機能)
@@ -94,6 +122,7 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
- [はじめに](#はじめに)
- [ビルドとパッケージ](#ビルドとパッケージ)
- [技術スタック](#技術スタック)
- [コミュニティ](#コミュニティ)
- [コントリビューション](#コントリビューション)
- [コントリビューター](#コントリビューター)
- [Star 履歴](#star-履歴)
@@ -326,6 +355,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="コミュニティ"></a>
# 💬 コミュニティ
WeChat で QR コードをスキャンして **Netcatty 公式ユーザーグループ** に参加し、フィードバックやプラグインの話題を共有しましょう:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 公式 WeChat グループ QR コード" width="260" />
</p>
---
<a name="コントリビューション"></a>
# コントリビューション
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
A beautiful, feature-rich SSH workspace built with Electron, React, and xterm.js.<br/>
🔥 Built-in AI Agent · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
🔥 Built-in AI Agent · 🧩 Plugin System · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="Sponsor on GitHub"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Support on Ko-fi"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/WeChat-Official%20Group-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="Join Official WeChat Group"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,11 +83,35 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
<img width="3294" height="1974" alt="image" src="docs/assets/readme/catty-multi-host.webp" />
---
<a name="plugin-system"></a>
# 🧩 Plugin System — Extend Netcatty Safely
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
### ✨ Highlights
- 🔒 **Offline Sandbox & Least-Privilege Permissions** — Plugins never touch SSH passwords, private keys, or the host renderer; every capability goes through host-mediated **Allow / Ask / Deny** brokers.
- 🖥️ **Host-Rendered IDE Components** — Build native-feeling Vault pages, terminal sidebars, and modals with React or DOM via `@netcatty/plugin-sdk`.
- 🗄️ **Official Plugins Out of the Box** — Install [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database) (113 database profiles, SQL IDE, Catty Agent sidebar & BI Dashboard) and [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor) (agentless cross-OS SSH fleet observability, Monaco live logs & multi-host compare) directly in **Settings → Plugins**.
- 🚀 **Flexible Distribution** — Install from the built-in **Official Marketplace** (`plugins.netcatty.app`), directly from any public GitHub Release (**Install from GitHub**), via local `.ncpkg` import, or self-hosted static market sources.
### 🔗 Resources & Guides
- 🛒 [**Official Plugin Marketplace**](https://netcatty.app/en/plugins) — Browse official and curated plugins
- 📖 [**Plugin Platform Overview**](https://netcatty.app/en/docs/plugins-overview) — Sandbox architecture, host-rendered UI, and permission model
- 🛠️ [**Plugin Development Guide**](https://netcatty.app/en/docs/plugins-development) — Scaffold, build host-rendered views, declare permissions, and pack `.ncpkg`
- 📤 [**Marketplace Submission & Publishing Guide**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release contract & official catalog PR workflow ([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# Contents <!-- omit in toc -->
- [🔥 Catty Agent — AI Partner](#catty-agent)
- [🧩 Plugin System](#plugin-system)
- [What is Netcatty](#what-is-netcatty)
- [Why Netcatty](#why-netcatty)
- [Features](#features)
@@ -96,6 +124,7 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
- [Open a local terminal from the command line](#open-a-local-terminal-from-the-command-line)
- [Build & Package](#build--package)
- [Tech Stack](#tech-stack)
- [Community](#community)
- [Contributing](#contributing)
- [Contributors](#contributors)
- [Star History](#star-history)
@@ -359,6 +388,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="community"></a>
# 💬 Community
Scan the QR code with WeChat to join the **Netcatty Official User Group** for feedback, tips, and plugin discussions:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty Official WeChat Group QR Code" width="260" />
</p>
---
<a name="contributing"></a>
# Contributing
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
一个基于 Electron、React 和 xterm.js 构建的功能丰富的 SSH 工作空间。<br/>
🔥 内置 AI Agent · 分屏终端 · Vault 多视图 · SFTP 工作流 · 自定义主题 —— 一应俱全。
🔥 内置 AI Agent · 🧩 插件系统 · 分屏终端 · Vault 多视图 · SFTP 工作流 · 自定义主题 —— 一应俱全。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="通过 GitHub 赞助我"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="在 Ko-fi 上支持我"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/%E5%BE%AE%E4%BF%A1%E7%BE%A4-%E5%AE%98%E6%96%B9%E4%BA%A4%E6%B5%81%E7%BE%A4-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="加入官方微信交流群"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@
---
<a name="plugin-system"></a>
# 🧩 插件系统 — 安全扩展你的工作台
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
### ✨ 核心亮点
- 🔒 **离线沙箱与最小权限控制** —— 插件永远无法读取 SSH 密码或私钥,所有宿主能力均受 **允许 / 询问 / 拒绝** 三态权限代理与审计保护。
- 🖥️ **宿主原生 IDE 组件** —— 通过 `@netcatty/plugin-sdk` 使用 React 或原生 DOM 构建 Vault 页面、终端侧栏与弹窗,无缝复用宿主主题。
- 🗄️ **官方插件开箱即用** —— 在 **设置 → 插件** 一键安装 [**Netcatty 数据库**](https://netcatty.app/zh/plugins/netcatty-database)(覆盖 113 种数据库配置、SQL IDE、Catty Agent 侧栏与 BI 看板)和 [**Netcatty 监控**](https://netcatty.app/zh/plugins/netcatty-monitor)(无 Agent 跨平台 SSH 集群监控、Monaco 实时日志与多机对比)。
- 🚀 **多渠道分发与自动检查更新** —— 支持内置**官方插件市场**(`plugins.netcatty.app`)、**从 GitHub 安装**公开 Release、本地导入 `.ncpkg` 以及自建第三方静态市场源。
### 🔗 相关链接与指南
- 🛒 [**官方插件市场**](https://netcatty.app/zh/plugins) —— 浏览官方与社区插件
- 📖 [**插件平台概览**](https://netcatty.app/zh/docs/plugins-overview) —— 隔离架构、宿主渲染 UI 与权限安全模型
- 🛠️ [**插件开发指南**](https://netcatty.app/zh/docs/plugins-development) —— 脚手架初始化、UI 开发、权限声明与 `.ncpkg` 打包调试
- 📤 [**插件市场发布与提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契约与官方市场 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目录 <!-- omit in toc -->
- [🔥 Catty Agent — AI 搭档](#catty-agent)
- [🧩 插件系统](#plugin-system)
- [Netcatty 是什么](#netcatty-是什么)
- [为什么是 Netcatty](#为什么是-netcatty)
- [功能特性](#功能特性)
@@ -94,6 +122,7 @@
- [快速开始](#快速开始)
- [构建与打包](#构建与打包)
- [技术栈](#技术栈)
- [社区交流](#社区交流)
- [参与贡献](#参与贡献)
- [贡献者](#贡献者)
- [Star 历史](#star-历史)
@@ -326,6 +355,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="社区交流"></a>
# 💬 社区交流
欢迎使用微信扫码加入 **Netcatty 官方用户交流群**,交流使用技巧、插件开发与反馈建议:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 官方用户交流群二维码" width="260" />
</p>
---
<a name="参与贡献"></a>
# 参与贡献
+41 -1
View File
@@ -17,7 +17,7 @@
<p align="center">
以 Electron、React 與 xterm.js 打造,介面精緻、功能完整的 SSH 工作區。<br/>
🔥 內建 AI Agent · 分割終端 · Vault 檢視 · SFTP 工作流 · 自訂主題 —— 全部整合在一起。
🔥 內建 AI Agent · 🧩 外掛系統 · 分割終端 · Vault 檢視 · SFTP 工作流 · 自訂主題 —— 全部整合在一起。
</p>
<p align="center">
@@ -38,12 +38,16 @@
<a href="https://github.com/sponsors/binaricat"><img src="https://img.shields.io/badge/GitHub-Sponsors-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" height="28" alt="透過 GitHub 贊助我"></a>
&nbsp;
<a href="https://ko-fi.com/binaricat"><img src="https://img.shields.io/badge/Ko--fi-Support-29abe0?style=for-the-badge&logo=kofi&logoColor=white" height="28" alt="Support on Ko-fi"></a>
&nbsp;
<a href="docs/assets/readme/wechat-group.jpg"><img src="https://img.shields.io/badge/%E5%BE%AE%E4%BF%A1%E7%BE%A4-%E5%AE%98%E6%96%B9%E4%BA%A4%E6%B5%81%E7%BE%A4-07C160?style=for-the-badge&logo=wechat&logoColor=white" height="28" alt="加入官方微信交流群"></a>
</p>
<p align="center">
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -79,9 +83,33 @@
---
<a name="plugin-system"></a>
# 🧩 外掛系統 —— 安全擴充你的工作台
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
### ✨ 核心亮點
- 🔒 **離線沙箱與最小權限控制** —— 外掛永遠無法讀取 SSH 密碼或私鑰,所有宿主能力均受 **允許 / 詢問 / 拒絕** 三態權限代理保護。
- 🖥️ **宿主原生 IDE 元件** —— 透過 `@netcatty/plugin-sdk` 以 React 或原生 DOM 開發 Vault 頁面、終端側欄與視窗,無縫跟隨宿主主題。
- 🗄️ **官方外掛開箱即用** —— 在 **設定 → 外掛** 一鍵安裝 [**Netcatty 資料庫**](https://netcatty.app/zh/plugins/netcatty-database)(113 種資料庫設定、SQL IDE、Catty Agent 側欄與 BI 看板)與 [**Netcatty 監控**](https://netcatty.app/zh/plugins/netcatty-monitor)(無 Agent 跨平台 SSH 叢集監控、Monaco 即時日誌與多機對比)。
- 🚀 **多元分發與自動檢查更新** —— 支援內建**官方外掛市場**(`plugins.netcatty.app`)、**從 GitHub 安裝**公開 Release、本機匯入 `.ncpkg` 以及自建第三方靜態市場源。
### 🔗 相關連結與指南
- 🛒 [**官方外掛市場**](https://netcatty.app/zh/plugins) —— 瀏覽官方與社群外掛
- 📖 [**外掛平台概覽**](https://netcatty.app/zh/docs/plugins-overview) —— 隔離架構、宿主渲染 UI 與權限安全模型
- 🛠️ [**外掛開發指南**](https://netcatty.app/zh/docs/plugins-development) —— 初始化專案、UI 開發、權限宣告與 `.ncpkg` 打包除錯
- 📤 [**外掛市場發布與提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契約與官方市場 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
---
# 目錄 <!-- omit in toc -->
- [🔥 Catty Agent —— AI 夥伴](#catty-agent)
- [🧩 外掛系統](#plugin-system)
- [Netcatty 是什麼](#netcatty-是什麼)
- [為什麼選 Netcatty](#為什麼選-netcatty)
- [功能特色](#功能特色)
@@ -94,6 +122,7 @@
- [快速開始](#快速開始)
- [建置與打包](#建置與打包)
- [技術堆疊](#技術堆疊)
- [社群交流](#社群交流)
- [參與貢獻](#參與貢獻)
- [貢獻者](#貢獻者)
- [Star 紀錄](#star-紀錄)
@@ -325,6 +354,17 @@ npm run pack:linux # Linux (AppImage + DEB + RPM)
---
<a name="社群交流"></a>
# 💬 社群交流
歡迎使用微信掃描下方 QR Code 加入 **Netcatty 官方用戶交流群**,交流使用技巧、外掛開發與回饋建議:
<p align="center">
<img src="docs/assets/readme/wechat-group.jpg" alt="Netcatty 官方用戶交流群 QR Code" width="260" />
</p>
---
<a name="參與貢獻"></a>
# 參與貢獻
+31 -1
View File
@@ -604,7 +604,37 @@ export function AppSideEffects() {
});
// Window controls - must be before update toast effect which uses openSettingsWindow
const { openSettingsWindow } = useWindowControls();
const { openSettingsWindow, isFullscreen, onFullscreenChanged } = useWindowControls();
// Sync host platform and fullscreen state to DOM so platform-aware chrome
// (such as macOS rounded window corners on outer split-pane focus borders)
// stays accurate across fullscreen transitions without per-pane polling.
useEffect(() => {
const isMac = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform);
if (isMac) {
document.documentElement.setAttribute('data-platform', 'darwin');
} else {
document.documentElement.removeAttribute('data-platform');
document.documentElement.removeAttribute('data-window-fullscreen');
return undefined;
}
let cancelled = false;
const syncFullscreen = (value: boolean) => {
if (value) {
document.documentElement.setAttribute('data-window-fullscreen', 'true');
} else {
document.documentElement.removeAttribute('data-window-fullscreen');
}
};
void isFullscreen().then((value) => {
if (!cancelled) syncFullscreen(!!value);
});
const unsubscribe = onFullscreenChanged((value) => syncFullscreen(!!value));
return () => {
cancelled = true;
unsubscribe();
};
}, [isFullscreen, onFullscreenChanged]);
const _handleTrayJumpToSession = useEffectEvent((sessionId: string) => {
return handleTrayJumpToSessionImpl(() => ({
sessionId,
+5 -2
View File
@@ -8,7 +8,7 @@ export const enCoreMessages: Messages = {
"settings.plugins.github.busy": "Downloading, validating or installing the package...",
"settings.plugins.github.review": "Repository ownership and package integrity do not verify publisher trust. No build scripts run. The plugin installs disabled; review permission modes before enabling.",
"settings.plugins.github.accept": "I trust this repository and have reviewed the declared permissions.",
"settings.plugins.github.confirm": "Install disabled",
"settings.plugins.github.confirm": "Install",
"settings.plugins.github.download": "Download and review",
"settings.plugins.github.error.invalidRepository": "Enter https://github.com/owner/repo, github.com/owner/repo or owner/repo (repository only; no credentials, query, fragment or extra paths).",
"settings.plugins.github.error.unavailable": "GitHub plugin installation is unavailable in this session.",
@@ -1407,7 +1407,10 @@ Highlight the focused split pane:
"settings.plugins.market.title": "Marketplace",
"settings.plugins.market.note": "Curated open-source plugins. Review is not a security certification. Updates are manual.",
"settings.plugins.market.back": "All plugins",
"settings.plugins.market.install": "Install this version (disabled)",
"settings.plugins.market.install": "Install",
"settings.plugins.market.installing": "Installing...",
"settings.plugins.market.update": "Update",
"settings.plugins.market.updating": "Updating...",
"settings.plugins.market.installNote": "This replaces and stops the installed version. Review its permissions in Installed plugins before enabling.",
"settings.plugins.market.sourceOnly": "First-party source example. Build with the local CLI and import the .ncpkg; no downloadable release has been published.",
"settings.plugins.market.readmeNote": "Pinned to the commit above. HTML is inert and remote images are not loaded. Written by the plugin author.",
+1
View File
@@ -15,6 +15,7 @@ export const enTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell directory integration is not ready. Startup arguments or execution policy may prevent it.',
'terminal.directory.cmdIntegrationUnavailable': 'Waiting for a directory report from the original Command Prompt session.',
'terminal.directory.gitBashIntegrationUnavailable': 'Waiting for an accessible directory from the original Git Bash session.',
'terminal.directory.wslIntegrationUnavailable': 'Waiting for an idle Bash session in the selected WSL distribution.',
'terminal.directory.nonFilesystem': 'The current PowerShell location is not a filesystem directory.',
'terminal.directory.busy': 'Wait for an empty shell prompt.',
'terminal.directory.readFailed': 'Could not read this directory. Try refreshing.',
+5 -2
View File
@@ -8,7 +8,7 @@ export const esCoreMessages: Messages = {
"settings.plugins.github.busy": "Descargando, validando o instalando el paquete...",
"settings.plugins.github.review": "El origen y la integridad no verifican la confianza en el autor. No se ejecutan scripts de compilación. Se instala desactivado; revisa los permisos antes de activarlo.",
"settings.plugins.github.accept": "Confío en este repositorio y he revisado los permisos declarados.",
"settings.plugins.github.confirm": "Instalar desactivado",
"settings.plugins.github.confirm": "Instalar",
"settings.plugins.github.download": "Descargar y revisar",
"settings.plugins.github.error.invalidRepository": "Introduce https://github.com/owner/repo, github.com/owner/repo u owner/repo. Usa solo el repositorio, sin credenciales, parámetros, fragmentos ni rutas adicionales.",
"settings.plugins.github.error.unavailable": "La instalación de plugins desde GitHub no está disponible en esta sesión.",
@@ -1407,7 +1407,10 @@ Resalta el panel dividido enfocado:
"settings.plugins.market.title": "Catálogo",
"settings.plugins.market.note": "Plugins de código abierto seleccionados. La revisión no certifica su seguridad. Las actualizaciones son manuales.",
"settings.plugins.market.back": "Todos los plugins",
"settings.plugins.market.install": "Instalar esta versión (desactivada)",
"settings.plugins.market.install": "Instalar",
"settings.plugins.market.installing": "Instalando...",
"settings.plugins.market.update": "Actualizar",
"settings.plugins.market.updating": "Actualizando...",
"settings.plugins.market.installNote": "Esto reemplaza y detiene la versión instalada. Revisa sus permisos antes de activarla.",
"settings.plugins.market.sourceOnly": "Ejemplo propio con código fuente. Compílalo con la CLI local e importa el .ncpkg; no hay versión publicada para descargar.",
"settings.plugins.market.readmeNote": "Fijado al commit indicado. El HTML no se ejecuta y las imágenes remotas no se cargan. Contenido del autor.",
+1
View File
@@ -15,6 +15,7 @@ export const esTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'La integración de directorios de PowerShell no está lista. Los argumentos de inicio o la política de ejecución pueden impedirla.',
'terminal.directory.cmdIntegrationUnavailable': 'Esperando el directorio de la sesión original del símbolo del sistema.',
'terminal.directory.gitBashIntegrationUnavailable': 'Esperando un directorio accesible de la sesión original de Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Esperando una sesión de Bash inactiva en la distribución WSL seleccionada.',
'terminal.directory.nonFilesystem': 'La ubicación actual de PowerShell no es un directorio del sistema de archivos.',
'terminal.directory.accessDenied': 'Permiso denegado al listar este directorio.',
'terminal.directory.busy': 'Espera a que el prompt esté vacío.',
+5 -2
View File
@@ -8,7 +8,7 @@ export const ruCoreMessages: Messages = {
"settings.plugins.github.busy": "Загрузка, проверка или установка пакета...",
"settings.plugins.github.review": "Источник и целостность пакета не подтверждают доверие к издателю. Скрипты сборки не запускаются. Плагин устанавливается выключенным; проверьте разрешения перед включением.",
"settings.plugins.github.accept": "Я доверяю этому репозиторию и проверил заявленные разрешения.",
"settings.plugins.github.confirm": "Установить выключенным",
"settings.plugins.github.confirm": "Установить",
"settings.plugins.github.download": "Загрузить и проверить",
"settings.plugins.github.error.invalidRepository": "Введите https://github.com/owner/repo, github.com/owner/repo или owner/repo. Укажите только репозиторий, без учётных данных, параметров, фрагментов и дополнительных путей.",
"settings.plugins.github.error.unavailable": "Установка плагинов из GitHub недоступна в этом сеансе.",
@@ -1348,7 +1348,10 @@ export const ruCoreMessages: Messages = {
"settings.plugins.market.title": "Каталог",
"settings.plugins.market.note": "Отобранные плагины с открытым кодом. Проверка не гарантирует безопасность. Обновления выполняются вручную.",
"settings.plugins.market.back": "Все плагины",
"settings.plugins.market.install": "Установить эту версию (отключённой)",
"settings.plugins.market.install": "Установить",
"settings.plugins.market.installing": "Установка...",
"settings.plugins.market.update": "Обновить",
"settings.plugins.market.updating": "Обновление...",
"settings.plugins.market.installNote": "Установленная версия будет заменена и остановлена. Проверьте разрешения перед включением.",
"settings.plugins.market.sourceOnly": "Пример из этого проекта. Соберите локальной CLI и импортируйте .ncpkg; готовый пакет для скачивания не опубликован.",
"settings.plugins.market.readmeNote": "Зафиксирован указанный коммит. HTML не выполняется, внешние изображения не загружаются. Текст автора плагина.",
+1
View File
@@ -15,6 +15,7 @@ export const ruTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
+5 -2
View File
@@ -8,7 +8,7 @@ export const zhCNCoreMessages: Messages = {
"settings.plugins.github.busy": "正在下载、验证或安装插件包…",
"settings.plugins.github.review": "确认仓库来源并通过完整性校验,并不代表发布者值得信任。安装过程不会运行构建脚本,插件安装后默认禁用。启用前,请确认来源可信并检查各项权限的授权方式。",
"settings.plugins.github.accept": "已审查并信任此仓库,且已查看声明的权限。",
"settings.plugins.github.confirm": "安装并保持禁用",
"settings.plugins.github.confirm": "安装",
"settings.plugins.github.download": "下载并审查",
"settings.plugins.github.error.invalidRepository": "请输入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。请只填写仓库地址,不要包含账号密码、查询参数、片段或额外路径。",
"settings.plugins.github.error.unavailable": "当前会话无法从 GitHub 安装插件。",
@@ -1324,7 +1324,10 @@ Vaults 标签保持扁平,不使用这块背景。
"settings.plugins.market.title": "插件市场",
"settings.plugins.market.note": "精选开源插件。审核不代表安全认证,更新由你手动确认。",
"settings.plugins.market.back": "所有插件",
"settings.plugins.market.install": "安装此版本(保持停用)",
"settings.plugins.market.install": "安装",
"settings.plugins.market.installing": "安装中...",
"settings.plugins.market.update": "更新",
"settings.plugins.market.updating": "更新中...",
"settings.plugins.market.installNote": "这会替换并停止已安装版本。请在已安装列表检查权限后再启用。",
"settings.plugins.market.sourceOnly": "第一方源码示例。请用本地 CLI 构建并导入 .ncpkg;尚未发布可下载发行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不执行,远程图片不加载。内容由插件作者提供。",
@@ -15,6 +15,7 @@ export const zhCNTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
'terminal.directory.accessDenied': '没有权限列出此目录。',
'terminal.directory.busy': '请等待终端回到空命令提示符。',
+5 -2
View File
@@ -8,7 +8,7 @@ export const zhTWCoreMessages: Messages = {
"settings.plugins.github.busy": "正在下載、驗證或安裝套件…",
"settings.plugins.github.review": "確認儲存庫來源並通過完整性驗證,並不代表發布者值得信任。安裝過程不會執行建置指令碼,外掛安裝後預設停用。啟用前,請確認來源可信並檢查各項權限的授權方式。",
"settings.plugins.github.accept": "已審查並信任此儲存庫,且已查看宣告的權限。",
"settings.plugins.github.confirm": "安裝並保持停用",
"settings.plugins.github.confirm": "安裝",
"settings.plugins.github.download": "下載並審查",
"settings.plugins.github.error.invalidRepository": "請輸入 https://github.com/owner/repo、github.com/owner/repo 或 owner/repo。請只填寫儲存庫位址,不要包含帳號密碼、查詢參數、片段或額外路徑。",
"settings.plugins.github.error.unavailable": "目前的工作階段無法從 GitHub 安裝外掛。",
@@ -1354,7 +1354,10 @@ Vaults 分頁維持扁平,不使用這塊背景。
"settings.plugins.market.title": "外掛市集",
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
"settings.plugins.market.back": "所有外掛",
"settings.plugins.market.install": "安裝此版本(保持停用)",
"settings.plugins.market.install": "安裝",
"settings.plugins.market.installing": "安裝中...",
"settings.plugins.market.update": "更新",
"settings.plugins.market.updating": "更新中...",
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
@@ -15,6 +15,7 @@ export const zhTWTerminalMessages: Messages = {
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
@@ -9,7 +9,7 @@ test('selected metadata projects only the allowlist and replacement invalidates
const resources = new PluginHostActionResources();
resources.observe([first]);
const metadata = resources.metadata(first.id);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags']);
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags', 'os']);
assert.equal(JSON.stringify(metadata).includes('synthetic-password'), false);
resources.observe([first]);
assert.equal(resources.resolve(first.id, metadata.revision), first);
@@ -16,14 +16,17 @@ export function createTerminalDirectoryController(options: {
target?: DirectoryTarget;
capabilities?: DirectoryCapabilities;
buildChangeCommand?: (path: string) => string | null;
trustOsc7?: boolean;
}) {
const target = Object.freeze({ ...options.target ?? { authority: `session:${options.sessionId}`, pathFlavor: 'posix' as const } });
const capabilities = Object.freeze({ ...options.capabilities ?? COMPLETE_DIRECTORY_CAPABILITIES });
const trustsOsc7 = target.pathFlavor === 'posix' && options.trustOsc7 !== false;
const valid = (path: string | null | undefined): path is string => isDirectoryPath(path, target.pathFlavor);
const same = (a: string, b: string) => sameDirectoryPath(a, b, target.pathFlavor);
let disposed = false;
let changing = false;
let confirmed = false;
let verifiedCwd: string | null = null;
let refreshing: Promise<string> | null = null;
let refreshAgain = false;
let cwdError: DirectoryPickerError | null = null;
@@ -57,7 +60,7 @@ export function createTerminalDirectoryController(options: {
if (!capabilities.readCwd) throw new DirectoryPickerError('unavailable');
const activeShellCwd = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision)
? cwd : null;
};
@@ -79,8 +82,9 @@ export function createTerminalDirectoryController(options: {
cwd = await bounded(options.io.cwd());
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
} catch (error) {
if (current() && target.pathFlavor === 'win32') {
if (current() && !trustsOsc7) {
confirmed = false;
verifiedCwd = null;
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
options.publish('');
}
@@ -89,10 +93,13 @@ export function createTerminalDirectoryController(options: {
check();
const reported = activeShellCwd();
const live = terminalCwdStore.getCwd(options.sessionId);
const verifiedCwdChanged = verifiedCwd !== cwd;
confirmed = true;
verifiedCwd = cwd;
cwdError = null;
if (reported) return reported;
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd);
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|| (options.trustOsc7 === false && verifiedCwdChanged)) options.publish(cwd);
return cwd;
})();
refreshing = pending;
@@ -119,7 +126,7 @@ export function createTerminalDirectoryController(options: {
check(signal);
if (!valid(canonical)) throw new DirectoryPickerError('unsupportedPath');
ready(); // The shell can become busy while resolving a remote symlink.
if (expectedCwd && terminalCwdStore.getCwd(options.sessionId) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedCwd && (options.trustOsc7 === false ? verifiedCwd : terminalCwdStore.getCwd(options.sessionId)) !== expectedCwd) throw new DirectoryPickerError('unavailable');
if (expectedRevision !== undefined && terminalCwdStore.getSessionRevision(options.sessionId) !== expectedRevision) throw new DirectoryPickerError('unavailable');
const submittedRevision = terminalCwdStore.getSessionRevision(options.sessionId);
options.io.write(command + '\r');
@@ -127,7 +134,7 @@ export function createTerminalDirectoryController(options: {
const deadline = Date.now() + (options.confirmationMs ?? 8000);
const hasFreshOsc7 = () => {
const cwd = terminalCwdStore.getCwd(options.sessionId);
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
&& terminalCwdStore.getSource(options.sessionId) === 'osc7'
&& (same(cwd, path) || same(cwd, canonical));
};
@@ -171,6 +178,8 @@ export function createTerminalDirectoryController(options: {
return {
target,
capabilities,
trustsOsc7,
getVerifiedCwd: () => verifiedCwd,
getCwdError: () => cwdError?.code ?? null,
refresh: () => refresh(),
hasConfirmedCwd: () => confirmed,
+15 -1
View File
@@ -16,5 +16,19 @@ export const useClipboardBackend = () => {
return await bridge.writeClipboardText(text) === true;
}, []);
return { readClipboardText, writeClipboardText };
const readClipboardImagePng = useCallback(async (): Promise<Uint8Array | null> => {
const bridge = netcattyBridge.get();
if (bridge?.readClipboardImagePng) return await bridge.readClipboardImagePng();
// Browser fallback when the native clipboard bridge is unavailable.
const items = await navigator.clipboard?.read();
for (const item of items ?? []) {
if (!item.types.includes("image/png")) continue;
const blob = await item.getType("image/png");
return new Uint8Array(await blob.arrayBuffer());
}
return null;
}, []);
return { readClipboardText, writeClipboardText, readClipboardImagePng };
};
@@ -10,9 +10,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
useSyncExternalStore(terminalCwdStore.subscribe, terminalCwdStore.getVersion, terminalCwdStore.getVersion);
const [confirmation, setConfirmation] = useState<{ sessionId: string; controller: typeof controller } | null>(null);
const confirmed = confirmation?.sessionId === sessionId && confirmation.controller === controller;
const observedCwd = terminalCwdStore.getCwd(sessionId);
const getCurrentCwd = useCallback(() => controller?.trustsOsc7 === false && pathFlavor === 'posix'
? controller.getVerifiedCwd() : terminalCwdStore.getCwd(sessionId), [controller, pathFlavor, sessionId]);
const observedCwd = getCurrentCwd();
const cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
&& (confirmed || controller.hasConfirmedCwd() || (controller.trustsOsc7 && terminalCwdStore.getSource(sessionId) === 'osc7'))
? observedCwd : null;
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
@@ -77,7 +79,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
for (let attempt = 0; attempt < 3; attempt++) {
const revision = terminalCwdStore.getSessionRevision(sessionId);
const result = await controller.list(cwd, task.signal);
if (task.signal.aborted || id !== generation.current || terminalCwdStore.getCwd(sessionId) !== cwd) return;
if (task.signal.aborted || id !== generation.current || getCurrentCwd() !== cwd) return;
if (terminalCwdStore.getSessionRevision(sessionId) !== revision) continue;
listingBase.current = cwd; listingRevision.current = revision; setEntries(result.entries); setHome(result.home);
return;
@@ -86,7 +88,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
} catch (failure) {
if (!task.signal.aborted && id === generation.current) report(failure, 'readFailed');
} finally { if (!task.signal.aborted && id === generation.current) setLoading(false); }
}, [controller, cwd, report, sessionId, setHome]);
}, [controller, cwd, getCurrentCwd, report, sessionId, setHome]);
useEffect(() => {
if (!cwd) {
@@ -102,7 +104,7 @@ export function useComposeDirectoryPicker(sessionId: string) {
const change = useCallback(async (path: string) => {
if (!controller) { setError('unavailable'); return; }
if (sending.current) return;
if (!cwd || terminalCwdStore.getCwd(sessionId) !== cwd
if (!cwd || getCurrentCwd() !== cwd
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
sending.current = true; setPending(true); setError(null);
@@ -115,12 +117,12 @@ export function useComposeDirectoryPicker(sessionId: string) {
finally {
if (id === generation.current) { sending.current = false; setPending(false); }
}
}, [controller, report, cwd, sessionId, pathFlavor]);
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
const cwdError = controller?.getCwdError() ?? null;
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|| error === 'gitBashIntegrationUnavailable' || error === 'nonFilesystem';
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'nonFilesystem';
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
error: cwdError ?? (cwd && waitsForCwd ? null : error),
+74
View File
@@ -2,6 +2,28 @@ import { useEffect, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
type Raster = { light: string; dark?: string };
const MAX_CATALOG_BRAND_ICON_CACHE = 256;
const SAFE_PNG_DATA_URI = /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/;
const catalogBrandIconCache = new Map<string, Raster | null>();
const catalogBrandIconPending = new Map<string, Promise<Raster | null>>();
function normalizeCatalogBrandIcon(value: { light?: string | null; dark?: string | null } | null | undefined): Raster | null {
if (!value || typeof value !== 'object') return null;
const isSafe = (uri: unknown): uri is string =>
typeof uri === 'string' && uri.length <= 700_000 && SAFE_PNG_DATA_URI.test(uri);
const light = isSafe(value.light) ? value.light : null;
const dark = isSafe(value.dark) ? value.dark : null;
if (light) return dark ? { light, dark } : { light };
if (dark) return { light: dark, dark };
return null;
}
export function clearCatalogBrandIconCacheForTests(): void {
catalogBrandIconCache.clear();
catalogBrandIconPending.clear();
}
export function usePluginBrandIcon(plugin?: NetcattyInstalledPlugin): Raster | null {
const pluginId = plugin?.id;
const kind = plugin?.manifest?.icon?.kind;
@@ -17,3 +39,55 @@ export function usePluginBrandIcon(plugin?: NetcattyInstalledPlugin): Raster | n
}, [key, pluginId, kind]);
return loaded?.key === key ? loaded.value : null;
}
export function useCatalogBrandIcon(entry?: NetcattyPluginCatalogEntry, sourceId = 'official'): Raster | null {
const entryId = entry?.id;
const selectionToken = entry?.selectionToken;
const iconKind = entry?.manifest?.icon?.kind;
const cacheKey = entryId && selectionToken && iconKind !== 'theme'
? JSON.stringify([sourceId, entryId, selectionToken])
: null;
const cached = cacheKey && catalogBrandIconCache.has(cacheKey)
? catalogBrandIconCache.get(cacheKey) ?? null
: undefined;
const [loaded, setLoaded] = useState<{ key: string; value: Raster | null } | null>(null);
useEffect(() => {
if (!cacheKey || !entryId || !selectionToken) return;
if (catalogBrandIconCache.has(cacheKey)) {
setLoaded({ key: cacheKey, value: catalogBrandIconCache.get(cacheKey) ?? null });
return;
}
const fetchIcon = netcattyBridge.get()?.getPluginCatalogBrandIcon;
if (!fetchIcon) return;
let cancelled = false;
let request = catalogBrandIconPending.get(cacheKey);
if (!request) {
request = Promise.resolve(fetchIcon(entryId, selectionToken, sourceId))
.then((raw) => {
const normalized = normalizeCatalogBrandIcon(raw);
if (catalogBrandIconCache.size >= MAX_CATALOG_BRAND_ICON_CACHE) {
catalogBrandIconCache.clear();
}
catalogBrandIconCache.set(cacheKey, normalized);
return normalized;
})
.finally(() => {
if (catalogBrandIconPending.get(cacheKey) === request) {
catalogBrandIconPending.delete(cacheKey);
}
});
catalogBrandIconPending.set(cacheKey, request);
}
void request.then((value) => {
if (!cancelled) setLoaded({ key: cacheKey, value });
}).catch(() => {
if (!cancelled) setLoaded({ key: cacheKey, value: null });
});
return () => { cancelled = true; };
}, [cacheKey, entryId, selectionToken, sourceId]);
if (!cacheKey) return null;
if (cached !== undefined) return cached;
return loaded?.key === cacheKey ? loaded.value : null;
}
+60 -23
View File
@@ -1,42 +1,32 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { checkPluginUpdates, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
import { checkPluginUpdates, type PluginUpdateCandidate, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
/** Manual catalog checks only; no scheduler, install or permission mutation. */
export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]) {
/** Automatic update checks on plugin view entry and package changes; explicit installUpdate runs only on user click. */
export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[], onUpdated?: () => Promise<unknown> | void) {
const [result, setResult] = useState<PluginUpdateCheckResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [updatingId, setUpdatingId] = useState<string | null>(null);
const [updateError, setUpdateError] = useState<string | null>(null);
const pending = useRef(false);
const updating = useRef(false);
const mounted = useRef(false);
const onUpdatedRef = useRef(onUpdated);
onUpdatedRef.current = onUpdated;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const generation = useRef(0);
const pluginsCount = plugins.length;
const identityKey = useMemo(() => JSON.stringify(plugins.map((plugin) => [
plugin.id, plugin.activeVersion, plugin.archiveSha256, plugin.source?.id,
plugin.source?.kind, plugin.source?.origin,
])), [plugins]);
useEffect(() => {
generation.current++;
setResult(null);
setError(null);
const requests = generation;
return () => { requests.current++; };
}, [identityKey]);
useEffect(() => {
const invalidate = () => {
generation.current++;
setResult(null);
setError(null);
};
const unsubscribe = netcattyBridge.get()?.onPluginContributionsChanged?.(invalidate);
window.addEventListener('netcatty:plugin-packages-changed', invalidate);
return () => { unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', invalidate); };
}, []);
const check = useCallback(async () => {
const check = useCallback(async (options?: { silent?: boolean }) => {
if (pending.current) return;
pending.current = true;
const current = generation.current;
setBusy(true); setError(null); setResult(null);
setBusy(true); setError(null); setUpdateError(null);
if (!options?.silent) setResult(null);
try {
const value = await checkPluginUpdates(netcattyBridge.require());
if (mounted.current && current === generation.current) setResult(value);
@@ -48,5 +38,52 @@ export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]
if (mounted.current) setBusy(false);
}
}, []);
return { result, error, busy, check };
useEffect(() => {
generation.current++;
setResult(null);
setError(null);
const requests = generation;
if (pluginsCount > 0 && netcattyBridge.get()?.listPluginCatalog) {
void check();
}
return () => { requests.current++; };
}, [identityKey, pluginsCount, check]);
useEffect(() => {
const invalidate = () => {
generation.current++;
setResult(null);
setError(null);
};
const unsubscribe = netcattyBridge.get()?.onPluginContributionsChanged?.(invalidate);
window.addEventListener('netcatty:plugin-packages-changed', invalidate);
return () => { unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', invalidate); };
}, []);
const installUpdate = useCallback(async (candidate: PluginUpdateCandidate, wasEnabled = false) => {
if (updating.current) return;
updating.current = true;
setUpdatingId(candidate.pluginId);
setUpdateError(null);
try {
const bridge = netcattyBridge.require();
if (!bridge.listPluginCatalog || !bridge.installCatalogPlugin) throw new Error('Catalog installation unavailable');
const catalog = await bridge.listPluginCatalog(candidate.sourceId);
if (catalog.error || catalog.source !== 'registry') {
throw new Error(catalog.error ?? 'Registry refresh failed');
}
const entry = catalog.entries.find((item) => item.id === candidate.pluginId && item.artifact);
if (!entry) throw new Error('Published update is no longer available');
await bridge.installCatalogPlugin(candidate.pluginId, entry.selectionToken, candidate.sourceId, candidate.sourceId);
if (wasEnabled && bridge.setPluginEnabled) {
await bridge.setPluginEnabled(candidate.pluginId, true);
}
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
await onUpdatedRef.current?.();
} catch (cause) {
if (mounted.current) setUpdateError(cause instanceof Error ? cause.message : String(cause));
} finally {
updating.current = false;
if (mounted.current) setUpdatingId(null);
}
}, []);
return { result, error, busy, check, updatingId, updateError, installUpdate };
}
@@ -58,6 +58,7 @@ export const isAutoStartProxyReady = (
host.proxyProfileId && !validProxyProfileIds.has(host.proxyProfileId),
);
const missingGroupProxyProfile = Boolean(
!host.directProxy &&
!host.proxyConfig &&
!host.proxyProfileId &&
rawGroupDefaults.proxyProfileId &&
@@ -44,7 +44,8 @@ export function useTerminalDirectorySession(options: {
pathFlavor,
windowsShell: integration,
}, isCurrent),
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
target: { authority: `${integration === 'wsl' ? 'wsl' : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
trustOsc7: integration !== 'wsl',
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
isCurrent,
@@ -60,7 +61,11 @@ export function useTerminalDirectorySession(options: {
if (windowsShell) register('win32', windowsShell);
else if (shellType === 'posix' && host.localShell) {
const shells = await bridge.discoverShells?.();
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
const command = host.localShell.toLowerCase();
if (shells?.some(shell => shell.id.startsWith('wsl-')
&& (command === shell.id.toLowerCase() || command === shell.command.toLowerCase()))) {
register('posix', 'wsl');
} else if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
register('win32', 'git-bash');
}
}
@@ -0,0 +1,167 @@
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.tsx";
import type { GroupConfig } from "../types.ts";
import GroupDetailsPanel from "./GroupDetailsPanel.tsx";
import { ProxyPanel } from "./host-details/ProxyPanel.tsx";
import { AsidePanel } from "./ui/aside-panel.tsx";
import { Badge } from "./ui/badge.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
async function mountGroupDetails(config: GroupConfig | undefined) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
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);
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let saved: GroupConfig | undefined;
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath={config?.path ?? "corp/local"}
config={config}
availableKeys={[]}
identities={[]}
proxyProfiles={[]}
allHosts={[]}
groups={["corp", "corp/local"]}
groupConfigs={[
{ path: "corp", proxyConfig: { type: "http", host: "corp-proxy.example.com", port: 8080 } },
...(config ? [config] : []),
]}
terminalThemeId="default"
terminalFontSize={14}
onSave={(value) => { saved = value; }}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const cleanup = async () => {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
environment.IS_REACT_ACT_ENVIRONMENT = previous;
};
return {
get root() {
return renderer!.root;
},
getSaved: () => saved,
cleanup,
};
}
const findProxySummaryButton = (root: ReactTestRenderer["root"]) =>
root.findAllByType("button").find((button) => {
const badges = button.findAllByType(Badge);
return badges.some((badge) =>
badge.props.children === "HTTP" || badge.props.children === "Direct (no proxy)",
);
});
test("GroupDetailsPanel lets a child group choose Direct (no proxy) and persists directProxy", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
protocol: "ssh",
proxyConfig: { type: "http", host: "old-proxy.example.com", port: 8080 },
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "Proxy summary button should be rendered");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(typeof proxyPanel.props.onSelectDirectProxy, "function");
assert.equal(proxyPanel.props.directProxy, undefined);
await act(async () => {
proxyPanel.props.onSelectDirectProxy!();
});
const updatedPanel = harness.root.findByType(ProxyPanel);
assert.equal(updatedPanel.props.directProxy, true);
assert.equal(updatedPanel.props.proxyConfig, undefined);
assert.equal(updatedPanel.props.selectedProxyProfileId, undefined);
await act(async () => {
updatedPanel.props.onBack();
});
const proxyButtonAfter = findProxySummaryButton(harness.root);
assert.ok(proxyButtonAfter);
const badge = proxyButtonAfter.findByType(Badge);
assert.equal(badge.props.children, "Direct (no proxy)");
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, true);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
test("GroupDetailsPanel clears directProxy when removed in ProxyPanel so parent proxy applies again", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
directProxy: true,
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "SSH section and Proxy summary should open automatically for directProxy groups");
assert.equal(proxyButton.findByType(Badge).props.children, "Direct (no proxy)");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(proxyPanel.props.directProxy, true);
await act(async () => {
proxyPanel.props.onClearProxy();
});
assert.equal(harness.root.findByType(ProxyPanel).props.directProxy, undefined);
await act(async () => {
harness.root.findByType(ProxyPanel).props.onBack();
});
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, undefined);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
+5
View File
@@ -33,6 +33,11 @@ test("GroupDetailsPanel keeps the SSH section when X11 forwarding is set", () =>
assert.equal(hasGroupSshFields({ x11Forwarding: false }), true);
});
test("GroupDetailsPanel keeps the SSH section when directProxy is set", () => {
assert.equal(hasGroupSshFields({ directProxy: true }), true);
assert.equal(hasGroupSshFields({ directProxy: false }), false);
});
test("GroupDetailsPanel treats cleared telnet credentials as explicit settings", () => {
assert.equal(hasGroupTelnetFields({ telnetUsername: "" }), true);
assert.equal(hasGroupTelnetFields({ telnetPassword: "" }), true);
+47 -24
View File
@@ -121,6 +121,7 @@ export const hasGroupSshFields = (c: Partial<GroupConfig>): boolean => {
return Boolean(
c.proxyProfileId ||
c.proxyConfig ||
c.directProxy === true ||
c.hostChain ||
c.startupCommand ||
c.startupCommandRunMode !== undefined,
@@ -350,23 +351,29 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
[form.proxyProfileId, proxyProfiles],
);
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
const hasMissingProxyProfile = Boolean(!form.directProxy && form.proxyProfileId && !selectedProxyProfile);
const hasProxyConfig = Boolean(
form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
form.directProxy || form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const proxySummaryType = form.directProxy
? t("hostDetails.proxy.direct")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = form.directProxy
? t("hostDetails.proxy.directHint")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = form.directProxy
? `${t("hostDetails.proxy.direct")} - ${t("hostDetails.proxy.directHint")}`
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const update = <K extends keyof GroupConfig>(key: K, value: GroupConfig[K] | undefined) => {
setForm((prev) => ({ ...prev, [key]: value }));
@@ -463,6 +470,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -479,6 +487,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -494,6 +503,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -513,6 +523,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -525,7 +536,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const updateProxyConfig = useCallback(
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
setForm((prev) => {
const { proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return {
...rest,
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
@@ -537,19 +548,26 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const clearProxyConfig = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return rest;
});
}, []);
const selectProxyProfile = useCallback((profileId: string | undefined) => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) return rest;
return { ...rest, proxyProfileId: profileId };
});
}, []);
const selectDirectProxy = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
return { ...rest, directProxy: true };
});
}, []);
// Chain helpers
const chainedHosts = useMemo(() => {
const ids = form.hostChain?.hostIds || [];
@@ -751,7 +769,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
setNameError(t("vault.groups.errors.invalidChars"));
return;
}
const newPath = parentGroup ? `${parentGroup}/${trimmedName}` : trimmedName;
if (newPath !== groupPath && groups.includes(newPath)) {
setNameError(t("vault.groups.errors.duplicatePath"));
@@ -772,7 +789,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const anyProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled || telnetEnabled;
const anyRoutingProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled;
const proxySave = anyProtocolEnabled
const proxySave = anyProtocolEnabled && !form.directProxy
? prepareProxyConfigForSave({
proxyConfig: form.proxyConfig,
proxyProfileId: form.proxyProfileId,
@@ -917,10 +934,14 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
}),
...(finalRdpConfig && { rdpConfig: finalRdpConfig }),
...(finalVncConfig && { vncConfig: finalVncConfig }),
...(anyProtocolEnabled && {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}),
...(anyProtocolEnabled && (
form.directProxy === true
? { directProxy: true }
: {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}
)),
...(anyRoutingProtocolEnabled && {
...(form.hostChain !== undefined && { hostChain: form.hostChain }),
}),
@@ -954,8 +975,10 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={form.proxyProfileId}
directProxy={form.directProxy}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
onSelectDirectProxy={selectDirectProxy}
onClearProxy={clearProxyConfig}
onBack={() => setActiveSubPanel("none")}
onCancel={onCancel}
+5 -1
View File
@@ -63,6 +63,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxySummaryType,
proxySummaryLabel,
proxySummaryTooltip,
displayDirectProxy = Boolean(form.directProxy),
proxyInherited = false,
clearProxyConfig,
}) => {
@@ -784,7 +785,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
title={t("hostDetails.proxy")}
className="overflow-hidden"
>
{form.directProxy ? (
{displayDirectProxy ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<button
type="button"
@@ -796,8 +797,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
<span className="block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{t("hostDetails.proxy.directHint")}
{proxyInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</button>
{!proxyInherited && (
<Button
type="button"
variant="ghost"
@@ -808,6 +811,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<X size={14} />
</Button>
)}
</div>
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId || proxyInherited ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
@@ -691,6 +691,34 @@ test("HostDetailsPanel direct proxy hides inherited group proxy", () => {
assert.match(markup, /Direct \(no proxy\)/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel displays inherited group directProxy and hides global default proxy", () => {
const previous = getActiveGlobalDefaultProxyProfileId();
try {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
const markup = renderHostDetailsWithGroup(networkSshHost, {
directProxy: true,
});
assert.match(markup, /Direct \(no proxy\)/);
assert.match(markup, /Inherited from group/);
assert.doesNotMatch(markup, /Configure proxy/);
const overridden = renderHostDetailsWithGroup({
...networkSshHost,
proxyConfig: { type: "http", host: "host-proxy.example.com", port: 9090 },
}, {
directProxy: true,
});
assert.match(overridden, /host-proxy\.example\.com/);
assert.doesNotMatch(overridden, /Direct \(no proxy\)/);
assert.doesNotMatch(overridden, /Inherited from group/);
} finally {
publishActiveGlobalDefaultProxyProfileId(previous);
}
});
test("HostDetailsPanel displays inherited group jump hosts", () => {
+6 -3
View File
@@ -517,8 +517,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasHostProxyOverride = form.directProxy === true
|| form.proxyProfileId !== undefined
|| form.proxyConfig !== undefined;
const displayDirectProxy = form.directProxy === true
|| (!hasHostProxyOverride && effectiveAuthHost.directProxy === true);
const displayProxyProfileId = resolveDisplayProxyProfileId(form, effectiveAuthHost.proxyProfileId);
const displayProxyConfig = form.directProxy
const displayProxyConfig = displayDirectProxy
? undefined
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
const selectedProxyProfile = useMemo(
@@ -527,7 +529,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
displayDirectProxy || displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
@@ -1518,7 +1520,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={displayProxyProfileId}
directProxy={form.directProxy}
directProxy={displayDirectProxy}
allowClear={hasHostProxyOverride}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
@@ -1902,6 +1904,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxySummaryType={proxySummaryType}
proxySummaryLabel={proxySummaryLabel}
proxySummaryTooltip={proxySummaryTooltip}
displayDirectProxy={displayDirectProxy}
proxyInherited={proxyInherited}
clearProxyConfig={clearProxyConfig}
/>
+12
View File
@@ -226,3 +226,15 @@ test("ProxyPanel offers keychain identities for HTTP and SOCKS5 proxy credential
assert.match(markup, /Proxy login/);
assert.match(markup, /proxy-user/);
});
test("ProxyPanel shows saved proxy selector and enables saving without profiles when directProxy is selected", () => {
const markup = renderPanel({
directProxy: true,
onSelectDirectProxy: () => {},
});
assert.match(markup, /Saved proxy/);
assert.match(markup, /Remove Proxy/);
assert.doesNotMatch(markup, /Proxy host/);
assert.doesNotMatch(markup, /disabled=""/);
});
+85 -57
View File
@@ -137,8 +137,10 @@ import {
} from '../domain/sidePanelLayout';
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
import {
isPaneMagnificationSelectionValid,
canMagnifyPaneSurface,
pruneMagnifiedPanesByTab,
resolvePaneMagnificationCandidate,
setTabMagnifiedPane,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../domain/paneMagnification';
@@ -318,12 +320,11 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onRemoveSessionFromWorkspace,
}) => {
const { t } = useI18n();
const [magnifiedPane, setMagnifiedPane] = useState<{
tabId: string;
target: PaneMagnificationTarget;
} | null>(null);
const magnifiedPaneRef = useRef(magnifiedPane);
magnifiedPaneRef.current = magnifiedPane;
const [magnifiedPanesByTab, setMagnifiedPanesByTab] = useState<
ReadonlyMap<string, PaneMagnificationTarget>
>(() => new Map());
const magnifiedPanesByTabRef = useRef(magnifiedPanesByTab);
magnifiedPanesByTabRef.current = magnifiedPanesByTab;
const lastInteractedPaneRef = useRef<Map<string, PaneMagnificationTarget>>(new Map());
// Side panel state must be initialized before any callbacks reference its
// setters or refs in their dependency arrays.
@@ -345,8 +346,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}, [sessions]);
useEffect(() => {
setMagnifiedPane((current) => {
if (!current) return current;
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
const terminalPanes = sessions.map((session) => ({
tabId: session.workspaceId ?? session.id,
sessionId: session.id,
@@ -354,9 +355,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const sidePanelPanes = Array.from(sidePanelLayouts.entries()).flatMap(([tabId, layout]) => (
collectSidePanelPanes(layout.root).map((pane) => ({ tabId, paneId: pane.id }))
));
return isPaneMagnificationSelectionValid(current, terminalPanes, sidePanelPanes)
? current
: null;
return pruneMagnifiedPanesByTab(current, terminalPanes, sidePanelPanes);
});
}, [sessions, sidePanelLayouts]);
const terminalRendererCwdBySessionRef = useRef<Map<string, string>>(new Map());
@@ -475,11 +474,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
// Stable callback references for Terminal components
const handleCloseSession = useCallback((sessionId: string) => {
setMagnifiedPane((current) => (
current?.target.kind === 'terminal' && current.target.sessionId === sessionId
? null
: current
));
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
let changed = false;
const next = new Map(current);
for (const [tabId, target] of next) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
next.delete(tabId);
changed = true;
}
}
return changed ? next : current;
});
for (const [tabId, target] of lastInteractedPaneRef.current) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
lastInteractedPaneRef.current.delete(tabId);
@@ -1773,9 +1779,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleCloseSidePanel = useCallback(() => {
const activeTabId = activeTabIdRef.current;
if (!activeTabId) return;
setMagnifiedPane((current) => (
current?.tabId === activeTabId && current.target.kind === 'side-panel'
? null
setMagnifiedPanesByTab((current) => (
current.get(activeTabId)?.kind === 'side-panel'
? setTabMagnifiedPane(current, activeTabId, null)
: current
));
const sessionIdToRefocus = getActiveTerminalSessionId();
@@ -1906,14 +1912,27 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleMagnifyTerminalPane = useCallback((tabId: string, sessionId: string) => {
const target: PaneMagnificationTarget = { kind: 'terminal', sessionId };
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'terminal'
&& current.target.sessionId === sessionId
? null
: { tabId, target }
));
}, []);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'terminal' && existing.sessionId === sessionId) {
return setTabMagnifiedPane(current, tabId, null);
}
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
candidate.id === tabId && !candidate.workspaceId
));
const terminalCount = workspaceSessionIds.length > 0
? workspaceSessionIds.length
: standaloneSession ? 1 : 0;
const layout = sidePanelLayoutsRef.current.get(tabId);
const sidePanelCount = layout ? collectSidePanelPanes(layout.root).length : 0;
if (!canMagnifyPaneSurface(terminalCount, sidePanelCount)) {
return current;
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleMagnifySidePanelPane = useCallback((paneId: string) => {
const tabId = activeTabIdRef.current;
@@ -1929,18 +1948,19 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
tool: pane.tool,
};
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: { tabId, target }
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'side-panel' && existing.paneId === paneId) {
return setTabMagnifiedPane(current, tabId, null);
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleRestoreMagnifiedPane = useCallback(() => {
const tabId = activeTabIdRef.current;
setMagnifiedPane((current) => current?.tabId === tabId ? null : current);
if (!tabId) return;
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, tabId, null));
}, []);
useEffect(() => {
@@ -1949,7 +1969,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const tabId = activeTabStore.getActiveTabId();
if (!tabId) return null;
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const hasCurrentMagnification = magnifiedPaneRef.current?.tabId === tabId;
const currentTarget = magnifiedPanesByTabRef.current.get(tabId);
const hasCurrentMagnification = !!currentTarget;
if (workspace?.viewMode === 'focus' && !hasCurrentMagnification) return null;
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
@@ -1971,7 +1992,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
? [focusedSidePanelPane, ...sidePanelPanes.filter((pane) => pane !== focusedSidePanelPane)]
: sidePanelPanes,
lastTarget: lastInteractedPaneRef.current.get(tabId),
current: magnifiedPaneRef.current,
current: currentTarget ? { tabId, target: currentTarget } : null,
});
return candidate ? { tabId, ...candidate } : null;
};
@@ -1983,19 +2004,23 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
focus: () => {
const target = getTarget();
if (!target || target.focused) return false;
setMagnifiedPane({ tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, target.target));
return true;
},
restore: () => {
const target = getTarget();
if (!target?.focused) return false;
setMagnifiedPane(null);
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, null));
return true;
},
toggle: () => {
const target = getTarget();
if (!target) return false;
setMagnifiedPane(target.focused ? null : { tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(
current,
target.tabId,
target.focused ? null : target.target,
));
return true;
},
};
@@ -2029,13 +2054,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const closingPane = layout
? collectSidePanelPanes(layout.root).find((pane) => pane.id === paneId)
: undefined;
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
const closesWholePanel = closeSidePanelPaneForTab(tabId, paneId);
if (closesWholePanel) {
handleCloseSidePanel();
@@ -2063,8 +2087,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const layout = sidePanelLayoutsRef.current.get(tabId);
const pane = layout && collectSidePanelPanes(layout.root).find((item) => item.id === paneId);
if (pane?.tool !== expectedTool) return;
setMagnifiedPane((current) => current?.tabId === tabId && current.target.kind === 'side-panel'
&& current.target.paneId === paneId ? null : current);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
closeSidePanelPaneForTab(tabId, paneId);
}, [closeSidePanelPaneForTab, sidePanelLayoutsRef]);
@@ -2151,12 +2179,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false;
tabId = terminal.id;
}
setMagnifiedPane((current) => (
current?.tabId === tabId
&& !(current.target.kind === 'side-panel' && current.target.tool === 'ai')
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing && !(existing.kind === 'side-panel' && existing.tool === 'ai')
? setTabMagnifiedPane(current, tabId, null)
: current;
});
activeTabStore.setActiveTabId(tabId);
if (prepareSidePanelTool(tabId, 'ai')) {
startTransition(() => {
@@ -2886,7 +2914,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
lastSidePanelTabRef,
mountedAiTabIds: aiMountedTabIds,
mountedSftpTabIds,
magnifiedPane,
magnifiedPanesByTab,
notesMountedTabIds,
browserMountedTabIds,
notesOpenNoteByTab,
+1
View File
@@ -659,6 +659,7 @@ function TerminalPopupPageInner({
accentMode={settings.accentMode}
customAccent={settings.customAccent}
terminalSettings={settings.terminalSettings}
shellType={config.sourceSession.shellType}
vaultInitializedOverride={vaultInitialized}
disableTerminalFontZoom={settings.disableTerminalFontZoom}
sessionId={sessionId}
+7 -7
View File
@@ -77,7 +77,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
const hasManualProxyCommand = Boolean(proxyConfig?.command?.trim());
const hasManualProxyValue = isCommandProxy ? hasManualProxyCommand : hasManualProxyHost;
const hasInvalidManualProxyPort = !isCommandProxy && hasManualProxyHost && !isValidProxyPort(proxyConfig?.port);
const effectiveProxyConfig = selectedProfile?.config ?? proxyConfig;
const effectiveProxyConfig = directProxy ? undefined : (selectedProfile?.config ?? proxyConfig);
const hasMissingIdentity = hasMissingProxyIdentity(effectiveProxyConfig, identities);
const hasIncompleteIdentity = hasIncompleteProxyIdentity(effectiveProxyConfig, identities);
const hasUnreadableIdentity = hasUnreadableProxyCredential(effectiveProxyConfig, identities);
@@ -92,9 +92,9 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
);
const selectedIdentityValue = selectedIdentity?.id || (hasMissingIdentity ? missingIdentityValue : manualCredentialsValue);
const handleBack = useCallback(() => {
if (hasInvalidManualProxyPort || hasInvalidIdentity) return;
if (!directProxy && (hasInvalidManualProxyPort || hasInvalidIdentity)) return;
onBack();
}, [hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
}, [directProxy, hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
return (
<AsidePanel
@@ -153,7 +153,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
{t('hostDetails.proxyPanel.missingSaved')}
</div>
)}
{selectedProfile && (
{isUsingProfile && selectedProfile && (
<div className="min-w-0 rounded-md bg-secondary/50 p-2 text-sm">
<div className="flex min-w-0 items-center gap-2">
<Badge variant="secondary" className="text-xs shrink-0">
@@ -165,17 +165,17 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
</div>
</div>
)}
{selectedProfile && hasMissingIdentity && (
{isUsingProfile && selectedProfile && hasMissingIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.missingIdentity')}
</div>
)}
{selectedProfile && hasIncompleteIdentity && (
{isUsingProfile && selectedProfile && hasIncompleteIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.incompleteIdentity')}
</div>
)}
{selectedProfile && hasUnreadableIdentity && (
{isUsingProfile && selectedProfile && hasUnreadableIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.unreadableIdentity')}
</div>
+10 -4
View File
@@ -1,8 +1,7 @@
import React, { useState } from 'react';
import { Globe, HardDrive, Store } from 'lucide-react';
import { BadgeCheck, Globe, HardDrive, Store } from 'lucide-react';
import { usePluginAuthorIdentity } from '../../application/state/usePluginAuthorIdentity';
import { useI18n } from '../../application/i18n/I18nProvider';
import { Badge } from '../ui/badge';
export function PluginAuthorRow({ entry, plugin, sourceId, showSource = false }: {
entry?: NetcattyPluginCatalogEntry; plugin?: NetcattyInstalledPlugin; sourceId?: string; showSource?: boolean;
@@ -25,8 +24,15 @@ export function PluginAuthorRow({ entry, plugin, sourceId, showSource = false }:
{(author || showImage || identity?.officialMaintained === true) && <span data-plugin-author className="inline-flex min-w-0 items-center gap-1.5 overflow-hidden">
{showImage && <img src={avatar} alt="" width={16} height={16} className="h-4 w-4 shrink-0 rounded-full object-cover" onError={() => setFailed(imageKey)} />}
{author && <span className="min-w-0 truncate" title={author}>{author}</span>}
{identity?.officialMaintained === true && <Badge className="shrink-0 whitespace-nowrap border-0 bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-800 hover:bg-amber-500/15 dark:bg-amber-400/15 dark:text-amber-300 dark:hover:bg-amber-400/15"
title={t('settings.plugins.author.officialMeaning')} data-plugin-official-maintainer>{t('settings.plugins.author.official')}</Badge>}
{identity?.officialMaintained === true && <span
role="img"
className="inline-flex shrink-0 items-center text-primary"
aria-label={t('settings.plugins.author.official')}
title={`${t('settings.plugins.author.official')} — ${t('settings.plugins.author.officialMeaning')}`}
data-plugin-official-maintainer
>
<BadgeCheck size={14} aria-hidden="true" />
</span>}
</span>}
{showSource && <span data-plugin-source className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap" title={sourceDescription} aria-label={sourceDescription}>
<SourceIcon size={12} aria-hidden="true" />{sourceLabel}
+10 -4
View File
@@ -1,12 +1,13 @@
import React, { useState } from 'react';
import { Package } from 'lucide-react';
import { usePluginBrandIcon } from '../../application/state/usePluginBrandIcon';
import { useCatalogBrandIcon, usePluginBrandIcon } from '../../application/state/usePluginBrandIcon';
import { PluginContributionIcon } from './PluginContributionIcon';
import { resolveCatalogBrandIcon } from './catalogBrandIcons';
export function PluginBrandIcon({ plugin, entry, size = 32, className = '' }: {
export function PluginBrandIcon({ plugin, entry, sourceId = 'official', size = 32, className = '' }: {
plugin?: NetcattyInstalledPlugin;
entry?: NetcattyPluginCatalogEntry;
sourceId?: string;
size?: number;
className?: string;
}) {
@@ -14,9 +15,14 @@ export function PluginBrandIcon({ plugin, entry, size = 32, className = '' }: {
const icon = manifest?.icon;
const key = JSON.stringify([plugin?.id, plugin?.activeVersion, plugin?.archiveSha256, plugin?.runtime?.quarantinedAt, icon]);
const loaded = usePluginBrandIcon(plugin);
const remoteCatalogIcon = useCatalogBrandIcon(plugin ? undefined : entry, sourceId);
const bundledCatalogIcon = !plugin && entry ? resolveCatalogBrandIcon(entry) : null;
const [failed, setFailed] = useState<string | null>(null);
const raster = plugin ? loaded : entry ? resolveCatalogBrandIcon(entry) : null;
const imageKey = JSON.stringify([key, raster]);
const remoteKey = JSON.stringify([key, entry?.id, entry?.selectionToken, sourceId, remoteCatalogIcon]);
const raster = plugin
? loaded
: (remoteCatalogIcon && failed !== remoteKey ? remoteCatalogIcon : bundledCatalogIcon);
const imageKey = JSON.stringify([key, entry?.id, entry?.selectionToken, sourceId, raster]);
if (icon?.kind === 'theme') return <PluginContributionIcon icon={icon} size={size} className={className} />;
if (!raster || failed === imageKey) return <Package size={size} className={className} aria-hidden="true" data-plugin-brand="fallback" />;
return <span className={`inline-flex shrink-0 ${className}`} style={{ width: size, height: size }} aria-hidden="true" data-plugin-brand="package">
@@ -6,6 +6,7 @@ import {
Database,
FileText,
Folder,
Gauge,
Globe,
HardDrive,
Key,
@@ -38,6 +39,7 @@ const THEME_ICONS: Readonly<Record<string, LucideIcon>> = Object.freeze({
database: Database,
file: FileText,
folder: Folder,
gauge: Gauge,
globe: Globe,
'hard-drive': HardDrive,
key: Key,
@@ -704,3 +704,107 @@ test('RemoteImageElement renders a transparent placeholder while loading and nev
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid clears stale editingCell and pending blur timer when insertedRows shrink or row is deleted', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'ShadowRoot']) {
saved.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 });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const makeTree = (insertedRows: Array<Record<string, unknown>>, deletedRowIndices: number[] = []) => ({
children: [
{
id: 'grid',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'data-grid',
'data-plugin-widget-props': JSON.stringify({
columns: [
{ name: 'id', type: 'INTEGER', primaryKey: true },
{ name: 'name', type: 'TEXT' },
],
rows: [[1, 'Alice']],
insertedRows,
deletedRowIndices,
editable: true,
}),
},
children: [],
},
],
});
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
const insertedNameCell = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"]') as HTMLElement;
assert.ok(insertedNameCell, 'inserted row cell rendered');
await act(async () => {
insertedNameCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const input = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input') as HTMLInputElement;
assert.ok(input, 'cell input opened on inserted row');
await act(async () => {
input.dispatchEvent(new dom.window.FocusEvent('blur', { bubbles: false }));
});
// Discard insertedRows immediately after blur and before blurTimeout(0) fires
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 25));
});
assert.equal(
events.some((e) => e.widgetEvent === 'cellEdit' && (e.detail as { rowIndex?: number })?.rowIndex === 1),
false,
'discarding inserted row must cancel pending blur cellEdit for removed row',
);
// Re-adding an inserted row must NOT reopen the stale editing input
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
assert.equal(
gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input'),
null,
're-adding inserted row starts clean without stale editingCell input',
);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
+25 -10
View File
@@ -1,17 +1,32 @@
[
{
"id": "com.netcatty.starter",
"version": "0.1.2",
"repository": "binaricat/Netcatty",
"commit": "f4a6b205adca486d4e9cda0270e13a9ff0afd7be",
"id": "com.binaricat.netcatty-database",
"version": "0.3.2",
"repository": "binaricat/netcatty-database-plugin",
"commit": "81c3dd7ad9193b0d3a44df1531daeb6c758b4ee8",
"icon": {
"kind": "package",
"light": "assets/logo-light.png",
"dark": "assets/logo-dark.png"
"light": "assets/plugin-icon-light.png",
"dark": "assets/plugin-icon-dark.png"
},
"light": "data:image/png;base64,iVBORw0KGgoAAA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nr6rt55f0URBtlluEwhhRKXkYDLq5TYjYKo6RM5ScIqrpkyZF7Qrf9ACoG5JnU7TVAoAeLw8mqz2YIuUDWNSYqzDJzLZ6SlymxAwjRabfz8JTcPEp7uvCbbMoAWA4xj/jGRVbVNMufyeTJI2+N1zhOgmJyNVbhMCRpIk1NRb/J85jpt5hst7RLACQHEM65+MqK6P7eCeHffJE+KTnIzY7QEAndsYy7ITgi0vKAE498aHx1A0koFWhwWbwxWsPbKiJwIQ92SlxbYA2Bwu/yQ7TcM07sbHRgRTXlACoKBVU9uOmyyxO/ZvQ68lAhDvZMXwHADQOgxotranzePATAumvKAEgGXoyW3HsTz514Zeq5LbBEKY4dioSYgdME1Wm/+Y4ejzgikrSAFgRrcdx0MPIBQhtAjRTaz6AXSksbm9rbEMe/pw1T0gYAEYf/Oc/LZgnz6fAIfLHYwdUYFKqej+IkJME8urVG04XG7/3gCahmHc9DkBu68GLAA0j6HtBskbOTZUqJSc3CYQCD2i4wuXpsRhgZYTuAAwGNJ2LHfo6FChVIQtRiohSojV8Gon43C2tzmaoYac4dIzEoQAUP69lfHQ/QcAJUd6APFOvPTynO4OAkBTAe9zDlwAKLqw7Th+hgBkDiDeUSvCE3Mw0nQaAtB030DLCVgAKBr+bXOxknqpOxRkCBD3qFTxIfIdc0zQFN37lElt9wZ6I0VR/tjNfIwG/zgZpSI+uoeE0xMvzl4dcxxQQMDr14HPiEjtAiCIsZNw4XSMGlKI4YPCGwmYID/DBxXg1mumyG1G0HTMskVRdMCJFIKYA6D8qhPrPQCdRoUPXvxjXHiJEbrnlSfvwsghhd1fGMV0ynJEydEDoODvS8V6D+Afc2ehf36m3GYQIoRKyeGTvz8Y03kYOvcAqMgLAEWLine truncated
"lightSha256": "0ca2e946c2462d340818d467a64da392164787466cf417d4d52e9bb3f973f0e2",
"dark": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO2d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6UZ0aL0czx0xAHEPNlRvBQIAJAkOKzt82wSrbwmkOICcgCsWjO57dhljn4xTJ1GLbcJhBDDciHTwAkbTlO7A+DUquOr1faCgByAQmXwrZs5onj2vw29nswBxDrRGgfQkY5tTaEyZAVSlt8OIGfK9SPbxD5FDw/eYQ3EjohArQp4WZUQ4UTzKlUbvMMCUfDuDaBZBZ0/dZ7f8et+OwCGUp7iM8hl8beYiEKpVMptAoHQK3hn+wtXkuhTTnDrCfF/CMAofUkLeEdsaOArFJzcJhBCTLi2eoca3tn+0qUYxQR/y/H7f4NlWZ9Ws9sZIz0AjjiAWEeljI1hXschN92hLfYVvx0AxSh8eys9MdIDiJUvB+H4qGNkmMc729scwyry/C3HbwdAM6xv0Vzgo0v083goFMQBxDoqVWw4AKGD0C7NcH4HsPjfA6AZX39ZEDwnujVqIHMAsU+sBHuJYoc2R9N+v7n87wHQjC+iQhIEf4uJGEYPH4gRQ0vkNoMQYkYMKcEVF50htxkBI3V46dIULine truncated
"darkSha256": "25db063da92a0e6795b5bb122c81fa64786006661da278316002bc1dca627c20"
},
{
"id": "com.binaricat.netcatty-monitor",
"version": "0.2.2",
"repository": "binaricat/netcatty-monitor-plugin",
"commit": "bee26d2092666940c881f93b83d923550571fe63",
"icon": {
"kind": "package",
"light": "assets/plugin-icon-light.png",
"dark": "assets/plugin-icon-dark.png"
},
"light": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO2dd3xUVfr/P+eWaem9BxI6oRO6Ih0ULKhY1rquSFvEgnV/rqzu2lGxYMG+lq9tFUUFASnSe68BAklI78nUW35/hJn0TJ87Mznv18uXc++ce+4z5J7nnvOcpwAUCoVCoVAoFAqFQqFQKBQKhUKhUCgUCoVCoVAoFAqFQqFQKBQKhUKhUCgUCoVCoVD8G6K0AN5m0qJF6RJjGQgi92UI34tlmO6EIJIAOoYwWgBhIERLCDilZaX4DlmGAFk2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C7HsLszA8i0fq5voo0CGQ1dAgQ9Wl6ttAgeoemYYxjicgor12cABJHWz+YAKb1kD1WQvB0o7aNRB4cCMDVJtMsQxuVc8a7PAAhse2aBVPCjI1R0CRD0BIuvhyg21jgghLj8o9ywiBCbAgikggvtMaRHLwzM7K60GBQvM7Bbd9w+eZrSYriNIDW+dAngsgOLG0bARq0T6DOAUK0WHzzyD/Cc1yqlUfyIV+c/gMHdeyothls0nQHIiswACLFFzjQVJhB5Zd796J6SqrQYFB+hUanLine truncated
"lightSha256": "e6e9dcdc2de2fe068b38f4fc1963e48b67c6a8e3b8a34735065f8debf7a36387",
"dark": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO2dd5gT1frHv9PSk+2VBZaFRQRUmtKbFEURsVdsV8X204sN9eq1d8Vyi9eLvYsVUa80qVIFbEjvbK9JNn3K74+w2YRtk2SSSbLn8zz7PJnJzDnv7s5555z3vAUgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoGQ2FBqCxBrcieNPVmkcDpNc0Npjj6RYrkiMLSBZiiOohkGNMVSDENRVMr/KQhBSJIESRAkiBIviYIgCpIPgugUed8RySfuFEXfFlrCj9XL1/ymtqyxJNWeejpr0tgZDMfOYnXakbROl09zbKr9joQ4Ivl4yedyVYpe7zrBy39Qt3zNNwBEteVSiuQfHBMm6LI14lxWp7uGNRp70CxDqy0SIXUReV7km1yHebf77VrW8Cz+9z+P2jJFQ9IqgNwzJl5Ac+xc1mQcSnNsu4Ne4nkIbg94pxu82w3B5Ybo9UESRUiCCFEQAEGAJEnxFJ+gMhRFAQwDmmFAMTQohgHNsWD0OrDHfmidDjTLtNuG6ONFn83+h+h0vVSzct078ZNeOZJNAdA5U8c/wZlNt7MGvbGtCyQfD6/NDq/VDp/VDt7tjreMhBSC1enApZmhSTNDYzGD4tg2r+OdL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H7pr6qJuUi16doufQYoQf3RaLTLSk3er1V1TH/jMmYxDMGBA6+qkYRK1AsjW4D6aY2kAEH1ef6HOJCU9TXkPNEJi0S0veZcBXqst4FRHcxyTVZh5d7RtRq0AWJ3m6ubP7pr6pHL5PR6z0dz5RYSkpii/oPOLEhVJgru2JX8mpzdcF22T0SoAmjUaA2lMgoVLRswKhM8SEptkNgQCgLuuZRnAGvS9EKUzX1QKIOv0MefSrD/kT/Lx4B0JVfg0bJSInyckNgW5eWqLEBW8wxXYYqc5ls6ePFZeuqp2iEoBMBruyubPXlty5F7rCJPRqLYIhBhTmJ/cCgCSFGJnY1j2qmiai0oBsDrtyObPqZDe22QgCiDVYVlObRGixme1BT7TWm1UEU5RKQBapwssqFJhBkBsAKlPsvoBBOO1tswAWKMuKqtmxAog94wxpzQn+5R4HoLLHY0cCYHeH8pASGGSpVZAR/AuF8Rj2Y0ohqXzJ43tH2lbESsAUaAmBgRyq5f5Vkm0Wm3nFxEICYDoahlzAt0yFsMlYgVAc2wgtlJwJv/bH/AXASGkNkwSZ1gKhg+acVM0c1qk7USuABjmxIAw7tRQABqOKIBUR5cis7zgJTfFtYzFcIlYAVAMF0hQmArrfyB1Hg5C++i0qWHnCX7p0hzbPdJ2Ip8PMbSh+WOyRv8dD1kCpD6pYugVfcFpARlDuxd2QhRLADqwoSoJqaEANEQBpDyp4uwlHcsQBAA0Q0X84EY+A6DpQFWhYGGSlcEDB+LkEyPeTSEkCSef2B9XnHeB2mJEjcQHjbmgsRgukdsAKCpQU0BMcgVgMhgw/7l54NiYVUojJBAv/v1RDBoQ27TvsUYMqnJEs5FvbUSuAFimxaUqiUoutcXzDz6MPsW91BaDECd0Wi3eeenV5K7DIAaNueYafBEQzQwg8DmZvatmTDkDl808X20xCHGmuKgH/vnELine truncated
"darkSha256": "0b0616b653f735898137bd969d9eb5779f7f2432b7209fa9f32c7a052a93fdd6"
}
]
@@ -89,6 +89,22 @@ export function PluginDataGrid({
);
const totalRows = rows.length + insertedRows.length;
useEffect(() => {
if (!editingCell) return;
const colAtIdx = visibleCols[editingCell.colIndex];
const invalidRow =
editingCell.rowIndex < 0 || editingCell.rowIndex >= totalRows || deletedSet.has(editingCell.rowIndex);
const invalidCol = !colAtIdx || colAtIdx.col.name !== editingCell.colName;
if (invalidRow || invalidCol) {
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
editingCellRef.current = null;
setEditingCell(null);
}
}, [editingCell, totalRows, deletedSet, visibleCols]);
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
const custom = colWidths[col.name];
if (custom !== undefined) return custom;
+37 -20
View File
@@ -9,6 +9,8 @@ import React, {
} from 'react';
import { AlertCircle, UploadCloud } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData } from '../../domain/rdpClipboard';
import {
computeMonitorVirtualBounds,
mapViewportToVirtualDesktopCoords,
@@ -186,6 +188,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
ref,
) {
const { t } = useI18n();
const { readClipboardImagePng } = useClipboardBackend();
const containerRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -199,7 +202,9 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const modRef = useRef<IronRdpModule | null>(null);
const audioPlayerRef = useRef<RdpAudioPlayer | null>(null);
const lastAltRightUpRef = useRef(0);
const lastRemoteClipboardTextRef = useRef('');
const lastClipboardGuardStateRef = useRef<ReturnType<typeof nextRdpClipboardGuardState>>({
lastText: '', lastPngFingerprint: null,
});
const uploadedFilesRef = useRef<File[]>([]);
const uploadTransferIdRef = useRef<string>('');
const uploadedHighWaterByIndexRef = useRef<Map<number, number>>(new Map());
@@ -601,21 +606,31 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const mod = modRef.current;
if (!session || !mod) return;
try {
const text = await navigator.clipboard?.readText();
if (text && (force || text !== lastRemoteClipboardTextRef.current)) {
lastRemoteClipboardTextRef.current = text;
const data = new mod.ClipboardData();
try {
data.addText('text/plain', text);
await session.onClipboardPaste(data);
} finally {
try { data.free(); } catch { /* ignore */ }
}
// A denied or unsupported read of one format must not block the other.
const [textResult, pngResult] = await Promise.allSettled([
Promise.resolve().then(() => navigator.clipboard?.readText()),
readClipboardImagePng(),
]);
const { text, pngBytes } = selectRdpClipboardData({
text: textResult.status === 'fulfilled' ? textResult.value : null,
pngBytes: pngResult.status === 'fulfilled' ? pngResult.value : null,
...lastClipboardGuardStateRef.current,
force,
});
if (!text && !pngBytes) return;
const data = new mod.ClipboardData();
try {
if (text) data.addText('text/plain', text);
if (pngBytes) data.addBinary('image/png', pngBytes);
await session.onClipboardPaste(data);
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text, pngBytes });
} finally {
try { data.free(); } catch { /* ignore */ }
}
} catch {
// Clipboard permission or empty
}
}, []);
}, [readClipboardImagePng]);
const syncClipboardNow = useCallback(() => syncLocalClipboardToRdp(true), [syncLocalClipboardToRdp]);
@@ -1168,18 +1183,20 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
pngBytes = val;
}
}
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text: plainText, pngBytes });
if (pngBytes && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
const blob = new Blob([pngCopy], { type: 'image/png' });
void navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {
if (plainText) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
const data = buildRdpClipboardItemData({ text: plainText, pngBytes });
void navigator.clipboard.write([new ClipboardItem(data)]).catch(async () => {
if (plainText !== null) {
// Some clipboards reject mixed formats; keep the PNG if possible.
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': data['image/png'] })]);
} catch {
await navigator.clipboard?.writeText(plainText).catch(() => {});
}
}
});
} else if (plainText !== null) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
}
} catch {
@@ -108,10 +108,11 @@ test('mounted author rows load only when visible, retain fallbacks, cancel stale
const image = document.querySelector('img')!;
assert.equal(image.getAttribute('src'), identity.avatar); assert.equal(image.width, 16); assert.equal(image.height, 16);
const badge = document.querySelector<HTMLElement>('[data-plugin-official-maintainer]')!;
assert.equal(badge.textContent, 'Official maintainer'); assert.match(badge.title, /not a safety certification/);
assert.ok(badge.classList.contains('border-0'));
assert.ok(badge.classList.contains('bg-amber-500/15')); assert.ok(badge.classList.contains('dark:bg-amber-400/15'));
assert.ok(badge.classList.contains('text-amber-800')); assert.ok(badge.classList.contains('dark:text-amber-300'));
assert.equal(badge.getAttribute('aria-label'), 'Official maintainer');
assert.match(badge.title, /Official maintainer/);
assert.match(badge.title, /not a safety certification/);
assert.ok(badge.classList.contains('text-primary'));
assert.ok(badge.querySelector('svg[aria-hidden="true"]'));
document.documentElement.classList.add('dark');
assert.ok(document.querySelector('[data-plugin-author-row]')?.classList.contains('items-center'));
await act(async () => image.dispatchEvent(new Event('error')));
@@ -6,6 +6,7 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { inspectPluginBrandIcon } from '@netcatty/plugin-contract';
import { clearCatalogBrandIconCacheForTests } from '../../../application/state/usePluginBrandIcon';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { resolveCatalogBrandIcon } from '../../plugins/catalogBrandIcons';
import previews from '../../plugins/catalog-brand-icons.json';
@@ -15,16 +16,20 @@ const entry = { ...preview, manifest: { icon: preview.icon } } as unknown as Net
test('reviewed catalog brand previews bind version, source and declaration, never arbitrary URLs', () => {
assert.ok(resolveCatalogBrandIcon(entry));
const catalog = JSON.parse(readFileSync(new URL('../../../electron/plugins/catalog.json', import.meta.url), 'utf8')) as NetcattyPluginCatalogEntry[];
assert.ok(resolveCatalogBrandIcon(catalog.find((item) => item.id === preview.id)!));
assert.equal(previews.length, 2);
assert.equal(catalog.length, 2);
for (const item of previews) {
assert.ok(resolveCatalogBrandIcon(catalog.find((c) => c.id === item.id)!), `catalog should match preview for ${item.id}`);
for (const theme of ['light', 'dark'] as const) {
const bytes = Buffer.from(item[theme].split(',')[1], 'base64');
assert.equal(createHash('sha256').update(bytes).digest('hex'), item[`${theme}Sha256`]);
const inspected = inspectPluginBrandIcon(bytes, item.icon[theme]);
assert.ok(inspected.width === 128 || inspected.width === 256);
}
}
for (const replacement of [{ version: '9.0.0' }, { commit: '0'.repeat(40) }, { repository: 'untrusted/plugin' }, { manifest: { icon: { kind: 'package', light: 'https://attacker.invalid/a.png' } } }]) {
assert.equal(resolveCatalogBrandIcon({ ...entry, ...replacement } as NetcattyPluginCatalogEntry), null);
}
for (const theme of ['light', 'dark'] as const) {
const bytes = Buffer.from(preview[theme].split(',')[1], 'base64');
assert.equal(createHash('sha256').update(bytes).digest('hex'), preview[`${theme}Sha256`]);
assert.equal(inspectPluginBrandIcon(bytes, preview.icon[theme]).width, 128);
assert.deepEqual(bytes, readFileSync(new URL(`../../../examples/plugins/starter-netcatty/${preview.icon[theme]}`, import.meta.url)));
}
const html = renderToStaticMarkup(<PluginBrandIcon entry={entry} />);
assert.match(html, /data-plugin-brand="package"/);
assert.match(html, /dark:hidden/);
@@ -68,3 +73,68 @@ test('disabled brand theme names cannot resolve Object prototype members', () =>
assert.doesNotMatch(html, /<img/);
}
});
test('catalog brand icon fetches verified remote icons, caches per selectionToken, and falls back safely', async () => {
clearCatalogBrandIconCacheForTests();
const oldWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
const previousAct = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const calls: Array<{ id: string; selectionToken?: string; sourceId?: string }> = [];
const remoteLight = 'data:image/png;base64,iVBORw0KGgo=';
const remoteDark = 'data:image/png;base64,iVBORw0KGgoAAA==';
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
netcatty: {
getPluginCatalogBrandIcon: async (id: string, selectionToken?: string, sourceId?: string) => {
calls.push({ id, selectionToken, sourceId });
if (selectionToken === 'tok-unsafe') return { light: 'https://attacker.invalid/evil.png', dark: null };
if (selectionToken === 'tok-empty') return { light: null, dark: null };
return { light: remoteLight, dark: remoteDark };
},
},
},
});
const unbundledEntry = {
id: 'com.example.remote',
version: '1.0.0',
repository: 'example/remote',
commit: '1'.repeat(40),
selectionToken: 'tok-1',
manifest: { icon: { kind: 'package', light: 'assets/light.png', dark: 'assets/dark.png' } },
} as unknown as NetcattyPluginCatalogEntry;
let renderer: ReactTestRenderer | undefined;
try {
await act(async () => { renderer = create(<PluginBrandIcon entry={unbundledEntry} sourceId="official" />); });
assert.equal(calls.length, 1);
assert.deepEqual(calls[0], { id: 'com.example.remote', selectionToken: 'tok-1', sourceId: 'official' });
const imgs = renderer!.root.findAllByType('img');
assert.equal(imgs.length, 2);
assert.equal(imgs[0].props.src, remoteLight);
assert.equal(imgs[1].props.src, remoteDark);
// Remounting with the same selectionToken uses the in-memory cache without refetching.
await act(async () => renderer!.unmount());
await act(async () => { renderer = create(<PluginBrandIcon entry={unbundledEntry} sourceId="official" />); });
assert.equal(calls.length, 1);
assert.equal(renderer!.root.findAllByType('img').length, 2);
// Unsafe URLs from bridge are rejected and fall back to default glyph.
await act(async () => { renderer!.update(<PluginBrandIcon entry={{ ...unbundledEntry, selectionToken: 'tok-unsafe' }} sourceId="official" />); });
assert.equal(calls.length, 2);
assert.equal(renderer!.root.findAllByType('img').length, 0);
// Bundled preview is used as fallback when remote delivery has no icons.
await act(async () => { renderer!.update(<PluginBrandIcon entry={{ ...entry, selectionToken: 'tok-empty' }} sourceId="official" />); });
assert.equal(calls.length, 3);
const bundledImgs = renderer!.root.findAllByType('img');
assert.equal(bundledImgs.length, 2);
assert.equal(bundledImgs[0].props.src, preview.light);
assert.equal(bundledImgs[1].props.src, preview.dark);
} finally {
await act(async () => renderer?.unmount());
clearCatalogBrandIconCacheForTests();
if (oldWindow) Object.defineProperty(globalThis, 'window', oldWindow); else Reflect.deleteProperty(globalThis, 'window');
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousAct;
}
});
@@ -61,7 +61,7 @@ test('catalog keeps search during selection/back, switches detail, and displays
assert.match(detailText, /Incompatible with this host/);
assert.match(detailText, /Last recorded error/);
assert.equal(renderer.root.findAllByType('details').length, 0, 'permissions are not hidden in a disclosure');
assert.equal(renderer.root.findAll((node) => node.type === 'button' && node.children.includes('Install this version (disabled)')).length, 0, 'source-only cards have no install action');
assert.equal(renderer.root.findAll((node) => node.type === 'button' && node.children.includes('Install')).length, 0, 'source-only cards have no install action');
const back = () => renderer.root.findAllByType('button').find((node) => node.children.includes('All plugins'))!;
await act(async () => back().props.onClick());
assert.equal(renderer.root.findAllByType('article').length, 0);
@@ -82,7 +82,12 @@ test('catalog keeps search during selection/back, switches detail, and displays
});
test('README failure leaves the permissions and source visible, before the failure message', () => {
test('README renders before Compatibility and permissions, and README failure still leaves permissions and source visible below', () => {
const readyHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={catalog}
selected={entries[0].id} onSelect={() => {}} installed={[]} /></I18nProvider>);
assert.ok(readyHtml.indexOf('Author documentation') < readyHtml.indexOf('Compatibility and permissions'), 'README content renders before Compatibility and permissions');
const html = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, readmeStatus: 'error', readme: null, readmeError: 'Network unavailable' }}
selected={entries[0].id} onSelect={() => {}} installed={[]} /></I18nProvider>);
@@ -94,7 +99,7 @@ test('README failure leaves the permissions and source visible, before the failu
assert.match(html, /Host validation and the selected permission mode still apply/);
assert.doesNotMatch(html, /Check the actual scope in the permission prompt/);
assert.match(html, /Source example/);
assert.ok(html.indexOf('settings.read') < html.indexOf('Network unavailable'));
assert.ok(html.indexOf('Network unavailable') < html.indexOf('settings.read'), 'README section stays above Compatibility and permissions');
assert.match(html, /Retry/);
assert.doesNotMatch(html, /<details/);
});
@@ -147,7 +152,7 @@ test('offline catalog warning keeps details visible and disables market installa
selected={downloadable.id} onSelect={() => {}} installed={[]} /></I18nProvider>);
assert.match(html, /Offline catalog · installation unavailable/);
assert.match(html, /Compatibility and permissions/);
assert.match(html, /<button[^>]*disabled=""[^>]*>Install this version/);
assert.match(html, /<button[^>]*disabled=""[^>]*>Install<\/button>/);
assert.match(html, /Notices: 1/);
});
@@ -158,13 +163,44 @@ test('manual refresh remains available after success and is disabled while loadi
assert.match(loading, /<button[^>]*disabled=""[^>]*>Refresh<\/button>/);
});
test('replacing an installed plugin discloses that its running version will stop beside the install action', () => {
test('installing shows a spinner, same-version install hides Install and toggles Enable/Enabled, and upgrades keep replacement notice', () => {
const downloadable = { ...entries[0], artifact: { url: 'https://github.com/example/plugin/releases/download/v1/plugin.ncpkg', sha256: 'a'.repeat(64) } };
const html = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
const freshHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, entries: [downloadable] }} selected={downloadable.id} onSelect={() => {}}
installed={[{ id: downloadable.id, activeVersion: '0.9.0', enabled: true, source: { id: 'official', kind: 'official', name: 'Official', origin: 'https://plugins.netcatty.app' } } as NetcattyInstalledPlugin]} /></I18nProvider>);
assert.match(html, /<p[^>]*>This replaces and stops the installed version\./);
assert.ok(html.indexOf('This replaces and stops') < html.indexOf('Install this version (disabled)'));
installed={[]} onToggleEnabled={() => {}} /></I18nProvider>);
assert.doesNotMatch(freshHtml, /This replaces and stops/);
assert.match(freshHtml, />Install<\/button>/);
assert.doesNotMatch(freshHtml, /disabled\)/i);
const busyHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, entries: [downloadable], busy: true }} selected={downloadable.id} onSelect={() => {}}
installed={[]} onToggleEnabled={() => {}} /></I18nProvider>);
assert.match(busyHtml, /animate-spin/);
assert.match(busyHtml, /Installing\.\.\./);
const sameDisabledHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, entries: [downloadable] }} selected={downloadable.id} onSelect={() => {}}
installed={[{ id: downloadable.id, activeVersion: '1.0.0', enabled: false, source: { id: 'official', kind: 'official', name: 'Official', origin: 'https://plugins.netcatty.app' } } as NetcattyInstalledPlugin]}
onToggleEnabled={() => {}} /></I18nProvider>);
assert.doesNotMatch(sameDisabledHtml, />Install<\/button>/);
assert.doesNotMatch(sameDisabledHtml, /This replaces and stops/);
assert.match(sameDisabledHtml, /aria-pressed="false"[^>]*>Enable<\/button>/);
const sameEnabledHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, entries: [downloadable] }} selected={downloadable.id} onSelect={() => {}}
installed={[{ id: downloadable.id, activeVersion: '1.0.0', enabled: true, source: { id: 'official', kind: 'official', name: 'Official', origin: 'https://plugins.netcatty.app' } } as NetcattyInstalledPlugin]}
onToggleEnabled={() => {}} /></I18nProvider>);
assert.doesNotMatch(sameEnabledHtml, />Install<\/button>/);
assert.match(sameEnabledHtml, /aria-pressed="true"[^>]*>.*Enabled<\/button>/);
const upgradeHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginMarketplaceContent
catalog={{ ...catalog, entries: [downloadable] }} selected={downloadable.id} onSelect={() => {}}
installed={[{ id: downloadable.id, activeVersion: '0.9.0', enabled: true, source: { id: 'official', kind: 'official', name: 'Official', origin: 'https://plugins.netcatty.app' } } as NetcattyInstalledPlugin]}
onToggleEnabled={() => {}} /></I18nProvider>);
assert.match(upgradeHtml, /<p[^>]*>This replaces and stops the installed version\./);
assert.match(upgradeHtml, /bg-emerald-600[^>]*>.*Update<\/button>/);
assert.ok(upgradeHtml.indexOf('This replaces and stops') < upgradeHtml.indexOf('Update</button>'));
assert.match(upgradeHtml, /aria-pressed="true"[^>]*>.*Enabled<\/button>/);
});
test('a mirror cannot claim another source installation or offer cross-source replacement', () => {
@@ -178,7 +214,7 @@ test('a mirror cannot claim another source installation or offer cross-source re
marketSource={mirror} selected={downloadable.id} onSelect={() => {}} installed={[existing]} /></I18nProvider>);
assert.match(detail, /installed from another source/);
assert.match(detail, /https:\/\/plugins.netcatty.app/);
assert.match(detail, /disabled=""[^>]*>Install this version/);
assert.match(detail, /disabled=""[^>]*>Install<\/button>/);
});
test('catalog search matches name, author and description without case sensitivity', () => {
+24 -14
View File
@@ -5,22 +5,22 @@ import { PluginInfo } from './PluginInfo';
import React, { useRef, useState } from 'react';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { ArrowLeft, ArrowUpCircle, Check, Loader2 } from 'lucide-react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { usePluginCatalog } from '../../../application/state/usePluginCatalog';
import { Input } from '../../ui/input';
import { Button } from '../../ui/button';
import { PluginPackageDetails } from './PluginPackageManager';
import { PluginReadme } from './PluginReadme';
import { PluginReadmeSection } from './PluginReadmeSection';
export function PluginMarketplace({ installed = [], toolbarContainer, noVault, source }: { source?: NetcattyPluginSource; noVault?: boolean; installed?: NetcattyInstalledPlugin[]; toolbarContainer?: HTMLElement | null }) {
export function PluginMarketplace({ installed = [], toolbarContainer, noVault, source, onToggleEnabled, managerBusy }: { source?: NetcattyPluginSource; noVault?: boolean; installed?: NetcattyInstalledPlugin[]; toolbarContainer?: HTMLElement | null; onToggleEnabled?: (pluginId: string, enabled: boolean) => Promise<unknown> | void; managerBusy?: boolean }) {
const [selected, setSelected] = useState<string | null>(null);
const catalog = usePluginCatalog(selected, source?.id);
return <PluginMarketplaceContent catalog={catalog} marketSource={source} installed={installed} selected={selected} onSelect={setSelected} toolbarContainer={toolbarContainer} noVault={noVault} />;
return <PluginMarketplaceContent catalog={catalog} marketSource={source} installed={installed} selected={selected} onSelect={setSelected} toolbarContainer={toolbarContainer} noVault={noVault} onToggleEnabled={onToggleEnabled} managerBusy={managerBusy} />;
}
// The browser owns only presentation state; installation and README policy stay in the existing hook.
export function PluginMarketplaceContent({ catalog, installed, selected, onSelect, toolbarContainer, noVault, marketSource }: {
export function PluginMarketplaceContent({ catalog, installed, selected, onSelect, toolbarContainer, noVault, marketSource, onToggleEnabled, managerBusy = false }: {
marketSource?: NetcattyPluginSource;
noVault?: boolean;
toolbarContainer?: HTMLElement | null;
@@ -28,6 +28,8 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
installed: NetcattyInstalledPlugin[];
selected: string | null;
onSelect: (id: string | null) => void;
onToggleEnabled?: (pluginId: string, enabled: boolean) => Promise<unknown> | void;
managerBusy?: boolean;
}) {
const { t } = useI18n();
const [search, setSearch] = useState('');
@@ -43,6 +45,8 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
const sourceId = marketSource?.id ?? 'official';
const sameSource = (plugin: NetcattyInstalledPlugin) => (plugin.source?.id ?? 'local') === sourceId;
const installedEntry = installed.find((item) => item.id === entry?.id && sameSource(item));
const isSameVersionInstalled = Boolean(installedEntry && entry && installedEntry.activeVersion === entry.version);
const isUpdateAvailable = Boolean(installedEntry && !isSameVersionInstalled);
const conflictingInstall = installed.find((item) => item.id === entry?.id && !sameSource(item));
const choose = (id: string) => {
const pane = listRef.current?.closest<HTMLElement>('[data-settings-scroll-pane]');
@@ -82,7 +86,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
const isInstalled = installed.some((plugin) => plugin.id === item.id && sameSource(plugin));
return <button key={item.id} type="button" data-plugin-id={item.id} aria-current={selected === item.id ? 'true' : undefined} onClick={() => choose(item.id)}
className="plugin-card min-w-0 flex min-h-[200px] flex-col gap-3 rounded-lg bg-card p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<div className="flex items-center gap-3"><span className="flex h-8 w-8 shrink-0 items-center justify-center"><PluginBrandIcon entry={item} size={32} className="text-muted-foreground" /></span><span className="min-w-0 break-words text-sm font-semibold leading-5">{item.name}</span></div>
<div className="flex items-center gap-3"><span className="flex h-8 w-8 shrink-0 items-center justify-center"><PluginBrandIcon entry={item} sourceId={sourceId} size={32} className="text-muted-foreground" /></span><span className="min-w-0 break-words text-sm font-semibold leading-5">{item.name}</span></div>
<PluginAuthorRow entry={item} sourceId={sourceId} />
<p className="line-clamp-3 break-words text-sm leading-5 text-muted-foreground">{item.description}</p>
<div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1 text-xs text-muted-foreground"><span>{item.version} · {item.license}</span><span className="text-foreground">{t('settings.plugins.manager.details')}</span></div>
@@ -92,19 +96,25 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
</div>}
{entry && <article key={entry.id} aria-label={entry.name} className="plugin-marketplace-detail mx-auto w-full max-w-[920px] min-w-0 space-y-6 focus:outline-none">
<Button variant="ghost" size="sm" onClick={back}><ArrowLeft size={14} className="mr-2" />{t('settings.plugins.market.back')}</Button>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><PluginAuthorRow entry={entry} sourceId={sourceId} /><p className="text-xs text-muted-foreground">{entry.version} · {entry.license}</p>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} sourceId={sourceId} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><PluginAuthorRow entry={entry} sourceId={sourceId} /><p className="text-xs text-muted-foreground">{entry.version} · {entry.license}</p>
{installedEntry && <p className="text-xs text-muted-foreground">{t('settings.plugins.market.installed')} · {installedEntry.activeVersion} · {t(installedEntry.enabled ? 'settings.plugins.manager.enabled' : 'settings.plugins.manager.disabled')}</p>}
</div>
{installedEntry?.runtime?.lastError && <p role="status" className="break-words text-xs text-destructive">{t('settings.plugins.manager.lastError')}: {installedEntry.runtime.lastError}</p>}
<p className="text-sm leading-6 text-muted-foreground">{entry.description}</p>
<a className="block break-all text-xs text-primary underline underline-offset-4" href={`https://github.com/${entry.repository}/tree/${entry.commit}`} target="_blank" rel="noopener noreferrer">{entry.repository} @ {entry.commit.slice(0, 12)}</a>
{conflictingInstall && <p role="status" className="text-xs text-muted-foreground">{t('settings.plugins.sources.conflict')} {conflictingInstall.source?.origin ?? t('settings.plugins.sources.local')}</p>}
{entry.artifact ? <div className="space-y-2"><p className="text-xs text-muted-foreground">{t('settings.plugins.market.installNote')}</p>{catalog.listError && <p role="status" className="text-xs text-muted-foreground">{t('settings.plugins.market.offlineShort')}</p>}<Button ref={installButtonRef} size="sm" disabled={catalog.busy || Boolean(catalog.listError) || Boolean(conflictingInstall)} onClick={() => { if (marketSource?.kind === 'third-party' || (catalog.sourceBinding && catalog.sourceBinding.id !== (marketSource?.id ?? 'official'))) { setClearPreviousSource(false); setConfirmInstall(true); } else void catalog.install(entry.id); }}>{t('settings.plugins.market.install')}</Button></div> : <div className="flex items-center gap-1 text-xs text-muted-foreground"><span>{t('settings.plugins.market.sourceBadge')}</span><PluginInfo label={t('settings.plugins.market.sourceBadge')}>{t(marketSource?.kind === 'third-party' ? 'settings.plugins.sources.sourceOnly' : 'settings.plugins.market.sourceOnly')}</PluginInfo></div>}
<section><h4 className="mb-3 text-sm font-semibold">{t('settings.plugins.market.manifest')}</h4><PluginPackageDetails plugin={{ id: entry.id, activeVersion: entry.version, enabled: false, manifest: entry.manifest, archiveSha256: entry.artifact?.sha256, runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } }} /></section>
<div className="min-w-0 border-t pt-4"><div className="flex items-center gap-1"><h4 className="text-sm font-semibold">README</h4><PluginInfo label={t('settings.plugins.market.readmeInfo')}>{t('settings.plugins.market.readmeNote')}</PluginInfo></div>{catalog.readmeStatus === 'loading' && <p className="mt-3 text-xs text-muted-foreground">{t('settings.plugins.loading')}</p>}
{catalog.readmeStatus === 'error' && <div role="alert" className="mt-3 space-y-2 text-xs text-destructive"><p>{catalog.readmeError}</p><Button variant="outline" size="sm" onClick={catalog.retryReadme}>{t('settings.plugins.market.retry')}</Button></div>}
{catalog.readmeStatus === 'ready' && (catalog.readme?.trim() ? <PluginReadme markdown={catalog.readme} images={catalog.readmeImages} /> : <p className="mt-3 text-xs text-muted-foreground">{t('settings.plugins.market.emptyReadme')}</p>)}
</div>
{entry.artifact ? <div className="space-y-2">{isUpdateAvailable && <p className="text-xs text-muted-foreground">{t('settings.plugins.market.installNote')}</p>}{!isSameVersionInstalled && catalog.listError && <p role="status" className="text-xs text-muted-foreground">{t('settings.plugins.market.offlineShort')}</p>}<div className="flex flex-wrap items-center gap-2">{!isSameVersionInstalled && <Button ref={installButtonRef} size="sm" aria-busy={catalog.busy} className={isUpdateAvailable ? 'bg-emerald-600 text-white hover:bg-emerald-500 dark:bg-emerald-600 dark:hover:bg-emerald-500' : undefined} disabled={catalog.busy || managerBusy || Boolean(catalog.listError) || Boolean(conflictingInstall)} onClick={() => { if (marketSource?.kind === 'third-party' || (catalog.sourceBinding && catalog.sourceBinding.id !== (marketSource?.id ?? 'official'))) { setClearPreviousSource(false); setConfirmInstall(true); } else void catalog.install(entry.id); }}>{catalog.busy ? <Loader2 size={14} className="mr-1.5 animate-spin" aria-hidden="true" /> : isUpdateAvailable ? <ArrowUpCircle size={14} className="mr-1.5" aria-hidden="true" /> : null}{t(isUpdateAvailable ? (catalog.busy ? 'settings.plugins.market.updating' : 'settings.plugins.market.update') : (catalog.busy ? 'settings.plugins.market.installing' : 'settings.plugins.market.install'))}</Button>}{installedEntry && onToggleEnabled && <Button variant={installedEntry.enabled ? 'secondary' : 'default'} size="sm" aria-pressed={installedEntry.enabled} aria-busy={managerBusy} title={t(installedEntry.enabled ? 'settings.plugins.manager.disable' : 'settings.plugins.manager.enable')} className={installedEntry.enabled ? 'bg-primary/15 text-primary hover:bg-primary/20' : undefined} disabled={catalog.busy || managerBusy} onClick={() => void onToggleEnabled(installedEntry.id, !installedEntry.enabled)}>{managerBusy ? <Loader2 size={14} className="mr-1.5 animate-spin" aria-hidden="true" /> : installedEntry.enabled ? <Check size={14} className="mr-1.5" aria-hidden="true" /> : null}{t(installedEntry.enabled ? 'settings.plugins.manager.enabled' : 'settings.plugins.manager.enable')}</Button>}</div></div> : <div className="flex items-center gap-1 text-xs text-muted-foreground"><span>{t('settings.plugins.market.sourceBadge')}</span><PluginInfo label={t('settings.plugins.market.sourceBadge')}>{t(marketSource?.kind === 'third-party' ? 'settings.plugins.sources.sourceOnly' : 'settings.plugins.market.sourceOnly')}</PluginInfo></div>}
<PluginReadmeSection
status={catalog.readmeStatus}
markdown={catalog.readme}
images={catalog.readmeImages}
error={catalog.readmeError}
onRetry={catalog.retryReadme}
/>
<section data-plugin-permissions-section="" className="border-t border-border/60 pt-4">
<h4 className="mb-3 text-sm font-semibold">{t('settings.plugins.market.manifest')}</h4>
<PluginPackageDetails plugin={{ id: entry.id, activeVersion: entry.version, enabled: false, manifest: entry.manifest, archiveSha256: entry.artifact?.sha256, runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } }} />
</section>
</article>}
</div>
<Dialog open={confirmInstall && Boolean(entry)} onOpenChange={setConfirmInstall}><DialogContent className="max-h-[85vh] overflow-y-auto" onCloseAutoFocus={(event) => { event.preventDefault(); installButtonRef.current?.focus(); }}>
@@ -112,7 +122,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
<p className="break-all text-sm font-medium">{marketSource?.origin}</p>
{entry && <PluginPackageDetails plugin={{ id: entry.id, activeVersion: entry.version, enabled: false, manifest: entry.manifest, source: marketSource, archiveSha256: entry.artifact?.sha256, runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } }} />}
{catalog.sourceBinding && catalog.sourceBinding.id !== (marketSource?.id ?? 'official') && <label className="flex items-start gap-2 text-xs"><input type="checkbox" checked={clearPreviousSource} onChange={(event) => setClearPreviousSource(event.target.checked)} />{t('settings.plugins.sources.clearPrivate')}<span className="break-all">{catalog.sourceBinding.origin ?? t('settings.plugins.sources.local')}</span></label>}
<Button disabled={catalog.busy || Boolean(catalog.listError) || Boolean(catalog.sourceBinding && catalog.sourceBinding.id !== (marketSource?.id ?? 'official') && !clearPreviousSource)} onClick={() => { if (entry) void catalog.install(entry.id, marketSource?.id, clearPreviousSource).then(() => setConfirmInstall(false)); }}>{t('settings.plugins.market.install')}</Button>
<Button aria-busy={catalog.busy} className={isUpdateAvailable ? 'bg-emerald-600 text-white hover:bg-emerald-500 dark:bg-emerald-600 dark:hover:bg-emerald-500' : undefined} disabled={catalog.busy || Boolean(catalog.listError) || Boolean(catalog.sourceBinding && catalog.sourceBinding.id !== (marketSource?.id ?? 'official') && !clearPreviousSource)} onClick={() => { if (entry) void catalog.install(entry.id, marketSource?.id, clearPreviousSource).then(() => setConfirmInstall(false)); }}>{catalog.busy && <Loader2 size={14} className="mr-1.5 animate-spin" aria-hidden="true" />}{t(isUpdateAvailable ? (catalog.busy ? 'settings.plugins.market.updating' : 'settings.plugins.market.update') : (catalog.busy ? 'settings.plugins.market.installing' : 'settings.plugins.market.install'))}</Button>
</DialogContent></Dialog>
</section>;
}
@@ -54,3 +54,32 @@ test('package detail renders manifest resources as text and explains advanced au
assert.doesNotMatch(html, /before granting/);
assert.match(html, /aaaaaaaaaaaaaaaa/);
});
test('installed cards and detail header expose one-click emerald Update action when an update is available', () => {
const plugin = {
id: 'com.example.synthetic', enabled: true, activeVersion: '1.0.0',
source: { id: 'official', kind: 'official', name: 'Official', origin: 'https://plugins.netcatty.app' },
manifest: { manifestVersion: 1, id: 'com.example.synthetic', name: 'Synthetic', publisher: 'Publisher', version: '1.0.0', engines: { netcatty: '*', api: '*' }, main: { browser: 'index.js' } },
runtime: { status: 'running', kind: 'browser', lastError: null, quarantinedAt: null },
} as NetcattyInstalledPlugin;
const manager = { plugins: [plugin], available: true, statusKnown: true, busy: false } as ReturnType<typeof usePluginManager>;
const updates = {
result: { checkedAt: 1, checked: 1, skipped: 0, failedSources: 0, updates: [{ pluginId: plugin.id, sourceId: 'official', installedVersion: '1.0.0', availableVersion: '1.2.0' }] },
error: null, busy: false, updatingId: null, updateError: null, async check() {}, async installUpdate() {},
};
const cardHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginPackageManager manager={manager} updates={updates} initialSelectedId={null} /></I18nProvider>);
assert.match(cardHtml, /data-plugin-card-update="com\.example\.synthetic"/);
assert.match(cardHtml, /bg-emerald-600/);
assert.match(cardHtml, /Update 1\.2\.0/);
const detailHtml = renderToStaticMarkup(<I18nProvider locale="en"><PluginPackageManager manager={manager} updates={updates} initialSelectedId={plugin.id} /></I18nProvider>);
assert.match(detailHtml, /data-plugin-detail-update="com\.example\.synthetic"/);
assert.match(detailHtml, /bg-emerald-600/);
assert.ok(detailHtml.indexOf('Update 1.2.0') < detailHtml.indexOf('>Enabled</button>'));
assert.match(detailHtml, /data-plugin-readme-section=""/);
assert.match(detailHtml, /data-plugin-permissions-section=""/);
assert.ok(
detailHtml.indexOf('data-plugin-readme-section=""') < detailHtml.indexOf('data-plugin-permissions-section=""'),
'installed marketplace plugin detail renders README before Compatibility and permissions',
);
});
@@ -1,15 +1,17 @@
import { describePluginPermission } from '@/domain/pluginPermissionDescriptions.cjs';
import { describePluginRuntime } from '@/domain/pluginRuntimePolicy.cjs';
import React, { useRef, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { PluginPermissionPanel } from './PluginPermissionPanel';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { ArrowLeft, ArrowUpCircle, Loader2 } from 'lucide-react';
import type { usePluginUpdateCheck } from '../../../application/state/usePluginUpdateCheck';
import { usePluginManager } from '../../../application/state/usePluginManager';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { PluginInfo } from './PluginInfo';
import { PluginInstalledReadme } from './PluginReadmeSection';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '../../ui/dialog';
export function PluginPackageDetails({ plugin }: { plugin: NetcattyInstalledPlugin }) {
@@ -53,7 +55,7 @@ export function PluginPackageDetails({ plugin }: { plugin: NetcattyInstalledPlug
</div>;
}
export function PluginPackageManager({ manager, onSelectionChange, initialSelectedId, detailActions }: { initialSelectedId?: string | null; manager: ReturnType<typeof usePluginManager>; onSelectionChange?: (id: string | null) => void; detailActions?: React.ReactNode }) {
export function PluginPackageManager({ manager, updates, onSelectionChange, initialSelectedId, detailActions }: { initialSelectedId?: string | null; manager: ReturnType<typeof usePluginManager>; updates?: ReturnType<typeof usePluginUpdateCheck>; onSelectionChange?: (id: string | null) => void; detailActions?: React.ReactNode }) {
const { t, resolvedLocale } = useI18n();
const [selected, setSelected] = useState<string | null>(initialSelectedId ?? null);
const [search, setSearch] = useState('');
@@ -62,6 +64,11 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
const scrollTop = useRef(0);
const lastSelection = useRef<string | null>(null);
const selectedPlugin = manager.plugins.find((plugin) => plugin.id === selected);
const checkUpdates = updates?.check;
useEffect(() => {
if (!checkUpdates || !manager.available || manager.statusKnown === false || manager.plugins.length === 0) return;
void checkUpdates({ silent: true });
}, [checkUpdates, manager.available, manager.statusKnown, manager.plugins.length, selected]);
const nameOf = (plugin: NetcattyInstalledPlugin) => typeof plugin.manifest?.displayName === 'string' ? plugin.manifest.displayName : plugin.manifest?.displayName?.[resolvedLocale] ?? plugin.manifest?.displayName?.en ?? plugin.manifest?.name ?? plugin.id;
const descriptionOf = (plugin: NetcattyInstalledPlugin) => {
const value = plugin.manifest?.description;
@@ -88,14 +95,19 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
{!selectedPlugin && manager.plugins.length > 0 && <Input value={search} onChange={(event) => setSearch(event.target.value)} placeholder={t('settings.plugins.market.search')} aria-label={t('settings.plugins.market.search')} />}
{!selectedPlugin && manager.plugins.length > 0 && visible.length === 0 && <p className="p-6 text-center text-sm text-muted-foreground">{t('settings.plugins.market.noResults')}</p>}
{manager.error && <p role="alert" className="text-sm text-destructive">{manager.error}</p>}
{updates?.error && <p role="alert" className="text-sm text-destructive">{updates.error}</p>}
{updates?.updateError && <p role="alert" className="text-sm text-destructive">{updates.updateError}</p>}
{!manager.plugins.length && <div className="rounded-xl border border-dashed border-border p-8 text-center text-sm text-muted-foreground">{t('settings.plugins.manager.empty')}</div>}
<div className={selectedPlugin ? 'space-y-4' : 'grid grid-cols-[repeat(auto-fill,minmax(min(100%,280px),1fr))] gap-3'}>
{visible.map((plugin) => <article key={plugin.id} data-plugin-detail={selectedPlugin ? true : undefined} tabIndex={selectedPlugin ? -1 : undefined} aria-label={nameOf(plugin)} className={`min-w-0 rounded-lg focus:outline-none ${selectedPlugin ? 'space-y-4' : 'plugin-card flex min-h-[200px] flex-col gap-3 bg-card p-4'}`}>
{visible.map((plugin) => {
const availableUpdate = updates?.result?.updates.find((item) => item.pluginId === plugin.id && item.sourceId === plugin.source?.id);
const isUpdating = updates?.updatingId === plugin.id;
return <article key={plugin.id} data-plugin-detail={selectedPlugin ? true : undefined} tabIndex={selectedPlugin ? -1 : undefined} aria-label={nameOf(plugin)} className={`min-w-0 rounded-lg focus:outline-none ${selectedPlugin ? 'mx-auto w-full max-w-[920px] space-y-6' : 'plugin-card flex min-h-[200px] flex-col gap-3 bg-card p-4'}`}>
<div className="flex flex-wrap items-center gap-3">
<div className="flex h-12 w-12 shrink-0 items-center justify-center"><PluginBrandIcon plugin={plugin} size={32} /></div>
{!selectedPlugin ? <button type="button" aria-label={`${t('settings.plugins.manager.details')} ${nameOf(plugin)}`} onClick={() => choose(plugin.id)} className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-opacity hover:opacity-85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><PluginBrandIcon plugin={plugin} size={32} /></button> : <div className="flex h-12 w-12 shrink-0 items-center justify-center"><PluginBrandIcon plugin={plugin} size={48} /></div>}
<div className="flex min-w-0 flex-1 items-center gap-1">
<button type="button" data-plugin-card={plugin.id} className="min-w-0 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-expanded={selected === plugin.id} onClick={() => choose(selected === plugin.id ? null : plugin.id)}>
<div className="break-words text-sm font-medium">{nameOf(plugin)}</div>
<div className={`break-words ${selectedPlugin ? 'text-xl font-semibold' : 'text-sm font-medium'}`}>{nameOf(plugin)}</div>
</button>
{plugin.runtime.lastError && <PluginInfo variant="error" label={`${t('settings.plugins.manager.lastError')} — ${nameOf(plugin)}`}>
@@ -105,13 +117,20 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
</div>
<div className="ml-auto flex shrink-0 items-center gap-2" data-plugin-header-actions="">
{selected === plugin.id && detailActions}
{selected === plugin.id && availableUpdate && <Button size="sm" type="button" data-plugin-detail-update={plugin.id}
className="h-7 shrink-0 rounded-full border-0 bg-emerald-600 px-3 text-xs text-white hover:bg-emerald-500 dark:bg-emerald-600 dark:hover:bg-emerald-500"
disabled={manager.busy || Boolean(updates?.updatingId)}
onClick={() => void updates?.installUpdate(availableUpdate, plugin.enabled)}>
{isUpdating ? <Loader2 size={12} className="mr-1.5 animate-spin" aria-hidden="true" /> : <ArrowUpCircle size={12} className="mr-1.5" aria-hidden="true" />}
{isUpdating ? t('settings.plugins.market.updating') : `${t('settings.plugins.market.update')} ${availableUpdate.availableVersion}`}
</Button>}
<Button variant="ghost" size="sm" type="button"
className={`h-7 shrink-0 rounded-full border-0 px-3 text-xs focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background ${manager.statusKnown !== false && plugin.enabled ? 'bg-primary/10 hover:bg-primary/15' : 'bg-muted/60 text-muted-foreground hover:bg-muted hover:text-foreground'}`}
style={manager.statusKnown !== false && plugin.enabled ? { color: 'color-mix(in srgb, hsl(var(--primary)) 40%, hsl(var(--foreground)))' } : undefined}
aria-pressed={manager.statusKnown === false ? undefined : plugin.enabled} aria-busy={manager.busy}
aria-label={`${t(manager.statusKnown === false ? 'settings.plugins.permissions.statusUnknown' : plugin.enabled ? 'settings.plugins.manager.disable' : 'settings.plugins.manager.enable')} ${plugin.manifest?.name ?? plugin.id}`}
title={t(manager.statusKnown === false ? 'settings.plugins.permissions.statusUnknown' : plugin.enabled ? 'settings.plugins.manager.disable' : 'settings.plugins.manager.enable')}
disabled={manager.busy || manager.statusKnown === false} onClick={() => void manager.setEnabled(plugin.id, !plugin.enabled)}>
disabled={manager.busy || Boolean(updates?.updatingId) || manager.statusKnown === false} onClick={() => void manager.setEnabled(plugin.id, !plugin.enabled)}>
{t(manager.statusKnown === false ? 'settings.plugins.permissions.statusUnknown' : plugin.enabled ? 'settings.plugins.manager.enabled' : 'settings.plugins.manager.disabled')}
</Button>
</div>
@@ -119,11 +138,27 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
<PluginAuthorRow plugin={plugin} showSource />
<p className={`break-words text-sm leading-5 text-muted-foreground ${selectedPlugin ? 'whitespace-pre-wrap' : 'line-clamp-3'}`}>{descriptionOf(plugin) || t('settings.plugins.manager.noDescription')}</p>
{!selectedPlugin ? <div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1">
<p className="break-words text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>
<div className="flex flex-wrap items-center gap-2">
<p className="break-words text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>
{availableUpdate && <button
type="button"
data-plugin-card-update={plugin.id}
disabled={manager.busy || Boolean(updates?.updatingId)}
onClick={() => void updates?.installUpdate(availableUpdate, plugin.enabled)}
className="inline-flex h-5 shrink-0 items-center gap-1 rounded-full bg-emerald-600 px-2 text-[11px] font-medium text-white transition-colors hover:bg-emerald-500 disabled:opacity-50"
>
{isUpdating ? <Loader2 size={11} className="animate-spin" aria-hidden="true" /> : <ArrowUpCircle size={11} aria-hidden="true" />}
<span>{isUpdating ? t('settings.plugins.market.updating') : `${t('settings.plugins.market.update')} ${availableUpdate.availableVersion}`}</span>
</button>}
</div>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => choose(plugin.id)} aria-label={`${t('settings.plugins.manager.details')} ${nameOf(plugin)}`}>{t('settings.plugins.manager.details')}</Button>
</div> : <p className="text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>}
{selected === plugin.id && <>
<PluginPackageDetails plugin={plugin} />
<PluginInstalledReadme plugin={plugin} />
<section data-plugin-permissions-section="" className="border-t border-border/60 pt-4">
<h4 className="mb-3 text-sm font-semibold">{t('settings.plugins.market.manifest')}</h4>
<PluginPackageDetails plugin={plugin} />
</section>
<PluginPermissionPanel key={plugin.id} pluginId={plugin.id} onChanged={async () => { await manager.refresh(); }}
actions={<Dialog open={removing === plugin.id} onOpenChange={(open) => {
if (manager.busy) return;
@@ -148,7 +183,7 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
</Dialog>}
/>
</>}
</article>)}
</article>; })}
</div>
</section>;
}
@@ -21,3 +21,37 @@ test('README only renders registered local rasterized images and placeholders ot
assert.match(html, /\[bad\]/);
assert.doesNotMatch(html, /evil\.test/);
});
test('README renders GitHub-style centered HTML headers and GFM pipe tables cleanly without leaking raw HTML or remote images', () => {
const md = [
'<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/icon.svg"><img src="assets/icon.svg" alt="Icon" width="84"></picture></p>',
'<h1 align="center">Netcatty Database</h1>',
'<p align="center"><strong>Enterprise IDE &amp; BI Dashboard</strong></p>',
'<p align="center"><a href="https://github.com/binaricat/netcatty-database-plugin"><img src="https://img.shields.io/badge/version-v0.3.0-0ea5e9" alt="v0.3.0"></a></p>',
'',
'| Engine | Status |',
'| --- | --- |',
'| PostgreSQL | **Live** |',
'| MongoDB | `Aggregation` |',
].join('\n');
const html = renderToStaticMarkup(<PluginReadme markdown={md} />);
assert.match(html, /<h3[^>]*text-center[^>]*>Netcatty Database<\/h3>/);
assert.match(html, /<strong>Enterprise IDE &amp; BI Dashboard<\/strong>/);
assert.doesNotMatch(html, /&lt;p align=/);
assert.doesNotMatch(html, /&lt;picture&gt;/);
assert.doesNotMatch(html, /<(img|picture|source)\b/);
assert.doesNotMatch(html, /shields\.io/);
assert.match(html, /<table[^>]*>.*<th[^>]*>Engine<\/th>.*<td[^>]*>PostgreSQL<\/td>.*<strong>Live<\/strong>/);
});
test('README renders verified theme-aware <picture> dark/light screenshots when present in images map', () => {
const darkPath = `/assets/${'a'.repeat(64)}.webp`;
const lightPath = `/assets/${'b'.repeat(64)}.webp`;
const md = `<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="${darkPath}"><source media="(prefers-color-scheme: light)" srcset="${lightPath}"><img src="${darkPath}" alt="Workbench"></picture></p>`;
const html = renderToStaticMarkup(<PluginReadme markdown={md} images={{
[darkPath]: 'data:image/png;base64,REFS',
[lightPath]: 'data:image/png;base64,TElH',
}} />);
assert.match(html, /src="data:image\/png;base64,TElH"[^>]*dark:hidden/);
assert.match(html, /src="data:image\/png;base64,REFS"[^>]*dark:inline-block/);
});
+331 -12
View File
@@ -1,42 +1,361 @@
import React, { useMemo } from 'react';
import { fromMarkdown } from 'mdast-util-from-markdown';
import { gfmStrikethrough } from 'micromark-extension-gfm-strikethrough';
import { gfmStrikethroughFromMarkdown } from 'mdast-util-gfm-strikethrough';
import type { RootContent, Root } from 'mdast';
const SAFE_HTML_TAGS = new Set([
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'div', 'span', 'strong', 'b', 'em', 'i', 'code', 'pre',
'br', 'hr', 'ul', 'ol', 'li', 'blockquote',
'details', 'summary', 'table', 'thead', 'tbody', 'tr', 'th', 'td',
'a', 'picture', 'source', 'img', 'sup', 'sub',
]);
const VOID_HTML_TAGS = new Set(['br', 'hr', 'img', 'source']);
const DATA_PNG_RE = /^data:image\/png;base64,[A-Za-z0-9+/]+=*$/;
function isSafeHttpsUrl(raw: string): boolean {
try {
const url = new URL(raw);
return url.protocol === 'https:' && !url.username && !url.password;
} catch {
return false;
}
}
function decodeHtmlEntities(input: string): string {
return input.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]+);/g, (match, entity: string) => {
switch (entity) {
case 'amp': return '&';
case 'lt': return '<';
case 'gt': return '>';
case 'quot': return '"';
case 'apos': return "'";
case 'nbsp': return '\u00a0';
case 'middot': return '\u00b7';
case 'mdash': return '\u2014';
case 'ndash': return '\u2013';
default: {
if (entity.startsWith('#x') || entity.startsWith('#X')) {
const code = Number.parseInt(entity.slice(2), 16);
return Number.isFinite(code) && code >= 0x20 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
}
if (entity.startsWith('#')) {
const code = Number.parseInt(entity.slice(1), 10);
return Number.isFinite(code) && code >= 0x20 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
}
return match;
}
}
});
}
type HtmlAstNode =
| { kind: 'text'; value: string }
| { kind: 'element'; tag: string; attrs: Record<string, string>; children: HtmlAstNode[] };
function parseAttributes(raw: string): Record<string, string> {
const attrs: Record<string, string> = {};
const attrRe = /([a-zA-Z][a-zA-Z0-9:-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
let match: RegExpExecArray | null;
while ((match = attrRe.exec(raw)) !== null) {
const name = match[1].toLowerCase();
const val = match[2] ?? match[3] ?? match[4] ?? '';
attrs[name] = decodeHtmlEntities(val);
}
return attrs;
}
function parseSafeHtml(raw: string): HtmlAstNode[] | null {
const cleaned = raw.replace(/<!--[\s\S]*?-->/g, '');
const tokenRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*?)(\/?)>/g;
const root: HtmlAstNode[] = [];
const stack: Array<{ tag: string; children: HtmlAstNode[] }> = [{ tag: '#root', children: root }];
let lastIndex = 0;
let sawTag = false;
let match: RegExpExecArray | null;
while ((match = tokenRe.exec(cleaned)) !== null) {
if (match.index > lastIndex) {
const text = decodeHtmlEntities(cleaned.slice(lastIndex, match.index));
if (text) stack[stack.length - 1].children.push({ kind: 'text', value: text });
}
lastIndex = tokenRe.lastIndex;
const isClose = match[1] === '/';
const tag = match[2].toLowerCase();
const attrText = match[3] ?? '';
const selfClosing = match[4] === '/' || VOID_HTML_TAGS.has(tag);
sawTag = true;
if (!SAFE_HTML_TAGS.has(tag)) {
return null;
}
if (isClose) {
for (let i = stack.length - 1; i > 0; i -= 1) {
if (stack[i].tag === tag) {
stack.length = i;
break;
}
}
continue;
}
if (stack.length > 16) return null;
const node: HtmlAstNode = { kind: 'element', tag, attrs: parseAttributes(attrText), children: [] };
stack[stack.length - 1].children.push(node);
if (!selfClosing) {
stack.push({ tag, children: node.children });
}
}
if (!sawTag) {
return cleaned.trim() ? [{ kind: 'text', value: decodeHtmlEntities(cleaned) }] : [];
}
if (lastIndex < cleaned.length) {
const tail = decodeHtmlEntities(cleaned.slice(lastIndex));
if (tail) stack[stack.length - 1].children.push({ kind: 'text', value: tail });
}
return root;
}
function hasVisibleContent(nodes: React.ReactNode[]): boolean {
return nodes.some((child) => {
if (child === null || child === undefined || typeof child === 'boolean') return false;
if (typeof child === 'string') return child.trim().length > 0;
return true;
});
}
function renderHtmlAst(nodes: HtmlAstNode[], images: Record<string, string>, depth = 0): React.ReactNode[] {
if (depth > 16) return [];
const out: React.ReactNode[] = [];
nodes.forEach((node, idx) => {
if (node.kind === 'text') {
out.push(node.value);
return;
}
const { tag, attrs } = node;
if (tag === 'source') return;
if (tag === 'br') { out.push(<br key={idx} />); return; }
if (tag === 'hr') { out.push(<hr key={idx} className="my-4 border-border/60" />); return; }
if (tag === 'img') {
const rawSrc = attrs.src ?? '';
const src = Object.hasOwn(images, rawSrc) ? images[rawSrc] : undefined;
if (src && DATA_PNG_RE.test(src)) {
out.push(<img key={idx} src={src} alt={attrs.alt ?? ''} className="my-2 inline-block max-w-full rounded" />);
}
return;
}
const children = renderHtmlAst(node.children, images, depth + 1);
const center = attrs.align?.toLowerCase() === 'center' ? ' text-center' : '';
if (tag === 'picture') {
const darkSrc = node.children.find((child) =>
child.kind === 'element'
&& child.tag === 'source'
&& /prefers-color-scheme:\s*dark/i.test(child.attrs.media ?? ''))?.attrs.srcset?.trim();
const lightSrc = node.children.find((child) =>
child.kind === 'element'
&& child.tag === 'source'
&& /prefers-color-scheme:\s*light/i.test(child.attrs.media ?? ''))?.attrs.srcset?.trim();
const imgChild = node.children.find((child) => child.kind === 'element' && child.tag === 'img');
const alt = imgChild && imgChild.kind === 'element' ? (imgChild.attrs.alt ?? '') : '';
const darkData = darkSrc && Object.hasOwn(images, darkSrc) && DATA_PNG_RE.test(images[darkSrc]) ? images[darkSrc] : undefined;
const lightData = lightSrc && Object.hasOwn(images, lightSrc) && DATA_PNG_RE.test(images[lightSrc]) ? images[lightSrc] : undefined;
if (darkData && lightData) {
out.push(
<React.Fragment key={idx}>
<img src={lightData} alt={alt} className="my-2 inline-block max-w-full rounded-md border border-border/50 dark:hidden" />
<img src={darkData} alt={alt} className="my-2 hidden max-w-full rounded-md border border-border/50 dark:inline-block" />
</React.Fragment>,
);
return;
}
if (darkData || lightData) {
out.push(<img key={idx} src={darkData ?? lightData} alt={alt} className="my-2 inline-block max-w-full rounded-md border border-border/50" />);
return;
}
if (hasVisibleContent(children)) out.push(<React.Fragment key={idx}>{children}</React.Fragment>);
return;
}
if (tag === 'a') {
if (!hasVisibleContent(children)) return;
const href = attrs.href ?? '';
out.push(isSafeHttpsUrl(href)
? <a key={idx} href={href} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">{children}</a>
: <span key={idx}>{children}</span>);
return;
}
if (!hasVisibleContent(children)) return;
switch (tag) {
case 'h1': out.push(<h3 key={idx} className={`mt-4 text-lg font-semibold${center}`}>{children}</h3>); break;
case 'h2': out.push(<h4 key={idx} className={`mt-5 border-b border-border/50 pb-1 text-base font-semibold${center}`}>{children}</h4>); break;
case 'h3': out.push(<h5 key={idx} className={`mt-4 text-sm font-semibold${center}`}>{children}</h5>); break;
case 'h4':
case 'h5':
case 'h6': out.push(<h6 key={idx} className={`mt-3 text-sm font-medium${center}`}>{children}</h6>); break;
case 'p': out.push(<p key={idx} className={`my-2 leading-relaxed${center}`}>{children}</p>); break;
case 'div': out.push(<div key={idx} className={`my-2${center}`}>{children}</div>); break;
case 'span': out.push(<span key={idx}>{children}</span>); break;
case 'strong':
case 'b': out.push(<strong key={idx}>{children}</strong>); break;
case 'em':
case 'i': out.push(<em key={idx}>{children}</em>); break;
case 'code': out.push(<code key={idx} className="rounded bg-muted px-1 py-0.5 text-xs">{children}</code>); break;
case 'pre': out.push(<pre key={idx} className="my-3 overflow-auto rounded-lg bg-muted p-3 text-xs">{children}</pre>); break;
case 'ul': out.push(<ul key={idx} className="my-2 list-disc space-y-1 pl-5">{children}</ul>); break;
case 'ol': out.push(<ol key={idx} className="my-2 list-decimal space-y-1 pl-5">{children}</ol>); break;
case 'li': out.push(<li key={idx}>{children}</li>); break;
case 'blockquote': out.push(<blockquote key={idx} className="my-2 border-l-2 border-border pl-3 text-muted-foreground">{children}</blockquote>); break;
case 'details': out.push(<details key={idx} className="my-2 rounded-md border border-border/60 px-3 py-2">{children}</details>); break;
case 'summary': out.push(<summary key={idx} className="cursor-pointer font-medium">{children}</summary>); break;
case 'table': out.push(<div key={idx} className="my-3 overflow-x-auto"><table className="w-full border-collapse text-xs">{children}</table></div>); break;
case 'thead': out.push(<thead key={idx}>{children}</thead>); break;
case 'tbody': out.push(<tbody key={idx}>{children}</tbody>); break;
case 'tr': out.push(<tr key={idx} className="border-b border-border/50">{children}</tr>); break;
case 'th': out.push(<th key={idx} className="px-2.5 py-1.5 text-left font-semibold">{children}</th>); break;
case 'td': out.push(<td key={idx} className="px-2.5 py-1.5 align-top">{children}</td>); break;
case 'sup': out.push(<sup key={idx}>{children}</sup>); break;
case 'sub': out.push(<sub key={idx}>{children}</sub>); break;
default: out.push(<span key={idx}>{children}</span>); break;
}
});
return out;
}
function splitTableRow(line: string): string[] {
const trimmed = line.trim().replace(/^\|/, '').replace(/\|$/, '');
const cells: string[] = [];
let current = '';
for (let i = 0; i < trimmed.length; i += 1) {
if (trimmed[i] === '\\' && trimmed[i + 1] === '|') {
current += '|';
i += 1;
} else if (trimmed[i] === '|') {
cells.push(current.trim());
current = '';
} else {
current += trimmed[i];
}
}
cells.push(current.trim());
return cells;
}
const TABLE_DIVIDER_RE = /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/;
function extractRawParagraphText(node: RootContent): string | null {
if (node.type !== 'paragraph') return null;
let out = '';
for (const child of node.children) {
if (child.type === 'text') out += child.value;
else if (child.type === 'inlineCode') out += `\`${child.value}\``;
else if (child.type === 'strong') out += `**${child.children.map((c) => ('value' in c ? c.value : '')).join('')}**`;
else if (child.type === 'emphasis') out += `*${child.children.map((c) => ('value' in c ? c.value : '')).join('')}*`;
else if (child.type === 'link') out += `[${child.children.map((c) => ('value' in c ? c.value : '')).join('')}](${child.url})`;
else return null;
}
return out;
}
function tryRenderPipeTable(node: RootContent, key: number, images: Record<string, string>, depth: number): React.ReactNode | null {
const raw = extractRawParagraphText(node);
if (!raw || !raw.includes('|') || !raw.includes('\n')) return null;
const lines = raw.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
if (lines.length < 2 || !TABLE_DIVIDER_RE.test(lines[1])) return null;
const headers = splitTableRow(lines[0]);
if (headers.length < 2) return null;
const rows = lines.slice(2).map(splitTableRow);
const renderCell = (cellText: string) => {
const cellTree = parseMarkdown(cellText);
const first = cellTree.children[0];
if (first && first.type === 'paragraph') {
return first.children.map((child, idx) => renderNode(child as RootContent, idx, images, depth + 1));
}
return cellText;
};
return (
<div key={key} className="my-3 overflow-x-auto rounded-md border border-border/60">
<table className="w-full border-collapse text-xs">
<thead className="bg-muted/40">
<tr className="border-b border-border/60">
{headers.map((cell, idx) => <th key={idx} className="px-2.5 py-1.5 text-left font-semibold">{renderCell(cell)}</th>)}
</tr>
</thead>
<tbody>
{rows.map((row, rowIdx) => (
<tr key={rowIdx} className="border-b border-border/40 last:border-b-0">
{headers.map((_, colIdx) => <td key={colIdx} className="px-2.5 py-1.5 align-top">{renderCell(row[colIdx] ?? '')}</td>)}
</tr>
))}
</tbody>
</table>
</div>
);
}
function parseMarkdown(markdown: string): Root {
return fromMarkdown(markdown, {
extensions: [gfmStrikethrough()],
mdastExtensions: [gfmStrikethroughFromMarkdown()],
});
}
function renderNode(node: Root | RootContent, key: number, images: Record<string, string>, depth = 0): React.ReactNode {
if (depth > 24) return null;
if (node.type === 'paragraph') {
const table = tryRenderPipeTable(node, key, images, depth);
if (table) return table;
}
const children = 'children' in node ? node.children.map((child, index) => renderNode(child as RootContent, index, images, depth + 1)) : null;
switch (node.type) {
case 'root': return <React.Fragment key={key}>{children}</React.Fragment>;
case 'heading': return <h4 key={key} className="mt-5 font-semibold">{children}</h4>;
case 'heading': {
if (node.depth === 1) return <h3 key={key} className="mt-5 text-lg font-semibold">{children}</h3>;
if (node.depth === 2) return <h4 key={key} className="mt-5 border-b border-border/50 pb-1 text-base font-semibold">{children}</h4>;
return <h5 key={key} className="mt-4 text-sm font-semibold">{children}</h5>;
}
case 'paragraph': return <p key={key} className="my-2 leading-relaxed">{children}</p>;
case 'text': return node.value;
case 'strong': return <strong key={key}>{children}</strong>;
case 'emphasis': return <em key={key}>{children}</em>;
case 'inlineCode': return <code key={key} className="rounded bg-muted px-1">{node.value}</code>;
case 'delete': return <del key={key}>{children}</del>;
case 'inlineCode': return <code key={key} className="rounded bg-muted px-1 py-0.5 text-xs">{node.value}</code>;
case 'code': return <pre key={key} className="my-3 overflow-auto rounded-lg bg-muted p-3 text-xs"><code>{node.value}</code></pre>;
case 'list': return <ul key={key} className="my-2 list-disc pl-5">{children}</ul>;
case 'list': return node.ordered
? <ol key={key} className="my-2 list-decimal space-y-1 pl-5">{children}</ol>
: <ul key={key} className="my-2 list-disc space-y-1 pl-5">{children}</ul>;
case 'listItem': return <li key={key}>{children}</li>;
case 'blockquote': return <blockquote key={key} className="border-l-2 pl-3 text-muted-foreground">{children}</blockquote>;
case 'blockquote': return <blockquote key={key} className="my-2 border-l-2 border-border pl-3 text-muted-foreground">{children}</blockquote>;
case 'break': return <br key={key} />;
case 'thematicBreak': return <hr key={key} />;
case 'thematicBreak': return <hr key={key} className="my-4 border-border/60" />;
case 'link': {
let safe = false;
try { const url = new URL(node.url); safe = url.protocol === 'https:' && !url.username && !url.password; } catch { /* relative and unsafe links stay text */ }
return safe ? <a key={key} href={node.url} target="_blank" rel="noopener noreferrer" className="underline">{children}</a> : <span key={key}>{children}</span>;
return isSafeHttpsUrl(node.url)
? <a key={key} href={node.url} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2">{children}</a>
: <span key={key}>{children}</span>;
}
case 'image': {
const src = Object.hasOwn(images, node.url) ? images[node.url] : undefined;
return src && /^data:image\/png;base64,[A-Za-z0-9+/]+=*$/.test(src)
? <img key={key} src={src} alt={node.alt ?? ''} className="my-2 max-w-full" />
return src && DATA_PNG_RE.test(src)
? <img key={key} src={src} alt={node.alt ?? ''} className="my-2 max-w-full rounded-md border border-border/50" />
: <span key={key} className="text-muted-foreground">[{node.alt ?? 'image'}]</span>;
}
case 'imageReference': return <span key={key} className="text-muted-foreground">[{node.alt ?? 'image'}]</span>;
case 'html': return <span key={key}>{node.value}</span>;
case 'html': {
const parsed = parseSafeHtml(node.value);
if (parsed === null) return <span key={key}>{node.value}</span>;
const rendered = renderHtmlAst(parsed, images, 0);
return hasVisibleContent(rendered) ? <React.Fragment key={key}>{rendered}</React.Fragment> : null;
}
default: return <React.Fragment key={key}>{children}</React.Fragment>;
}
}
export function PluginReadme({ markdown, images = {} }: { markdown: string; images?: Record<string, string> }) {
const tree = useMemo(() => fromMarkdown(markdown.slice(0, 256 * 1024)), [markdown]);
const tree = useMemo(() => parseMarkdown(markdown.slice(0, 256 * 1024)), [markdown]);
return <div className="break-words text-sm">{renderNode(tree, 0, images)}</div>;
}
@@ -0,0 +1,88 @@
import React from 'react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { usePluginCatalog } from '../../../application/state/usePluginCatalog';
import { Button } from '../../ui/button';
import { PluginInfo } from './PluginInfo';
import { PluginReadme } from './PluginReadme';
export function PluginReadmeSection({
status,
markdown,
images,
error,
onRetry,
}: {
status: 'idle' | 'loading' | 'ready' | 'error';
markdown: string | null;
images: Record<string, string>;
error: string | null;
onRetry: () => void;
}) {
const { t } = useI18n();
return (
<section data-plugin-readme-section="" className="min-w-0 border-t border-border/60 pt-4">
<div className="flex items-center gap-1">
<h4 className="text-sm font-semibold">README</h4>
<PluginInfo label={t('settings.plugins.market.readmeInfo')}>
{t('settings.plugins.market.readmeNote')}
</PluginInfo>
</div>
{status === 'loading' && (
<p className="mt-3 text-xs text-muted-foreground">{t('settings.plugins.loading')}</p>
)}
{status === 'error' && (
<div role="alert" className="mt-3 space-y-2 text-xs text-destructive">
<p>{error}</p>
<Button variant="outline" size="sm" onClick={onRetry}>
{t('settings.plugins.market.retry')}
</Button>
</div>
)}
{status === 'ready' && (
markdown?.trim() ? (
<PluginReadme markdown={markdown} images={images} />
) : (
<p className="mt-3 text-xs text-muted-foreground">{t('settings.plugins.market.emptyReadme')}</p>
)
)}
</section>
);
}
function PluginCatalogBackedReadme({ pluginId, sourceId }: { pluginId: string; sourceId: string }) {
const catalog = usePluginCatalog(pluginId, sourceId);
const entry = catalog.entries.find((item) => item.id === pluginId);
// Hide cleanly if the source is loaded and no longer lists this plugin.
if (catalog.listStatus === 'ready' && !entry) return null;
if (catalog.listStatus === 'error' && !entry) return null;
const status = catalog.listStatus === 'loading' ? 'loading' : catalog.readmeStatus;
return (
<div className="space-y-4">
{entry?.repository && entry?.commit && (
<a
className="block break-all text-xs text-primary underline underline-offset-4"
href={`https://github.com/${entry.repository}/tree/${entry.commit}`}
target="_blank"
rel="noopener noreferrer"
>
{entry.repository} @ {entry.commit.slice(0, 12)}
</a>
)}
<PluginReadmeSection
status={status}
markdown={catalog.readme}
images={catalog.readmeImages}
error={catalog.readmeError}
onRetry={catalog.retryReadme}
/>
</div>
);
}
export function PluginInstalledReadme({ plugin }: { plugin: NetcattyInstalledPlugin }) {
const source = plugin.source;
if (!source || (source.kind !== 'official' && source.kind !== 'third-party')) {
return null;
}
return <PluginCatalogBackedReadme key={`${source.id}:${plugin.id}`} pluginId={plugin.id} sourceId={source.id} />;
}
@@ -30,11 +30,12 @@ test('landing rows expose real sources/status/settings and quick toggles preserv
}] as NetcattyInstalledPlugin[];
const changes: Array<[string, boolean]> = [];
const opened: Array<string | null> = [];
const detailsOpened: string[] = [];
let refreshes = 0;
const manager = { plugins, available: true, statusKnown: true, busy: false, error: null as string | null, credentialStorageAvailable: true,
async refresh() { refreshes++; }, async setEnabled(id: string, enabled: boolean) { changes.push([id, enabled]); }, async importPackage() {}, async uninstall() {} };
Object.assign(dom.window, { netcatty: { async getPluginLogStatus() { return { saveToDisk: false, verbose: false, droppedRecords: 0, writeErrors: 0, pendingBytes: 0, maxBytes: 3145728, retentionDays: 7 }; } } });
const render = async (value = manager, settingsAvailable = new Set(['com.example.alpha'])) => act(async () => root.render(<I18nProvider locale="en"><PluginSettingsLanding manager={value} settingsAvailable={settingsAvailable} onManage={(id) => opened.push(id)} /></I18nProvider>));
const render = async (value = manager, settingsAvailable = new Set(['com.example.alpha'])) => act(async () => root.render(<I18nProvider locale="en"><PluginSettingsLanding manager={value} settingsAvailable={settingsAvailable} onManage={(id) => opened.push(id)} onOpenDetail={(id) => detailsOpened.push(id)} /></I18nProvider>));
const button = (label: string) => [...document.querySelectorAll<HTMLButtonElement>('button')].find((item) => item.textContent === label)!;
const byLabel = (label: string) => document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
try {
@@ -52,7 +53,8 @@ test('landing rows expose real sources/status/settings and quick toggles preserv
assert.ok(content.classList.contains('min-w-0'));
assert.equal(content.firstElementChild?.querySelector('[title="Alpha"]')?.textContent, 'Alpha');
assert.ok(content.firstElementChild?.classList.contains('text-sm'), 'title remains 14px');
assert.equal(content.lastElementChild?.textContent, 'Synthetic description');
assert.equal(content.lastElementChild, sourceRows[0], 'landing rows omit verbose description text');
assert.doesNotMatch(installedSection().textContent!, /Synthetic description/);
assert.ok(content.classList.contains('text-xs'), 'metadata and description remain 12px');
assert.ok(!content.parentElement?.classList.contains('mt-0.5'), 'shared SettingRow margin does not compress the local stack');
const thirdParty = sourceRows[1].querySelector<HTMLElement>('[data-plugin-source]')!;
@@ -63,6 +65,8 @@ test('landing rows expose real sources/status/settings and quick toggles preserv
await act(async () => button('Browse').click());
await act(async () => byLabel('Settings for Alpha').click());
assert.deepEqual(opened, [null, 'com.example.alpha']);
await act(async () => document.querySelector<HTMLButtonElement>('[data-plugin-open-detail="com.example.alpha"]')!.click());
assert.deepEqual(detailsOpened, ['com.example.alpha']);
await act(async () => byLabel('Disable Alpha').click());
assert.deepEqual(changes, [['com.example.alpha', false]]);
assert.equal(byLabel('Disable Alpha').getAttribute('aria-checked'), 'true', 'no optimistic flip before host approval');
@@ -1,5 +1,5 @@
import React, { useCallback, useMemo, useState } from 'react';
import { RefreshCw, Settings } from 'lucide-react';
import { ArrowUpCircle, Loader2, RefreshCw, Settings } from 'lucide-react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import type { usePluginUpdateCheck } from '../../../application/state/usePluginUpdateCheck';
import type { usePluginManager } from '../../../application/state/usePluginManager';
@@ -12,13 +12,14 @@ import { PluginLogSettings } from './PluginLogSettings';
type Manager = ReturnType<typeof usePluginManager>;
export function PluginSettingsLanding({ manager, settingsAvailable, settingsError, managerButtonRef, updates, onManage }: {
export function PluginSettingsLanding({ manager, settingsAvailable, settingsError, managerButtonRef, updates, onManage, onOpenDetail }: {
manager: Manager;
settingsAvailable: ReadonlySet<string>;
settingsError?: string;
managerButtonRef?: React.Ref<HTMLButtonElement>;
updates?: ReturnType<typeof usePluginUpdateCheck>;
onManage: (pluginId: string | null, opener: HTMLElement) => void;
onOpenDetail?: (pluginId: string, opener: HTMLElement) => void;
}) {
const { t, resolvedLocale } = useI18n();
const [search, setSearch] = useState('');
@@ -49,6 +50,7 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro
<Button className="focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2" variant="ghost" size="icon" disabled={manager.busy} aria-label={t('settings.plugins.landing.refresh')} onClick={() => void manager.refresh({ clearError: true }).catch(() => {})}><RefreshCw size={16} /></Button>
</>}>
{updates?.error && <p role="alert" className="text-sm text-destructive">{updates.error}</p>}
{updates?.updateError && <p role="alert" className="text-sm text-destructive">{updates.updateError}</p>}
{updates?.result && <p role="status" className="text-xs text-muted-foreground">{t('settings.plugins.landing.updateSummary').replace('{checked}', String(updates.result.checked)).replace('{updates}', String(updates.result.updates.length)).replace('{skipped}', String(updates.result.skipped))}{updates.result.failedSources > 0 && ` ${t('settings.plugins.landing.updateSourcesFailed').replace('{count}', String(updates.result.failedSources))}`} {t('settings.plugins.landing.updateReview')}</p>}
{settingsError && <p role="alert" className="text-sm text-destructive">{settingsError}</p>}
{manager.error && <p role="alert" className="text-sm text-destructive">{manager.error}</p>}
@@ -60,20 +62,31 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro
{visible.length === 0 ? <p role="status" className="text-sm text-muted-foreground">{t('settings.plugins.market.noResults')}</p> : <SettingCard divided>
{visible.map((plugin) => {
const name = nameOf(plugin);
const description = localized(plugin.manifest?.description);
const status = statusOf(plugin);
const hasError = manager.statusKnown && ['error', 'quarantined'].includes(plugin.runtime.status);
const availableUpdate = updates?.result?.updates.find((item) => item.pluginId === plugin.id && item.sourceId === plugin.source?.id);
const declaredSettings = Boolean(plugin.manifest?.contributes?.settings?.length);
return <SettingRow key={plugin.id} leading={<PluginBrandIcon plugin={plugin} size={40} />} description={<div className="flex min-w-0 flex-col gap-1 text-xs text-muted-foreground">
<span className="flex min-w-0 items-center gap-2 text-sm font-medium text-foreground">
<span className="truncate" title={name}>{name}</span>
return <SettingRow key={plugin.id} leading={onOpenDetail ? <button type="button" data-plugin-open-detail={plugin.id} aria-label={`${t('settings.plugins.manager.details')} ${name}`} title={`${t('settings.plugins.manager.details')} · ${name}`} onClick={(event) => onOpenDetail(plugin.id, event.currentTarget)} className="rounded-lg transition-opacity hover:opacity-85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><PluginBrandIcon plugin={plugin} size={40} /></button> : <PluginBrandIcon plugin={plugin} size={40} />} description={<div className="flex min-w-0 flex-col gap-1 text-xs text-muted-foreground">
<span className="flex min-w-0 flex-wrap items-center gap-2 text-sm font-medium text-foreground">
{onOpenDetail ? <button type="button" onClick={(event) => onOpenDetail(plugin.id, event.currentTarget)} className="min-w-0 truncate rounded text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" title={name}>{name}</button> : <span className="truncate" title={name}>{name}</span>}
{status && <span role="status" className={`inline-flex h-5 shrink-0 items-center justify-center rounded-full px-2 text-[10px] font-medium leading-4 ${hasError ? 'bg-red-500/15 text-red-600 dark:text-red-400' : 'bg-muted text-muted-foreground'}`}>{status}</span>}
{plugin.activeVersion && <span className="shrink-0 text-xs font-normal text-muted-foreground">{plugin.activeVersion}</span>}
{availableUpdate && <button
type="button"
data-plugin-quick-update={plugin.id}
disabled={manager.busy || Boolean(updates?.updatingId)}
onClick={() => void updates?.installUpdate(availableUpdate, plugin.enabled)}
title={t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}
className="inline-flex h-5 shrink-0 items-center gap-1 rounded-full bg-emerald-600 px-2 text-[11px] font-medium text-white transition-colors hover:bg-emerald-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
>
{updates?.updatingId === plugin.id
? <Loader2 size={11} className="animate-spin" aria-hidden="true" />
: <ArrowUpCircle size={11} aria-hidden="true" />}
<span>{updates?.updatingId === plugin.id ? t('settings.plugins.market.updating') : `${t('settings.plugins.market.update')} ${availableUpdate.availableVersion}`}</span>
<span className="sr-only">{t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}</span>
</button>}
</span>
<PluginAuthorRow plugin={plugin} showSource />
{availableUpdate && <span className="block text-primary">{t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}</span>}
{description && <span className="line-clamp-2 break-words">{description}</span>}
</div>}>
<div className="flex shrink-0 items-center gap-2">
{declaredSettings && <Button className="h-8 w-8 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2" variant="ghost" size="icon" disabled={manager.busy || !manager.statusKnown || !settingsAvailable.has(plugin.id)} aria-label={t('settings.plugins.landing.settingsFor').replace('{name}', name)} title={t(settingsAvailable.has(plugin.id) ? 'common.settings' : !plugin.enabled ? 'settings.plugins.landing.enableSettings' : 'settings.plugins.landing.settingsUnavailable')} onClick={(event) => onManage(plugin.id, event.currentTarget)}><Settings size={15} /></Button>}
@@ -7,19 +7,27 @@ import { PluginPackageManager } from './PluginPackageManager';
import type { usePluginManager } from '../../../application/state/usePluginManager';
test('state pill exposes actual state, opposite action, focus styling and pending disable without granting permissions', async () => {
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean; requestAnimationFrame?: typeof requestAnimationFrame };
const previous = globals.IS_REACT_ACT_ENVIRONMENT; globals.IS_REACT_ACT_ENVIRONMENT = true;
const previousRaf = globals.requestAnimationFrame;
globals.requestAnimationFrame ??= (fn) => { fn(0); return 0; };
const calls: unknown[] = [];
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill' }, runtime: {} } as NetcattyInstalledPlugin;
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill', engines: { netcatty: '*', api: '*' } }, runtime: {} } as NetcattyInstalledPlugin;
const manager = { available: true, plugins: [plugin], busy: false, setEnabled: async (...args: unknown[]) => { calls.push(args); } } as unknown as ReturnType<typeof usePluginManager>;
let renderer: ReactTestRenderer;
const render = (enabled: boolean, busy = false) => <I18nProvider locale="en"><PluginPackageManager manager={{ ...manager, busy, plugins: [{ ...plugin, enabled }] }} /></I18nProvider>;
try {
await act(async () => { renderer = create(render(true)); });
const pill = () => renderer.root.findAllByType('button').find((node) => node.props['aria-pressed'] !== undefined)!;
const listAvatar = () => renderer.root.findAllByType('button').find((node) => node.props['aria-label'] === 'View details Pill' && typeof node.props.className === 'string' && node.props.className.includes('h-8 w-8'));
const detailLogoSlot = () => renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(listAvatar(), 'list card renders 32px avatar details button');
assert.doesNotMatch(listAvatar()!.props.className, /\bbg-/, 'list avatar has no extra decorative background');
assert.equal(detailLogoSlot(), undefined, 'list render does not include the 48px detail logo slot');
await act(async () => listAvatar()!.props.onClick());
assert.ok(detailLogoSlot(), 'logo keeps its 48px layout slot without an extra decorative background');
assert.doesNotMatch(detailLogoSlot()!.props.className, /\bbg-/);
assert.equal(pill().props['aria-pressed'], true);
const logoSlot = renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(logoSlot, 'logo keeps its 48px layout slot without an extra decorative background');
assert.equal(pill().props['aria-label'], 'Disable Pill');
assert.ok(pill().children.includes('Enabled'));
assert.match(pill().props.className, /rounded-full/);
@@ -39,5 +47,9 @@ test('state pill exposes actual state, opposite action, focus styling and pendin
assert.match(pill().props.className, /bg-muted/);
assert.equal(pill().props.style, undefined);
await act(async () => renderer.unmount());
} finally { globals.IS_REACT_ACT_ENVIRONMENT = previous; }
} finally {
globals.IS_REACT_ACT_ENVIRONMENT = previous;
if (previousRaf === undefined) Reflect.deleteProperty(globals, 'requestAnimationFrame');
else globals.requestAnimationFrame = previousRaf;
}
});
@@ -6,8 +6,8 @@ import { Input } from '../../ui/input';
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../ui/dialog';
import { PluginMarketplace } from './PluginMarketplace';
export function PluginThirdPartyMarket({ installed, toolbarContainer, noVault }: {
installed: NetcattyInstalledPlugin[]; toolbarContainer?: HTMLElement | null; noVault?: boolean;
export function PluginThirdPartyMarket({ installed, toolbarContainer, noVault, onToggleEnabled, managerBusy }: {
installed: NetcattyInstalledPlugin[]; toolbarContainer?: HTMLElement | null; noVault?: boolean; onToggleEnabled?: (pluginId: string, enabled: boolean) => Promise<unknown> | void; managerBusy?: boolean;
}) {
const { t } = useI18n();
const model = usePluginSources();
@@ -36,7 +36,7 @@ export function PluginThirdPartyMarket({ installed, toolbarContainer, noVault }:
{!source && <div className="py-8 text-center text-sm text-muted-foreground"><p>{t('settings.plugins.sources.empty')}</p><Button className="mt-3" variant="outline" onClick={openManager}>{t('settings.plugins.sources.add')}</Button></div>}
{/* Keep each visited source mounted to preserve its own selection/search/scroll. */}
{sources.filter((item) => item.enabled && (item.id === selected || visited.includes(item.id))).map((item) => {
return <div key={item.id} hidden={item.id !== source?.id}><PluginMarketplace source={item} installed={installed} toolbarContainer={item.id === source?.id ? toolbarContainer : undefined} noVault={noVault} /></div>;
return <div key={item.id} hidden={item.id !== source?.id}><PluginMarketplace source={item} installed={installed} toolbarContainer={item.id === source?.id ? toolbarContainer : undefined} noVault={noVault} onToggleEnabled={onToggleEnabled} managerBusy={managerBusy} /></div>;
})}
<Dialog open={managing} onOpenChange={setManaging}><DialogContent className="max-h-[85vh] overflow-y-auto" onCloseAutoFocus={(event) => { event.preventDefault(); opener.current?.focus(); }}>
<DialogTitle>{t('settings.plugins.sources.manage')}</DialogTitle><DialogDescription>{t('settings.plugins.sources.risk')}</DialogDescription>
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
test('manual update action coalesces clicks, never runs on mount, and reports incomplete source checks honestly', async () => {
test('update check runs automatically on plugin view entry and detail navigation, coalesces concurrent requests, and reports incomplete source checks honestly', 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) => {
@@ -10,11 +10,13 @@ test('manual update action coalesces clicks, never runs on mount, and reports in
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
install('requestAnimationFrame', (callback: FrameRequestCallback) => { callback(0); return 0; });
install('IS_REACT_ACT_ENVIRONMENT', true);
const { default: React, act } = await import('react');
const { default: React, act, useState } = await import('react');
const { createRoot } = await import('react-dom/client');
const { I18nProvider } = await import('../../../application/i18n/I18nProvider');
const { PluginSettingsLanding } = await import('./PluginSettingsLanding');
const { PluginPackageManager } = await import('./PluginPackageManager');
const { usePluginUpdateCheck } = await import('../../../application/state/usePluginUpdateCheck');
const root = createRoot(document.getElementById('root')!);
const source: NetcattyPluginSource = { id: 'official', kind: 'official', name: 'Official source', origin: 'https://plugins.example.com', enabled: true };
@@ -29,21 +31,48 @@ test('manual update action coalesces clicks, never runs on mount, and reports in
Object.assign(dom.window, { netcatty: {
async listPlugins() { return plugins; }, async listPluginSources() { return [source]; },
async listPluginCatalog(id: string) { assert.equal(id, source.id); catalogReads++; await gate; return { entries: [{ id: plugin.id, version: '1.1.0', artifact: { url: 'https://plugins.example.com/synthetic.ncpkg', sha256: 'b'.repeat(64) } }], source: offline ? 'cached' : 'registry', error: offline ? 'synthetic offline' : null }; },
async getPluginCatalogReadme() { return '# Alpha'; },
async getPluginCatalogReadmeImages() { return {}; },
async getPluginPermissions() { return { pluginId: plugin.id, policies: [], grants: [], audit: [] }; },
async getPluginLogStatus() { return { saveToDisk: false, verbose: false, droppedRecords: 0, writeErrors: 0, pendingBytes: 0, maxBytes: 3145728, retentionDays: 7 }; },
async installCatalogPlugin() { mutations++; }, async setPluginEnabled() { mutations++; }, async checkForUpdates() { mutations++; },
} });
function Page() { const updates = usePluginUpdateCheck(plugins); return <PluginSettingsLanding manager={manager} updates={updates} settingsAvailable={new Set()} onManage={() => {}} />; }
let showManagerView!: (next: boolean) => void;
function Page() {
const updates = usePluginUpdateCheck(plugins);
const [showManager, setShowManager] = useState(false);
showManagerView = setShowManager;
return showManager
? <PluginPackageManager manager={manager} updates={updates} />
: <PluginSettingsLanding manager={manager} updates={updates} settingsAvailable={new Set()} onManage={() => {}} />;
}
const check = () => [...document.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === 'Check for updates')!;
try {
await act(async () => root.render(<I18nProvider locale="en"><Page /></I18nProvider>));
assert.equal(catalogReads, 0, 'rendering settings does not schedule checks');
await act(async () => { const button = check(); button.click(); button.click(); });
assert.equal(catalogReads, 1);
assert.equal([...document.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === 'Checking…')!.disabled, true);
assert.equal(catalogReads, 1, 'entering plugin settings automatically checks for updates once');
const checkingButton = [...document.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === 'Checking…')!;
assert.equal(checkingButton.disabled, true);
await act(async () => { checkingButton.click(); });
assert.equal(catalogReads, 1, 'concurrent clicks coalesce with the in-flight automatic check');
await act(async () => release());
assert.match(document.body.textContent!, /Published updates: 1/);
assert.match(document.body.textContent!, /Version 1.1.0 available/);
assert.equal(mutations, 0);
const quickUpdate = document.querySelector<HTMLButtonElement>('[data-plugin-quick-update="com.example.alpha"]');
assert.ok(quickUpdate, 'quick update pill renders beside installed version');
assert.match(quickUpdate.textContent!, /Update 1\.1\.0/);
// Navigating to Installed list and then Detail page also triggers silent update checks while preserving the update pill.
await act(async () => showManagerView(true));
assert.equal(catalogReads, 2, 'entering installed list triggers an update check');
assert.ok(document.querySelector('[data-plugin-card-update="com.example.alpha"]'));
await act(async () => {
document.querySelector<HTMLButtonElement>('[data-plugin-card="com.example.alpha"]')!.click();
});
assert.ok(catalogReads >= 3, 'opening plugin detail triggers an update check');
assert.ok(document.querySelector('[data-plugin-detail-update="com.example.alpha"]'));
await act(async () => showManagerView(false));
await act(async () => window.dispatchEvent(new Event('netcatty:plugin-packages-changed')));
assert.doesNotMatch(document.body.textContent!, /Version 1.1.0 available/, 'source/package changes invalidate prior results');
offline = true;
@@ -17,12 +17,14 @@ import { Button } from '../../ui/button';
import { SettingsAnchor, SettingsTabContent } from '../settings-ui';
import { PluginSettingsEntry, PluginSettingsDialog } from '../../plugins/PluginSettingsEntry';
function PluginManagementContent({ manager }: {
function PluginManagementContent({ manager, updates, initialPluginId }: {
manager: ReturnType<typeof usePluginManager>;
updates: ReturnType<typeof usePluginUpdateCheck>;
initialPluginId?: string | null;
}) {
const { t } = useI18n();
const [catalogToolbar, setCatalogToolbar] = useState<HTMLDivElement | null>(null);
const [selectedInstalled, setSelectedInstalled] = useState<string | null>(null);
const [selectedInstalled, setSelectedInstalled] = useState<string | null>(initialPluginId ?? null);
const [pluginView, setPluginView] = useState<'installed' | 'marketplace' | 'thirdparty'>('installed');
return (
<div className="space-y-5">
@@ -35,15 +37,16 @@ function PluginManagementContent({ manager }: {
</TabsList>
<div className="flex items-center gap-2">
{pluginView === 'installed' && <PluginStatus noVault={manager.credentialStorageAvailable === false} />}
{pluginView === 'installed' && manager.plugins.length > 0 && <Button variant="outline" size="sm" disabled={updates.busy || manager.busy || Boolean(updates.updatingId) || !manager.available || !manager.statusKnown} onClick={() => void updates.check()}>{t(updates.busy ? 'settings.plugins.landing.checkingUpdates' : 'settings.plugins.landing.checkUpdates')}</Button>}
<div ref={setCatalogToolbar} className="flex items-center gap-2" />
<PluginGitHubInstall disabled={!manager.available || manager.busy} onInstalled={async () => { setPluginView('installed'); await manager.refresh(); }} />
<Button variant="outline" size="sm" disabled={!manager.available || manager.busy} onClick={() => { setPluginView('installed'); void manager.importPackage(); }}><FolderOpen size={14} className="mr-2" />{t('settings.plugins.manager.import')}</Button>
</div>
</div>
<TabsContent forceMount hidden={pluginView !== 'marketplace'} value="marketplace" className="m-0 space-y-6"><PluginMarketplace installed={manager.plugins} toolbarContainer={pluginView === 'marketplace' ? catalogToolbar : undefined} noVault={manager.credentialStorageAvailable === false} /></TabsContent>
<TabsContent forceMount hidden={pluginView !== 'thirdparty'} value="thirdparty" className="m-0 space-y-6"><PluginThirdPartyMarket installed={manager.plugins} toolbarContainer={pluginView === 'thirdparty' ? catalogToolbar : undefined} noVault={manager.credentialStorageAvailable === false} /></TabsContent>
<TabsContent forceMount hidden={pluginView !== 'marketplace'} value="marketplace" className="m-0 space-y-6"><PluginMarketplace installed={manager.plugins} toolbarContainer={pluginView === 'marketplace' ? catalogToolbar : undefined} noVault={manager.credentialStorageAvailable === false} onToggleEnabled={(pluginId, enabled) => manager.setEnabled(pluginId, enabled)} managerBusy={manager.busy} /></TabsContent>
<TabsContent forceMount hidden={pluginView !== 'thirdparty'} value="thirdparty" className="m-0 space-y-6"><PluginThirdPartyMarket installed={manager.plugins} toolbarContainer={pluginView === 'thirdparty' ? catalogToolbar : undefined} noVault={manager.credentialStorageAvailable === false} onToggleEnabled={(pluginId, enabled) => manager.setEnabled(pluginId, enabled)} managerBusy={manager.busy} /></TabsContent>
<TabsContent value="installed" className="m-0 space-y-6">
<PluginPackageManager manager={manager} initialSelectedId={selectedInstalled} onSelectionChange={(id) => { setSelectedInstalled(id); }} detailActions={selectedInstalled && <PluginSettingsEntry key={`settings:${selectedInstalled}`} pluginId={selectedInstalled} />} />
<PluginPackageManager manager={manager} updates={updates} initialSelectedId={selectedInstalled} onSelectionChange={(id) => { setSelectedInstalled(id); }} detailActions={selectedInstalled && <PluginSettingsEntry key={`settings:${selectedInstalled}`} pluginId={selectedInstalled} />} />
</TabsContent>
</Tabs>
</div>
@@ -54,8 +57,9 @@ function PluginManagementContent({ manager }: {
export default function SettingsPluginsTab() {
const { locale } = useI18n();
const manager = usePluginManager();
const updates = usePluginUpdateCheck(manager.plugins);
const updates = usePluginUpdateCheck(manager.plugins, () => manager.refresh());
const [open, setOpen] = useState(false);
const [initialDetailId, setInitialDetailId] = useState<string | null>(null);
const [settingsPluginId, setSettingsPluginId] = useState<string | null>(null);
const opener = useRef<HTMLElement | null>(null);
const managerButton = useRef<HTMLButtonElement | null>(null);
@@ -69,10 +73,14 @@ export default function SettingsPluginsTab() {
<PluginSettingsLanding manager={manager} updates={updates} managerButtonRef={managerButton} settingsAvailable={settingsAvailable} settingsError={contributions.error?.message} onManage={(pluginId, element) => {
opener.current = element;
if (pluginId) setSettingsPluginId(pluginId);
else setOpen(true);
else { setInitialDetailId(null); setOpen(true); }
}} onOpenDetail={(pluginId, element) => {
opener.current = element;
setInitialDetailId(pluginId);
setOpen(true);
}} />
<PluginManagementDialog open={open} onOpenChange={setOpen} trigger={null} restoreFocusTo={opener} fallbackFocusTo={managerButton}>
<PluginManagementContent manager={manager} />
<PluginManagementDialog open={open} onOpenChange={(next) => { setOpen(next); if (!next) setInitialDetailId(null); }} trigger={null} restoreFocusTo={opener} fallbackFocusTo={managerButton}>
<PluginManagementContent key={initialDetailId ?? 'all'} manager={manager} updates={updates} initialPluginId={initialDetailId} />
</PluginManagementDialog>
{settingsPluginId && <PluginSettingsDialog key={settingsPluginId} pluginId={settingsPluginId} onClose={() => setSettingsPluginId(null)} restoreFocusTo={opener} />}
</SettingsAnchor>
@@ -301,7 +301,8 @@ export function getCommandToRecordOnEnter(
/**
* Keystrokes that remove the text a snippet acceptance replaces.
* Line-start keeps the shell kill-line (Ctrl+U, or backspaces on Windows).
* Mid-line and program read-prompts delete only the word being typed.
* Matching label prefixes replace the longest suffix starting at a word boundary.
* Otherwise, mid-line and program read-prompts delete only the word being typed.
* POSIX word delete sends DEL, the tty erase character. Ctrl-H is literal
* input to canonical `read` when erase is ^?, while readline still deletes
* on DEL. Windows line editing keeps backspace.
@@ -313,18 +314,35 @@ export function computeSnippetAcceptClearSequence(options: {
os: string;
promptText: string;
snippetKind?: "snippet" | "script";
snippetLabel?: string;
}): string {
const line = options.line ?? "";
if (line.length === 0) return "";
let matchedLabelSuffix: string | undefined;
if (options.snippetKind !== "script" && options.snippetLabel) {
const label = options.snippetLabel.toLowerCase();
// Scan from the start so the first boundary match is the longest suffix.
for (let start = 0; start < line.length; start += 1) {
if (start > 0 && !/\s/.test(line[start - 1])) continue;
const suffix = line.slice(start);
if (label.startsWith(suffix.toLowerCase())) {
matchedLabelSuffix = suffix;
break;
}
}
}
const { currentWord, wordIndex } = parseCommandLine(line);
const replaceWord = options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
const replaceWord = matchedLabelSuffix !== undefined
? matchedLabelSuffix !== line
: options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
if (replaceWord) {
const eraseChar = isWindowsShellLineInput(options.os, options.promptText) ? "\b" : "\x7f";
return eraseChar.repeat(Array.from(currentWord).length);
return eraseChar.repeat(Array.from(matchedLabelSuffix ?? currentWord).length);
}
return isWindowsShellLineInput(options.os, options.promptText)
@@ -1340,7 +1340,7 @@ export function useTerminalAutocomplete(
[handleCommandHistoryCleared],
);
/** Accept a snippet: clear the matched word (or the whole line for a script
/** Accept a snippet: clear the matched label or word (or the whole line for a script
* or a shell prompt), then run it via onAcceptSnippet. */
const acceptSnippet = useCallback((snippet: Snippet): boolean => {
const term = termRef.current;
@@ -1358,6 +1358,7 @@ export function useTerminalAutocomplete(
os: hostOsRef.current,
promptText: prompt.promptText,
snippetKind: snippet.kind,
snippetLabel: snippet.label,
});
if (clearSequence) writeToTerminal(clearSequence);
}
@@ -387,6 +387,102 @@ test("snippet accept deletes only the mid-line word (#3622)", () => {
);
});
test("snippet accept clears a whole-line label prefix (#4549)", () => {
for (const snippetKind of [undefined, "snippet"] as const) {
for (const line of ["Check size", "Check si", "check size"]) {
for (const os of ["linux", "windows"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind,
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat(line.length) : "\x15",
);
}
}
}
});
test("snippet accept deletes the longest matching label suffix at a word boundary (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const suffix of ["Check size", "Check si", "check size", "Check \u{1F680}"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: `git pull ${suffix}`,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind: "snippet",
snippetLabel: suffix === "Check \u{1F680}" ? suffix : "Check size",
}),
(os === "windows" ? "\b" : "\x7f").repeat(Array.from(suffix).length),
);
}
}
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull\tCheck\tsize",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check\tsize",
}),
"\x7f".repeat("Check\tsize".length),
);
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "use use more",
}),
"\x7f".repeat("use use".length),
);
});
test("snippet accept preserves word deletion with a single-word or unmatched label (#3622, #4549)", () => {
for (const snippetLabel of [undefined, "use", "user name", "Check size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel,
}),
"\x7f".repeat(3),
);
}
for (const line of ["size", "git pull size", "git pull xCheck size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check size",
}),
line === "size" ? "\x15" : "\x7f".repeat(4),
);
}
});
test("script snippet accept ignores matching labels and clears the whole line (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const promptText of ["user@host:~$ ", "Email: "]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull Check size",
os,
promptText,
snippetKind: "script",
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat("git pull Check size".length) : "\x15",
);
}
}
});
test("script snippet accept still clears the whole line (#3622)", () => {
assert.equal(
computeSnippetAcceptClearSequence({
@@ -453,4 +549,4 @@ test("computeAutocompleteAcceptWrite clears with backspaces on a mislabeled Wind
}),
"\b\b\buv run tkauto video sync-fs",
);
});
});
@@ -38,19 +38,21 @@ test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it aw
);
});
test('magnified side panels use an inner rounded 1px border in the side panel accent', () => {
test('magnified side panels use an inner rounded 1px theme-accent border and skip zoom animation on tab switch', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeStart = source.indexOf('"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]"');
assert.ok(chromeStart > 0, 'magnified side panel chrome must exist');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
const strokeStart = source.indexOf('data-section="pane-magnification-stroke"', chromeStart);
const strokeSource = source.slice(strokeStart, source.indexOf('/>', strokeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /\[clip-path:inset\(0_round_0\.375rem\)\]/);
assert.match(chromeSource, /animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150"/);
assert.doesNotMatch(chromeSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -1148,10 +1148,32 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
const magnifiedSidePane = activeMagnifiedPane?.target.kind === 'side-panel'
? activeSidePanelPanes.find((pane) => pane.id === activeMagnifiedPane.target.paneId) ?? null
: null;
const sidePaneMagAnimRef = useRef<{
tabId: string | null;
paneId: string | null;
animate: boolean;
}>({
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: false,
});
if (
sidePaneMagAnimRef.current.tabId !== (activeTabId ?? null)
|| sidePaneMagAnimRef.current.paneId !== (magnifiedSidePane?.id ?? null)
) {
const sameTab = sidePaneMagAnimRef.current.tabId === (activeTabId ?? null);
const entering = !!magnifiedSidePane && sidePaneMagAnimRef.current.paneId !== magnifiedSidePane.id;
sidePaneMagAnimRef.current = {
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: sameTab && entering,
};
}
const animateMagnifiedSidePane = sidePaneMagAnimRef.current.animate;
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!magnifiedSidePane) {
if (!magnifiedSidePane || !sidePaneMagAnimRef.current.animate) {
setShowMagnificationHint(false);
return undefined;
}
@@ -1583,7 +1605,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)] animate-in fade-in zoom-in-95 duration-150"
className={cn(
"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]",
animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150",
)}
style={{
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
@@ -1616,7 +1641,7 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sidePanelTheme.accent}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -65,9 +65,13 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
getWorkspacePaneOuterEdges,
PANE_MAGNIFICATION_DURATION_MS,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
shouldAnimatePaneMagnificationTransition,
type MagnifiedSurfaceBounds,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../../domain/paneMagnification';
@@ -1560,6 +1564,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
}, [deferPaneLayoutUpdate, isFocusedPane, isFocusMode, isSplitViewVisible, isVisible, livePaneLayoutKey]);
const paneLayoutKey = paneLayoutKeyRef.current;
const workspacePaneCount = layoutWorkspace ? collectSessionIds(layoutWorkspace.root).length : 0;
const hasMultipleWorkspacePanes = inActiveWorkspace && !isFocusMode && workspacePaneCount > 1;
const paneOuterEdges = useMemo(
() => (hasMultipleWorkspacePanes
? getWorkspacePaneOuterEdges(layoutWorkspace?.root, session.id)
: { left: false, right: false, top: false, bottom: false }),
[hasMultipleWorkspacePanes, layoutWorkspace?.root, session.id],
);
const isMagnified = isVisible
&& magnifiedPane?.target.kind === 'terminal'
&& magnifiedPane.target.sessionId === session.id
@@ -1567,16 +1579,22 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
const isCoveredByMagnification = isVisible
&& magnifiedPane?.tabId === (activeWorkspaceId ?? session.id)
&& !isMagnified;
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<{
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
} | null>(null);
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<MagnifiedSurfaceBounds | null>(null);
const prevMagnificationTransitionRef = useRef({
isVisible,
isMagnified,
});
useLayoutEffect(() => {
const prev = prevMagnificationTransitionRef.current;
prevMagnificationTransitionRef.current = { isVisible, isMagnified };
const shouldAnimate = shouldAnimatePaneMagnificationTransition({
wasVisible: prev.isVisible,
isVisible,
wasMagnified: prev.isMagnified,
isMagnified,
});
if (!isMagnified) {
if (!isVisible) {
if (!isVisible || !shouldAnimate) {
setMagnifiedSurfaceBounds(null);
return undefined;
}
@@ -1593,10 +1611,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
// the pane is fixed (offsetParent would be null during a quick re-zoom).
const layoutParent = pane?.parentElement;
if (!surface || !layoutParent) return undefined;
const update = () => {
const update = (animate: boolean) => {
const bounds = surface.getBoundingClientRect();
const origin = layoutParent.getBoundingClientRect();
if (pane && pane.style.position !== 'fixed') {
if (animate && pane && pane.style.position !== 'fixed') {
const geometry = {
left: pane.style.left,
top: pane.style.top,
@@ -1611,27 +1629,30 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
pane.getBoundingClientRect();
}
}
setMagnifiedSurfaceBounds({
setMagnifiedSurfaceBounds((current) => resolveNextMagnifiedSurfaceBounds(current, {
left: bounds.left,
top: bounds.top,
width: bounds.width,
height: bounds.height,
layoutOrigin: { left: origin.left, top: origin.top, width: origin.width, height: origin.height },
});
animate,
}));
};
update();
update(shouldAnimate);
if (typeof ResizeObserver === 'undefined') return undefined;
const observer = new ResizeObserver(update);
const observer = new ResizeObserver(() => update(false));
observer.observe(surface);
return () => observer.disconnect();
}, [isMagnified, isVisible]);
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
const animateMagnification = !isMagnified || (magnifiedSurfaceBounds?.animate ?? true);
const style: React.CSSProperties = resolvePaneMagnificationStyle(
layoutStyle,
isMagnified && !!magnifiedSurfaceBounds,
magnifiedSurfaceBounds,
magnifiedDevicePixelRatio,
magnifiedSurfaceBounds?.layoutOrigin,
animateMagnification,
);
useLayoutEffect(() => {
@@ -1821,6 +1842,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
data-session-id={session.id}
data-section="terminal-split-pane"
data-focused={isFocusedPane ? 'true' : undefined}
data-multi-pane={hasMultipleWorkspacePanes ? 'true' : undefined}
data-magnified={magnifiedSurfaceBounds ? 'true' : undefined}
data-workspace-corner-bl={paneOuterEdges.left && paneOuterEdges.bottom ? 'true' : undefined}
data-workspace-corner-br={paneOuterEdges.right && paneOuterEdges.bottom ? 'true' : undefined}
inert={isVisible && !isCoveredByMagnification ? undefined : true}
className={cn(
"absolute bg-background",
@@ -1999,7 +2024,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sessionAppearanceTheme.colors.cursor}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -28,6 +28,7 @@ import {
collectSidePanelPanes,
type SidePanelLayout,
} from '../../domain/sidePanelLayout';
import type { PaneMagnificationTarget } from '../../domain/paneMagnification';
type StableRef = React.MutableRefObject<Record<string, any>>;
@@ -54,8 +55,15 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
const sftpAuthHostBySessionId = s.sftpAuthHostBySessionId as Map<string, Host>;
const sidePanelOpenTabs = s.sidePanelOpenTabs as Map<string, SidePanelTab>;
const sidePanelLayouts = s.sidePanelLayouts as Map<string, SidePanelLayout>;
const magnifiedPanesByTab = s.magnifiedPanesByTab as ReadonlyMap<string, PaneMagnificationTarget>;
const showHostTreeSidebar = s.showHostTreeSidebar as boolean | undefined;
const activeMagnifiedPane = useMemo(() => {
if (!activeTabId) return null;
const target = magnifiedPanesByTab.get(activeTabId);
return target ? { tabId: activeTabId, target } : null;
}, [activeTabId, magnifiedPanesByTab]);
const activeWorkspace = useMemo(
() => (activeTabId ? workspaceById.get(activeTabId) : undefined),
[activeTabId, workspaceById],
@@ -116,7 +124,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
activeSession,
activeWorkspace,
isFocusMode,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === s.magnifiedPane?.tabId,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === activeMagnifiedPane?.tabId,
shouldKeepHiddenWorkspaceLaidOut,
onAddSessionToWorkspace: s.onAddSessionToWorkspace,
onCreateWorkspaceFromSessions: s.onCreateWorkspaceFromSessions,
@@ -574,7 +582,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
keys: s.keys,
knownHosts: s.knownHosts,
MessageSquare: s.MessageSquare,
magnifiedPane: s.magnifiedPane,
magnifiedPane: activeMagnifiedPane,
mountedAiTabIds: s.mountedAiTabIds,
mountedSftpTabIds: s.mountedSftpTabIds,
notesMountedTabIds: s.notesMountedTabIds,
@@ -724,7 +732,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
isFocusMode,
isSidePanelOpenForCurrentTab,
isTerminalLayerVisible,
s.magnifiedPane,
activeMagnifiedPane,
resizing,
resolveAIExecutorContext,
sessionHostsMap,
+19 -6
View File
@@ -44,6 +44,11 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
const isBottomDock = ctx.sidePanelPosition === 'bottom';
const workspaceTouchesBottom = !ctx.isComposeBarOpen && !(ctx.isSidePanelOpenForCurrentTab && isBottomDock);
const workspaceTouchesLeft = hostTreeLayoutWidth <= 0
&& !ctx.isFocusMode
&& !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'left');
const workspaceTouchesRight = !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'right');
return (
<div
@@ -51,12 +56,20 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
className={`absolute inset-0 bg-background flex min-h-0${isBottomDock ? ' flex-col' : ''}`}
data-section="terminal-workspace"
inert={ctx.isTerminalLayerVisible ? undefined : true}
style={getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
})}
style={{
...getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
}),
'--workspace-corner-bl-radius': workspaceTouchesBottom && workspaceTouchesLeft
? 'var(--window-corner-radius)'
: '0px',
'--workspace-corner-br-radius': workspaceTouchesBottom && workspaceTouchesRight
? 'var(--window-corner-radius)'
: '0px',
} as React.CSSProperties}
>
{/* Keep TerminalLayerSidePanelSection at a stable tree position (first
child) so cycling between side and bottom docks reorders it via flex
@@ -9,20 +9,24 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("terminal pane chrome uses an inner rounded 1px border while retaining overflow clipping", () => {
test("terminal pane chrome uses an inner rounded 1px theme-accent border while retaining overflow clipping", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf('TerminalPane.displayName'));
const hostSource = paneSource.slice(0, paneSource.indexOf("<LazyLoadBoundary"));
const strokeSource = paneSource.slice(paneSource.indexOf("{magnifiedSurfaceBounds && ("));
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl \[clip-path:inset\(0_round_0\.375rem\)\]",$/m);
assert.match(hostSource, /data-multi-pane=\{hasMultipleWorkspacePanes \? 'true' : undefined\}/);
assert.match(hostSource, /data-magnified=\{magnifiedSurfaceBounds \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-bl=\{paneOuterEdges\.left && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-br=\{paneOuterEdges\.right && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /style=\{style\}/);
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /aria-hidden="true"/);
assert.match(strokeSource, /data-section="pane-magnification-stroke"/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -34,30 +38,31 @@ test("restoring terminal chrome retains its inner 1px border until surface bound
assert.ok(condition);
assert.ok(styleSource);
const resolveStroke = new Function(
"isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme", "magnifiedDevicePixelRatio",
"isMagnified", "magnifiedSurfaceBounds", "magnifiedDevicePixelRatio",
`return ${condition[1]} ? ({${styleSource[1]}}) : null;`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
const bounds = { left: 0, top: 80, width: 1200, height: 800, animate: true };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStroke(true, bounds, theme, dpr);
const restoring = resolveStroke(false, bounds, theme, dpr);
const magnified = resolveStroke(true, bounds, dpr);
const restoring = resolveStroke(false, bounds, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.border, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.border, '1px solid hsl(var(--primary))');
assert.equal(restoring.boxSizing, 'border-box');
assert.equal(restoring.borderRadius, 'inherit');
for (const isMagnified of [false, true]) {
assert.equal(resolveStroke(isMagnified, null, theme, dpr), null);
assert.equal(resolveStroke(isMagnified, null, dpr), null);
}
}
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
test("magnified terminal panes snap overlay bounds to the device-pixel grid and skip animation on tab restore", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*\)/);
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*animateMagnification,\s*\)/);
assert.match(source, /layoutOrigin: \{ left: origin\.left, top: origin\.top, width: origin\.width, height: origin\.height \}/);
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
assert.match(source, /shouldAnimatePaneMagnificationTransition\(/);
assert.match(source, /resolveNextMagnifiedSurfaceBounds\(current,/);
});
test("percentage zoom entry flushes pixel geometry before applying fixed bounds", () => {
@@ -80,8 +85,8 @@ test("terminal keyboard focus updates the pane selected for magnification", () =
test("closing a magnified terminal clears the overlay selection", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /isPaneMagnificationSelectionValid\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /current\?\.target\.kind === 'terminal' && current\.target\.sessionId === sessionId/);
assert.match(source, /pruneMagnifiedPanesByTab\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /target\.kind === 'terminal' && target\.sessionId === sessionId/);
});
test("terminal panes expose focus mode and temporary magnification as separate actions", () => {
@@ -96,8 +101,28 @@ test("terminal panes expose focus mode and temporary magnification as separate a
test("focus mode cannot start temporary magnification but can restore stale magnification", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /const hasCurrentMagnification = magnifiedPaneRef\.current\?\.tabId === tabId;/);
assert.match(source, /const currentTarget = magnifiedPanesByTabRef\.current\.get\(tabId\);/);
assert.match(source, /const hasCurrentMagnification = !!currentTarget;/);
assert.match(source, /if \(workspace\?\.viewMode === 'focus' && !hasCurrentMagnification\) return null;/);
assert.match(source, /if \(!canMagnifyPaneSurface\(terminalCount, sidePanelCount\)\) \{/);
});
test("workspace focus border CSS uses 1px deterministic state, suppresses on magnified/single panes, and handles macOS corners", () => {
const css = readFileSync(new URL("../../index.css", import.meta.url), "utf8");
// Default dim mode preserved
assert.match(css, /\.workspace-pane:not\(:focus-within\) \.xterm-screen \{\s*opacity: 0\.82;\s*\}/);
// 1px customizable border on multi-pane workspaces only
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]::after/);
assert.match(css, /border: var\(--workspace-focus-border-width, 1px\) solid transparent;/);
// Deterministic data-focused state (not :focus-within), suppressed while magnified
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]\[data-focused="true"\]:not\(\[data-magnified="true"\]\)::after/);
assert.match(css, /border-color: var\(--workspace-focus-border-color, hsl\(var\(--primary\)\)\);/);
assert.doesNotMatch(css, /\[data-workspace-focus="border"\] \.workspace-pane:focus-within::after/);
// macOS non-fullscreen rounded window corners
assert.match(css, /:root\[data-platform="darwin"\]:not\(\[data-window-fullscreen="true"\]\) \{\s*--window-corner-radius: 10px;\s*\}/);
assert.match(css, /border-bottom-left-radius: var\(--workspace-corner-bl-radius, 0px\);/);
assert.match(css, /border-bottom-right-radius: var\(--workspace-corner-br-radius, 0px\);/);
});
test("closing a magnified terminal restores its pane instead of ending the session", () => {
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { memo, useEffect, useState, useSyncExternalStore } from 'react';
import React, { memo, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { LayoutGrid, Plus } from 'lucide-react';
import { Button } from '../ui/button';
@@ -147,10 +147,34 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
&& magnifiedPane.target.kind === 'terminal'
? magnifiedPane
: null;
const activeMagnifiedSessionId = activeMagnifiedTerminal?.target.kind === 'terminal'
? activeMagnifiedTerminal.target.sessionId
: null;
const terminalMagHintRef = useRef<{
tabId: string | null;
sessionId: string | null;
shouldShowHint: boolean;
}>({
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: false,
});
if (
terminalMagHintRef.current.tabId !== (activeTabId ?? null)
|| terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId
) {
const sameTab = terminalMagHintRef.current.tabId === (activeTabId ?? null);
const entering = !!activeMagnifiedSessionId && terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId;
terminalMagHintRef.current = {
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: sameTab && entering,
};
}
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!activeMagnifiedTerminal) {
if (!activeMagnifiedTerminal || !terminalMagHintRef.current.shouldShowHint) {
setShowMagnificationHint(false);
return undefined;
}
@@ -32,7 +32,8 @@ function closePane(tool: 'browser' | 'notes') {
useCallback: (callback: unknown) => callback,
activeTabIdRef: { current: 'terminal' }, sidePanelLayoutsRef: { current: layouts },
collectSidePanelPanes,
setMagnifiedPane: () => {},
setMagnifiedPanesByTab: () => {},
setTabMagnifiedPane: (current: unknown) => current,
closeSidePanelPaneForTab: (tabId: string, paneId: string) => {
const next = closeSidePanelPane(layouts.get(tabId)!, paneId);
assert.ok(next);
+8 -39
View File
@@ -4,7 +4,6 @@ import {
GripVertical,
Pin,
RotateCcw,
SlidersHorizontal,
} from 'lucide-react';
import React, { useCallback, useRef, useState } from 'react';
@@ -14,7 +13,7 @@ import type {
} from '../../domain/vaultNavConfig';
import { cn } from '../../lib/utils';
import { Button } from '../ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover';
import { primaryOnlyDragHandlers } from '../ui/primaryOnlyDrag';
import { Switch } from '../ui/switch';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
@@ -34,7 +33,6 @@ export interface VaultNavCustomizeItem {
export interface VaultNavCustomizePopoverProps {
open: boolean;
onOpenChange: (open: boolean) => void;
collapsed: boolean;
items: VaultNavCustomizeItem[];
isCustomized: boolean;
onToggleVisible: (id: VaultNavItemId) => void;
@@ -51,7 +49,6 @@ export interface VaultNavCustomizePopoverProps {
export const VaultNavCustomizePopover: React.FC<VaultNavCustomizePopoverProps> = ({
open,
onOpenChange,
collapsed,
items,
isCustomized,
onToggleVisible,
@@ -81,41 +78,13 @@ export const VaultNavCustomizePopover: React.FC<VaultNavCustomizePopoverProps> =
return (
<Popover open={open} onOpenChange={onOpenChange}>
<Tooltip>
<TooltipTrigger asChild>
<PopoverTrigger asChild>
<Button
type="button"
variant={open ? 'secondary' : 'ghost'}
aria-label={t('vault.nav.customize')}
data-vault-nav-customize-trigger="true"
className={cn(
'w-full',
collapsed ? 'justify-center p-0' : 'justify-start gap-3',
open && 'bg-foreground/10 text-foreground hover:bg-foreground/15',
)}
>
<span className="relative flex-shrink-0">
<SlidersHorizontal size={16} />
{isCustomized && (
<span
aria-hidden="true"
className="absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-primary"
/>
)}
</span>
{!collapsed && (
<span className="truncate">{t('vault.nav.customize')}</span>
)}
</Button>
</PopoverTrigger>
</TooltipTrigger>
{collapsed && !open && (
<TooltipContent side="right">
{t('vault.nav.customize')}
</TooltipContent>
)}
</Tooltip>
<PopoverAnchor asChild>
<div
aria-hidden="true"
data-vault-nav-customize-anchor="true"
className="pointer-events-none h-0 w-full"
/>
</PopoverAnchor>
<PopoverContent
side="right"
+17 -3
View File
@@ -57,6 +57,7 @@ test('VaultNavSidebar supports drag-and-drop reorder (expanded + collapsed), sho
'Event',
'KeyboardEvent',
'MouseEvent',
'DOMRect',
'ResizeObserver',
]) {
if (key === 'ResizeObserver') {
@@ -180,7 +181,6 @@ test('VaultNavSidebar supports drag-and-drop reorder (expanded + collapsed), sho
<VaultNavCustomizePopover
open={customizeOpen}
onOpenChange={setCustomizeOpen}
collapsed={collapsed}
items={customizeItems}
isCustomized={nav.isCustomized}
onToggleVisible={handleToggle}
@@ -271,7 +271,12 @@ test('VaultNavSidebar supports drag-and-drop reorder (expanded + collapsed), sho
});
assert.equal(getVisibleOrder()[1], 'logs', 'Logs moved after Hosts in collapsed mode');
// 4. Select Logs, open Customize popover, toggle Logs off -> active section auto-falls back to Hosts.
// 4. Select Logs, verify no standalone Customize button exists, open Customize via right-click context menu on a normal nav button, and toggle Logs off -> active section auto-falls back to Hosts.
assert.equal(
document.querySelector('[data-vault-nav-customize-trigger="true"]'),
null,
'sidebar must not render a standalone Customize button',
);
await act(async () => {
document.querySelector<HTMLButtonElement>('[data-vault-nav-item="logs"] button')!.click();
await settle();
@@ -279,7 +284,15 @@ test('VaultNavSidebar supports drag-and-drop reorder (expanded + collapsed), sho
assert.equal(currentSectionRef, 'logs');
await act(async () => {
document.querySelector<HTMLButtonElement>('[data-vault-nav-customize-trigger="true"]')!.click();
document
.querySelector<HTMLElement>('[data-vault-nav-item="logs"]')!
.dispatchEvent(new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 }));
await settle();
});
const contextCustomizeItem = document.querySelector<HTMLElement>('[data-vault-nav-context-customize="true"]');
assert.ok(contextCustomizeItem, 'right-clicking a nav button opens the Customize Sidebar context menu item');
await act(async () => {
contextCustomizeItem.click();
await settle();
});
assert.ok(document.querySelector('[data-vault-nav-customize-popover="true"]'));
@@ -404,6 +417,7 @@ test('VaultNavSidebar renders plugin view badges in expanded and collapsed modes
'Event',
'KeyboardEvent',
'MouseEvent',
'DOMRect',
'ResizeObserver',
]) {
if (key === 'ResizeObserver') {
+18 -2
View File
@@ -83,6 +83,7 @@ export const VaultNavSidebarList: React.FC<VaultNavSidebarListProps> = ({
t,
}) => {
const draggedIdRef = useRef<VaultNavItemId | null>(null);
const openingCustomizeRef = useRef(false);
const [draggedId, setDraggedId] = useState<VaultNavItemId | null>(null);
const [dropTarget, setDropTarget] = useState<{
id: VaultNavItemId;
@@ -247,7 +248,15 @@ export const VaultNavSidebarList: React.FC<VaultNavSidebarListProps> = ({
</div>
</ContextMenuTrigger>
<ContextMenuContent className="min-w-[12rem]">
<ContextMenuContent
className="min-w-[12rem]"
onCloseAutoFocus={(event) => {
if (openingCustomizeRef.current) {
openingCustomizeRef.current = false;
event.preventDefault();
}
}}
>
{!item.locked && (
<ContextMenuItem
disabled={!itemCanHide}
@@ -277,7 +286,14 @@ export const VaultNavSidebarList: React.FC<VaultNavSidebarListProps> = ({
<span>{t('vault.nav.moveDown')}</span>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem onSelect={onOpenCustomize} className="gap-2">
<ContextMenuItem
data-vault-nav-context-customize="true"
onSelect={() => {
openingCustomizeRef.current = true;
onOpenCustomize();
}}
className="gap-2"
>
<SlidersHorizontal size={14} className="shrink-0 text-muted-foreground" />
<span>{t('vault.nav.customize')}</span>
</ContextMenuItem>
+1 -2
View File
@@ -868,14 +868,13 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
<div
className={cn(
"mt-auto shrink-0 pb-4 space-y-1",
"mt-auto shrink-0 pb-4",
sidebarCollapsed ? "px-1.5" : "px-2.5",
)}
>
<VaultNavCustomizePopover
open={isNavCustomizeOpen}
onOpenChange={setIsNavCustomizeOpen}
collapsed={sidebarCollapsed}
items={customizeNavItems}
isCustomized={Boolean(vaultNavConfig?.isCustomized)}
onToggleVisible={handleToggleVaultNavItemVisible}
Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

@@ -8,7 +8,7 @@ Context Chips 位于终端撰写栏的快捷命令与输入区之间,为当前
| 功能 | 当前范围 | 文档 |
| --- | --- | --- |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD 和 Git Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Directory Picker | 目录展示、当前层搜索和导航,覆盖 POSIX、PowerShell、CMD、Git Bash 和 WSL Bash | [功能规格](directory-picker.md) · [跨平台设计](directory-picker-cross-platform.md) · [开发计划](directory-picker-follow-up.md) |
| Git Branch | 后续接入仓库识别、分支读取与切换 | [Git Branch](git-branch.md) |
| Git Changes | 后续接入变更统计与详情入口 | [Git Changes](git-changes.md) |
| Node Version | 后续接入当前 shell 的运行时与版本管理器 | [Node Version](node-version.md) |
@@ -67,11 +67,15 @@ PSDrive 根的 ProviderPath 可能带尾部反斜杠,因此路径比较按根
启动参数、profile 和提示符沿用用户配置。存在子进程时暂缓目录操作,原 Bash 恢复后重新读取。共享路径和虚拟挂载留到各自的路径语义明确后扩展。
## WSL 会话集成
通过 `WSLENV` 为所选发行版的交互会话传递标记。辅助进程在同一发行版和用户下读取 `/proc`,绑定原 Bash 的进程和终端,按 POSIX 路径处理 Linux 目录与挂载盘。检测到同终端的子进程时暂缓导航,原 Bash 恢复后重新读取位置。目录切换使用 Bash 内建 `cd`,以会话 cwd 确认结果。终端换窗口时保留原 shell 类型,目录请求跟随当前显示窗口。枚举目录时,按条目处理读取异常,保留可读的子目录。
## 后续设计方向
- POSIX hook:分别处理 bash 的 PROMPT_COMMAND、zsh 的启动链和 fish 事件,补齐事件上报。
- CMD:补充扩展关闭、提示符被启动脚本覆盖、变量展开字符和 UNC 映射场景。
- WSL/MSYS/Cygwin:以 distro/mount authority 组织目录 helper 和路径映射。
- WSL 扩展与 Cygwin:验证各自的发行版或挂载边界,复用目录控制器。
- 扩展远程环境:逐项明确活动 shell 与 SFTP/provider 的文件系统对应关系。
阶段交付与推进顺序统一维护在 [开发计划](directory-picker-follow-up.md)。
@@ -10,6 +10,7 @@
| B:PowerShell | 5.1/7 会话级脚本;原 runspace ProviderPath;私有位置报告;本地 FS;LiteralPath 切换和实际结果确认 | 用原 shell 状态串联展示、读取和执行 |
| C:CMD | 交互 CMD 的 PROMPT 上报;盘符目录读取与 `cd /d` 切换;原进程和新提示符确认 | 复用目录控制器,按 CMD 的变量展开和进程继承划定支持范围 |
| D1:Git Bash | 绑定原 Git for Windows Bash,读取 MSYS cwd 并映射为 Windows 盘符路径 | 保留 Bash 启动行为,复用 Windows 文件系统和目录控制器 |
| D2:WSL | 从原交互 Bash 读取 POSIX cwd,在同发行版和用户下解析路径、枚举目录并确认切换 | 保留 WSL 启动配置,让 Linux 目录和 Windows 挂载盘共享同一会话身份 |
| 状态恢复 | provider 切换清空旧目录与列表;恢复 FileSystem 后重新读取;提交输入使旧报告失效 | 让菜单始终对应当前有效的文件系统位置 |
| 生命周期 | 单会话请求排序、旧控制器失效、受管脚本清理、终端就绪门控 | 将异步操作与实际会话代次绑定 |
@@ -17,7 +18,14 @@ Windows CI 使用原生 ConPTY 覆盖 PowerShell 5.1/7 以及 CMD 的特殊字
## 后续阶段
Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库与 worktree 状态推进 [Git Changes](git-changes.md) 和 [Pull Request](pull-request.md)。[Node Version](node-version.md) 独立接入 shell 与版本管理器。目录兼容性按环境分别提交。
| PR 顺序 | 交付范围 |
| --- | --- |
| 1. WSL | Ubuntu Bash 的 Directory Picker,覆盖 Linux 目录和挂载盘。 |
| 2. Cygwin | 识别原 Bash 及其挂载,接入目录枚举、跳转和确认。 |
| 3. Git Branch | 识别当前工作树,读取分支并确认切换。见 [Git Branch](git-branch.md)。 |
| 4. Git Changes | 复用工作树状态,提供变更统计和详情入口。见 [Git Changes](git-changes.md)。 |
| 5. Pull Request | 使用当前工作树和分支关联托管服务。见 [Pull Request](pull-request.md)。 |
| 6. Node Version | 独立接入当前 shell 和版本管理器。见 [Node Version](node-version.md)。 |
### PowerShell 覆盖扩展
@@ -38,15 +46,15 @@ Git Bash 后先交付 [Git Branch](git-branch.md) 芯片,再按共享的仓库
为 `%`、`!` 目录验证保留字面值的传递方式;为自定义 AutoRun、关闭命令扩展和前后台子进程补充原生用例。UNC 的 `pushd`/`popd` 单独定义临时盘符、目录栈和退出清理语义。
### D2/D3:WSL 与 Cygwin
### D2:WSL
为每类环境定义文件系统 authority、cwd 来源、结构化目录 helper 与执行策略:
启动时通过 `WSLENV` 传入会话标记,保留原登录 shell 和配置。辅助进程在同一发行版和用户下运行,通过 `/proc` 绑定原 Bash 及其终端。目录读取使用 Linux 路径,切换结果由原 Bash 的 cwd 确认。
- WSL:绑定所选 distro,验证 Linux home、挂载盘及 wslpath/UNC 映射。
- Cygwin:验证 mount、驱动器、链接和编码转换。Git Bash 后续补充共享路径和虚拟挂载语义。
- helper:保留原始名称、类型和目录链接,提供输出边界、取消及权限状态。
首轮以带 Python 3.10 及以上版本的 Ubuntu Bash 为目标。WSL 1 已覆盖原生 ConPTY 核心行为。后续补充 WSL 2、其他发行版及 shell,并评估更轻量的辅助进程实现。
交付目标是让目录读取与命令执行处于同一命名空间,并按 distro/mount 身份组织缓存。
### D3:Cygwin
先确认 Cygwin 进程与终端的对应关系,再验证 `/cygdrive`、自定义挂载、符号链接和 Unicode。由同一安装的工具读取 cwd 和目录,保留原路径命名空间。Git Bash 后续扩展共享路径和虚拟挂载。
### E:扩展远程与嵌套 shell
+4 -3
View File
@@ -3,8 +3,8 @@ import { resolveInteractiveTerminalCdIntent } from './sessionRestore';
import { isAbsoluteDirectoryPath, joinDirectoryPath, labelDirectoryPath, parentDirectoryPath, type DirectoryPathFlavor } from './directoryPath';
export type DirectoryEntry = { name: string; path: string; hidden: boolean };
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'nonFilesystem';
export type WindowsDirectoryShell = 'powershell' | 'cmd' | 'git-bash' | 'wsl';
export type DirectoryPickerErrorCode = 'unavailable' | 'unknown' | 'busy' | 'readFailed' | 'accessDenied' | 'changeFailed' | 'unsupportedPath' | 'integrationUnavailable' | 'cmdIntegrationUnavailable' | 'gitBashIntegrationUnavailable' | 'wslIntegrationUnavailable' | 'nonFilesystem';
export class DirectoryPickerError extends Error {
constructor(public readonly code: DirectoryPickerErrorCode) { super(code); }
@@ -22,7 +22,7 @@ export function directoryLabel(path: string, home?: string | null, flavor: Direc
return labelDirectoryPath(path, home, flavor);
}
export function directoryEntries(path: string, files: readonly RemoteFile[], flavor: DirectoryPathFlavor = 'posix'): DirectoryEntry[] {
export function directoryEntries<T extends Pick<RemoteFile, 'name' | 'type' | 'linkTarget' | 'hidden'>>(path: string, files: readonly T[], flavor: DirectoryPathFlavor = 'posix'): DirectoryEntry[] {
return files.filter(file => file.type === 'directory' || (file.type === 'symlink' && file.linkTarget === 'directory'))
.flatMap(file => {
const child = joinDirectoryPath(path, file.name, flavor);
@@ -55,6 +55,7 @@ export function directoryChangeCommand(path: string, shell: 'posix' | WindowsDir
const target = path.replace(/\\/g, '/').replace(/'/g, "'\\''");
return `\\builtin cd -- '${target}'`;
}
if (shell === 'wsl') return flavor === 'posix' ? `\\builtin cd -- '${path.replace(/'/g, "'\\''")}'` : null;
return flavor === 'posix' ? resolveInteractiveTerminalCdIntent(path)?.command ?? null : null;
}
+103
View File
@@ -1239,3 +1239,106 @@ test("applyGroupDefaults lets standalone RDP host with inline password inherit a
assert.equal(result.rdpConfig?.username, "Administrator");
});
test("resolveGroupDefaults and applyGroupDefaults let a child group Direct override parent group and global proxies", () => {
const configs: GroupConfig[] = [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
];
const childDefaults = resolveGroupDefaults("corp/local", configs);
assert.equal(childDefaults.directProxy, true);
assert.equal(childDefaults.proxyProfileId, undefined);
assert.equal(childDefaults.proxyConfig, undefined);
const grandchildDefaults = resolveGroupDefaults("corp/local/lab", configs);
assert.equal(grandchildDefaults.directProxy, true);
assert.equal(grandchildDefaults.proxyProfileId, undefined);
const effective = applyGroupDefaults(
host({ group: "corp/local/lab" }),
grandchildDefaults,
globalProxyOptions,
);
assert.equal(effective.directProxy, true);
assert.equal(effective.proxyProfileId, undefined);
assert.equal(effective.proxyConfig, undefined);
});
test("resolveGroupDefaults lets a child group proxy override a parent group Direct setting", () => {
const configs: GroupConfig[] = [
{ path: "corp", directProxy: true },
{ path: "corp/bastion", proxyProfileId: "bastion-proxy" },
{ path: "corp/custom", proxyConfig: { type: "http", host: "custom.example.com", port: 8080 } },
];
const withProfile = resolveGroupDefaults("corp/bastion", configs);
assert.equal(withProfile.directProxy, undefined);
assert.equal(withProfile.proxyProfileId, "bastion-proxy");
const withCustom = resolveGroupDefaults("corp/custom", configs);
assert.equal(withCustom.directProxy, undefined);
assert.equal(withCustom.proxyConfig?.host, "custom.example.com");
const effective = applyGroupDefaults(host({ group: "corp/bastion" }), withProfile, globalProxyOptions);
assert.equal(effective.directProxy, undefined);
assert.equal(effective.proxyProfileId, "bastion-proxy");
});
test("resolveGroupDefaults prioritizes directProxy when co-present with proxy fields on the same group", () => {
const resolved = resolveGroupDefaults("corp", [
{
path: "corp",
directProxy: true,
proxyProfileId: "stale-profile",
proxyConfig: { type: "http", host: "stale.example.com", port: 8080 },
},
]);
assert.equal(resolved.directProxy, true);
assert.equal(resolved.proxyProfileId, undefined);
assert.equal(resolved.proxyConfig, undefined);
});
test("applyGroupDefaults lets a host choose its own proxy inside a Direct group", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
const hostWithProfile = applyGroupDefaults(
host({ group: "corp/local", proxyProfileId: "host-proxy" }),
groupDefaults,
globalProxyOptions,
);
assert.equal(hostWithProfile.proxyProfileId, "host-proxy");
assert.equal(hostWithProfile.directProxy, undefined);
const customProxy = { type: "socks5" as const, host: "host-proxy.example.com", port: 1080 };
const hostWithCustom = applyGroupDefaults(
host({ group: "corp/local", proxyConfig: customProxy }),
groupDefaults,
globalProxyOptions,
);
assert.deepEqual(hostWithCustom.proxyConfig, customProxy);
assert.equal(hostWithCustom.directProxy, undefined);
assert.equal(hostWithCustom.proxyProfileId, undefined);
});
test("applyGroupDefaults inherits group directProxy for vnc/rdp hosts and skips global default", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
for (const protocol of ["rdp", "vnc"] as const) {
const result = applyGroupDefaults(
host({ group: "corp/local", protocol }),
groupDefaults,
globalProxyOptions,
);
assert.equal(result.directProxy, true);
assert.equal(result.proxyProfileId, undefined);
assert.equal(result.proxyConfig, undefined);
}
});
+30 -5
View File
@@ -183,7 +183,20 @@ export function resolveGroupDefaults(
}
}
const groupSetsDirectProxy = config.directProxy === true;
if (groupSetsDirectProxy) {
delete merged.proxyProfileId;
delete merged.proxyConfig;
merged.directProxy = true;
}
for (const [key, value] of Object.entries(config)) {
if (key === 'directProxy') {
continue;
}
if (groupSetsDirectProxy && (key === 'proxyProfileId' || key === 'proxyConfig')) {
continue;
}
if (
key === 'proxyProfileId' &&
typeof value === 'string' &&
@@ -217,9 +230,11 @@ export function resolveGroupDefaults(
}
if (key === 'proxyProfileId') {
delete merged.proxyConfig;
delete merged.directProxy;
}
if (key === 'proxyConfig') {
delete merged.proxyProfileId;
delete merged.directProxy;
}
merged[key] = value;
}
@@ -243,7 +258,7 @@ export function resolveGroupDefaults(
const INHERITABLE_KEYS: (keyof GroupConfig)[] = [
'username', 'password', 'savePassword', 'authMethod', 'identityId', 'identityFileId', 'identityFilePaths',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'directProxy', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'legacyAlgorithms', 'skipEcdsaHostKey', 'algorithms',
'environmentVariables', 'charset', 'moshEnabled', 'moshServerPath',
'etEnabled', 'etPort',
@@ -297,6 +312,7 @@ const REMOTE_DESKTOP_INHERITABLE_KEYS = new Set<keyof GroupConfig>([
'hostChain',
'proxyProfileId',
'proxyConfig',
'directProxy',
]);
const STANDALONE_REMOTE_DESKTOP_SKIP_KEYS = new Set<string>([
@@ -460,6 +476,13 @@ export function applyGroupDefaults(
if (host.proxyConfig !== undefined || !groupDefaults.proxyProfileId) continue;
}
if (key === 'proxyConfig' && (host.proxyProfileId !== undefined || hostHasUsableProxyProfile)) continue;
if (key === 'directProxy') {
if (
groupDefaults.directProxy !== true ||
Boolean(host.proxyProfileId) ||
host.proxyConfig !== undefined
) continue;
}
const hostValue = (effective as unknown as Record<string, unknown>)[key];
const groupValue = (groupDefaults as unknown as Record<string, unknown>)[key];
const emptyStringIsOverride = EMPTY_STRING_OVERRIDES_GROUP_DEFAULT.has(key);
@@ -471,9 +494,6 @@ export function applyGroupDefaults(
(effective as unknown as Record<string, unknown>)[key] = groupValue;
}
}
// Explicit direct beats a host proxy, the nearest group proxy, and the
// global default. Clearing the host setting leaves directProxy unset and
// still inherits.
const isPluginHost = typeof host.protocol === 'string' && host.protocol.startsWith('plugin:');
if (!isLocalShellHost && !isSerialHost && !isPluginHost) {
const isStandaloneRdp = host.protocol === 'rdp';
@@ -506,7 +526,12 @@ export function applyGroupDefaults(
}
}
}
if (host.directProxy === true) return withoutInheritedProxy(effective);
// Explicit direct (on the host or inherited from the nearest group) beats
// parent group proxies and the global default. Clearing the setting leaves
// directProxy unset and still inherits.
if (host.directProxy === true || effective.directProxy === true) {
return withoutInheritedProxy(effective);
}
if (!effective.proxyConfig && !effective.proxyProfileId) {
const globalProxyProfileId = resolveGlobalProxyProfileId(options);
if (globalProxyProfileId) effective.proxyProfileId = globalProxyProfileId;
+5
View File
@@ -529,6 +529,11 @@ export interface GroupConfig {
x11Forwarding?: boolean;
proxyProfileId?: string;
proxyConfig?: ProxyConfig;
/**
* Explicit direct connection default for hosts in this group. Overrides
* parent group proxies and the global default proxy. Absent means inherit.
*/
directProxy?: boolean;
hostChain?: HostChainConfig;
startupCommand?: string;
startupCommandRunMode?: MultiLineRunMode;
+163
View File
@@ -2,14 +2,20 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
canMagnifyPaneSurface,
getAvailablePaneMagnificationController,
getPaneMagnificationShortcutLabel,
getWorkspacePaneOuterEdges,
isPaneMagnificationSelectionValid,
PANE_MAGNIFICATION_DURATION_MS,
pruneMagnifiedPanesByTab,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationCandidate,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
resolveTwoPaneMagnificationStyle,
setTabMagnifiedPane,
shouldAnimatePaneMagnificationTransition,
snapCssRectToDevicePixels,
type PaneMagnificationController,
} from './paneMagnification.ts';
@@ -299,3 +305,160 @@ test('keeps a valid magnified pane focused and rejects a single-pane surface', (
current: null,
}), null);
});
test('canMagnifyPaneSurface disables magnification for a lone terminal without a side panel', () => {
assert.equal(canMagnifyPaneSurface(0, 0), false);
assert.equal(canMagnifyPaneSurface(1, 0), false);
assert.equal(canMagnifyPaneSurface(0, 1), false);
assert.equal(canMagnifyPaneSurface(1, 1), true);
assert.equal(canMagnifyPaneSurface(2, 0), true);
});
test('getWorkspacePaneOuterEdges identifies bottom-left and bottom-right corner panes in nested splits', () => {
const root = {
id: 'root',
type: 'split' as const,
direction: 'vertical' as const,
children: [
{ id: 'left', type: 'pane' as const, sessionId: 's-left' },
{
id: 'right-col',
type: 'split' as const,
direction: 'horizontal' as const,
children: [
{ id: 'top-right', type: 'pane' as const, sessionId: 's-top-right' },
{ id: 'bottom-right', type: 'pane' as const, sessionId: 's-bottom-right' },
],
},
],
};
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-left'), {
left: true,
right: false,
top: true,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-top-right'), {
left: false,
right: true,
top: true,
bottom: false,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-bottom-right'), {
left: false,
right: true,
top: false,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 'missing'), {
left: false,
right: false,
top: false,
bottom: false,
});
});
test('shouldAnimatePaneMagnificationTransition skips zoom animation on tab-switch restore', () => {
// User triggers magnify on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), true);
// User triggers restore on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: true,
isMagnified: false,
}), true);
// Switching back to an already-magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: false,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), false);
// Switching away from a magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: false,
wasMagnified: true,
isMagnified: false,
}), false);
});
test('resolvePaneMagnificationStyle omits transition properties when animate is false', () => {
const original = { left: '0px', top: '0px', width: '500px', height: '400px' };
const surface = { left: 0, top: 40, width: 1000, height: 800 };
const origin = { left: 0, top: 40, width: 1000, height: 800 };
const snapped = resolvePaneMagnificationStyle(original, true, surface, 1, origin, false);
assert.equal(snapped.position, 'fixed');
assert.equal(snapped.zIndex, 50);
assert.equal(snapped.transitionProperty, undefined);
assert.equal(snapped.transitionDuration, undefined);
assert.equal(snapped.transitionTimingFunction, undefined);
assert.equal(snapped.left, '12px');
assert.equal(snapped.top, '12px');
assert.equal(snapped.width, '976px');
assert.equal(snapped.height, '776px');
});
test('per-tab magnification map preserves independent tab states and prunes closed panes', () => {
let byTab = new Map();
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-a', { kind: 'terminal', sessionId: 's1' }));
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-b', { kind: 'side-panel', paneId: 'p1', tool: 'sftp' }));
assert.deepEqual(byTab.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.deepEqual(byTab.get('tab-b'), { kind: 'side-panel', paneId: 'p1', tool: 'sftp' });
const pruned = pruneMagnifiedPanesByTab(
byTab,
[{ tabId: 'tab-a', sessionId: 's1' }],
[],
);
assert.deepEqual(pruned.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.equal(pruned.has('tab-b'), false);
const cleared = setTabMagnifiedPane(pruned, 'tab-a', null);
assert.equal(cleared.size, 0);
});
test('resolveNextMagnifiedSurfaceBounds preserves entry animation on unchanged initial ResizeObserver callback', () => {
const initial = {
left: 0,
top: 40,
width: 1200,
height: 800,
layoutOrigin: { left: 0, top: 40, width: 1200, height: 800 },
animate: true,
};
// Unchanged resize notification with animate=false must preserve initial animate=true reference
const afterInitialObserver = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
layoutOrigin: { ...initial.layoutOrigin },
animate: false,
});
assert.equal(afterInitialObserver, initial);
assert.equal(afterInitialObserver.animate, true);
// Real surface resize updates bounds with animate=false
const resized = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
width: 1400,
layoutOrigin: { ...initial.layoutOrigin, width: 1400 },
animate: false,
});
assert.equal(resized.width, 1400);
assert.equal(resized.animate, false);
// Restoring from hidden tab (current=null) applies animate=false immediately
const restored = resolveNextMagnifiedSurfaceBounds(null, {
...initial,
animate: false,
});
assert.equal(restored.animate, false);
});
+172 -7
View File
@@ -1,4 +1,5 @@
import type React from 'react';
import type { WorkspaceNode } from './models';
export type PaneMagnificationState = 'unavailable' | 'focusable' | 'focused';
@@ -13,6 +14,161 @@ export type PaneMagnificationTarget =
| { kind: 'terminal'; sessionId: string }
| { kind: 'side-panel'; paneId: string; tool: string };
export type WorkspacePaneOuterEdges = {
left: boolean;
right: boolean;
top: boolean;
bottom: boolean;
};
/**
* Pure threshold check matching resolvePaneMagnificationCandidate:
* a surface with fewer than 2 total panes (e.g. a single terminal with no side
* panel) is already full-size and must not magnify.
*/
export function canMagnifyPaneSurface(
terminalPaneCount: number,
sidePanelPaneCount: number,
): boolean {
return terminalPaneCount + sidePanelPaneCount >= 2;
}
/**
* Determine which outer edges of the workspace split tree a terminal session
* touches, so focus borders can match the host window's rounded corners on
* macOS without clipping while keeping interior split edges crisp.
*/
export function getWorkspacePaneOuterEdges(
root: WorkspaceNode | null | undefined,
sessionId: string,
): WorkspacePaneOuterEdges {
const empty: WorkspacePaneOuterEdges = { left: false, right: false, top: false, bottom: false };
if (!root) return empty;
const walk = (node: WorkspaceNode, edges: WorkspacePaneOuterEdges): WorkspacePaneOuterEdges | null => {
if (node.type === 'pane') {
return node.sessionId === sessionId ? edges : null;
}
const count = node.children.length;
for (let index = 0; index < count; index += 1) {
const child = node.children[index];
const childEdges: WorkspacePaneOuterEdges = node.direction === 'vertical'
? {
left: edges.left && index === 0,
right: edges.right && index === count - 1,
top: edges.top,
bottom: edges.bottom,
}
: {
left: edges.left,
right: edges.right,
top: edges.top && index === 0,
bottom: edges.bottom && index === count - 1,
};
const found = walk(child, childEdges);
if (found) return found;
}
return null;
};
return walk(root, { left: true, right: true, top: true, bottom: true }) ?? empty;
}
/**
* Animate magnification/restore only when the pane stays visible across the
* state transition (user action on the active tab). Returning to an already
* magnified tab must snap directly without replaying a zoom animation.
*/
export function shouldAnimatePaneMagnificationTransition({
wasVisible,
isVisible,
wasMagnified,
isMagnified,
}: {
wasVisible: boolean;
isVisible: boolean;
wasMagnified: boolean;
isMagnified: boolean;
}): boolean {
return wasVisible && isVisible && wasMagnified !== isMagnified;
}
export type MagnifiedSurfaceBounds = {
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
animate: boolean;
};
/**
* Merge a magnified surface measurement into existing state while ignoring
* ResizeObserver notifications whose geometry has not actually changed (most
* notably the initial observation callback delivered right after observe(),
* which would otherwise overwrite `animate: true` and cancel user-triggered
* zoom animations).
*/
export function resolveNextMagnifiedSurfaceBounds(
current: MagnifiedSurfaceBounds | null,
next: MagnifiedSurfaceBounds,
): MagnifiedSurfaceBounds {
if (
!next.animate
&& current
&& current.left === next.left
&& current.top === next.top
&& current.width === next.width
&& current.height === next.height
&& current.layoutOrigin.left === next.layoutOrigin.left
&& current.layoutOrigin.top === next.layoutOrigin.top
&& current.layoutOrigin.width === next.layoutOrigin.width
&& current.layoutOrigin.height === next.layoutOrigin.height
) {
return current;
}
return next;
}
export function setTabMagnifiedPane(
current: ReadonlyMap<string, PaneMagnificationTarget>,
tabId: string,
target: PaneMagnificationTarget | null,
): ReadonlyMap<string, PaneMagnificationTarget> {
const existing = current.get(tabId);
if (!target) {
if (!existing) return current;
const next = new Map(current);
next.delete(tabId);
return next;
}
const sameTarget = existing && existing.kind === target.kind && (
existing.kind === 'terminal'
? target.kind === 'terminal' && existing.sessionId === target.sessionId
: target.kind === 'side-panel' && existing.paneId === target.paneId && existing.tool === target.tool
);
if (sameTarget) return current;
const next = new Map(current);
next.set(tabId, target);
return next;
}
export function pruneMagnifiedPanesByTab(
current: ReadonlyMap<string, PaneMagnificationTarget>,
terminalPanes: Array<{ tabId: string; sessionId: string }>,
sidePanelPanes: Array<{ tabId: string; paneId: string }>,
): ReadonlyMap<string, PaneMagnificationTarget> {
if (current.size === 0) return current;
let changed = false;
const next = new Map<string, PaneMagnificationTarget>();
for (const [tabId, target] of current) {
if (isPaneMagnificationSelectionValid({ tabId, target }, terminalPanes, sidePanelPanes)) {
next.set(tabId, target);
} else {
changed = true;
}
}
return changed ? next : current;
}
export function isPaneMagnificationSelectionValid(
selection: { tabId: string; target: PaneMagnificationTarget },
terminalPanes: Array<{ tabId: string; sessionId: string }>,
@@ -42,7 +198,7 @@ export function resolvePaneMagnificationCandidate({
lastTarget?: PaneMagnificationTarget;
current: { tabId: string; target: PaneMagnificationTarget } | null;
}): { target: PaneMagnificationTarget; focused: boolean } | null {
if (terminalSessionIds.length + sidePanelPanes.length < 2) return null;
if (!canMagnifyPaneSurface(terminalSessionIds.length, sidePanelPanes.length)) return null;
const targetIsValid = (target: PaneMagnificationTarget) => (
target.kind === 'terminal'
? terminalSessionIds.includes(target.sessionId)
@@ -140,15 +296,24 @@ export function resolvePaneMagnificationStyle(
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
devicePixelRatio = 1,
layoutOrigin?: { left: number; top: number; width?: number; height?: number },
animate = true,
): React.CSSProperties {
// Keep the fixed overlay and transition while restoring too, so the split
// container cannot clip the pane before it has finished shrinking.
const transition: React.CSSProperties = surfaceBounds ? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
} : {};
// When restoring magnification after a tab switch (`animate = false`), skip
// transition properties so the pane snaps immediately before paint.
const transition: React.CSSProperties = surfaceBounds ? (
animate
? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
}
: {
zIndex: 50,
}
) : {};
// Margins compensate for the containing-block switch without animating or
// transforming the terminal and its descendants. Local split offsets then
// keep the same viewport origin when fixed positioning starts or ends.
+157
View File
@@ -0,0 +1,157 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildRdpClipboardItemData, fingerprintRdpClipboardPng, nextRdpClipboardGuardState, selectRdpClipboardData } from './rdpClipboard';
const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
const emptyState = { lastText: '', lastPngFingerprint: null };
test('mixed remote clipboard data preserves both local formats and does not echo on refocus', async () => {
const snapshot = { text: 'caption', pngBytes };
const data = buildRdpClipboardItemData(snapshot);
assert.deepEqual(Object.keys(data).sort(), ['image/png', 'text/plain']);
assert.equal(data['image/png'].type, 'image/png');
assert.equal(data['text/plain'].type, 'text/plain');
const localSnapshot = {
text: await data['text/plain'].text(),
pngBytes: new Uint8Array(await data['image/png'].arrayBuffer()),
};
assert.deepEqual(localSnapshot, snapshot);
assert.deepEqual(selectRdpClipboardData({
...nextRdpClipboardGuardState(snapshot),
...localSnapshot,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
test('local clipboard item data preserves image-only, text-only and empty text formats', async () => {
const imageData = buildRdpClipboardItemData({ text: null, pngBytes });
assert.deepEqual(Object.keys(imageData), ['image/png']);
assert.deepEqual(new Uint8Array(await imageData['image/png'].arrayBuffer()), pngBytes);
for (const text of ['hello', '']) {
const textData = buildRdpClipboardItemData({ text, pngBytes: null });
assert.deepEqual(Object.keys(textData), ['text/plain']);
assert.equal(await textData['text/plain'].text(), text);
}
});
test('image-only RDP clipboard data is sent', () => {
assert.deepEqual(selectRdpClipboardData({ ...emptyState, text: '', pngBytes }), {
text: null,
pngBytes,
pngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
});
test('the last pushed or received PNG is skipped unless forced', () => {
const input = {
...emptyState,
text: null,
pngBytes: new Uint8Array(pngBytes),
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
};
assert.equal(selectRdpClipboardData(input).pngBytes, null);
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }).pngBytes, pngBytes);
assert.notEqual(fingerprintRdpClipboardPng(new Uint8Array([1, 2, 3, 4])), input.lastPngFingerprint);
});
test('text-only RDP clipboard behavior is unchanged', () => {
const input = { ...emptyState, text: 'hello', pngBytes: null };
assert.equal(selectRdpClipboardData(input).text, 'hello');
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello' }).text, null);
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello', force: true }).text, 'hello');
});
test('text and PNG are selected together', () => {
const result = selectRdpClipboardData({ ...emptyState, text: 'caption', pngBytes });
assert.equal(result.text, 'caption');
assert.equal(result.pngBytes, pngBytes);
});
test('a changed clipboard snapshot sends every present format', () => {
const result = selectRdpClipboardData({
...emptyState,
text: 'new text',
pngBytes,
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
assert.equal(result.text, 'new text');
assert.equal(result.pngBytes, pngBytes);
const imageResult = selectRdpClipboardData({
...emptyState,
text: 'same text',
lastText: 'same text',
pngBytes,
});
assert.equal(imageResult.text, 'same text');
assert.equal(imageResult.pngBytes, pngBytes);
});
test('text then image then the same text replaces each clipboard snapshot', () => {
const imageResult = selectRdpClipboardData({
lastText: 'B', lastPngFingerprint: null, text: null, pngBytes,
});
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(imageResult, { text: null, pngBytes, pngFingerprint });
const imageState = nextRdpClipboardGuardState(imageResult);
assert.deepEqual(imageState, { lastText: '', lastPngFingerprint: pngFingerprint });
const textResult = selectRdpClipboardData({ ...imageState, text: 'B', pngBytes: null });
assert.deepEqual(textResult, { text: 'B', pngBytes: null, pngFingerprint: null });
const textState = nextRdpClipboardGuardState(textResult);
assert.deepEqual(textState, { lastText: 'B', lastPngFingerprint: null });
assert.deepEqual(selectRdpClipboardData({ ...textState, text: null, pngBytes }), imageResult);
});
test('text-only replacement sends unchanged text when the previous snapshot included a PNG', () => {
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
text: 'B',
pngBytes: null,
}), { text: 'B', pngBytes: null, pngFingerprint: null });
});
test('image-only replacement sends the same PNG when the previous snapshot included text', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: null,
pngBytes,
}), { text: null, pngBytes, pngFingerprint });
});
test('an identical text and PNG snapshot is skipped unless forced', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
const input = {
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: 'B',
pngBytes: new Uint8Array(pngBytes),
};
assert.deepEqual(selectRdpClipboardData(input), {
text: null, pngBytes: null, pngFingerprint: null,
});
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }), {
text: 'B', pngBytes, pngFingerprint,
});
assert.deepEqual(nextRdpClipboardGuardState(input), {
lastText: 'B', lastPngFingerprint: pngFingerprint,
});
});
test('an empty clipboard snapshot clears both guard fields and sends nothing', () => {
const input = { text: undefined, pngBytes: new Uint8Array() };
assert.deepEqual(nextRdpClipboardGuardState(input), emptyState);
assert.deepEqual(selectRdpClipboardData({ ...emptyState, ...input }), {
text: null, pngBytes: null, pngFingerprint: null,
});
});
test('empty clipboard formats are ignored even when forced', () => {
assert.deepEqual(selectRdpClipboardData({
...emptyState,
text: undefined,
pngBytes: new Uint8Array(),
force: true,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
+58
View File
@@ -0,0 +1,58 @@
export function buildRdpClipboardItemData({ text, pngBytes }: {
text: string | null;
pngBytes: Uint8Array | null;
}): Record<string, Blob> {
const data: Record<string, Blob> = {};
if (pngBytes) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
data['image/png'] = new Blob([pngCopy], { type: 'image/png' });
}
if (text !== null) {
data['text/plain'] = new Blob([text], { type: 'text/plain' });
}
return data;
}
export function fingerprintRdpClipboardPng(bytes: Uint8Array): string {
// FNV-1a plus the byte length is sufficient for clipboard echo detection.
let hash = 0x811c9dc5;
for (const byte of bytes) {
hash = Math.imul(hash ^ byte, 0x01000193);
}
return `${bytes.length}:${(hash >>> 0).toString(16)}`;
}
export function nextRdpClipboardGuardState({ text, pngBytes }: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
}) {
return {
lastText: text || '',
lastPngFingerprint: pngBytes?.length ? fingerprintRdpClipboardPng(pngBytes) : null,
};
}
export function selectRdpClipboardData({
text,
pngBytes,
lastText,
lastPngFingerprint,
force = false,
}: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
lastText: string;
lastPngFingerprint: string | null;
force?: boolean;
}) {
const current = nextRdpClipboardGuardState({ text, pngBytes });
if (!force && current.lastText === lastText && current.lastPngFingerprint === lastPngFingerprint) {
return { text: null, pngBytes: null, pngFingerprint: null };
}
return {
text: current.lastText || null,
pngBytes: current.lastPngFingerprint !== null ? pngBytes : null,
pngFingerprint: current.lastPngFingerprint,
};
}
+2
View File
@@ -159,11 +159,13 @@ test('generateRdpFileContent round-trips cleanly through parseRdpFile and strips
});
assert.ok(generated.includes('full address:s:[2001:db8::10]:33890\r\n'));
assert.ok(generated.includes('\r\nuse redirection server name:i:1\r\n'));
assert.ok(!generated.includes('\r\nfull address:s:evil.example'));
const reparsed = parseRdpFile(generated);
assert.equal(reparsed.hostname, '2001:db8::10');
assert.equal(reparsed.port, 33890);
assert.equal(reparsed.username, 'alice|token-123');
assert.equal(reparsed.useRedirectionServerName, true);
assert.equal(reparsed.resolutionMode, 'dynamic');
assert.equal(reparsed.audioEnabled, true);
assert.equal(reparsed.clipboardSync, true);
+1
View File
@@ -400,6 +400,7 @@ export const generateRdpFileContent = (spec: GenerateRdpFileSpec): string => {
`full address:s:${formatRdpFullAddress(spec.hostname, port)}`,
`server port:i:${port}`,
'prompt for credentials:i:1',
'use redirection server name:i:1',
'screen mode id:i:2',
];
+52
View File
@@ -47,6 +47,58 @@ describe('vaultGroupAgentOps', () => {
assert.equal(effective.proxyConfig?.host, 'parent-gw.test');
});
it('supports setting and clearing directProxy on groups consistently with Group Details', () => {
const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: 'proxy-1' };
const initialState = {
groups: ['prod', 'prod/web'],
configs: [
{ path: 'prod', proxyConfig: { type: 'http' as const, host: 'parent-gw.test', port: 3128 } },
{ path: 'prod/web', proxyProfileId: 'proxy-1' },
],
hosts,
managedSources: [],
};
const setDirect = upsertGroup(initialState, 'prod/web', '{"directProxy":true}', [], proxyProfiles);
assert.equal(setDirect.ok, true);
if (!setDirect.ok) return;
assert.equal(setDirect.config?.directProxy, true);
assert.equal(setDirect.config?.proxyProfileId, undefined);
assert.equal(setDirect.config?.proxyConfig, undefined);
const directEffective = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', setDirect.state.configs, proxyOptions), proxyOptions,
);
assert.equal(directEffective.directProxy, true);
assert.equal(directEffective.proxyProfileId, undefined);
assert.equal(directEffective.proxyConfig, undefined);
const replacedWithProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":"proxy-1"}', [], proxyProfiles);
assert.equal(replacedWithProfile.ok, true);
if (!replacedWithProfile.ok) return;
assert.equal(replacedWithProfile.config?.directProxy, undefined);
assert.equal(replacedWithProfile.config?.proxyProfileId, 'proxy-1');
const clearedViaEmptyProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles);
assert.equal(clearedViaEmptyProfile.ok, true);
if (!clearedViaEmptyProfile.ok) return;
assert.equal(clearedViaEmptyProfile.config?.directProxy, undefined);
assert.equal(clearedViaEmptyProfile.config?.proxyProfileId, undefined);
const inheritedAgain = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', clearedViaEmptyProfile.state.configs, proxyOptions), proxyOptions,
);
assert.equal(inheritedAgain.proxyConfig?.host, 'parent-gw.test');
const clearedViaFalse = upsertGroup(setDirect.state, 'prod/web', '{"directProxy":false}', [], proxyProfiles);
assert.equal(clearedViaFalse.ok, true);
if (!clearedViaFalse.ok) return;
assert.equal(clearedViaFalse.config?.directProxy, undefined);
assert.equal(
upsertGroup(initialState, 'prod/web', '{"directProxy":true,"proxyProfileId":"proxy-1"}', [], proxyProfiles).ok,
false,
);
});
it('rejects missing identities, proxy profiles, and jump hosts', () => {
const state = { groups: ['prod'], configs: [], hosts, managedSources: [] };
assert.equal(upsertGroup(state, 'prod', '{"identityId":"missing"}', [], proxyProfiles).ok, false);
+21 -1
View File
@@ -144,8 +144,18 @@ export function patchGroupConfig(
next.authMethod = undefined;
}
}
if (Object.hasOwn(defaults, 'proxyProfileId')) {
const hasProxyProfileId = Object.hasOwn(defaults, 'proxyProfileId');
const hasDirectProxy = Object.hasOwn(defaults, 'directProxy');
let parsedDirectProxy: boolean | undefined;
if (hasDirectProxy) {
parsedDirectProxy = bool(defaults.directProxy);
if (parsedDirectProxy === undefined) return { ok: false, error: 'directProxy must be true or false.' };
}
if (hasProxyProfileId) {
const proxyProfileId = String(defaults.proxyProfileId ?? '');
if (proxyProfileId && parsedDirectProxy === true) {
return { ok: false, error: 'directProxy and proxyProfileId cannot both be set.' };
}
if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) {
return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` };
}
@@ -153,6 +163,16 @@ export function patchGroupConfig(
// group proxy (or the global default) applies, instead of blocking it.
next.proxyProfileId = proxyProfileId || undefined;
next.proxyConfig = undefined;
next.directProxy = undefined;
}
if (hasDirectProxy) {
if (parsedDirectProxy) {
next.directProxy = true;
next.proxyProfileId = undefined;
next.proxyConfig = undefined;
} else {
next.directProxy = undefined;
}
}
if (Object.hasOwn(defaults, 'jumpHostIds')) {
let ids: unknown = defaults.jumpHostIds;
+28
View File
@@ -456,6 +456,34 @@ test("CSV round-trips explicit direct proxy mode and still treats an empty Proxy
assert.equal(literal.hosts[1]?.directProxy, undefined);
});
test("CSV export writes direct for hosts inheriting group directProxy and preserves host proxy overrides", () => {
const groupProxy = { type: "socks5" as const, host: "group.example.com", port: 1080 };
const hostProxy = { type: "http" as const, host: "host.example.com", port: 8080 };
const hosts: Host[] = [
{ ...hostDefaults, id: "child-direct", label: "Child Direct", hostname: "child.example.com", group: "Corp/Local" },
{
...hostDefaults,
id: "child-override",
label: "Child Override",
hostname: "override.example.com",
group: "Corp/Local",
proxyConfig: hostProxy,
},
];
const { csv } = exportHostsToCsvWithStats(hosts, {
groupConfigs: [
{ path: "Corp", proxyConfig: groupProxy },
{ path: "Corp/Local", directProxy: true },
],
});
const lines = csv.replace(/^\uFEFF/, "").trimEnd().split("\r\n");
const proxyIndex = lines[0].split(",").indexOf("Proxy");
const proxyCell = (line: string) => line.split(",")[proxyIndex];
assert.equal(proxyCell(lines[1]), "direct");
assert.equal(proxyCell(lines[2]), "http://host.example.com:8080");
assert.equal(csv.includes("group.example.com"), false);
});
test("CSV export keeps an empty Proxy cell when only the global default is set", () => {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
try {
+5
View File
@@ -77,6 +77,10 @@ const POSIX_PROMPT_PATTERN = /^(?:[^\s@]+@[^\s:]+(?::[^\n\r]*)?|\[[^\s@\]]+@[^\s
// Require HH:MM:SS so loose `[word]$` output cannot count as idle.
const BRACKET_TIME_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+\d{2}:\d{2}:\d{2}(?:\s+[^\n\r\]]+)?\][#$]$/;
// Home Assistant / bash `[\h \W]$` or `[\u \W]$` prompts (#4527).
// Require a path field, not a time field, to keep loose `[word]$` rejected as in #4276.
const BRACKET_PATH_POSIX_PROMPT_PATTERN = /^\[[^\s@\]]+\s+[^\n\r\]]+\][#$]$/;
// Space-separated bash PS1 `\u@\h \w $ ` renders as `user@host ~ $`.
// macOS ships zsh with `%n@%m %1~ %#`, which renders as
// `user@host ~ %` / `user@host My Project %`; privileged shells end in `#`.
@@ -184,6 +188,7 @@ function isDefaultPosixPromptLine(line) {
(prompt) => (
POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
BRACKET_PATH_POSIX_PROMPT_PATTERN.test(prompt) ||
PAREN_POSIX_PROMPT_PATTERN.test(prompt) ||
ALPINE_PROMPT_PATTERN.test(prompt) ||
MACOS_ROOT_PROMPT_PATTERN.test(prompt) ||
+32 -2
View File
@@ -204,11 +204,26 @@ test("recognizes bracketed time prompts without a hostname and preserves trailin
}
});
test("bracketed time prompt recognition rejects pending input and prompts without time", () => {
test("recognizes bracketed host/path prompts without a time field and preserves trailing space", () => {
for (const prompt of [
"[core-ssh ~]$",
"[core-ssh ~]$ ",
"[core-ssh /config]$",
"[core-ssh homeassistant]$",
"[core-ssh ~]#",
"[root ~]$",
]) {
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
}
});
test("bracketed prompt recognition rejects pending input and loose single-word output", () => {
for (const line of [
"[root 12:04:23 ~]$ hostname",
"[root 12:04:23 ~]$ echo $",
"[root ~]$",
"[core-ssh ~]$ date",
"[core-ssh ~]$ echo $",
"[word]$",
]) {
assert.equal(isDefaultPosixPromptLine(line), false, line);
@@ -599,6 +614,13 @@ test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed time prompt
);
});
test("extractTrailingIdlePrompt recognizes an ANSI-colored bracketed host/path prompt", () => {
assert.equal(
extractTrailingIdlePrompt("welcome\r\n[\x1b[1;34mcore-ssh \x1b[1;32m~\x1b[0m]$ "),
"[core-ssh ~]$ ",
);
});
test("extractTrailingIdlePrompt recognizes a two-line user@host then bare $/# PS1", () => {
// export PS1="\u@\h: \w\n$ " paints the host line, then a lone "$ ".
// The cached prompt must keep both lines so a lone "$" cannot satisfy endsWith.
@@ -1422,6 +1444,14 @@ test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed time prom
assert.equal(getFreshIdlePrompt(session), prompt);
});
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a bracketed host/path prompt", () => {
const session = {};
const prompt = "[core-ssh ~]$ ";
assert.equal(trackSessionIdlePrompt(session, `Last login...\r\n${prompt}`), prompt);
assert.equal(session.lastIdlePrompt, prompt);
assert.equal(getFreshIdlePrompt(session), prompt);
});
test("visible idle prompt survives a PSReadLine erase that leaves the raw tail dirty", () => {
// PSReadLine echoes the pending-input clear prefix (`ggd2147483647d` / `i`),
// then homes the cursor and erases those keys with CSI. stripAnsi drops the
+20 -7
View File
@@ -237,16 +237,11 @@ function createClipboardImageFileName(date = new Date()) {
return `netcatty-paste-${formatClipboardImageTimestamp(date)}.png`;
}
async function readClipboardImage({
async function readClipboardImagePngBytes({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) {
return null;
}
if (!clipboard) return null;
try {
let content = null;
@@ -297,7 +292,24 @@ async function readClipboardImage({
}
if (!Buffer.isBuffer(content) || content.length === 0) return null;
return content;
} catch {
return null;
}
}
async function readClipboardImage({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) return null;
try {
const content = await readClipboardImagePngBytes({ clipboard, nativeImageImpl });
if (!content) return null;
const name = createClipboardImageFileName(now());
const imagePath = tempDirBridge.getTempFilePath(name);
await fsImpl.promises.writeFile(imagePath, content);
@@ -381,4 +393,5 @@ module.exports = {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
};
+55
View File
@@ -11,6 +11,7 @@ const {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
} = require("./clipboardFiles.cjs");
const createFs = (entries) => ({
@@ -158,6 +159,59 @@ test("creates stable clipboard image file names", () => {
);
});
test("reads native clipboard PNG bytes without a temp directory", async () => {
const content = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const result = await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({ isEmpty: () => false, toPNG: () => content }),
read: () => assert.fail("native image read should take precedence"),
},
});
assert.deepEqual(result, content);
});
test("PNG bytes helper returns null for empty native images or PNG buffers", async () => {
assert.equal(await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({
isEmpty: () => true,
toPNG: () => assert.fail("empty image must not be encoded"),
}),
},
}), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => ({ toPNG: () => Buffer.alloc(0) }) },
}), null);
});
test("PNG bytes helper returns null for missing or failing clipboard reads", async () => {
assert.equal(await readClipboardImagePngBytes(), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => { throw new Error("clipboard unavailable"); } },
}), null);
});
test("PNG bytes helper converts async clipboard images through nativeImage", async () => {
const rawBytes = Buffer.from("jpeg");
const pngBytes = Buffer.from("png");
const result = await readClipboardImagePngBytes({
clipboard: {
read: async () => [{
types: ["image/jpeg"],
getType: async () => new Blob([rawBytes], { type: "image/jpeg" }),
}],
},
nativeImageImpl: {
createFromBuffer: (bytes) => {
assert.deepEqual(bytes, rawBytes);
return { isEmpty: () => false, toPNG: () => pngBytes };
},
},
});
assert.deepEqual(result, pngBytes);
});
test("writes clipboard image to Netcatty temp directory", async () => {
const writes = [];
const content = Buffer.from([1, 2, 3]);
@@ -346,6 +400,7 @@ test("readClipboardImage and hasClipboardImage support Electron 44+ async W3C cl
};
assert.equal(await hasClipboardImage({ clipboard }), true);
assert.deepEqual(await readClipboardImagePngBytes({ clipboard }), pngBytes);
const saved = await readClipboardImage({
clipboard,
fsImpl: {
+1
View File
@@ -1866,6 +1866,7 @@ function buildDefaultRdpFileContent({
const lines = [
`full address:s:${hostPort}`,
"prompt for credentials:i:1",
"use redirection server name:i:1",
`audiomode:i:${audioEnabled === false ? 2 : 0}`,
`redirectclipboard:i:${clipboardSync === false ? 0 : 1}`,
"screen mode id:i:2",
@@ -305,6 +305,7 @@ describe("remoteDesktopBridge system client helpers", () => {
loadBalanceInfo: "tsv://MS Terminal Services Plugin.1.Desktop",
});
assert.match(content, /^full address:s:10\.1\.2\.3:33890/m);
assert.ok(content.includes("\r\nuse redirection server name:i:1\r\n"));
assert.match(content, /^username:s:alice\|token-uuid/m);
assert.match(content, /^domain:s:CORP/m);
assert.match(content, /^loadbalanceinfo:s:tsv:\/\//m);
@@ -312,6 +313,7 @@ describe("remoteDesktopBridge system client helpers", () => {
const rewritten = rewriteRdpFullAddress(content, "127.0.0.1", 54321);
assert.match(rewritten, /^full address:s:127\.0\.0\.1:54321/m);
assert.equal(rewritten, content.replace("full address:s:10.1.2.3:33890", "full address:s:127.0.0.1:54321"));
});
it("builds vnc:// URL safely without embedding passwords", () => {
@@ -0,0 +1,107 @@
import base64
import json
import os
import pwd
import sys
def process_stat(path):
try:
with open(path + '/stat', encoding='utf-8', errors='replace') as stream:
fields = stream.read().rsplit(') ', 1)[1].split()
return tuple(int(fields[index]) for index in (1, 2, 3, 4, 5, 19))
except (OSError, ValueError, IndexError):
return None
def marked(path, marker):
try:
if os.stat(path).st_uid != os.geteuid():
return False
with open(path + '/environ', 'rb') as stream:
return marker in stream.read(256 * 1024).split(b'\0')
except OSError:
return False
def interactive_bash(marker, expected):
processes = {}
tagged = set()
with os.scandir('/proc') as entries:
for entry in entries:
if not entry.name.isdecimal():
continue
stat = process_stat(entry.path)
if stat and stat[3]:
pid = int(entry.name)
processes[pid] = stat
if marked(entry.path, marker):
tagged.add(pid)
roots = [pid for pid in tagged if processes[pid][0] not in tagged]
if len(roots) != 1:
return None
pid = roots[0]
stat = processes[pid]
_, group, session, tty, foreground, started = stat
identity = f'{pid}:{started}'
if (expected and identity != expected) or group != pid or foreground not in (0, group):
return None
# WSL 1 can report foreground group 0. In both modes, a peer on the
# same terminal other than the launcher means the original Bash is busy.
ancestors = {pid}
parent = stat[0]
while parent in processes and parent not in ancestors:
ancestors.add(parent)
parent = processes[parent][0]
if any(other not in ancestors and row[2:4] == (session, tty) for other, row in processes.items()):
return None
proc = f'/proc/{pid}'
if os.path.basename(os.readlink(proc + '/exe')) != 'bash':
return None
return proc, identity, stat
def directory_result(operation, encoded_path, cwd):
if operation == 'cwd':
return {}
path = base64.b64decode(encoded_path, validate=True).decode('utf-8')
if operation == 'realpath':
canonical = os.path.realpath(path, strict=True)
if not os.path.isdir(canonical):
raise NotADirectoryError(canonical)
return {'path': canonical}
if path != cwd:
return {'error': 'unavailable'}
files = []
with os.scandir(path) as entries:
for entry in entries:
try:
entry.name.encode('utf-8')
if entry.is_dir():
files.append({'name': entry.name, 'type': 'directory'})
except (OSError, UnicodeError):
continue
if len(files) > 4096:
raise ValueError('Directory listing exceeds limit')
return {'files': files}
def main(operation, nonce, expected, encoded_path):
try:
marker = ('NETCATTY_WSL_DIRECTORY_SESSION=' + nonce).encode('ascii')
match = interactive_bash(marker, expected)
if not match:
return {'error': 'unavailable'}
proc, identity, stat = match
cwd = os.readlink(proc + '/cwd')
result = directory_result(operation, encoded_path, cwd)
if process_stat(proc) != stat or os.readlink(proc + '/cwd') != cwd:
return {'error': 'unavailable'}
return {'identity': identity, 'cwd': cwd, 'home': pwd.getpwuid(os.geteuid()).pw_dir, **result}
except PermissionError:
return {'error': 'accessDenied'}
except (OSError, ValueError, KeyError):
return {'error': 'readFailed'}
print(json.dumps(main(*sys.argv[1:]), ensure_ascii=True))
+27 -1
View File
@@ -99,6 +99,7 @@ const tempDirBridge = require("./tempDirBridge.cjs");
const { preparePowerShellDirectoryIntegration } = require('./powerShellDirectoryIntegration.cjs');
const { prepareCmdDirectoryIntegration } = require('./cmdDirectoryIntegration.cjs');
const { prepareGitBashDirectoryIntegration } = require('./gitBashDirectoryIntegration.cjs');
const { prepareWslDirectoryIntegration } = require('./wslDirectoryIntegration.cjs');
const { createTelnetAutoLogin, isAutoLoginWakeInput } = require("./telnetAutoLogin.cjs");
const telnetProtocol = require("./telnetProtocol.cjs");
const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs");
@@ -1164,6 +1165,8 @@ async function startLocalSession(event, payload) {
const directoryIntegration = preparePowerShellDirectoryIntegration(shell, shellArgs)
?? prepareCmdDirectoryIntegration(shell, shellArgs, env)
?? (isWslExecutable(shell) ? prepareWslDirectoryIntegration(shell, shellArgs, env,
discoverShells().find(item => item.id.startsWith('wsl-') && item.args?.[1] === shellArgs[1])) : null)
?? (process.platform === 'win32' && path.win32.basename(shell).toLowerCase() === 'bash.exe'
? prepareGitBashDirectoryIntegration(shell, shellArgs, env, discoverShells().find(item => item.id === 'git-bash')?.command) : null);
let proc;
@@ -1182,7 +1185,7 @@ async function startLocalSession(event, payload) {
directoryIntegration?.cleanup?.();
throw error;
}
directoryIntegration?.reader.setProcessId(proc.pid);
directoryIntegration?.reader.setProcessId?.(proc.pid);
if (directoryIntegration) {
// All writers (interactive input, snippets and AI exec) share this PTY.
// Invalidate at the transport boundary, including direct proc/pty writes.
@@ -2660,6 +2663,18 @@ function registerWorkerSend(ipcMain, terminalWorkerManager, channel) {
});
}
const WSL_DIRECTORY_CHANNEL = "netcatty:local:wslDirectory";
const wslDirectoryUnavailable = Object.freeze({ success: false, error: "unavailable" });
async function readWslSessionDirectory(event, { sessionId, operation, path } = {}, workerRuntime = false) {
const session = sessions.get(sessionId);
const canRead = () => session && !session.closed && sessions.get(sessionId) === session
&& (workerRuntime || session.webContentsId === event.sender.id);
if (!canRead() || !session.directoryIntegration?.readPath) return wslDirectoryUnavailable;
const result = await session.directoryIntegration.readPath(operation, path);
return canRead() ? result : wslDirectoryUnavailable;
}
function registerHandlers(ipcMain, options = {}) {
const terminalWorkerManager = options.terminalWorkerManager || null;
// Attach/observe popups rebind display routing in the main process even when
@@ -2813,6 +2828,14 @@ function registerHandlers(ipcMain, options = {}) {
terminalWorkerManager.onSessionClosed?.(({ sessionId }) => {
terminalFlowPauseArbiter.clearSession(sessionId);
});
// Output routing lives in main. Only the current routed window can read WSL paths.
ipcMain.handle(WSL_DIRECTORY_CHANNEL, async (event, { sessionId, operation, path } = {}) => {
const webContentsId = event.sender.id;
const ownsOutput = () => terminalWorkerManager.getSessionOwnerWebContentsId(sessionId) === webContentsId;
if (!ownsOutput()) return wslDirectoryUnavailable;
const result = await terminalWorkerManager.request(WSL_DIRECTORY_CHANNEL, { sessionId, operation, path }, { webContentsId });
return ownsOutput() ? result : wslDirectoryUnavailable;
});
[
"netcatty:local:start",
"netcatty:telnet:start",
@@ -2893,6 +2916,9 @@ function registerHandlers(ipcMain, options = {}) {
? sessionLogStreamManager.withSessionLogRestart
: (handler) => handler;
ipcMain.handle("netcatty:local:start", wrapSessionStart(startLocalSession));
// The worker endpoint is reachable only through main's authorized proxy.
ipcMain.handle(WSL_DIRECTORY_CHANNEL, (event, payload) =>
readWslSessionDirectory(event, payload, options.workerRuntime === true));
ipcMain.handle("netcatty:telnet:start", wrapSessionStart(startTelnetSession));
ipcMain.handle("netcatty:mosh:start", wrapSessionStart(startMoshSession));
ipcMain.handle("netcatty:et:start", wrapSessionStart(startEtSession));
@@ -395,6 +395,52 @@ test("fallback log restart guard wraps all six starts only when main explicitly
assert.equal(wrappers.size, 0, "worker proxies must not also apply the main fallback guard");
});
test("WSL directory requests follow the active output window and discard results after a handoff", async () => {
const channel = "netcatty:local:wslDirectory";
const unavailable = { success: false, error: "unavailable" };
const listing = { success: true, files: [{ name: "child", type: "directory" }] };
const home = { sender: { id: 42 } };
const popup = { sender: { id: 43 } };
const payload = { sessionId: "wsl", operation: "list", path: "/home/example" };
let outputOwner = home.sender.id;
let finish;
const sessions = new Map([["wsl", {
webContentsId: home.sender.id,
directoryIntegration: {
readPath: () => new Promise(resolve => { finish = resolve; }),
},
}]]);
const main = createFakeIpcMain();
const worker = createFakeIpcMain();
const fallback = createFakeIpcMain();
terminalBridge.init({ sessions });
terminalBridge.registerHandlers(worker, { workerRuntime: true });
terminalBridge.registerHandlers(fallback);
terminalBridge.registerHandlers(main, {
terminalWorkerManager: {
getSessionOwnerWebContentsId: id => id === "wsl" ? outputOwner : null,
request: (name, data, { webContentsId }) =>
worker.handlers.get(name)({ sender: { id: webContentsId } }, data),
},
});
const read = main.handlers.get(channel);
const beforeHandoff = read(home, payload);
outputOwner = popup.sender.id;
finish(listing);
assert.deepEqual(await beforeHandoff, unavailable);
assert.deepEqual(await read(home, payload), unavailable);
assert.deepEqual(await fallback.handlers.get(channel)(popup, payload), unavailable);
const afterHandoff = read(popup, payload);
finish(listing);
assert.deepEqual(await afterHandoff, listing);
const beforeClose = read(popup, payload);
sessions.delete("wsl");
finish(listing);
assert.deepEqual(await beforeClose, unavailable);
});
test("terminal worker mode handles stateless local shell and path queries in main without waking worker", async () => {
const ipcMain = createFakeIpcMain();
const terminalWorkerManager = createFakeWorkerManager();
@@ -0,0 +1,102 @@
const fs = require('node:fs');
const path = require('node:path');
const { randomBytes } = require('node:crypto');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const run = promisify(execFile);
const marker = 'NETCATTY_WSL_DIRECTORY_SESSION';
const unavailable = Object.freeze({ success: false, error: 'unavailable' });
const isPath = value => typeof value === 'string' && value.startsWith('/') && value.length <= 8192
&& !/[\x00-\x1f\x7f]|[\uD800-\uDFFF]/u.test(value);
function getWslDirectoryArgs(args, discovered) {
// A named distro is required so the helper cannot follow a changed default.
if (!['-d', '--distribution'].includes(args[0]) || args[1] !== discovered || !discovered) return null;
const target = ['--distribution', discovered];
for (let index = 2; index < args.length; index += 2) {
const option = args[index];
const value = args[index + 1];
if (option === '--cd' && value && !value.startsWith('-')) continue;
if (['-u', '--user'].includes(option) && /^[a-z_][a-z0-9_.-]*\$?$/i.test(value ?? '')
&& !target.includes('--user')) {
target.push('--user', value);
} else return null;
}
return target;
}
function createWslDirectoryReader(probe) {
let identity = '';
let revision = 0;
let pendingRead;
let generation = new AbortController();
let closed = false;
async function query(operation, target = '') {
const { signal } = generation;
if (closed) return unavailable;
try {
const result = await probe(operation, identity, target, signal);
if (signal.aborted) return unavailable;
if (result.error) return ['readFailed', 'accessDenied'].includes(result.error)
? { success: false, error: result.error } : unavailable;
if (!/^\d+:\d+$/.test(result.identity) || (identity && identity !== result.identity) || !isPath(result.cwd)) {
return unavailable;
}
identity = result.identity;
const home = isPath(result.home) ? result.home : null;
if (operation === 'list') return { success: true, files: result.files, home };
if (operation === 'realpath') return isPath(result.path) ? { success: true, path: result.path } : unavailable;
const cwd = result.cwd;
return { success: true, cwd, directoryState: { cwd, home, provider: 'FileSystem',
revision: ++revision, shellKind: 'wsl', pathFlavor: 'posix' } };
} catch {
return signal.aborted ? unavailable : { success: false, error: 'readFailed' };
}
}
function invalidate() {
generation.abort();
generation = new AbortController();
pendingRead = undefined;
}
return {
invalidate,
close() { closed = true; invalidate(); },
read() {
if (pendingRead) return pendingRead;
const result = query('cwd').finally(() => { if (pendingRead === result) pendingRead = undefined; });
pendingRead = result;
return result;
},
readPath(operation, target) {
if (!['list', 'realpath'].includes(operation) || !isPath(target)) return unavailable;
return query(operation, target);
},
};
}
function prepareWslDirectoryIntegration(shell, args, env, discovered) {
if (process.platform !== 'win32' || !discovered || shell.toLowerCase() !== discovered.command.toLowerCase()) return null;
const target = getWslDirectoryArgs(args, discovered.args?.[1]);
if (!target) return null;
let script;
try { script = fs.readFileSync(path.join(__dirname, 'shellIntegration', 'directory-wsl.py'), 'utf8'); }
catch { return null; }
const nonce = randomBytes(24).toString('hex');
const wslEnvKey = Object.keys(env).find(key => key.toUpperCase() === 'WSLENV') || 'WSLENV';
const forwarded = (env[wslEnvKey] || '').split(':').filter(entry => entry && entry.split('/')[0] !== marker);
const reader = createWslDirectoryReader(async (operation, identity, targetPath, signal) => {
// Encode the path as data. Only the fixed Python program is executable.
const encoded = Buffer.from(targetPath, 'utf8').toString('base64');
const { stdout } = await run(shell, [...target, '--cd', '/', '--exec', '/usr/bin/python3', '-I', '-c',
script, operation, nonce, identity, encoded], { encoding: 'utf8', windowsHide: true,
timeout: 2500, maxBuffer: 512 * 1024, signal, env });
return JSON.parse(stdout);
});
return { reader, env: { [wslEnvKey]: [...forwarded, `${marker}/u`].join(':'), [marker]: nonce }, cleanup: reader.close };
}
module.exports = { prepareWslDirectoryIntegration, createWslDirectoryReader, getWslDirectoryArgs };
@@ -0,0 +1,28 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const { createWslDirectoryReader, getWslDirectoryArgs } = require('./wslDirectoryIntegration.cjs');
test('directory helper keeps the named distro and user and accepts only interactive launch arguments', () => {
assert.deepEqual(getWslDirectoryArgs(['-d', 'Ubuntu', '--user', 'me', '--cd', '~'], 'Ubuntu'),
['--distribution', 'Ubuntu', '--user', 'me']);
assert.equal(getWslDirectoryArgs(['-d', 'Ubuntu'], 'Other'), null);
assert.equal(getWslDirectoryArgs(['-d', 'Ubuntu', '--exec', '/bin/bash'], 'Ubuntu'), null);
assert.equal(getWslDirectoryArgs(['--cd', '~'], 'Ubuntu'), null);
});
test('a result from before input or from a replacement WSL Bash cannot confirm cwd', async () => {
let finish;
const reader = createWslDirectoryReader(() => new Promise(resolve => { finish = resolve; }));
const old = reader.read();
reader.invalidate();
finish({ identity: '5:10', cwd: '/stale' });
assert.equal((await old).success, false);
const current = reader.read();
finish({ identity: '5:10', cwd: '/mnt/c' });
assert.equal((await current).cwd, '/mnt/c');
const replacement = reader.read();
finish({ identity: '5:99', cwd: '/different-session' });
assert.equal((await replacement).success, false);
});
+1 -1
View File
@@ -262,7 +262,7 @@ const TOOL_INPUT_FIELDS = Object.freeze({
"vault.group.list": {},
"vault.group.create": {
path: { type: "string", description: "New group path, for example prod/web." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
},
"vault.group.update": {
path: { type: "string", description: "Existing group path." },
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more