mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-29 13:50:35 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1eb4d33102 | ||
|
|
d04bf9ce72 | ||
|
|
bfe63719d8 | ||
|
|
08f22349c1 | ||
|
|
c846cd6fd8 | ||
|
|
2506b5d1bc | ||
|
|
a24be98a6b | ||
|
|
b08a1398e3 | ||
|
|
bc849a3aa2 | ||
|
|
2a48e30278 | ||
|
|
bf14ef9d8f | ||
|
|
0f1177a43b | ||
|
|
8c813a6fbd | ||
|
|
775bd12443 | ||
|
|
4e161b3a5b | ||
|
|
55906e1f46 | ||
|
|
8fd8983b4d | ||
|
|
a62c0f7f7f | ||
|
|
92db9371e6 | ||
|
|
0189ae996a | ||
|
|
61ca623a08 | ||
|
|
b4015f8719 | ||
|
|
880e11eff5 | ||
|
|
dc044961b5 | ||
|
|
873c8cfb52 | ||
|
|
cd0c24f3a4 | ||
|
|
93a3a37987 | ||
|
|
2df6aad44b | ||
|
|
5b669539c7 | ||
|
|
a4cacc4bc5 | ||
|
|
f491676ff9 |
No files matched your search
@@ -75,8 +75,6 @@
|
||||
!packages/**
|
||||
!patches/
|
||||
!patches/**
|
||||
!plugins/
|
||||
!plugins/**
|
||||
!public/
|
||||
!public/**
|
||||
!resources/
|
||||
|
||||
+37
-1
@@ -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,6 +38,8 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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">
|
||||
@@ -79,9 +81,31 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 プラグインシステム — Netcatty を安全に拡張
|
||||
|
||||
> **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 +118,7 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
- [はじめに](#はじめに)
|
||||
- [ビルドとパッケージ](#ビルドとパッケージ)
|
||||
- [技術スタック](#技術スタック)
|
||||
- [コミュニティ](#コミュニティ)
|
||||
- [コントリビューション](#コントリビューション)
|
||||
- [コントリビューター](#コントリビューター)
|
||||
- [Star 履歴](#star-履歴)
|
||||
@@ -326,6 +351,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>
|
||||
# コントリビューション
|
||||
|
||||
|
||||
@@ -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,6 +38,8 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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">
|
||||
@@ -79,11 +81,33 @@ 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
|
||||
|
||||
> **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 +120,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 +384,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
|
||||
|
||||
|
||||
+37
-1
@@ -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,6 +38,8 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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">
|
||||
@@ -79,9 +81,31 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 插件系统 — 安全扩展你的工作台
|
||||
|
||||
> **在不暴露 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 +118,7 @@
|
||||
- [快速开始](#快速开始)
|
||||
- [构建与打包](#构建与打包)
|
||||
- [技术栈](#技术栈)
|
||||
- [社区交流](#社区交流)
|
||||
- [参与贡献](#参与贡献)
|
||||
- [贡献者](#贡献者)
|
||||
- [Star 历史](#star-历史)
|
||||
@@ -326,6 +351,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>
|
||||
# 参与贡献
|
||||
|
||||
|
||||
+37
-1
@@ -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,6 +38,8 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
|
||||
<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">
|
||||
@@ -79,9 +81,31 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 外掛系統 —— 安全擴充你的工作台
|
||||
|
||||
> **在不暴露 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 +118,7 @@
|
||||
- [快速開始](#快速開始)
|
||||
- [建置與打包](#建置與打包)
|
||||
- [技術堆疊](#技術堆疊)
|
||||
- [社群交流](#社群交流)
|
||||
- [參與貢獻](#參與貢獻)
|
||||
- [貢獻者](#貢獻者)
|
||||
- [Star 紀錄](#star-紀錄)
|
||||
@@ -325,6 +350,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>
|
||||
# 參與貢獻
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -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.',
|
||||
|
||||
@@ -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 не выполняется, внешние изображения не загружаются. Текст автора плагина.",
|
||||
|
||||
@@ -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': 'Дождитесь пустой командной строки.',
|
||||
|
||||
@@ -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': '请等待终端回到空命令提示符。',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -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=""/);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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,897 @@ 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');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface forwards pointer gestures with capture/coalescing and wheel zoom without breaking scroll or widgets', 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', 'WheelEvent', 'PointerEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
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() {}
|
||||
},
|
||||
PointerEvent: dom.window.MouseEvent,
|
||||
});
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
|
||||
});
|
||||
|
||||
const capturedPointers: Array<{ target: Element; pointerId: number }> = [];
|
||||
const releasedPointers: Array<{ target: Element; pointerId: number }> = [];
|
||||
dom.window.HTMLElement.prototype.setPointerCapture = function (pointerId: number) {
|
||||
capturedPointers.push({ target: this, pointerId });
|
||||
};
|
||||
dom.window.HTMLElement.prototype.releasePointerCapture = function (pointerId: number) {
|
||||
releasedPointers.push({ target: this, pointerId });
|
||||
};
|
||||
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const makePointerEvent = (
|
||||
type: string,
|
||||
opts: { clientX: number; clientY: number; pointerId?: number; button?: number; buttons?: number; pointerType?: string; shiftKey?: boolean; composed?: boolean },
|
||||
) => {
|
||||
const evt = new dom.window.MouseEvent(type, {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: opts.composed ?? true,
|
||||
clientX: opts.clientX,
|
||||
clientY: opts.clientY,
|
||||
button: opts.button ?? 0,
|
||||
buttons: opts.buttons ?? 0,
|
||||
shiftKey: opts.shiftKey ?? false,
|
||||
});
|
||||
if (opts.pointerId !== undefined) Object.defineProperty(evt, 'pointerId', { value: opts.pointerId });
|
||||
if (opts.pointerType !== undefined) Object.defineProperty(evt, 'pointerType', { value: opts.pointerType });
|
||||
return evt;
|
||||
};
|
||||
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
|
||||
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const gridProps = {
|
||||
columns: [{ name: 'id', type: 'int4', primaryKey: true }],
|
||||
rows: [{ id: 1 }],
|
||||
editable: false,
|
||||
};
|
||||
const tree = {
|
||||
children: [
|
||||
{
|
||||
id: 'stage',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'graph-stage', style: 'overflow:hidden;touch-action:none' },
|
||||
children: [
|
||||
{
|
||||
id: 'node-1',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button', class: 'graph-node', style: 'touch-action:none' },
|
||||
children: [{ id: 'n1t', type: 3, data: 'Alpha' }],
|
||||
},
|
||||
{
|
||||
id: 'plain-btn',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button', class: 'plain-btn' },
|
||||
children: [{ id: 'pbt', type: 3, data: 'Click me' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'scroll-box',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'scroll-box', style: 'overflow-y:auto;height:120px' },
|
||||
children: [
|
||||
{ id: 'scroll-row', type: 1, element: 'div', attributes: { class: 'scroll-row' }, children: [{ id: 'srt', type: 3, data: 'Item' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'fit-box',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'fit-box', style: 'overflow-y:auto;height:120px' },
|
||||
children: [
|
||||
{ id: 'fit-row', type: 1, element: 'div', attributes: { class: 'fit-row' }, children: [{ id: 'frt', type: 3, data: 'Short' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'split',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-widget': 'split-pane',
|
||||
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 200, minSize: 100, maxSize: 400 }),
|
||||
},
|
||||
children: [
|
||||
{ id: 'pane-node', type: 1, element: 'div', attributes: { class: 'pane-node' }, children: [{ id: 'pn', type: 3, data: 'Pane' }] },
|
||||
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'grid',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const renderSurface = async (settled = true) => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginRemoteSurface
|
||||
tree={tree}
|
||||
css=""
|
||||
settled={settled}
|
||||
onEvent={(e) => {
|
||||
assert.equal(validateEvent(e), true, `Emitted event must satisfy contract schema: ${JSON.stringify(e)} -> ${JSON.stringify(validateEvent.errors)}`);
|
||||
events.push(e as unknown as Record<string, unknown>);
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await renderSurface(true);
|
||||
const mainShadow = shadows[0]!;
|
||||
const stage = mainShadow.querySelector('.graph-stage') as HTMLElement;
|
||||
const nodeBtn = mainShadow.querySelector('.graph-node') as HTMLElement;
|
||||
const plainBtn = mainShadow.querySelector('.plain-btn') as HTMLElement;
|
||||
const scrollBox = mainShadow.querySelector('.scroll-box') as HTMLElement;
|
||||
const scrollRow = mainShadow.querySelector('.scroll-row') as HTMLElement;
|
||||
const fitBox = mainShadow.querySelector('.fit-box') as HTMLElement;
|
||||
const fitRow = mainShadow.querySelector('.fit-row') as HTMLElement;
|
||||
const paneNode = mainShadow.querySelector('.pane-node') as HTMLElement;
|
||||
const splitHandle = mainShadow.querySelector('[data-split-handle]') as HTMLElement;
|
||||
|
||||
// 1. Hover pointermove before any pointerdown must NOT forward
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointermove', { clientX: 150, clientY: 90, pointerId: 3, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.length, 0, 'idle hover pointermove must not flood plugin IPC');
|
||||
|
||||
// 2. pointerdown -> move (including outside node/surface) -> coalesce -> flush before pointerup
|
||||
const downEvt = makePointerEvent('pointerdown', { clientX: 140, clientY: 90, pointerId: 7, button: 0, buttons: 1, pointerType: 'mouse' });
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(downEvt);
|
||||
});
|
||||
assert.equal(downEvt.defaultPrevented, false, 'pointerdown must not preventDefault so focus/click/text-selection remain intact');
|
||||
assert.deepEqual(capturedPointers, [{ target: nodeBtn, pointerId: 7 }], 'touch-action:none node engages host pointer capture');
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'node-1',
|
||||
type: 'pointerdown',
|
||||
x: 40,
|
||||
y: 40,
|
||||
pointerId: 7,
|
||||
button: 0,
|
||||
buttons: 1,
|
||||
pointerType: 'mouse',
|
||||
});
|
||||
|
||||
// Unchanged coordinate move is skipped; first changed move forwards immediately (leading edge)
|
||||
// and rapid subsequent moves outside the surface coalesce and flush right before pointerup.
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 140, clientY: 90, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 200, clientY: 130, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 215, clientY: 140, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 80, clientY: 20, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 80, clientY: 20, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' }));
|
||||
});
|
||||
assert.deepEqual(releasedPointers, [{ target: nodeBtn, pointerId: 7 }], 'pointer capture released on pointerup');
|
||||
assert.deepEqual(events.slice(1), [
|
||||
{ nodeId: 'node-1', type: 'pointermove', x: 100, y: 80, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse', shiftKey: true },
|
||||
{ nodeId: 'node-1', type: 'pointermove', x: -20, y: -30, pointerId: 7, button: -1, buttons: 1, pointerType: 'mouse' },
|
||||
{ nodeId: 'node-1', type: 'pointerup', x: -20, y: -30, pointerId: 7, button: 0, buttons: 0, pointerType: 'mouse' },
|
||||
]);
|
||||
|
||||
// Moves after pointerup are ignored
|
||||
const countAfterUp = events.length;
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 300, clientY: 300, pointerId: 7, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.length, countAfterUp);
|
||||
|
||||
// 3. Backpressure via settled={false} holds coalesced pointermove until settled flips true
|
||||
events.length = 0;
|
||||
await renderSurface(false);
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 150, clientY: 100, pointerId: 9, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 190, clientY: 120, pointerId: 9, button: -1, buttons: 1 }));
|
||||
});
|
||||
assert.deepEqual(events.map((e) => e.type), ['pointerdown'], 'unsettled move waits for acknowledgement');
|
||||
await renderSurface(true);
|
||||
assert.deepEqual(events.map((e) => ({ type: e.type, x: e.x, y: e.y })), [
|
||||
{ type: 'pointerdown', x: 50, y: 50 },
|
||||
{ type: 'pointermove', x: 90, y: 70 },
|
||||
], 'move flushes immediately once settled becomes true');
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointerEvent('pointercancel', { clientX: 95, clientY: 75, pointerId: 9, button: -1, buttons: 0 }));
|
||||
});
|
||||
assert.equal(events.at(-1)?.type, 'pointercancel');
|
||||
assert.equal(events.at(-1)?.nodeId, 'node-1');
|
||||
|
||||
// 4. Plain button does not engage setPointerCapture and still forwards normal click
|
||||
events.length = 0;
|
||||
const captureCountBeforePlain = capturedPointers.length;
|
||||
await act(async () => {
|
||||
plainBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 1 }));
|
||||
plainBtn.dispatchEvent(makePointerEvent('pointerup', { clientX: 120, clientY: 70, pointerId: 11, button: 0, buttons: 0 }));
|
||||
plainBtn.click();
|
||||
});
|
||||
assert.equal(capturedPointers.length, captureCountBeforePlain, 'plain button without touch-action:none skips setPointerCapture');
|
||||
assert.deepEqual(events.map((e) => e.type), ['pointerdown', 'pointerup', 'click']);
|
||||
|
||||
// 5. Wheel over non-scrollable remote node prevents default and forwards deltas; rapid ticks coalesce by summing deltas
|
||||
events.length = 0;
|
||||
const wheel1 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 260,
|
||||
clientY: 190,
|
||||
deltaX: 0,
|
||||
deltaY: -120,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
const wheel2 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 265,
|
||||
clientY: 195,
|
||||
deltaX: 4,
|
||||
deltaY: -60,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
const wheel3 = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 270,
|
||||
clientY: 200,
|
||||
deltaX: 6,
|
||||
deltaY: -40,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
await act(async () => {
|
||||
stage.dispatchEvent(wheel1);
|
||||
stage.dispatchEvent(wheel2);
|
||||
stage.dispatchEvent(wheel3);
|
||||
});
|
||||
assert.equal(wheel1.defaultPrevented, true, 'non-scrollable wheel must preventDefault');
|
||||
assert.equal(wheel2.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
|
||||
assert.equal(wheel3.defaultPrevented, true, 'coalesced wheel tick must also preventDefault');
|
||||
assert.deepEqual([...events], [
|
||||
{ nodeId: 'stage', type: 'wheel', x: 160, y: 140, deltaX: 0, deltaY: -120, deltaMode: 0, ctrlKey: true },
|
||||
]);
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
});
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'stage',
|
||||
type: 'wheel',
|
||||
x: 170,
|
||||
y: 150,
|
||||
deltaX: 10,
|
||||
deltaY: -100,
|
||||
deltaMode: 0,
|
||||
ctrlKey: true,
|
||||
});
|
||||
|
||||
// 6. Wheel over scrollable overflow container allows native scroll (no preventDefault, no wheel event)
|
||||
events.length = 0;
|
||||
Object.defineProperty(scrollBox, 'scrollHeight', { value: 600, configurable: true });
|
||||
Object.defineProperty(scrollBox, 'clientHeight', { value: 120, configurable: true });
|
||||
const scrollWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: 100,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
scrollRow.dispatchEvent(scrollWheel);
|
||||
});
|
||||
assert.equal(scrollWheel.defaultPrevented, false, 'scrollable overflow ancestor must keep native wheel scrolling');
|
||||
assert.equal(events.length, 0, 'wheel over scrollable overflow ancestor must not forward wheel');
|
||||
|
||||
// Non-overflowing overflow:auto container still forwards wheel
|
||||
Object.defineProperty(fitBox, 'scrollHeight', { value: 120, configurable: true });
|
||||
Object.defineProperty(fitBox, 'clientHeight', { value: 120, configurable: true });
|
||||
const fitWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: -80,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
fitRow.dispatchEvent(fitWheel);
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
});
|
||||
assert.equal(fitWheel.defaultPrevented, true, 'non-overflowing overflow:auto box forwards wheel');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].nodeId, 'fit-row');
|
||||
assert.equal(events[0].type, 'wheel');
|
||||
|
||||
// 7. touch-action:none canvas inside a scrollable surface host still claims wheel zoom
|
||||
events.length = 0;
|
||||
const hostDiv = mainShadow.host as HTMLElement;
|
||||
hostDiv.style.overflowY = 'auto';
|
||||
Object.defineProperty(hostDiv, 'scrollHeight', { value: 1400, configurable: true });
|
||||
Object.defineProperty(hostDiv, 'clientHeight', { value: 600, configurable: true });
|
||||
await act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 35));
|
||||
});
|
||||
const stageWheelInScrollableHost = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 220,
|
||||
clientY: 160,
|
||||
deltaX: 0,
|
||||
deltaY: -90,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(stageWheelInScrollableHost);
|
||||
});
|
||||
assert.equal(stageWheelInScrollableHost.defaultPrevented, true, 'touch-action:none graph node claims wheel even when outer host is scrollable');
|
||||
assert.equal(events.at(-1)?.type, 'wheel');
|
||||
assert.equal(events.at(-1)?.nodeId, 'node-1');
|
||||
|
||||
// 8. Slotted widget pointer & wheel events are never forwarded as generic plugin events
|
||||
events.length = 0;
|
||||
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement;
|
||||
const gridCell = gridHost.querySelector('[role="gridcell"]') as HTMLElement;
|
||||
const widgetWheel = new dom.window.WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
composed: true,
|
||||
clientX: 200,
|
||||
clientY: 150,
|
||||
deltaX: 0,
|
||||
deltaY: 120,
|
||||
deltaMode: 0,
|
||||
});
|
||||
await act(async () => {
|
||||
gridCell.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 150, pointerId: 21, button: 0, buttons: 1 }));
|
||||
gridCell.dispatchEvent(makePointerEvent('pointermove', { clientX: 240, clientY: 170, pointerId: 21, button: -1, buttons: 1 }));
|
||||
gridCell.dispatchEvent(makePointerEvent('pointerup', { clientX: 240, clientY: 170, pointerId: 21, button: 0, buttons: 0 }));
|
||||
gridCell.dispatchEvent(widgetWheel);
|
||||
});
|
||||
assert.equal(widgetWheel.defaultPrevented, false, 'slotted widget wheel must not be intercepted by surface');
|
||||
assert.equal(
|
||||
events.some((e) => ['pointerdown', 'pointermove', 'pointerup', 'wheel'].includes(String(e.type))),
|
||||
false,
|
||||
'slotted widget pointer and wheel events must not forward as generic surface events',
|
||||
);
|
||||
|
||||
// 9. SplitPane handle drag does not forward generic pointer events, while remote nodes inside its panes do
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
splitHandle.dispatchEvent(makePointerEvent('pointerdown', { clientX: 200, clientY: 100, pointerId: 31, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointermove', { clientX: 250, clientY: 100, pointerId: 31, button: -1, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 250, clientY: 100, pointerId: 31, button: 0, buttons: 0 }));
|
||||
});
|
||||
assert.equal(
|
||||
events.some((e) => ['pointerdown', 'pointermove', 'pointerup'].includes(String(e.type))),
|
||||
false,
|
||||
'split-pane handle must not forward generic pointer events',
|
||||
);
|
||||
assert.ok(events.some((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'), 'split-pane resize still works');
|
||||
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
paneNode.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 1 }));
|
||||
dom.window.dispatchEvent(makePointerEvent('pointerup', { clientX: 160, clientY: 110, pointerId: 32, button: 0, buttons: 0 }));
|
||||
});
|
||||
assert.deepEqual(events.map((e) => ({ nodeId: e.nodeId, type: e.type, x: e.x, y: e.y })), [
|
||||
{ nodeId: 'pane-node', type: 'pointerdown', x: 60, y: 60 },
|
||||
{ nodeId: 'pane-node', type: 'pointerup', x: 60, y: 60 },
|
||||
]);
|
||||
|
||||
// 10. Unmounting the surface mid-drag emits pointercancel so a retained plugin session does not stay in a drag.
|
||||
events.length = 0;
|
||||
await act(async () => {
|
||||
nodeBtn.dispatchEvent(makePointerEvent('pointerdown', { clientX: 160, clientY: 110, pointerId: 41, button: 0, buttons: 1, pointerType: 'mouse' }));
|
||||
});
|
||||
assert.equal(events[0]?.type, 'pointerdown');
|
||||
assert.equal(events[0]?.pointerId, 41);
|
||||
await act(async () => { root.unmount(); });
|
||||
assert.deepEqual(events.at(-1), {
|
||||
nodeId: 'node-1',
|
||||
type: 'pointercancel',
|
||||
x: 60,
|
||||
y: 60,
|
||||
pointerId: 41,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
} 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');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface leaves wheel to a scrollable host-owned popover panel', async () => {
|
||||
const { JSDOM } = await import('jsdom');
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
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', 'WheelEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
Object.assign(dom.window, {
|
||||
ResizeObserver: class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
});
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
|
||||
});
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const root = createRoot(dom.window.document.getElementById('root')!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<PluginRemoteSurface
|
||||
tree={{
|
||||
children: [
|
||||
{
|
||||
id: 'menu',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-popover': 'true',
|
||||
'data-plugin-anchor-x': '40',
|
||||
'data-plugin-anchor-y': '20',
|
||||
'data-plugin-popover-width': '240',
|
||||
'data-plugin-popover-max-height': '160',
|
||||
open: '',
|
||||
},
|
||||
children: [
|
||||
{
|
||||
id: 'row',
|
||||
type: 1,
|
||||
element: 'button',
|
||||
attributes: { type: 'button' },
|
||||
children: [{ id: 'row-t', type: 3, data: 'A tall menu item' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}}
|
||||
css=""
|
||||
settled={true}
|
||||
onEvent={(e) => { events.push(e as unknown as Record<string, unknown>); }}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const popover = dom.window.document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
|
||||
assert.ok(popover, 'host-owned popover panel is present');
|
||||
popover!.style.overflow = 'auto';
|
||||
Object.defineProperty(popover!, 'scrollHeight', { configurable: true, value: 400 });
|
||||
Object.defineProperty(popover!, 'clientHeight', { configurable: true, value: 160 });
|
||||
|
||||
const popoverShadow = shadows.find((s) => popover!.contains((s as ShadowRoot).host)) ?? shadows.at(-1);
|
||||
const row = popoverShadow!.querySelector('button') as HTMLElement;
|
||||
assert.ok(row, 'popover row is present');
|
||||
const wheel = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaX: 0, deltaY: 80, deltaMode: 0, clientX: 120, clientY: 80 });
|
||||
await act(async () => { row.dispatchEvent(wheel); });
|
||||
assert.equal(wheel.defaultPrevented, false, 'scrollable popover panel must keep native wheel scrolling');
|
||||
assert.equal(events.some((e) => e.type === 'wheel'), false, 'wheel over a scrollable popover panel must not be forwarded');
|
||||
} 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');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface + hostDom end-to-end round-trip supports node drag, incident edge tracking, background pan, and wheel zoom', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="host-root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent', 'WheelEvent', 'PointerEvent', 'CustomEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
Object.assign(dom.window, { PointerEvent: dom.window.MouseEvent });
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 40, y: 20, width: 600, height: 400, top: 20, left: 40, right: 640, bottom: 420, toJSON() {},
|
||||
});
|
||||
|
||||
// In Electron the visible host renderer and hidden plugin runtime run in separate
|
||||
// BrowserWindows. Guard host window capture listeners while forwarding into hostDom
|
||||
// so plugin-side synthetic dispatches do not loop back into the host in a shared JSDOM.
|
||||
let forwardingToPlugin = false;
|
||||
const origAdd = dom.window.addEventListener.bind(dom.window);
|
||||
const origRemove = dom.window.removeEventListener.bind(dom.window);
|
||||
const wrappedListeners = new WeakMap<EventListenerOrEventListenerObject, EventListener>();
|
||||
dom.window.addEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => {
|
||||
const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
|
||||
if (type === 'pointermove' || type === 'pointerup' || type === 'pointercancel') {
|
||||
const wrapped: EventListener = (evt) => {
|
||||
if (capture ? forwardingToPlugin : !forwardingToPlugin) return;
|
||||
if (typeof listener === 'function') listener(evt);
|
||||
else listener.handleEvent(evt);
|
||||
};
|
||||
wrappedListeners.set(listener, wrapped);
|
||||
return origAdd(type, wrapped, options);
|
||||
}
|
||||
return origAdd(type, listener, options);
|
||||
}) as typeof dom.window.addEventListener;
|
||||
dom.window.removeEventListener = ((type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions) => {
|
||||
return origRemove(type, wrappedListeners.get(listener) ?? listener, options);
|
||||
}) as typeof dom.window.removeEventListener;
|
||||
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const { act, useEffect, useRef, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
const { createPluginRemoteTree } = await import('../../application/state/pluginRemoteTree');
|
||||
const { registerHostReactView } = await import('../../packages/plugin-sdk/src/hostReact');
|
||||
const { createDefinitionValidator } = await import('../../electron/plugins/contractValidator.cjs');
|
||||
const validateEvent = createDefinitionValidator('HostDrawnViewEvent');
|
||||
|
||||
const remoteTree = createPluginRemoteTree();
|
||||
const hostRoot = createRoot(document.getElementById('host-root')!);
|
||||
let pluginReceive: (message: unknown) => void = () => {};
|
||||
let latestEventId = 0;
|
||||
let latestAck = 0;
|
||||
|
||||
const renderHostSurface = () => {
|
||||
hostRoot.render(
|
||||
<PluginRemoteSurface
|
||||
tree={remoteTree.snapshot()}
|
||||
css=""
|
||||
settled={latestAck >= latestEventId}
|
||||
onEvent={(event) => {
|
||||
const stamped = { ...event, eventId: ++latestEventId };
|
||||
assert.equal(validateEvent(stamped), true, `Host event failed contract schema: ${JSON.stringify(validateEvent.errors)}`);
|
||||
forwardingToPlugin = true;
|
||||
try {
|
||||
pluginReceive({ kind: 'host-ui.event', instanceId: 'e2e-1', event: stamped });
|
||||
} finally {
|
||||
forwardingToPlugin = false;
|
||||
}
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
};
|
||||
|
||||
const views = {
|
||||
onDidReceiveMessage(_id: string, listener: (value: unknown) => void) {
|
||||
pluginReceive = listener;
|
||||
return { dispose() {} };
|
||||
},
|
||||
postMessage(_id: string, value: unknown) {
|
||||
const msg = value as { kind?: string; mutations?: unknown[]; acknowledgedEvent?: number };
|
||||
if (msg.kind !== 'host-ui.update') return;
|
||||
if (Array.isArray(msg.mutations) && msg.mutations.length > 0) {
|
||||
remoteTree.apply(msg.mutations);
|
||||
}
|
||||
if (typeof msg.acknowledgedEvent === 'number') {
|
||||
latestAck = msg.acknowledgedEvent;
|
||||
}
|
||||
renderHostSurface();
|
||||
},
|
||||
getState: async () => undefined,
|
||||
setState: async () => {},
|
||||
setBadge: async () => {},
|
||||
};
|
||||
|
||||
function MiniGraphCanvas() {
|
||||
const stageRef = useRef<HTMLDivElement | null>(null);
|
||||
const [nodePos, setNodePos] = useState({ x: 80, y: 100 });
|
||||
const fixedPos = { x: 280, y: 100 };
|
||||
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const dragRef = useRef<{ kind: 'node' | 'pan'; pointerId: number; startX: number; startY: number; originX: number; originY: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const el = stageRef.current;
|
||||
if (!el) return;
|
||||
const onWheel = (event: WheelEvent) => {
|
||||
event.preventDefault();
|
||||
setViewport((prev) => ({
|
||||
...prev,
|
||||
zoom: Math.round(prev.zoom * (event.deltaY < 0 ? 1.2 : 0.8) * 100) / 100,
|
||||
}));
|
||||
};
|
||||
el.addEventListener('wheel', onWheel, { passive: false });
|
||||
return () => el.removeEventListener('wheel', onWheel);
|
||||
}, []);
|
||||
|
||||
// Mirror real canvas window-level drag listeners inside the plugin runtime.
|
||||
useEffect(() => {
|
||||
if (!dragging) return;
|
||||
const onMove = (event: PointerEvent) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || drag.pointerId !== event.pointerId) return;
|
||||
if (drag.kind === 'node') {
|
||||
setNodePos({ x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) });
|
||||
} else {
|
||||
setViewport((prev) => ({ ...prev, x: drag.originX + (event.clientX - drag.startX), y: drag.originY + (event.clientY - drag.startY) }));
|
||||
}
|
||||
};
|
||||
const onUp = (event: PointerEvent) => {
|
||||
if (dragRef.current?.pointerId === event.pointerId) {
|
||||
dragRef.current = null;
|
||||
setDragging(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener('pointermove', onMove as unknown as EventListener);
|
||||
window.addEventListener('pointerup', onUp as unknown as EventListener);
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', onMove as unknown as EventListener);
|
||||
window.removeEventListener('pointerup', onUp as unknown as EventListener);
|
||||
};
|
||||
}, [dragging]);
|
||||
|
||||
const edgeLen = Math.round(Math.hypot(fixedPos.x - nodePos.x, fixedPos.y - nodePos.y));
|
||||
|
||||
return (
|
||||
<div
|
||||
className="e2e-stage"
|
||||
ref={stageRef}
|
||||
style={{ overflow: 'hidden', touchAction: 'none' }}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
dragRef.current = { kind: 'pan', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: viewport.x, originY: viewport.y };
|
||||
setDragging(true);
|
||||
}}
|
||||
>
|
||||
<div className="e2e-world" style={{ transform: `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})` }}>
|
||||
<div className="e2e-edge" style={{ width: `${edgeLen}px`, transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }} />
|
||||
<button
|
||||
type="button"
|
||||
className="e2e-node"
|
||||
style={{ touchAction: 'none', transform: `translate(${nodePos.x}px, ${nodePos.y}px)` }}
|
||||
onPointerDown={(e) => {
|
||||
if (e.button !== 0) return;
|
||||
e.stopPropagation();
|
||||
dragRef.current = { kind: 'node', pointerId: e.pointerId, startX: e.clientX, startY: e.clientY, originX: nodePos.x, originY: nodePos.y };
|
||||
setDragging(true);
|
||||
}}
|
||||
>
|
||||
N1
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const makePointer = (type: string, clientX: number, clientY: number, pointerId: number, button: number, buttons: number) => {
|
||||
const evt = new dom.window.MouseEvent(type, { bubbles: true, cancelable: true, composed: true, clientX, clientY, button, buttons });
|
||||
Object.defineProperty(evt, 'pointerId', { value: pointerId });
|
||||
return evt;
|
||||
};
|
||||
|
||||
const registration = registerHostReactView(views as never, 'com.example.e2e-graph', () => <MiniGraphCanvas />);
|
||||
try {
|
||||
await act(async () => {
|
||||
pluginReceive({ kind: 'host-ui.open', instanceId: 'e2e-1' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
|
||||
const shadow = shadows[0]!;
|
||||
const stageEl = shadow.querySelector('.e2e-stage') as HTMLElement;
|
||||
const worldEl = shadow.querySelector('.e2e-world') as HTMLElement;
|
||||
const edgeEl = shadow.querySelector('.e2e-edge') as HTMLElement;
|
||||
const nodeEl = shadow.querySelector('.e2e-node') as HTMLElement;
|
||||
assert.equal(nodeEl.style.transform, 'translate(80px, 100px)');
|
||||
assert.equal(edgeEl.style.width, '200px');
|
||||
|
||||
// Drag node across the visible host surface (pointermove/up dispatched on host window outside the node)
|
||||
await act(async () => {
|
||||
nodeEl.dispatchEvent(makePointer('pointerdown', 120, 120, 1, 0, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointermove', 170, 160, 1, -1, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointerup', 170, 160, 1, 0, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
|
||||
assert.equal(nodeEl.style.transform, 'translate(130px, 140px)', 'visible host shadow DOM node must move by (+50, +40)');
|
||||
assert.equal(edgeEl.style.width, `${Math.round(Math.hypot(280 - 130, 100 - 140))}px`, 'visible host incident edge must follow node');
|
||||
|
||||
// Pan background stage and wheel-zoom
|
||||
await act(async () => {
|
||||
stageEl.dispatchEvent(makePointer('pointerdown', 300, 200, 2, 0, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointermove', 340, 230, 2, -1, 1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
});
|
||||
await act(async () => {
|
||||
dom.window.dispatchEvent(makePointer('pointerup', 340, 230, 2, 0, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
const wheelEvt = new dom.window.WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 250, clientY: 180, deltaX: 0, deltaY: -120, deltaMode: 0 });
|
||||
await act(async () => {
|
||||
stageEl.dispatchEvent(wheelEvt);
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
|
||||
assert.equal(wheelEvt.defaultPrevented, true);
|
||||
assert.equal(worldEl.style.transform, 'translate(40px, 30px) scale(1.2)', 'visible host shadow DOM world must pan and wheel-zoom');
|
||||
|
||||
await act(async () => {
|
||||
pluginReceive({ kind: 'host-ui.close', instanceId: 'e2e-1' });
|
||||
});
|
||||
} finally {
|
||||
await act(async () => {
|
||||
registration.dispose();
|
||||
hostRoot.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');
|
||||
}
|
||||
});
|
||||
@@ -19,8 +19,13 @@ export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnVi
|
||||
|
||||
const MAX_EVENT_VALUE_LENGTH = 131072;
|
||||
const SCROLL_THROTTLE_MS = 60;
|
||||
const POINTER_MOVE_THROTTLE_MS = 24;
|
||||
const POINTER_MOVE_BACKPRESSURE_MAX_MS = 96;
|
||||
const WHEEL_THROTTLE_MS = 24;
|
||||
const SURFACE_EVENTS = [
|
||||
'click', 'dblclick', 'contextmenu',
|
||||
'pointerdown', 'pointermove', 'pointerup', 'pointercancel',
|
||||
'wheel',
|
||||
'input', 'change',
|
||||
'keydown', 'keyup',
|
||||
'focusin', 'focusout',
|
||||
@@ -337,6 +342,163 @@ function readSelectionRange(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readSurfacePoint(
|
||||
event: MouseEvent,
|
||||
surfaceEl: HTMLElement | null,
|
||||
): { x: number; y: number } {
|
||||
const rect = surfaceEl?.getBoundingClientRect();
|
||||
const rawX = rect ? event.clientX - rect.left : event.clientX;
|
||||
const rawY = rect ? event.clientY - rect.top : event.clientY;
|
||||
return {
|
||||
x: Number.isFinite(rawX) ? Math.round(rawX) : 0,
|
||||
y: Number.isFinite(rawY) ? Math.round(rawY) : 0,
|
||||
};
|
||||
}
|
||||
|
||||
function readModifierKeys(event: MouseEvent | WheelEvent): {
|
||||
ctrlKey?: true;
|
||||
metaKey?: true;
|
||||
altKey?: true;
|
||||
shiftKey?: true;
|
||||
} {
|
||||
return {
|
||||
...(event.ctrlKey ? { ctrlKey: true as const } : {}),
|
||||
...(event.metaKey ? { metaKey: true as const } : {}),
|
||||
...(event.altKey ? { altKey: true as const } : {}),
|
||||
...(event.shiftKey ? { shiftKey: true as const } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPointerId(event: Event): number {
|
||||
const raw = (event as PointerEvent).pointerId;
|
||||
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
||||
return Math.max(-2147483648, Math.min(2147483647, Math.trunc(raw)));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function readPointerType(event: Event): 'mouse' | 'pen' | 'touch' | undefined {
|
||||
const raw = (event as PointerEvent).pointerType;
|
||||
return raw === 'mouse' || raw === 'pen' || raw === 'touch' ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPointerButton(event: MouseEvent): number {
|
||||
return typeof event.button === 'number' && Number.isFinite(event.button)
|
||||
? Math.max(-1, Math.min(32, Math.trunc(event.button)))
|
||||
: 0;
|
||||
}
|
||||
|
||||
function readPointerButtons(event: MouseEvent): number {
|
||||
return typeof event.buttons === 'number' && Number.isFinite(event.buttons)
|
||||
? Math.max(0, Math.min(65535, Math.trunc(event.buttons)))
|
||||
: 0;
|
||||
}
|
||||
|
||||
function roundWheelDelta(value: number): number {
|
||||
return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
|
||||
}
|
||||
|
||||
function isScrollableOverflowValue(value: string | undefined): boolean {
|
||||
return value === 'auto' || value === 'scroll' || value === 'overlay';
|
||||
}
|
||||
|
||||
function readOverflowToken(value: string | undefined, axis: 'x' | 'y'): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const parts = value.trim().split(/\s+/);
|
||||
return axis === 'y' ? (parts[1] ?? parts[0]) : parts[0];
|
||||
}
|
||||
|
||||
function readAxisOverflow(
|
||||
el: HTMLElement,
|
||||
style: CSSStyleDeclaration | undefined,
|
||||
axis: 'x' | 'y',
|
||||
): string | undefined {
|
||||
// Prefer a scrollable value from computed or inline styles. Some test DOMs
|
||||
// report the initial `visible` computed overflow even when the element has
|
||||
// an inline `overflow: auto` shorthand.
|
||||
const candidates = [
|
||||
axis === 'y' ? style?.overflowY : style?.overflowX,
|
||||
axis === 'y' ? el.style.overflowY : el.style.overflowX,
|
||||
readOverflowToken(style?.overflow, axis),
|
||||
readOverflowToken(el.style.overflow, axis),
|
||||
];
|
||||
for (const value of candidates) {
|
||||
if (isScrollableOverflowValue(value)) return value;
|
||||
}
|
||||
return candidates.find((value) => value && value !== 'visible') ?? candidates[0];
|
||||
}
|
||||
|
||||
function canElementScrollForWheel(
|
||||
el: HTMLElement,
|
||||
view: Window & typeof globalThis,
|
||||
deltaX: number,
|
||||
deltaY: number,
|
||||
): boolean {
|
||||
const style = view.getComputedStyle?.(el);
|
||||
const canScrollY = deltaY !== 0
|
||||
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'y'))
|
||||
&& el.scrollHeight > el.clientHeight + 1;
|
||||
const canScrollX = deltaX !== 0
|
||||
&& isScrollableOverflowValue(readAxisOverflow(el, style, 'x'))
|
||||
&& el.scrollWidth > el.clientWidth + 1;
|
||||
return canScrollY || canScrollX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheel vs native scroll rule:
|
||||
* Walk ancestors inside the shadow root (and then the surface's own scroll host
|
||||
* unless a non-scrollable element declares `touch-action: none` to claim canvas
|
||||
* gestures). If an ancestor has `overflow: auto|scroll|overlay` with actual
|
||||
* overflow along the wheel axis, leave the event to native scrolling (existing
|
||||
* throttled `scroll` events still forward). Otherwise `preventDefault()` so the
|
||||
* surrounding workbench does not steal the gesture, and forward coalesced `wheel`.
|
||||
*/
|
||||
function hasScrollableAncestorForWheel(
|
||||
target: HTMLElement,
|
||||
shadow: ShadowRoot,
|
||||
host: HTMLElement | null,
|
||||
view: Window & typeof globalThis,
|
||||
deltaX: number,
|
||||
deltaY: number,
|
||||
): boolean {
|
||||
let current: HTMLElement | null = target;
|
||||
let hitGestureBoundary = false;
|
||||
while (current) {
|
||||
if (canElementScrollForWheel(current, view, deltaX, deltaY)) return true;
|
||||
const touchAction = view.getComputedStyle?.(current)?.touchAction || current.style.touchAction;
|
||||
if (touchAction === 'none') {
|
||||
hitGestureBoundary = true;
|
||||
break;
|
||||
}
|
||||
const parent = current.parentElement;
|
||||
if (!parent || parent.getRootNode() !== shadow) break;
|
||||
current = parent;
|
||||
}
|
||||
if (!hitGestureBoundary && host && canElementScrollForWheel(host, view, deltaX, deltaY)) {
|
||||
return true;
|
||||
}
|
||||
// Nested popover surfaces live in a portaled PluginViewPopover panel. That
|
||||
// panel (not the inner overflow-auto host) is often the only element with a
|
||||
// bounded max-height, so include it when deciding who owns the wheel.
|
||||
if (!hitGestureBoundary) {
|
||||
const popover = (host ?? target).closest?.('[data-plugin-view-popover]') as HTMLElement | null;
|
||||
if (popover && canElementScrollForWheel(popover, view, deltaX, deltaY)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
type ActivePointerGesture = {
|
||||
nodeId: string;
|
||||
pointerId: number;
|
||||
capturedElement: HTMLElement | null;
|
||||
lastSentX: number;
|
||||
lastSentY: number;
|
||||
lastMoveSentAt: number;
|
||||
pendingMove: PluginSurfaceEvent | null;
|
||||
pendingMoveSince: number;
|
||||
moveTimer: ReturnType<typeof setTimeout> | null;
|
||||
};
|
||||
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const checkedTree = useMemo(() => {
|
||||
@@ -373,6 +535,8 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
const surfaceRef = useRef<HTMLDivElement>(null);
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
|
||||
const settledRef = useRef(settled); settledRef.current = settled;
|
||||
const flushPendingMovesRef = useRef<(() => void) | null>(null);
|
||||
const shadowRef = useRef<ShadowRoot | null>(null);
|
||||
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
|
||||
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
|
||||
@@ -387,6 +551,10 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
setShadowHost(host);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (settled) flushPendingMovesRef.current?.();
|
||||
}, [settled]);
|
||||
|
||||
const surfaceContextValue = useMemo(
|
||||
() => ({ css, onEvent, depth, shadowHost }),
|
||||
[css, onEvent, depth, shadowHost],
|
||||
@@ -394,8 +562,15 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
|
||||
useEffect(() => {
|
||||
if (!shadow) return;
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const pendingScroll = new Map<string, PluginSurfaceEvent>();
|
||||
const activeGestures = new Map<number, ActivePointerGesture>();
|
||||
const handledPointerEvents = new WeakSet<Event>();
|
||||
let windowPointerListenersAttached = false;
|
||||
let wheelTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pendingWheel: PluginSurfaceEvent | null = null;
|
||||
let lastWheelSentAt = 0;
|
||||
|
||||
const flushScroll = (nodeId: string) => {
|
||||
scrollTimers.delete(nodeId);
|
||||
@@ -406,10 +581,203 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
}
|
||||
};
|
||||
|
||||
const flushWheel = () => {
|
||||
if (wheelTimer !== null) {
|
||||
clearTimeout(wheelTimer);
|
||||
wheelTimer = null;
|
||||
}
|
||||
const evt = pendingWheel;
|
||||
pendingWheel = null;
|
||||
if (!evt || ((evt.deltaX ?? 0) === 0 && (evt.deltaY ?? 0) === 0)) return;
|
||||
lastWheelSentAt = Date.now();
|
||||
onEventRef.current(evt);
|
||||
};
|
||||
|
||||
const emitGestureMove = (gesture: ActivePointerGesture, moveEvent: PluginSurfaceEvent, now: number) => {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
gesture.pendingMove = null;
|
||||
gesture.pendingMoveSince = 0;
|
||||
if (moveEvent.x === gesture.lastSentX && moveEvent.y === gesture.lastSentY) return;
|
||||
gesture.lastSentX = moveEvent.x ?? gesture.lastSentX;
|
||||
gesture.lastSentY = moveEvent.y ?? gesture.lastSentY;
|
||||
gesture.lastMoveSentAt = now;
|
||||
onEventRef.current(moveEvent);
|
||||
};
|
||||
|
||||
const scheduleGestureMoveFlush = (gesture: ActivePointerGesture) => {
|
||||
if (gesture.moveTimer !== null || !gesture.pendingMove) return;
|
||||
const now = Date.now();
|
||||
const throttleWait = Math.max(0, POINTER_MOVE_THROTTLE_MS - (now - gesture.lastMoveSentAt));
|
||||
const backpressureWait = settledRef.current
|
||||
? 0
|
||||
: Math.max(0, POINTER_MOVE_BACKPRESSURE_MAX_MS - (now - gesture.pendingMoveSince));
|
||||
const delay = Math.max(1, throttleWait, backpressureWait);
|
||||
gesture.moveTimer = setTimeout(() => {
|
||||
gesture.moveTimer = null;
|
||||
if (activeGestures.get(gesture.pointerId) !== gesture || !gesture.pendingMove) return;
|
||||
const tickNow = Date.now();
|
||||
const elapsed = tickNow - gesture.lastMoveSentAt;
|
||||
const waitedEnough = settledRef.current || tickNow - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS;
|
||||
if (elapsed >= POINTER_MOVE_THROTTLE_MS && waitedEnough) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, tickNow);
|
||||
} else {
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const releaseGesture = (gesture: ActivePointerGesture) => {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
gesture.pendingMove = null;
|
||||
gesture.pendingMoveSince = 0;
|
||||
if (gesture.capturedElement) {
|
||||
try {
|
||||
gesture.capturedElement.releasePointerCapture?.(gesture.pointerId);
|
||||
} catch {
|
||||
// Capture may already have been released natively.
|
||||
}
|
||||
gesture.capturedElement = null;
|
||||
}
|
||||
activeGestures.delete(gesture.pointerId);
|
||||
if (activeGestures.size === 0) detachWindowPointerListeners();
|
||||
};
|
||||
|
||||
/**
|
||||
* Active pointer gestures are tracked at the host surface so plugin drags
|
||||
* continue after leaving the originating node or surface (plugin-side
|
||||
* setPointerCapture cannot capture the visible host pointer). Moves skip
|
||||
* unchanged coordinates, coalesce under POINTER_MOVE_THROTTLE_MS, and adapt
|
||||
* to host-ui acknowledgedEvent backpressure via `settled`.
|
||||
*/
|
||||
const onGesturePointerEvent = (event: Event) => {
|
||||
if (!view || activeGestures.size === 0 || handledPointerEvents.has(event)) return;
|
||||
const pointerId = readPointerId(event);
|
||||
const gesture = activeGestures.get(pointerId);
|
||||
if (!gesture) return;
|
||||
handledPointerEvents.add(event);
|
||||
|
||||
const isMouseLike = event instanceof view.MouseEvent;
|
||||
const coords = isMouseLike
|
||||
? readSurfacePoint(event, surfaceRef.current ?? hostRef.current)
|
||||
: { x: gesture.lastSentX, y: gesture.lastSentY };
|
||||
const pointerType = readPointerType(event);
|
||||
const button = isMouseLike ? readPointerButton(event) : -1;
|
||||
const buttons = isMouseLike ? readPointerButtons(event) : 0;
|
||||
const modifiers = isMouseLike ? readModifierKeys(event) : {};
|
||||
|
||||
if (event.type === 'pointermove') {
|
||||
const moveEvent: PluginSurfaceEvent = {
|
||||
nodeId: gesture.nodeId,
|
||||
type: 'pointermove',
|
||||
...coords,
|
||||
pointerId: gesture.pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
};
|
||||
if (gesture.pendingMove === null && coords.x === gesture.lastSentX && coords.y === gesture.lastSentY) {
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
const elapsed = now - gesture.lastMoveSentAt;
|
||||
const canSendNow =
|
||||
elapsed >= POINTER_MOVE_THROTTLE_MS
|
||||
&& (settledRef.current || (gesture.pendingMoveSince > 0 && now - gesture.pendingMoveSince >= POINTER_MOVE_BACKPRESSURE_MAX_MS));
|
||||
if (canSendNow) {
|
||||
emitGestureMove(gesture, moveEvent, now);
|
||||
} else {
|
||||
gesture.pendingMove = moveEvent;
|
||||
if (gesture.pendingMoveSince === 0) gesture.pendingMoveSince = now;
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'pointerup' && gesture.pendingMove) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, Date.now());
|
||||
}
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId: gesture.nodeId,
|
||||
type: event.type as 'pointerup' | 'pointercancel',
|
||||
...coords,
|
||||
pointerId: gesture.pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
});
|
||||
};
|
||||
|
||||
const onWindowBlur = (event: Event) => {
|
||||
if (!view || event.target !== view || activeGestures.size === 0) return;
|
||||
for (const gesture of [...activeGestures.values()]) {
|
||||
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointercancel',
|
||||
x: lastSentX,
|
||||
y: lastSentY,
|
||||
pointerId,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const attachWindowPointerListeners = () => {
|
||||
if (!view || windowPointerListenersAttached) return;
|
||||
windowPointerListenersAttached = true;
|
||||
view.addEventListener('pointermove', onGesturePointerEvent, true);
|
||||
view.addEventListener('pointerup', onGesturePointerEvent, true);
|
||||
view.addEventListener('pointercancel', onGesturePointerEvent, true);
|
||||
view.addEventListener('blur', onWindowBlur, false);
|
||||
};
|
||||
|
||||
const detachWindowPointerListeners = () => {
|
||||
if (!view || !windowPointerListenersAttached) return;
|
||||
windowPointerListenersAttached = false;
|
||||
view.removeEventListener('pointermove', onGesturePointerEvent, true);
|
||||
view.removeEventListener('pointerup', onGesturePointerEvent, true);
|
||||
view.removeEventListener('pointercancel', onGesturePointerEvent, true);
|
||||
view.removeEventListener('blur', onWindowBlur, false);
|
||||
};
|
||||
|
||||
flushPendingMovesRef.current = () => {
|
||||
const now = Date.now();
|
||||
for (const gesture of activeGestures.values()) {
|
||||
if (!gesture.pendingMove) continue;
|
||||
const elapsed = now - gesture.lastMoveSentAt;
|
||||
if (elapsed >= POINTER_MOVE_THROTTLE_MS) {
|
||||
emitGestureMove(gesture, gesture.pendingMove, now);
|
||||
} else {
|
||||
if (gesture.moveTimer !== null) {
|
||||
clearTimeout(gesture.moveTimer);
|
||||
gesture.moveTimer = null;
|
||||
}
|
||||
scheduleGestureMoveFlush(gesture);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const listener = (event: Event) => {
|
||||
if (!view || !SURFACE_EVENT_SET.has(event.type)) return;
|
||||
|
||||
if (event.type === 'pointermove' || event.type === 'pointerup' || event.type === 'pointercancel') {
|
||||
onGesturePointerEvent(event);
|
||||
return;
|
||||
}
|
||||
|
||||
const target = event.target;
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
|
||||
if (!(target instanceof view.HTMLElement)) return;
|
||||
|
||||
// Closed-shadow events hide their editable target from window capture.
|
||||
if (event.type === 'focusin') {
|
||||
@@ -420,8 +788,12 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
}
|
||||
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
|
||||
|
||||
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
|
||||
if (target.closest('[data-plugin-widget-host]')) return;
|
||||
// Internal events inside slotted host-rendered widgets or split-pane dividers are handled by the widget itself.
|
||||
if (
|
||||
target.closest('[data-plugin-widget-host]')
|
||||
|| target.closest('[data-split-handle]')
|
||||
|| SLOTTED_WIDGET_KINDS.has(target.dataset.pluginWidget ?? '')
|
||||
) return;
|
||||
|
||||
if (event.type === 'submit') event.preventDefault();
|
||||
if (event.type === 'contextmenu') event.preventDefault();
|
||||
@@ -436,6 +808,120 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
?? (event.type === 'keydown' ? (shadow.querySelector('[data-netcatty-remote-node]') as HTMLElement | null)?.dataset.netcattyRemoteNode : undefined);
|
||||
if (!nodeId) return;
|
||||
|
||||
if (event.type === 'pointerdown') {
|
||||
if (!(event instanceof view.MouseEvent)) return;
|
||||
const pointerId = readPointerId(event);
|
||||
const existing = activeGestures.get(pointerId);
|
||||
if (existing) releaseGesture(existing);
|
||||
|
||||
const coords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
|
||||
const pointerType = readPointerType(event);
|
||||
const button = readPointerButton(event);
|
||||
const buttons = readPointerButtons(event);
|
||||
const modifiers = readModifierKeys(event);
|
||||
|
||||
// Engage native pointer capture only on non-control elements that explicitly
|
||||
// declare `touch-action: none` so text selection, native form controls, and
|
||||
// normal button click cancellation stay intact. Window capture listeners still
|
||||
// sustain cross-node/cross-surface drags for every remote node.
|
||||
let capturedElement: HTMLElement | null = null;
|
||||
if (!target.matches('input, textarea, select, option')) {
|
||||
const touchAction = view.getComputedStyle?.(target)?.touchAction || target.style.touchAction;
|
||||
if (touchAction === 'none') {
|
||||
try {
|
||||
target.setPointerCapture?.(pointerId);
|
||||
capturedElement = target;
|
||||
} catch {
|
||||
// Synthetic or unsupported pointer capture environments rely on window listeners.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
activeGestures.set(pointerId, {
|
||||
nodeId,
|
||||
pointerId,
|
||||
capturedElement,
|
||||
lastSentX: coords.x,
|
||||
lastSentY: coords.y,
|
||||
lastMoveSentAt: 0,
|
||||
pendingMove: null,
|
||||
pendingMoveSince: 0,
|
||||
moveTimer: null,
|
||||
});
|
||||
attachWindowPointerListeners();
|
||||
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointerdown',
|
||||
...coords,
|
||||
pointerId,
|
||||
button,
|
||||
buttons,
|
||||
...(pointerType ? { pointerType } : {}),
|
||||
...modifiers,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'wheel') {
|
||||
const wheel = event as WheelEvent;
|
||||
const deltaX = roundWheelDelta(wheel.deltaX);
|
||||
const deltaY = roundWheelDelta(wheel.deltaY);
|
||||
if (deltaX === 0 && deltaY === 0) return;
|
||||
|
||||
if (hasScrollableAncestorForWheel(target, shadow, hostRef.current, view, deltaX, deltaY)) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
|
||||
const rawMode = wheel.deltaMode;
|
||||
const deltaMode = typeof rawMode === 'number' && Number.isFinite(rawMode)
|
||||
? Math.max(0, Math.min(2, Math.trunc(rawMode)))
|
||||
: 0;
|
||||
const coords = readSurfacePoint(wheel, surfaceRef.current ?? hostRef.current);
|
||||
const modifiers = readModifierKeys(wheel);
|
||||
const nextWheel: PluginSurfaceEvent = {
|
||||
nodeId,
|
||||
type: 'wheel',
|
||||
...coords,
|
||||
deltaX,
|
||||
deltaY,
|
||||
deltaMode,
|
||||
...modifiers,
|
||||
};
|
||||
|
||||
const now = Date.now();
|
||||
if (!pendingWheel && now - lastWheelSentAt >= WHEEL_THROTTLE_MS) {
|
||||
lastWheelSentAt = now;
|
||||
onEventRef.current(nextWheel);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
pendingWheel
|
||||
&& pendingWheel.nodeId === nodeId
|
||||
&& pendingWheel.deltaMode === deltaMode
|
||||
&& Boolean(pendingWheel.ctrlKey) === Boolean(modifiers.ctrlKey)
|
||||
&& Boolean(pendingWheel.metaKey) === Boolean(modifiers.metaKey)
|
||||
&& Boolean(pendingWheel.altKey) === Boolean(modifiers.altKey)
|
||||
&& Boolean(pendingWheel.shiftKey) === Boolean(modifiers.shiftKey)
|
||||
) {
|
||||
pendingWheel = {
|
||||
...pendingWheel,
|
||||
...coords,
|
||||
deltaX: roundWheelDelta((pendingWheel.deltaX ?? 0) + deltaX),
|
||||
deltaY: roundWheelDelta((pendingWheel.deltaY ?? 0) + deltaY),
|
||||
};
|
||||
} else {
|
||||
if (pendingWheel) flushWheel();
|
||||
pendingWheel = nextWheel;
|
||||
}
|
||||
if (wheelTimer === null) {
|
||||
const delay = Math.max(1, WHEEL_THROTTLE_MS - (Date.now() - lastWheelSentAt));
|
||||
wheelTimer = setTimeout(flushWheel, delay);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'scroll') {
|
||||
const scrollEvent: PluginSurfaceEvent = {
|
||||
nodeId,
|
||||
@@ -463,11 +949,7 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
|
||||
let pointerCoords: { x: number; y: number } | undefined;
|
||||
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
|
||||
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
|
||||
pointerCoords = {
|
||||
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
|
||||
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
|
||||
};
|
||||
pointerCoords = readSurfacePoint(event, surfaceRef.current ?? hostRef.current);
|
||||
}
|
||||
|
||||
const selection =
|
||||
@@ -488,12 +970,21 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
});
|
||||
};
|
||||
|
||||
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
|
||||
for (const event of SURFACE_EVENTS) {
|
||||
shadow.addEventListener(event, listener, event === 'wheel' ? { capture: true, passive: false } : true);
|
||||
}
|
||||
// Chromium only treats wheel as cancelable when a non-passive listener is
|
||||
// registered on a real element. A closed ShadowRoot listener alone can see
|
||||
// `cancelable: false`, so also listen on the shadow host (no-op targeting;
|
||||
// the shadow capture listener still owns forwarding).
|
||||
const shadowHostEl = hostRef.current;
|
||||
const hostWheelOptions: AddEventListenerOptions = { capture: true, passive: false };
|
||||
const hostWheelListener = (_event: Event) => {};
|
||||
shadowHostEl?.addEventListener('wheel', hostWheelListener, hostWheelOptions);
|
||||
|
||||
// When a full-bleed plugin view is visible and focus sits on document.body (e.g.
|
||||
// right after tab switch or drawer close), forward global Cmd/Ctrl+K / Cmd/Ctrl+S
|
||||
// into the plugin so its Command Palette and Save shortcuts work reliably.
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (depth !== 0 || event.defaultPrevented) return;
|
||||
const surfaceEl = surfaceRef.current;
|
||||
@@ -531,7 +1022,28 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: {
|
||||
view?.addEventListener('keydown', onWindowKeyDown, false);
|
||||
|
||||
return () => {
|
||||
flushPendingMovesRef.current = null;
|
||||
view?.removeEventListener('keydown', onWindowKeyDown, false);
|
||||
shadowHostEl?.removeEventListener('wheel', hostWheelListener, hostWheelOptions);
|
||||
// The retained plugin session keeps its SDK DOM when this surface unmounts
|
||||
// (tab hide). Send pointercancel so plugin drags do not stay stuck.
|
||||
for (const gesture of [...activeGestures.values()]) {
|
||||
const { nodeId, pointerId, lastSentX, lastSentY } = gesture;
|
||||
releaseGesture(gesture);
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: 'pointercancel',
|
||||
x: lastSentX,
|
||||
y: lastSentY,
|
||||
pointerId,
|
||||
button: -1,
|
||||
buttons: 0,
|
||||
});
|
||||
}
|
||||
detachWindowPointerListeners();
|
||||
if (wheelTimer !== null) clearTimeout(wheelTimer);
|
||||
wheelTimer = null;
|
||||
pendingWheel = null;
|
||||
for (const timer of scrollTimers.values()) clearTimeout(timer);
|
||||
scrollTimers.clear();
|
||||
pendingScroll.clear();
|
||||
|
||||
@@ -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,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAADMElEQVR4nO2d200cQRAAmwuAGJAcF3E4BsfhuCwRAwEYf9lGyz5mdqZf01WfSNydqJreYbUMIgAAAFCRJ8s3e3v//WH5fpl5eX6YuFF9E4TPQysIlRdFvB6zQ5j6Yoi3Y1YIU14E8X6MhvAY/QDI92X05z8UAPJjMOLh1vhAfFx6LwndEwD5sen10xUA8nPQ42l4Ewi5aQ6A1Z+LVl9NASA/Jy3eLgNAfm6u/LEHKM5pAKz+NTjzyAQozmEArP61OPLJBCjObgCs/jXZ88oEKA4BFIcAivMlAK7/a7P1ywQoDgEUhwCKQwDFIYDiEEBxCKA4YQL49v2n90coSYgA/sonAnvcA9hKJwJbXAM4kk0EdrgFcCWZCGxwCaBVLhHoYx5Ar1Qi0MU0gLsyiUAP0wB+/Xi9/b1EoIP5JYAIYuGyCSSCOLj9GkgEMXC9EUQE/rjfCiYCX9wDECECT0IEIEIEXoQJQIQIPAgVgAgRWBMuABEisCRkACJEYEXYAESIwILQAYgQgTbhAxAhAk1SBCBCBFqkCUCECDRIFYDI/QhG4lmZdAGI9MtE/jEpAxBpl4r8c9IGwKPlc0gZAI+WzyNdADxaPpdUAYxIZC+wT5oAkK9DigCQr0f4AJCvS+gAkK9P2ACQb0PIAJBvR7gAkG9LqACQb0+YAJDvQ4gAkO+HewDI9yXkOYEtIH8OYc8JPAP58wh9TuAeyJ9L+HMCP4P8+aQ4J1AE+VqkOCcQ+Xo8bb9g8Y8jeyaBhXzvx8WsA395fvzzHvqcQFa+PmHPCUS+DSHPCUS+He63greykW+LewAi/6Uj354QAYgg34swAYAPBFAclxtB4Iv7jSCIAwEUhwCKQwDFIYDiEEBxCKA4BFCcLwF8vkkA67H1ywQoDgEUhwCKsxsA+4A12fPKBCjOYQBMgbU48skEKM5pAEyBNTjzyAQozmUATIHcXPlrmgBEkJMWb82XACLIRasv9gDF6QqAKZCDHk/dE4AIYtPrZ0gmf0QSh7sLc2gPwDSIwYiH4U0gEfgy+vOfKo9Lgh2zFp7K6iUEPWZPXNXxTQjz0LrUml6/CaId9lYAAKDMHwpGNG+oRdPRAAAAAElFTkSuQmCC",
|
||||
"lightSha256": "ec7bcd5e470ee3d3d9f7f77d120a4de7496a9c0ba984094f84e560d240bea947",
|
||||
"dark": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAADMElEQVR4nO2cO07EMBQAH4iSk1FyBmokToJEzRkoOdn2UCHQko8d+/3yZvrdrJjxi4kiiwAAAEBFbiwvdv/w/GV5vcxcPt9M3KheBOHz0ApC5UsRr8fsEKZ+GeLtmBXClC9BvB+jIdyO/gDk+zL69x8KAPkxGPFwaHwgPi69t4TuCYD82PT66QoA+Tno8TS8CYTcNAfA6s9Fq6+mAJCfkxZvuwEgPzd7/tgDFGczAFb/OdjyyAQozmoArP5zseaTCVCcxQBY/edkySsToDgEUBwCKM6/ALj/n5trv0yA4hBAcQigOARQHAIoDgEUhwCKEyaAj/dX759QkhAB/MgnAnvcA7iWTgS2uAawJpsI7HALYE8yEdjgEkCrXCLQxzyAXqlEoItpAEdlEoEepgE8Pr0c/iwR6GB+CyCCWLhsAokgDm7/BhJBDFwfBBGBP+6PgonAF/cARIjAkxABiBCBF2ECECECD0IFIEIE1oQLQIQILAkZgAgRWBE2ABEisCB0ACJEoE34AESIQJMUAYgQgRZpAhAhAg1SBSByPIKReM5MugBE+mUif52UAYi0S0X+NmkD4NXyOaQMgFfL55EuAF4tn0uqAEYkshdYJk0AyNchRQDI1yN8AMjXJXQAyNcnbADItyFkAMi3I1wAyLclVADItydMAMj3IUQAyPfDPQDk+xLynMAWkD+HsOcEboH8eYQ+J3AJ5M8l/DmBf0H+fFKcEyiCfC1SnBOIfD3urC/4+PTSNQks5Hu/LuYZeOhzAln5+oQ9JxD5NoQ8JxD5drg/Cr6WjXxb3AMQ+ZWOfHtCBCCCfC/CBAA+EEBxzB8ERaTy7YcJUBwCKA4BFIcAikMAxSGA4hBAcQigOP8CuHy+3Xj8ELDh2i8ToDgEUBwCKM5iAOwDzsmSVyZAcVYDYAqcizWfTIDibAbAFDgHWx6ZAMXZDYApkJs9f00TgAhy0uKt+RZABLlo9cUeoDhdATAFctDjqXsCEEFsev0Mybx/eP4a+TzM4+jCHNoDMA1iMOJheBNIBL6M/v2nyuOWYMeshaeyeglBj9kTV3V8E8I8tG61pvdvgmiHvRUAACjzDQ0NL/vgx29SAAAAAElFTkSuQmCC",
|
||||
"darkSha256": "7a897a67ae6b652339c77a113d1c759919776fead82d2eefd0238d3c05ba87fe"
|
||||
"light": "data:image/png;base64,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 truncated
|
||||
"lightSha256": "0ca2e946c2462d340818d467a64da392164787466cf417d4d52e9bb3f973f0e2",
|
||||
"dark": "data:image/png;base64,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 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,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 truncated
|
||||
"lightSha256": "e6e9dcdc2de2fe068b38f4fc1963e48b67c6a8e3b8a34735065f8debf7a36387",
|
||||
"dark": "data:image/png;base64,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 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;
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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 & 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 & BI Dashboard<\/strong>/);
|
||||
assert.doesNotMatch(html, /<p align=/);
|
||||
assert.doesNotMatch(html, /<picture>/);
|
||||
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/);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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',
|
||||
];
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) ||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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." },
|
||||
|
||||
@@ -36,3 +36,46 @@ test('brand results cannot survive uninstall or a changed package hash during de
|
||||
await assert.rejects(pending, /ownership changed/);
|
||||
}
|
||||
});
|
||||
|
||||
test('catalog brand icon resolver verifies SHA-256/size/format, rasterizes, and caches', async () => {
|
||||
const { createHash } = require('node:crypto');
|
||||
const sourcePng = await fs.readFile(path.join(__dirname, '../..', 'examples/plugins/starter-netcatty/assets/logo-light.png'));
|
||||
const sha = createHash('sha256').update(sourcePng).digest('hex');
|
||||
const reference = { path: `/assets/${sha}.png`, sha256: sha, size: sourcePng.length };
|
||||
let rasterCalls = 0;
|
||||
let readCalls = 0;
|
||||
const service = new PluginContributionIconService({
|
||||
database: { getActivePlugin: () => null },
|
||||
packageStore: {},
|
||||
rasterizeIcon: async ({ body, maxEdge }) => {
|
||||
rasterCalls += 1;
|
||||
assert.equal(maxEdge, 128);
|
||||
return body;
|
||||
},
|
||||
});
|
||||
const req = {
|
||||
sourceId: 'official',
|
||||
reference,
|
||||
read: async () => { readCalls += 1; return sourcePng; },
|
||||
};
|
||||
const first = await service.resolveCatalogBrandIcon(req);
|
||||
assert.match(first, /^data:image\/png;base64,/);
|
||||
assert.equal(readCalls, 1);
|
||||
assert.equal(rasterCalls, 1);
|
||||
// Cached hit avoids re-reading and re-rasterizing.
|
||||
assert.equal(await service.resolveCatalogBrandIcon(req), first);
|
||||
assert.equal(readCalls, 1);
|
||||
assert.equal(rasterCalls, 1);
|
||||
// Tampered bytes reject.
|
||||
await assert.rejects(service.resolveCatalogBrandIcon({
|
||||
sourceId: 'official',
|
||||
reference: { ...reference, path: `/assets/${'b'.repeat(64)}.png`, sha256: 'b'.repeat(64) },
|
||||
read: async () => sourcePng,
|
||||
}), /Invalid plugin brand icon bytes/);
|
||||
// Extension/magic mismatch rejects.
|
||||
await assert.rejects(service.resolveCatalogBrandIcon({
|
||||
sourceId: 'official',
|
||||
reference: { ...reference, path: `/assets/${sha}.webp` },
|
||||
read: async () => sourcePng,
|
||||
}), /Brand icons require matching PNG or WebP|format/);
|
||||
});
|
||||
+115
-162
@@ -1,204 +1,153 @@
|
||||
[
|
||||
{
|
||||
"id": "com.netcatty.starter",
|
||||
"version": "0.1.2",
|
||||
"name": "Plugin Starter",
|
||||
"description": "First-party greeting panel, local settings and commands, without terminal or secret access.",
|
||||
"id": "com.binaricat.netcatty-database",
|
||||
"version": "0.3.2",
|
||||
"name": "Netcatty Database",
|
||||
"description": "Enterprise-grade multi-database IDE inside Netcatty covering 113 engine profiles (76 live pure-TS drivers across 13 families incl. SQL, CQL, Redis, MongoDB, Neo4j, Search/Vector, KV, RabbitMQ/Pulsar/MQTT/Kafka + 37 catalog entries), BI Dashboard across 53 engines (SQL/CQL/HTTP-SQL + MongoDB Aggregation), Catty Agent tools, Server Monitor, Users Admin, Data Compare, Mock Data, Data Dictionary/Model Codegen, Global Search, Dolt VC, and Vault SSH tunnels.",
|
||||
"author": "Netcatty",
|
||||
"repository": "binaricat/Netcatty",
|
||||
"commit": "f4a6b205adca486d4e9cda0270e13a9ff0afd7be",
|
||||
"repository": "binaricat/netcatty-database-plugin",
|
||||
"commit": "81c3dd7ad9193b0d3a44df1531daeb6c758b4ee8",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"readme": "examples/plugins/starter-netcatty/README.md",
|
||||
"readme": "README.md",
|
||||
"manifest": {
|
||||
"manifestVersion": 1,
|
||||
"id": "com.netcatty.starter",
|
||||
"name": "starter-netcatty",
|
||||
"id": "com.binaricat.netcatty-database",
|
||||
"name": "netcatty-database",
|
||||
"displayName": {
|
||||
"en": "Plugin Starter",
|
||||
"zh-CN": "插件入门"
|
||||
"en": "Netcatty Database",
|
||||
"zh-CN": "Netcatty 数据库"
|
||||
},
|
||||
"description": "First-party settings and command example. No terminal, network, filesystem or secret access.",
|
||||
"version": "0.1.2",
|
||||
"publisher": "netcatty",
|
||||
"description": {
|
||||
"en": "Enterprise-grade multi-database IDE inside Netcatty covering 113 engine profiles (76 live pure-TS drivers across 13 families incl. SQL, CQL, Redis, MongoDB, Neo4j, Search/Vector, KV, RabbitMQ/Pulsar/MQTT/Kafka + 37 catalog entries), BI Dashboard across 53 engines (SQL/CQL/HTTP-SQL + MongoDB Aggregation), Catty Agent tools, Server Monitor, Users Admin, Data Compare, Mock Data, Data Dictionary/Model Codegen, Global Search, Dolt VC, and Vault SSH tunnels.",
|
||||
"zh-CN": "内置于 Netcatty 的全功能企业级多数据库 IDE,覆盖 113 种引擎配置(76 个跨 13 大协议族原生驱动,含 SQL/CQL/Redis/MongoDB/Neo4j/检索向量/KV/RabbitMQ/Pulsar/MQTT/Kafka + 37 个目录引擎),支持 53 种引擎 BI 看板(SQL/CQL/HTTP-SQL + MongoDB 聚合)、Catty Agent 工具、服务监控、用户权限、数据对比、测试数据生成、数据字典与代码生成、全局搜索、Dolt 版本控制与 Vault SSH 隧道。"
|
||||
},
|
||||
"version": "0.3.2",
|
||||
"publisher": "binaricat",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"engines": {
|
||||
"netcatty": ">=0.0.0",
|
||||
"api": ">=0.1.0-internal.1 <0.2.0"
|
||||
},
|
||||
"features": {
|
||||
"required": [
|
||||
"views.host-drawn",
|
||||
"views.vault-pages",
|
||||
"metadata.brand-icon",
|
||||
"ai.model-invocation",
|
||||
"ai.agent-sessions",
|
||||
"vault.host-actions",
|
||||
"host.interactions",
|
||||
"network.byte-streams",
|
||||
"network.host-byte-streams"
|
||||
],
|
||||
"optional": [
|
||||
"ai.sidebar-tools"
|
||||
]
|
||||
},
|
||||
"main": {
|
||||
"browser": "dist/index.js"
|
||||
"browser": "browser.js"
|
||||
},
|
||||
"activationEvents": [
|
||||
"onCommand:com.netcatty.starter.greet",
|
||||
"onView:com.netcatty.starter.panel"
|
||||
"onView:com.binaricat.netcatty-database.workbench",
|
||||
"onView:com.binaricat.netcatty-database.connection"
|
||||
],
|
||||
"permissions": {
|
||||
"required": [
|
||||
"commands",
|
||||
"settings.read",
|
||||
"menus",
|
||||
"views"
|
||||
],
|
||||
"optional": []
|
||||
"optional": [
|
||||
"storage",
|
||||
"secrets",
|
||||
"network.stream",
|
||||
"network",
|
||||
"clipboard.read",
|
||||
{
|
||||
"permission": "ai.invoke",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Draft, explain, optimize, and fix SQL queries using schema metadata / 使用数据库结构生成、解释、优化和修复 SQL 草稿"
|
||||
},
|
||||
{
|
||||
"permission": "ai.agent.use",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Optional host Agent conversations for database guidance / 可选宿主 Agent 对话以提供数据库辅助"
|
||||
},
|
||||
{
|
||||
"permission": "vault.metadata",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Select existing Netcatty Vault SSH hosts for database tunneling / 选择已有 Netcatty Vault SSH 主机建立数据库隧道"
|
||||
},
|
||||
{
|
||||
"permission": "ui.interact",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Open and save local SQLite databases, SQL scripts, and CSV/JSON/XLSX exports via native file dialogs / 通过原生文件对话框打开和保存本地 SQLite、SQL 脚本及数据导出文件"
|
||||
},
|
||||
{
|
||||
"permission": "network.hostStream",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Connect to remote databases through a user-selected Netcatty Vault SSH server without exposing SSH credentials / 通过选定的 Netcatty Vault SSH 主机隧道连接远端数据库,不暴露 SSH 凭证"
|
||||
},
|
||||
{
|
||||
"permission": "clipboard.write",
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Copy query results, SQL statements, and connection URIs to the clipboard / 复制查询结果、SQL 语句与连接 URI 到剪贴板"
|
||||
}
|
||||
]
|
||||
},
|
||||
"contributes": {
|
||||
"settings": [
|
||||
{
|
||||
"id": "com.netcatty.starter.greeting",
|
||||
"label": {
|
||||
"en": "Greeting",
|
||||
"zh-CN": "问候语"
|
||||
},
|
||||
"description": "A local preference for the example command.",
|
||||
"control": "text",
|
||||
"scope": "application",
|
||||
"default": "Hello, synthetic world!"
|
||||
}
|
||||
],
|
||||
"commands": [
|
||||
{
|
||||
"id": "com.netcatty.starter.greet",
|
||||
"title": {
|
||||
"en": "Starter: Read Greeting",
|
||||
"zh-CN": "入门:读取问候语"
|
||||
}
|
||||
}
|
||||
],
|
||||
"menus": [
|
||||
{
|
||||
"command": "com.netcatty.starter.greet",
|
||||
"location": "commandPalette",
|
||||
"group": "examples"
|
||||
}
|
||||
],
|
||||
"views": [
|
||||
{
|
||||
"id": "com.netcatty.starter.panel",
|
||||
"id": "com.binaricat.netcatty-database.workbench",
|
||||
"title": {
|
||||
"en": "Starter: Greeting Panel",
|
||||
"zh-CN": "入门:问候面板"
|
||||
"en": "Database",
|
||||
"zh-CN": "数据库"
|
||||
},
|
||||
"location": "vault-page",
|
||||
"icon": {
|
||||
"kind": "theme",
|
||||
"name": "database"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "com.binaricat.netcatty-database.connection",
|
||||
"title": {
|
||||
"en": "Database: New connection",
|
||||
"zh-CN": "数据库:新建连接"
|
||||
},
|
||||
"location": "modal"
|
||||
}
|
||||
]
|
||||
},
|
||||
"features": {
|
||||
"required": [
|
||||
"metadata.brand-icon"
|
||||
]
|
||||
},
|
||||
"icon": {
|
||||
"kind": "package",
|
||||
"light": "assets/logo-light.png",
|
||||
"dark": "assets/logo-dark.png"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "com.netcatty.hello",
|
||||
"version": "0.1.0",
|
||||
"name": "Hello Netcatty",
|
||||
"description": "First-party example: greeting settings, commands and terminal providers. Build locally and import.",
|
||||
"author": "Netcatty",
|
||||
"repository": "binaricat/Netcatty",
|
||||
"commit": "4336f8fd53a05a48d6bbc9ad3ce0ca88b121862f",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"readme": "examples/plugins/hello-netcatty/README.md",
|
||||
"manifest": {
|
||||
"$schema": "../../../packages/plugin-contract/schema/plugin-contract.schema.json",
|
||||
"manifestVersion": 1,
|
||||
"id": "com.netcatty.hello",
|
||||
"name": "hello-netcatty",
|
||||
"displayName": {
|
||||
"en": "Hello Netcatty",
|
||||
"zh-CN": "你好,Netcatty"
|
||||
},
|
||||
"description": "Minimal plugin contract and SDK example.",
|
||||
"version": "0.1.0",
|
||||
"publisher": "netcatty",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"engines": {
|
||||
"netcatty": ">=0.0.0",
|
||||
"api": ">=0.1.0-internal <0.2.0"
|
||||
},
|
||||
"main": {
|
||||
"browser": "dist/index.js"
|
||||
},
|
||||
"activationEvents": [
|
||||
"onCommand:com.netcatty.hello.sayHello",
|
||||
"onProvider:com.netcatty.hello.completion",
|
||||
"onProvider:com.netcatty.hello.decoration",
|
||||
"onProvider:com.netcatty.hello.theme"
|
||||
],
|
||||
"permissions": {
|
||||
"required": [
|
||||
"commands",
|
||||
"settings.read",
|
||||
"menus",
|
||||
"provider.terminal",
|
||||
"terminal.complete",
|
||||
"terminal.output",
|
||||
"terminal.decorate"
|
||||
],
|
||||
"optional": []
|
||||
},
|
||||
"contributes": {
|
||||
"settings": [
|
||||
{
|
||||
"id": "com.netcatty.hello.greeting",
|
||||
"label": "Greeting",
|
||||
"description": "Text used by the example command.",
|
||||
"control": "text",
|
||||
"scope": "application",
|
||||
"default": "Hello from Netcatty"
|
||||
}
|
||||
],
|
||||
"commands": [
|
||||
{
|
||||
"id": "com.netcatty.hello.sayHello",
|
||||
"title": "Say Hello",
|
||||
"category": "Examples"
|
||||
}
|
||||
],
|
||||
"menus": [
|
||||
{
|
||||
"command": "com.netcatty.hello.sayHello",
|
||||
"location": "commandPalette",
|
||||
"group": "examples",
|
||||
"order": 10
|
||||
}
|
||||
],
|
||||
"providers": [
|
||||
{
|
||||
"id": "com.netcatty.hello.completion",
|
||||
"label": "Hello completion",
|
||||
"description": "Suggests the example hello command.",
|
||||
"kind": "terminal.completion"
|
||||
},
|
||||
{
|
||||
"id": "com.netcatty.hello.decoration",
|
||||
"label": "Hello decoration",
|
||||
"description": "Highlights the example greeting in terminal output.",
|
||||
"kind": "terminal.decoration"
|
||||
},
|
||||
{
|
||||
"id": "com.netcatty.hello.theme",
|
||||
"label": "Hello theme",
|
||||
"description": "Adds a subtle cursor color to the example terminal theme.",
|
||||
"kind": "terminal.theme"
|
||||
}
|
||||
]
|
||||
"light": "assets/plugin-icon-light.png",
|
||||
"dark": "assets/plugin-icon-dark.png"
|
||||
}
|
||||
},
|
||||
"artifact": {
|
||||
"url": "https://plugins.netcatty.app/assets/2897fedee8e6f5090622a99e08192ea34c7fd3d8a13bf465df4f169370b13cca.ncpkg",
|
||||
"sha256": "2897fedee8e6f5090622a99e08192ea34c7fd3d8a13bf465df4f169370b13cca"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "com.binaricat.netcatty-monitor",
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.2",
|
||||
"name": "Netcatty Monitor",
|
||||
"description": "Official agentless SSH fleet monitoring and server operations workbench with real-time CPU, memory, disk I/O, network, GPU & thermal charts, live process explorer, systemd/Docker/Podman services & logs, listening ports, and configurable threshold alerts.",
|
||||
"author": "Netcatty",
|
||||
"repository": "binaricat/netcatty-monitor-plugin",
|
||||
"commit": "997199f596d8b8ff358908d936909280fca2f27d",
|
||||
"commit": "bee26d2092666940c881f93b83d923550571fe63",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"readme": "README.md",
|
||||
"manifest": {
|
||||
@@ -213,7 +162,7 @@
|
||||
"en": "Agentless SSH fleet monitoring and server operations workbench inside Netcatty with real-time CPU, memory, disk I/O, network, GPU & thermal charts, live process explorer, systemd/Docker/Podman services & log tails, listening ports, and configurable threshold alerts.",
|
||||
"zh-CN": "内置于 Netcatty 的无 Agent SSH 服务器集群监控与运维工作台,提供实时 CPU、内存、磁盘 I/O、网络、GPU 与温度曲线,以及实时进程管理、systemd/Docker/Podman 服务与日志查看、监听端口分析与可配置阈值告警。"
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"version": "0.2.2",
|
||||
"publisher": "binaricat",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"homepage": "https://github.com/binaricat/netcatty-monitor-plugin",
|
||||
@@ -264,7 +213,7 @@
|
||||
"resources": [
|
||||
"*"
|
||||
],
|
||||
"reason": "Export monitoring snapshots as JSON files via native save dialogs / 通过原生保存对话框导出监控快照 JSON 文件"
|
||||
"reason": "Confirm destructive process, service, container, and panel actions via native dialogs and export JSON/Markdown diagnostic reports / 通过原生确认对话框确认进程、服务、容器及面板操作,并导出 JSON/Markdown 诊断报告"
|
||||
},
|
||||
{
|
||||
"permission": "clipboard.write",
|
||||
@@ -286,7 +235,7 @@
|
||||
"location": "vault-page",
|
||||
"icon": {
|
||||
"kind": "theme",
|
||||
"name": "activity"
|
||||
"name": "gauge"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -296,6 +245,10 @@
|
||||
"light": "assets/plugin-icon-light.png",
|
||||
"dark": "assets/plugin-icon-dark.png"
|
||||
}
|
||||
},
|
||||
"artifact": {
|
||||
"url": "https://plugins.netcatty.app/assets/4d00a1bcc5aedc64858695e428e92b60a50e85d8397e580df9fa83a357ea70fd.ncpkg",
|
||||
"sha256": "4d00a1bcc5aedc64858695e428e92b60a50e85d8397e580df9fa83a357ea70fd"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -7,14 +7,34 @@ const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { PluginCatalogService, validateCatalog, fetchBounded } = require("./catalogService.cjs");
|
||||
const { assertCatalogManifest } = require("./catalogPolicy.cjs");
|
||||
const { OFFICIAL_SOURCE, isOfficialMaintained } = require("./sourceIdentity.cjs");
|
||||
const { OFFICIAL_SOURCE, LOCAL_SOURCE, thirdPartySource, githubSource, isOfficialMaintained } = require("./sourceIdentity.cjs");
|
||||
const entries = require("./catalog.json");
|
||||
|
||||
test("curated catalog uses pinned public first-party source and rejects advanced manifests", () => {
|
||||
assert.equal(validateCatalog(entries).length, 3);
|
||||
assert.equal(validateCatalog(entries).length, 2);
|
||||
const database = entries.find((item) => item.id === "com.binaricat.netcatty-database");
|
||||
assert.ok(database, "catalog should include official com.binaricat.netcatty-database");
|
||||
assert.equal(database.version, "0.3.2");
|
||||
assert.equal(isOfficialMaintained(database, OFFICIAL_SOURCE), true);
|
||||
const monitor = entries.find((item) => item.id === "com.binaricat.netcatty-monitor");
|
||||
assert.ok(monitor, "catalog should include official com.binaricat.netcatty-monitor");
|
||||
assert.equal(monitor.version, "0.2.2");
|
||||
assert.equal(isOfficialMaintained(monitor, OFFICIAL_SOURCE), true);
|
||||
|
||||
// Future binaricat official plugins are auto-recognized from the official source without an app release.
|
||||
const futureOfficial = {
|
||||
id: "com.binaricat.netcatty-docker",
|
||||
repository: "binaricat/netcatty-docker-plugin",
|
||||
manifest: { publisher: "binaricat" },
|
||||
};
|
||||
assert.equal(isOfficialMaintained(futureOfficial, OFFICIAL_SOURCE), true);
|
||||
assert.equal(isOfficialMaintained({ ...futureOfficial, id: "com.netcatty.k8s", manifest: { publisher: "netcatty" } }, OFFICIAL_SOURCE), true);
|
||||
assert.equal(isOfficialMaintained(futureOfficial, LOCAL_SOURCE), false);
|
||||
assert.equal(isOfficialMaintained(futureOfficial, thirdPartySource("Mirror", "https://mirror.example.com")), false);
|
||||
assert.equal(isOfficialMaintained(futureOfficial, githubSource("binaricat/netcatty-docker-plugin")), false);
|
||||
assert.equal(isOfficialMaintained({ ...futureOfficial, repository: "other/netcatty-docker-plugin" }, OFFICIAL_SOURCE), false);
|
||||
assert.equal(isOfficialMaintained({ ...futureOfficial, id: "com.other.netcatty-docker" }, OFFICIAL_SOURCE), false);
|
||||
assert.equal(isOfficialMaintained({ ...futureOfficial, manifest: { publisher: "other" } }, OFFICIAL_SOURCE), false);
|
||||
for (const main of [{ node: "index.js" }, { browser: "index.js", node: "node.js" }]) {
|
||||
const entry = structuredClone(entries[0]); entry.manifest.main = main;
|
||||
assert.throws(() => validateCatalog([entry]), /browser-only packages/);
|
||||
|
||||
@@ -10,6 +10,7 @@ const { createPooledContributionIconRasterizer } = require("./contributionIconRa
|
||||
const MAX_ICON_SOURCE_BYTES = 512 * 1024;
|
||||
const MAX_ICON_PNG_BYTES = 512 * 1024;
|
||||
const MAX_ICON_EDGE = 64;
|
||||
const MAX_CATALOG_BRAND_ICON_EDGE = 128;
|
||||
const MAX_ICON_SOURCE_EDGE = 4_096;
|
||||
const MAX_ICON_SOURCE_PIXELS = 16 * 1024 * 1024;
|
||||
const MAX_CONCURRENT_ICON_RASTERIZATIONS = 2;
|
||||
@@ -292,6 +293,42 @@ class PluginContributionIconService {
|
||||
return pending;
|
||||
}
|
||||
|
||||
// Called only with a host-selected, hash-bound registry brand-icon reference.
|
||||
// Shares the isolated rasterizer, queue, cache, and in-flight deduplication.
|
||||
async resolveCatalogBrandIcon({ sourceId, reference, read }) {
|
||||
const key = JSON.stringify(["catalog-brand-icon", sourceId, reference.path, reference.sha256, reference.size]);
|
||||
if (this.cache.has(key)) return this.cache.get(key);
|
||||
if (this.pending.has(key)) return this.pending.get(key);
|
||||
if (this.pending.size >= MAX_QUEUED_ICON_RASTERIZATIONS + MAX_CONCURRENT_ICON_RASTERIZATIONS) {
|
||||
throw new Error("Plugin image queue is full");
|
||||
}
|
||||
const pending = (async () => {
|
||||
const body = await read();
|
||||
if (!Buffer.isBuffer(body) || body.length !== reference.size || body.length > 256 * 1024
|
||||
|| createHash("sha256").update(body).digest("hex") !== reference.sha256) {
|
||||
throw new Error("Invalid plugin brand icon bytes");
|
||||
}
|
||||
const extension = path.extname(reference.path).toLowerCase();
|
||||
if (![".png", ".webp"].includes(extension)) throw new Error("Invalid plugin brand icon format");
|
||||
const { inspectPluginBrandIcon } = await import("@netcatty/plugin-contract");
|
||||
const inspected = inspectPluginBrandIcon(body, reference.path);
|
||||
if (inspected.mimeType !== (extension === ".png" ? "image/png" : "image/webp")) {
|
||||
throw new Error("Plugin brand icon format mismatch");
|
||||
}
|
||||
const png = await this.rasterizeIcon({ body, ...inspected, maxEdge: MAX_CATALOG_BRAND_ICON_EDGE });
|
||||
if (!Buffer.isBuffer(png) || !png.length || png.length > MAX_ICON_PNG_BYTES) {
|
||||
throw new Error("Plugin brand icon output is too large");
|
||||
}
|
||||
inspectContributionIconSource(png, ".png", MAX_CATALOG_BRAND_ICON_EDGE);
|
||||
const value = `data:image/png;base64,${png.toString("base64")}`;
|
||||
if (this.cache.size >= 256) this.cache.clear();
|
||||
this.cache.set(key, value);
|
||||
return value;
|
||||
})().finally(() => this.pending.delete(key));
|
||||
this.pending.set(key, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
async #resolveUncached({ pluginId, plugin, icon, cacheKey }) {
|
||||
const useSingleFileVerify = typeof this.packageStore.readVerifiedPackageFile === "function";
|
||||
const packageRoot = useSingleFileVerify ? null : await this.packageStore.preparePackageRoot(plugin);
|
||||
@@ -365,6 +402,7 @@ class PluginContributionIconService {
|
||||
|
||||
module.exports = {
|
||||
MAX_ICON_EDGE,
|
||||
MAX_CATALOG_BRAND_ICON_EDGE,
|
||||
MAX_CONCURRENT_ICON_RASTERIZATIONS,
|
||||
MAX_QUEUED_ICON_RASTERIZATIONS,
|
||||
MAX_ICON_SOURCE_EDGE,
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
# Pinned static distribution schemas
|
||||
|
||||
`delivery.schema.json` and `index.schema.json` are unmodified UTF-8 files from
|
||||
`delivery.schema.json` and `index.schema.json` originate from
|
||||
binaricat/netcatty-plugins commit 7bfe23e5627e16ba63806de6dded5b2667c02984
|
||||
(PR 3). The host compiles them with the existing local plugin-contract schema;
|
||||
no schema reference causes network access.
|
||||
(PR 3); `index.schema.json` allows historical `versions[].entry.manifest` objects
|
||||
so immutable archived versions from older contract revisions do not block newer
|
||||
snapshots, while every `current` entry in `catalog.json` remains strictly
|
||||
validated against the local `PluginManifest` contract schema and deep-equal to
|
||||
its `index.json` entry. No schema reference causes network access.
|
||||
|
||||
`../fixtures/static-distribution/` contains that commit's actual
|
||||
`distribution/bootstrap/v1/snapshot.json`, snapshot catalog/index/delivery and
|
||||
|
||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user