mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-02 07:11:00 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
529003ad6f | ||
|
|
9fcb16cec7 |
No files matched your search
@@ -75,6 +75,8 @@
|
||||
!packages/**
|
||||
!patches/
|
||||
!patches/**
|
||||
!plugins/
|
||||
!plugins/**
|
||||
!public/
|
||||
!public/**
|
||||
!resources/
|
||||
|
||||
+1
-41
@@ -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,16 +38,12 @@
|
||||
<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">
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -83,33 +79,9 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 プラグインシステム — Netcatty を安全に拡張
|
||||
|
||||
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
|
||||
|
||||
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
|
||||
|
||||
### ✨ 主な特徴
|
||||
|
||||
- 🔒 **オフラインサンドボックス & 最小権限モデル** — プラグインは SSH パスワードや秘密鍵に直接アクセスできず、すべての機能はホスト管理の **許可 / 毎回確認 / 拒否** ポリシーを経由します。
|
||||
- 🖥️ **ホストネイティブ IDE コンポーネント** — `@netcatty/plugin-sdk` を使い、React または DOM で Vault ページ、ターミナルサイドバー、モーダルを構築できます。
|
||||
- 🗄️ **公式プラグインをすぐ導入** — **設定 → プラグイン** から [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database)(113 エンジン対応 SQL IDE・Catty Agent・BI ダッシュボード)や [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor)(エージェントレス SSH サーバー監視・Monaco ライブ可視化ログ)をワンクリック導入できます。
|
||||
- 🚀 **柔軟な配布と自動更新チェック** — 内蔵の**公式マーケットプレイス**(`plugins.netcatty.app`)、GitHub Release からの直接インストール、ローカル `.ncpkg` インポート、自社ホスト静的ソースに対応します。
|
||||
|
||||
### 🔗 関連リンク & ガイド
|
||||
|
||||
- 🛒 [**公式プラグインマーケットプレイス**](https://netcatty.app/en/plugins) — 公式・コミュニティプラグインを閲覧
|
||||
- 📖 [**プラグイン基盤概要**](https://netcatty.app/en/docs/plugins-overview) — サンドボックス設計・ホストレンダリング UI・権限モデル
|
||||
- 🛠️ [**プラグイン開発ガイド**](https://netcatty.app/en/docs/plugins-development) — プロジェクト作成・UI 実装・権限宣言・`.ncpkg` パッケージング
|
||||
- 📤 [**マーケットプレイス公開・提出ガイド**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release 規約と公式カタログ PR 手順([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
|
||||
|
||||
---
|
||||
|
||||
# 目次 <!-- omit in toc -->
|
||||
|
||||
- [🔥 Catty Agent — AI パートナー](#catty-agent)
|
||||
- [🧩 プラグインシステム](#plugin-system)
|
||||
- [Netcatty とは](#netcatty-とは)
|
||||
- [なぜ Netcatty](#なぜ-netcatty)
|
||||
- [機能](#機能)
|
||||
@@ -122,7 +94,6 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
- [はじめに](#はじめに)
|
||||
- [ビルドとパッケージ](#ビルドとパッケージ)
|
||||
- [技術スタック](#技術スタック)
|
||||
- [コミュニティ](#コミュニティ)
|
||||
- [コントリビューション](#コントリビューション)
|
||||
- [コントリビューター](#コントリビューター)
|
||||
- [Star 履歴](#star-履歴)
|
||||
@@ -355,17 +326,6 @@ 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 · 🧩 Plugin System · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
|
||||
🔥 Built-in AI Agent · Split terminals · Vault views · SFTP workflows · Custom themes — all in one.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -38,16 +38,12 @@
|
||||
<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">
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -83,35 +79,11 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
|
||||
<img width="3294" height="1974" alt="image" src="docs/assets/readme/catty-multi-host.webp" />
|
||||
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 Plugin System — Extend Netcatty Safely
|
||||
|
||||
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
|
||||
|
||||
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
|
||||
|
||||
### ✨ Highlights
|
||||
|
||||
- 🔒 **Offline Sandbox & Least-Privilege Permissions** — Plugins never touch SSH passwords, private keys, or the host renderer; every capability goes through host-mediated **Allow / Ask / Deny** brokers.
|
||||
- 🖥️ **Host-Rendered IDE Components** — Build native-feeling Vault pages, terminal sidebars, and modals with React or DOM via `@netcatty/plugin-sdk`.
|
||||
- 🗄️ **Official Plugins Out of the Box** — Install [**Netcatty Database**](https://netcatty.app/en/plugins/netcatty-database) (113 database profiles, SQL IDE, Catty Agent sidebar & BI Dashboard) and [**Netcatty Monitor**](https://netcatty.app/en/plugins/netcatty-monitor) (agentless cross-OS SSH fleet observability, Monaco live logs & multi-host compare) directly in **Settings → Plugins**.
|
||||
- 🚀 **Flexible Distribution** — Install from the built-in **Official Marketplace** (`plugins.netcatty.app`), directly from any public GitHub Release (**Install from GitHub**), via local `.ncpkg` import, or self-hosted static market sources.
|
||||
|
||||
### 🔗 Resources & Guides
|
||||
|
||||
- 🛒 [**Official Plugin Marketplace**](https://netcatty.app/en/plugins) — Browse official and curated plugins
|
||||
- 📖 [**Plugin Platform Overview**](https://netcatty.app/en/docs/plugins-overview) — Sandbox architecture, host-rendered UI, and permission model
|
||||
- 🛠️ [**Plugin Development Guide**](https://netcatty.app/en/docs/plugins-development) — Scaffold, build host-rendered views, declare permissions, and pack `.ncpkg`
|
||||
- 📤 [**Marketplace Submission & Publishing Guide**](https://netcatty.app/en/docs/plugins-marketplace) — GitHub Release contract & official catalog PR workflow ([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
|
||||
|
||||
---
|
||||
|
||||
# Contents <!-- omit in toc -->
|
||||
|
||||
- [🔥 Catty Agent — AI Partner](#catty-agent)
|
||||
- [🧩 Plugin System](#plugin-system)
|
||||
- [What is Netcatty](#what-is-netcatty)
|
||||
- [Why Netcatty](#why-netcatty)
|
||||
- [Features](#features)
|
||||
@@ -124,7 +96,6 @@ 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)
|
||||
@@ -388,17 +359,6 @@ 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
|
||||
|
||||
|
||||
+1
-41
@@ -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,16 +38,12 @@
|
||||
<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">
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -83,33 +79,9 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 插件系统 — 安全扩展你的工作台
|
||||
|
||||
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
|
||||
|
||||
### ✨ 核心亮点
|
||||
|
||||
- 🔒 **离线沙箱与最小权限控制** —— 插件永远无法读取 SSH 密码或私钥,所有宿主能力均受 **允许 / 询问 / 拒绝** 三态权限代理与审计保护。
|
||||
- 🖥️ **宿主原生 IDE 组件** —— 通过 `@netcatty/plugin-sdk` 使用 React 或原生 DOM 构建 Vault 页面、终端侧栏与弹窗,无缝复用宿主主题。
|
||||
- 🗄️ **官方插件开箱即用** —— 在 **设置 → 插件** 一键安装 [**Netcatty 数据库**](https://netcatty.app/zh/plugins/netcatty-database)(覆盖 113 种数据库配置、SQL IDE、Catty Agent 侧栏与 BI 看板)和 [**Netcatty 监控**](https://netcatty.app/zh/plugins/netcatty-monitor)(无 Agent 跨平台 SSH 集群监控、Monaco 实时日志与多机对比)。
|
||||
- 🚀 **多渠道分发与自动检查更新** —— 支持内置**官方插件市场**(`plugins.netcatty.app`)、**从 GitHub 安装**公开 Release、本地导入 `.ncpkg` 以及自建第三方静态市场源。
|
||||
|
||||
### 🔗 相关链接与指南
|
||||
|
||||
- 🛒 [**官方插件市场**](https://netcatty.app/zh/plugins) —— 浏览官方与社区插件
|
||||
- 📖 [**插件平台概览**](https://netcatty.app/zh/docs/plugins-overview) —— 隔离架构、宿主渲染 UI 与权限安全模型
|
||||
- 🛠️ [**插件开发指南**](https://netcatty.app/zh/docs/plugins-development) —— 脚手架初始化、UI 开发、权限声明与 `.ncpkg` 打包调试
|
||||
- 📤 [**插件市场发布与提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契约与官方市场 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
|
||||
|
||||
---
|
||||
|
||||
# 目录 <!-- omit in toc -->
|
||||
|
||||
- [🔥 Catty Agent — AI 搭档](#catty-agent)
|
||||
- [🧩 插件系统](#plugin-system)
|
||||
- [Netcatty 是什么](#netcatty-是什么)
|
||||
- [为什么是 Netcatty](#为什么是-netcatty)
|
||||
- [功能特性](#功能特性)
|
||||
@@ -122,7 +94,6 @@
|
||||
- [快速开始](#快速开始)
|
||||
- [构建与打包](#构建与打包)
|
||||
- [技术栈](#技术栈)
|
||||
- [社区交流](#社区交流)
|
||||
- [参与贡献](#参与贡献)
|
||||
- [贡献者](#贡献者)
|
||||
- [Star 历史](#star-历史)
|
||||
@@ -355,17 +326,6 @@ 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>
|
||||
# 参与贡献
|
||||
|
||||
|
||||
+1
-41
@@ -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,16 +38,12 @@
|
||||
<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">
|
||||
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
|
||||
</p>
|
||||
|
||||
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
---
|
||||
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
@@ -83,33 +79,9 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="plugin-system"></a>
|
||||
# 🧩 外掛系統 —— 安全擴充你的工作台
|
||||
|
||||
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
|
||||
|
||||
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
|
||||
|
||||
### ✨ 核心亮點
|
||||
|
||||
- 🔒 **離線沙箱與最小權限控制** —— 外掛永遠無法讀取 SSH 密碼或私鑰,所有宿主能力均受 **允許 / 詢問 / 拒絕** 三態權限代理保護。
|
||||
- 🖥️ **宿主原生 IDE 元件** —— 透過 `@netcatty/plugin-sdk` 以 React 或原生 DOM 開發 Vault 頁面、終端側欄與視窗,無縫跟隨宿主主題。
|
||||
- 🗄️ **官方外掛開箱即用** —— 在 **設定 → 外掛** 一鍵安裝 [**Netcatty 資料庫**](https://netcatty.app/zh/plugins/netcatty-database)(113 種資料庫設定、SQL IDE、Catty Agent 側欄與 BI 看板)與 [**Netcatty 監控**](https://netcatty.app/zh/plugins/netcatty-monitor)(無 Agent 跨平台 SSH 叢集監控、Monaco 即時日誌與多機對比)。
|
||||
- 🚀 **多元分發與自動檢查更新** —— 支援內建**官方外掛市場**(`plugins.netcatty.app`)、**從 GitHub 安裝**公開 Release、本機匯入 `.ncpkg` 以及自建第三方靜態市場源。
|
||||
|
||||
### 🔗 相關連結與指南
|
||||
|
||||
- 🛒 [**官方外掛市場**](https://netcatty.app/zh/plugins) —— 瀏覽官方與社群外掛
|
||||
- 📖 [**外掛平台概覽**](https://netcatty.app/zh/docs/plugins-overview) —— 隔離架構、宿主渲染 UI 與權限安全模型
|
||||
- 🛠️ [**外掛開發指南**](https://netcatty.app/zh/docs/plugins-development) —— 初始化專案、UI 開發、權限宣告與 `.ncpkg` 打包除錯
|
||||
- 📤 [**外掛市場發布與提交指南**](https://netcatty.app/zh/docs/plugins-marketplace) —— GitHub Release 契約與官方市場 PR 提交流程([`binaricat/netcatty-plugins`](https://github.com/binaricat/netcatty-plugins))
|
||||
|
||||
---
|
||||
|
||||
# 目錄 <!-- omit in toc -->
|
||||
|
||||
- [🔥 Catty Agent —— AI 夥伴](#catty-agent)
|
||||
- [🧩 外掛系統](#plugin-system)
|
||||
- [Netcatty 是什麼](#netcatty-是什麼)
|
||||
- [為什麼選 Netcatty](#為什麼選-netcatty)
|
||||
- [功能特色](#功能特色)
|
||||
@@ -122,7 +94,6 @@
|
||||
- [快速開始](#快速開始)
|
||||
- [建置與打包](#建置與打包)
|
||||
- [技術堆疊](#技術堆疊)
|
||||
- [社群交流](#社群交流)
|
||||
- [參與貢獻](#參與貢獻)
|
||||
- [貢獻者](#貢獻者)
|
||||
- [Star 紀錄](#star-紀錄)
|
||||
@@ -354,17 +325,6 @@ 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>
|
||||
# 參與貢獻
|
||||
|
||||
|
||||
@@ -1137,159 +1137,3 @@ test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and reco
|
||||
assert.equal(logs[1].username, 'dev');
|
||||
assert.equal(logs[1].protocol, 'local');
|
||||
});
|
||||
|
||||
for (const scheme of ['pc', 'mac'] as const) {
|
||||
test(`addSessionToWorkspace shortcut ${scheme}: opens append dialog and consumes event only when a workspace is active`, () => {
|
||||
const target = new FakeHTMLElement();
|
||||
|
||||
for (const scenario of [
|
||||
{ name: 'active workspace', activeTabId: 'workspace-1', expectConsume: true },
|
||||
{ name: 'standalone terminal', activeTabId: 'session-1', expectConsume: false },
|
||||
{ name: 'vault tab', activeTabId: 'vault', expectConsume: false },
|
||||
{ name: 'sftp tab', activeTabId: 'sftp', expectConsume: false },
|
||||
{ name: 'editor tab', activeTabId: 'editor:file-1', expectConsume: false },
|
||||
{ name: 'log view tab', activeTabId: 'log-1', expectConsume: false },
|
||||
{ name: 'plugin view tab', activeTabId: 'plugin-view:demo:main', expectConsume: false },
|
||||
]) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: scheme === 'pc',
|
||||
metaKey: scheme === 'mac',
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
const actionCtx = {
|
||||
activeTabStore: { getActiveTabId: () => scenario.activeTabId },
|
||||
editorTabs: [{ id: 'file-1' }],
|
||||
orderedTabs: ['session-1', 'workspace-1'],
|
||||
sessions: [{ id: 'session-1' }, { id: 's-ws', workspaceId: 'workspace-1' }],
|
||||
settings: { showSftpTab: true, shellOnlyTabNumberShortcuts: false },
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
};
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: scheme,
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => actionCtx, action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
dialogCalls,
|
||||
scenario.expectConsume ? [{ mode: 'append', workspaceId: 'workspace-1' }] : [],
|
||||
`${scheme} / ${scenario.name}: dialog calls`,
|
||||
);
|
||||
assert.equal(
|
||||
prevented,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: preventDefault count`,
|
||||
);
|
||||
assert.equal(
|
||||
stopped,
|
||||
scenario.expectConsume ? 1 : 0,
|
||||
`${scheme} / ${scenario.name}: stopPropagation count`,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('addSessionToWorkspace shortcut stays out of form inputs and Monaco even while a workspace is active', () => {
|
||||
for (const [label, target] of [
|
||||
['input', new FakeInputHTMLElement()],
|
||||
['monaco', new FakeMonacoHTMLElement()],
|
||||
] as const) {
|
||||
const dialogCalls: unknown[] = [];
|
||||
let prevented = 0;
|
||||
let stopped = 0;
|
||||
const event = {
|
||||
key: 'n',
|
||||
code: 'KeyN',
|
||||
ctrlKey: true,
|
||||
metaKey: false,
|
||||
altKey: false,
|
||||
shiftKey: false,
|
||||
target,
|
||||
composedPath: () => [target],
|
||||
preventDefault: () => { prevented += 1; },
|
||||
stopPropagation: () => { stopped += 1; },
|
||||
} as unknown as KeyboardEvent;
|
||||
|
||||
handleGlobalHotkeyKeyDownImpl(
|
||||
() => ({
|
||||
HOTKEY_DEBUG: false,
|
||||
closeTabKeyStr: '',
|
||||
hotkeyScheme: 'pc',
|
||||
keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
matchesKeyBinding,
|
||||
executeHotkeyAction: (action: string, ev: KeyboardEvent) =>
|
||||
executeHotkeyActionImpl(() => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: ['workspace-1'],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
}), action, ev),
|
||||
}),
|
||||
event,
|
||||
);
|
||||
|
||||
assert.deepEqual(dialogCalls, [], `${label} should not open workspace dialog`);
|
||||
assert.equal(prevented, 0, `${label} should not preventDefault`);
|
||||
assert.equal(stopped, 0, `${label} should not stopPropagation`);
|
||||
}
|
||||
});
|
||||
|
||||
test('executeHotkeyActionImpl addSessionToWorkspace returns boolean availability defensively', () => {
|
||||
const dialogCalls: unknown[] = [];
|
||||
const makeCtx = (overrides: Record<string, unknown> = {}) => ({
|
||||
activeTabStore: { getActiveTabId: () => 'workspace-1' },
|
||||
editorTabs: [],
|
||||
orderedTabs: [],
|
||||
sessions: [],
|
||||
settings: {},
|
||||
setAddToWorkspaceDialog: (value: unknown) => { dialogCalls.push(value); },
|
||||
toEditorTabId: (id: string) => `editor:${id}`,
|
||||
workspaces: [{ id: 'workspace-1', title: 'Workspace 1' }],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ workspaces: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ setAddToWorkspaceDialog: undefined }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx({ activeTabStore: { getActiveTabId: () => 'session-1' } }), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, []);
|
||||
|
||||
assert.equal(
|
||||
executeHotkeyActionImpl(() => makeCtx(), 'addSessionToWorkspace', {} as KeyboardEvent),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(dialogCalls, [{ mode: 'append', workspaceId: 'workspace-1' }]);
|
||||
});
|
||||
@@ -394,13 +394,8 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
|
||||
// An unavailable action must leave the chord to the terminal.
|
||||
// Broadcast keeps Ctrl/Cmd+B for tmux; the host list keeps Ctrl/Cmd+Shift+B
|
||||
// when the sidebar cannot show; addSessionToWorkspace keeps Ctrl/Cmd+N
|
||||
// when no workspace tab is active. Dispatch once before consuming it.
|
||||
if (
|
||||
binding.action === 'broadcast'
|
||||
|| binding.action === 'toggleHostTree'
|
||||
|| binding.action === 'addSessionToWorkspace'
|
||||
) {
|
||||
// when the sidebar cannot show. Dispatch once before consuming it.
|
||||
if (binding.action === 'broadcast' || binding.action === 'toggleHostTree') {
|
||||
if (executeHotkeyAction(binding.action, e) === true) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -1223,17 +1218,6 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
|
||||
// button, but without having to open QS first.
|
||||
setAddToWorkspaceDialog({ mode: 'create' });
|
||||
break;
|
||||
case 'addSessionToWorkspace': {
|
||||
// Open the same append-mode picker the workspace tab context menu
|
||||
// uses, targeting the currently active workspace. A standalone tab
|
||||
// (or vault/settings) has no workspace to append into, so return false
|
||||
// to leave the chord for the active surface or terminal.
|
||||
const currentId = activeTabStore.getActiveTabId();
|
||||
const activeWs = (workspaces ?? []).find((w) => w.id === currentId);
|
||||
if (!activeWs || typeof setAddToWorkspaceDialog !== 'function') return false;
|
||||
setAddToWorkspaceDialog({ mode: 'append', workspaceId: activeWs.id });
|
||||
return true;
|
||||
}
|
||||
case 'portForwarding':
|
||||
// Navigate to vault and open port forwarding section
|
||||
setActiveTabId('vault');
|
||||
|
||||
@@ -604,37 +604,7 @@ export function AppSideEffects() {
|
||||
});
|
||||
|
||||
// Window controls - must be before update toast effect which uses openSettingsWindow
|
||||
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 { openSettingsWindow } = useWindowControls();
|
||||
const _handleTrayJumpToSession = useEffectEvent((sessionId: string) => {
|
||||
return handleTrayJumpToSessionImpl(() => ({
|
||||
sessionId,
|
||||
@@ -1847,7 +1817,6 @@ export function AppSideEffects() {
|
||||
hostname: result.target.hostname,
|
||||
port: result.target.port,
|
||||
username: result.target.username || undefined,
|
||||
...(result.target.password ? { password: result.target.password } : {}),
|
||||
domain: result.target.domain || undefined,
|
||||
label: result.target.label,
|
||||
rdpContent: result.target.rawRdpFileContent,
|
||||
|
||||
@@ -572,7 +572,6 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
onRequestAddToWorkspace={handleRequestAddToWorkspace}
|
||||
onCloseWorkspace={closeWorkspace}
|
||||
onCloseLogView={closeLogView}
|
||||
onCloseTabsBatch={closeTabsBatch}
|
||||
|
||||
@@ -629,19 +629,12 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Choose a terminal or workspace…',
|
||||
'ai.chat.managerRebindHere': 'Current panel',
|
||||
'ai.chat.managerRebindDone': 'Moved "{title}" to {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Select chats',
|
||||
'ai.chat.managerSelectAll': 'Select all',
|
||||
'ai.chat.managerSelectedCount': '{n} selected',
|
||||
'ai.chat.managerSelectRow': 'Select this chat',
|
||||
'ai.chat.managerRegenerateTitle': 'Regenerate title with AI',
|
||||
'ai.chat.managerExportOne': 'Export this chat',
|
||||
'ai.chat.managerBadgeActive': 'Active',
|
||||
'ai.chat.managerBadgeIdle': 'Idle',
|
||||
'ai.chat.managerMessagesCount': '{n} messages',
|
||||
'ai.chat.managerDeleteTitle': 'Delete this chat?',
|
||||
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.justNow': 'Just now',
|
||||
'ai.chat.minutesAgo': '{n}m ago',
|
||||
'ai.chat.hoursAgo': '{n}h ago',
|
||||
@@ -695,15 +688,6 @@ export const enAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Messages kept per chat',
|
||||
'ai.chatHistory.messageCap.description': 'Maximum number of messages stored per chat (50–2000). Lowering it drops the oldest messages from storage on the next write. Larger values increase storage and cloud-sync size.',
|
||||
'ai.chatHistory.messageCap.unit': 'messages',
|
||||
'ai.chatHistory.autoLlmTitle': 'Auto-generate chat titles',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Use a small one-shot LLM call to write a short title after the first message. Falls back to the first line if unavailable. Local setting only.',
|
||||
'ai.chatHistory.titleModel': 'Title model',
|
||||
'ai.chatHistory.titleModel.description': 'Provider and model used to generate chat titles. Pick a small, cheap model. Defaults to the current Catty model.',
|
||||
'ai.chatHistory.titleModel.none': 'No enabled provider available.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Use current Catty model',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Unavailable',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Select provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Select model',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex main-process handlers are not loaded yet. Fully restart Netcatty, or restart the Electron dev process, then try again.',
|
||||
|
||||
@@ -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",
|
||||
"settings.plugins.github.confirm": "Install disabled",
|
||||
"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.",
|
||||
@@ -431,8 +431,6 @@ export const enCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Show SFTP tab',
|
||||
'settings.vault.showSftpTabDesc': 'Display the standalone SFTP view in the top tab bar. When hidden, use the in-session SFTP side panel instead.',
|
||||
'settings.vault.showHostTreeSidebar': 'Show host list sidebar',
|
||||
'settings.vault.removeTopTabsDragArea': 'Remove the top window-drag area',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'When enabled, remove the draggable space above the tabs so the top edge is available for clicks.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Display the host list sidebar and its top-bar toggle on terminal and editor tabs.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Auto-import system known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'When Vault loads, silently import entries from the OpenSSH known_hosts file. Turn this off to keep Netcatty known hosts separate; Scan System still imports on demand.',
|
||||
@@ -1063,7 +1061,6 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.binding.command-palette': 'Open Command Palette',
|
||||
'settings.shortcuts.binding.quick-switch': 'Quick Switch',
|
||||
'settings.shortcuts.binding.new-workspace': 'New Workspace',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Add Session to Workspace',
|
||||
'settings.shortcuts.binding.snippets': 'Open Snippets',
|
||||
'settings.shortcuts.binding.broadcast': 'Switch the Broadcast Mode',
|
||||
'settings.shortcuts.binding.toggle-side-panel': 'Toggle Side Panel',
|
||||
@@ -1333,8 +1330,6 @@ Highlight the focused split pane:
|
||||
"plugins.sidebar.selectTerminal": "Select an open terminal first.",
|
||||
"plugins.sidebar.loading": "Loading extension page…",
|
||||
"plugins.vault.loading": "Loading plugin page…",
|
||||
"plugins.vault.viewError": "The plugin page failed to render.",
|
||||
"plugins.vault.retry": "Retry",
|
||||
"plugins.interaction.title": "Plugin request",
|
||||
"plugins.interaction.openUrlTitle": "Open external link?",
|
||||
"plugins.interaction.openUrlNote": "This plugin wants to open the following HTTPS URL in your default browser:",
|
||||
@@ -1412,10 +1407,7 @@ 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",
|
||||
"settings.plugins.market.installing": "Installing...",
|
||||
"settings.plugins.market.update": "Update",
|
||||
"settings.plugins.market.updating": "Updating...",
|
||||
"settings.plugins.market.install": "Install this version (disabled)",
|
||||
"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.",
|
||||
@@ -1501,41 +1493,5 @@ Highlight the focused split pane:
|
||||
'plugins.hostActions.managedUnsupported': 'Managed SSH config changes require the Vault host editor.',
|
||||
'plugins.hostActions.failed': 'The request expired, was revoked, or the host changed. Select the host again.',
|
||||
'plugins.hostActions.selectionLimit': 'Select up to 50 current hosts.',
|
||||
'settings.externalEditor.title': 'External Remote Editor',
|
||||
'settings.externalEditor.desc': 'Open remote SSH projects and files directly in local editors such as Zed, VS Code, or Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Preferred editor',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Default local editor used for SFTP context menu actions and terminal open requests.',
|
||||
'settings.externalEditor.executablePath': 'Editor executable',
|
||||
'settings.externalEditor.executablePath.desc': 'Leave empty to auto-detect, or choose the local binary manually.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Auto-detect executable path',
|
||||
'settings.externalEditor.status.configured': 'Custom path',
|
||||
'settings.externalEditor.status.detected': 'Auto-detected',
|
||||
'settings.externalEditor.status.notFound': 'Not detected',
|
||||
'settings.externalEditor.browse': 'Browse…',
|
||||
'settings.externalEditor.resetPath': 'Reset to auto-detect',
|
||||
'settings.externalEditor.redetect': 'Re-detect installed editors',
|
||||
'settings.externalEditor.customArgs': 'Custom arguments',
|
||||
'settings.externalEditor.customArgs.desc': 'Space-separated arguments (placeholders: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'SSH connection mode',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH Bridge reuses your active authenticated session without exposing vault keys or host lists.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH Bridge (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'Direct OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty bridge rule',
|
||||
'settings.externalEditor.sshBridge.desc': 'Adds a single static Host *.netcatty block to your OpenSSH config without writing any hostnames, keys, or passwords.',
|
||||
'settings.externalEditor.sshBridge.install': 'Install bridge rule',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Reinstall rule',
|
||||
'settings.externalEditor.sshBridge.update': 'Update rule',
|
||||
'settings.externalEditor.sshBridge.remove': 'Remove rule',
|
||||
'settings.externalEditor.terminalRequests': 'Allow terminal open requests (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Let remote shells open paths in your configured local editor via commands like `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Enable remote editor commands for Netcatty sessions',
|
||||
'settings.externalEditor.autoSetup.desc': 'Install `zed` / `ncedit` helpers into ~/.netcatty/bin and activate them in PATH for this Netcatty terminal session only, without modifying ~/.bashrc or ~/.zshrc (can also be toggled per host).',
|
||||
'settings.externalEditor.defaultTrust': 'Default host trust',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Permission policy when an unrecognized remote host requests opening a local editor.',
|
||||
'settings.externalEditor.trust.ask': 'Ask every time',
|
||||
'settings.externalEditor.trust.allow': 'Always allow',
|
||||
'settings.externalEditor.trust.deny': 'Always deny',
|
||||
'settings.externalEditor.trustedHosts.host': 'Host',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Policy',
|
||||
|
||||
};
|
||||
@@ -2,8 +2,6 @@ import type { Messages } from '../types';
|
||||
|
||||
export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Current directory: {path}. Change directory',
|
||||
'terminal.gitBranch.current': 'Git branch: {{value}}',
|
||||
'terminal.gitBranch.detached': 'Detached HEAD: {{value}}',
|
||||
'terminal.directory.unknown': 'Directory unknown',
|
||||
'terminal.directory.search': 'Search child directories...',
|
||||
'terminal.directory.directories': 'Directories',
|
||||
@@ -17,8 +15,6 @@ 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.cygwinIntegrationUnavailable': 'Waiting for Cygwin Bash to return to an idle prompt.',
|
||||
'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.',
|
||||
@@ -472,7 +468,6 @@ export const enTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Before restore',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} keys, {snippets} snippets, {notes} notes',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} AI chats, {settings} settings',
|
||||
'cloudSync.localBackups.restore': 'Restore',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Local backup restored.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Restore failed',
|
||||
@@ -623,10 +618,6 @@ export const enTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Export script...',
|
||||
'keychain.export.missingCredentials':
|
||||
'Host has no saved password or key. Please add password credentials to the host first.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'This key has no public key. Open Edit, paste the public key, then try Export and Attach again.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'This key has no public key. Paste it in the key editor before exporting.',
|
||||
'keychain.export.successTitle': 'Export Successful',
|
||||
'keychain.export.successMessage': 'Public key exported and attached to {host}',
|
||||
'keychain.export.failedTitle': 'Export Failed',
|
||||
@@ -703,7 +694,6 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Log:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copy Tab',
|
||||
'tabs.addSessionToWorkspace': 'Add Session to Workspace',
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
@@ -997,12 +987,4 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'Show in every host’s browser.',
|
||||
'terminal.browser.downloadLocation': 'Saved to your Downloads folder',
|
||||
'terminal.browser.saveAs': 'Save as…',
|
||||
'terminal.externalEditor.opened': 'Opened {path} in {editor}',
|
||||
'terminal.externalEditor.failed': 'Failed to open in {editor}',
|
||||
'terminal.externalEditor.prompt.title': 'Open in {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'Remote host {host} requested opening this remote path in {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Deny',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Allow Once',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Always Trust Host',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Remote editor commands configured ({editor})',
|
||||
};
|
||||
@@ -1463,8 +1463,5 @@ export const enVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'This will permanently delete {count} recorded .webm file(s) from this device.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Removed {count} recording file(s).',
|
||||
'settings.remoteDesktopRecordings.hint': 'Recordings are stored locally on this device and never synced to the cloud. Bookmarked logs are protected from automatic cleanup.',
|
||||
'sftp.context.openInExternalEditor': 'Open in {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Enable external editor commands in this session',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Expose `zed` / `ncedit` via ~/.netcatty/bin for this Netcatty terminal session only (including tmux) without modifying ~/.bashrc or ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -629,19 +629,12 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Elegir terminal o espacio de trabajo…',
|
||||
'ai.chat.managerRebindHere': 'Panel actual',
|
||||
'ai.chat.managerRebindDone': 'Se movió «{title}» a {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Seleccionar chats',
|
||||
'ai.chat.managerSelectAll': 'Seleccionar todo',
|
||||
'ai.chat.managerSelectedCount': '{n} seleccionados',
|
||||
'ai.chat.managerSelectRow': 'Seleccionar este chat',
|
||||
'ai.chat.managerRegenerateTitle': 'Regenerar título con IA',
|
||||
'ai.chat.managerExportOne': 'Exportar este chat',
|
||||
'ai.chat.managerBadgeActive': 'Activo',
|
||||
'ai.chat.managerBadgeIdle': 'Inactivo',
|
||||
'ai.chat.managerMessagesCount': '{n} mensajes',
|
||||
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.justNow': 'Ahora mismo',
|
||||
'ai.chat.minutesAgo': 'hace {n} min',
|
||||
'ai.chat.hoursAgo': 'hace {n} h',
|
||||
@@ -695,15 +688,6 @@ export const esAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
|
||||
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
|
||||
'ai.chatHistory.messageCap.unit': 'mensajes',
|
||||
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
|
||||
'ai.chatHistory.titleModel': 'Modelo de título',
|
||||
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'No disponible',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Seleccionar proveedor',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Seleccionar modelo',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Los controladores del proceso principal de Codex aún no están cargados. Reinicia Netcatty por completo o reinicia el proceso de desarrollo de Electron y vuelve a intentarlo.',
|
||||
|
||||
@@ -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",
|
||||
"settings.plugins.github.confirm": "Instalar desactivado",
|
||||
"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.",
|
||||
@@ -431,8 +431,6 @@ export const esCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Mostrar pestaña SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Muestra la vista SFTP independiente en la barra de pestañas superior. Cuando está oculta, usa el panel lateral SFTP dentro de la sesión.',
|
||||
'settings.vault.showHostTreeSidebar': 'Mostrar barra lateral de lista de hosts',
|
||||
'settings.vault.removeTopTabsDragArea': 'Quitar el área superior para arrastrar la ventana',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'Al activarla, quita el espacio de arrastre sobre las pestañas para poder hacer clic en el borde superior.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Muestra la barra lateral de lista de hosts y su alternador en la barra superior en las pestañas de terminal y editor.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Importar automáticamente known_hosts del sistema',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'Cuando se carga el Vault, importa en silencio las entradas del archivo known_hosts de OpenSSH. Desactívalo para mantener los hosts conocidos de Netcatty separados; Escanear sistema sigue importando a pedido.',
|
||||
@@ -1064,7 +1062,6 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.binding.command-palette': 'Abrir paleta de comandos',
|
||||
'settings.shortcuts.binding.quick-switch': 'Cambio rápido',
|
||||
'settings.shortcuts.binding.new-workspace': 'Nuevo espacio de trabajo',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Añadir sesión al espacio de trabajo',
|
||||
'settings.shortcuts.binding.snippets': 'Abrir fragmentos',
|
||||
'settings.shortcuts.binding.broadcast': 'Alternar modo de transmisión',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Alternar la transparencia de la ventana',
|
||||
@@ -1333,8 +1330,6 @@ Resalta el panel dividido enfocado:
|
||||
"plugins.sidebar.selectTerminal": "Selecciona primero un terminal abierto.",
|
||||
"plugins.sidebar.loading": "Cargando página de extensión…",
|
||||
"plugins.vault.loading": "Cargando página del plugin…",
|
||||
"plugins.vault.viewError": "No se pudo renderizar la página del plugin.",
|
||||
"plugins.vault.retry": "Reintentar",
|
||||
"plugins.interaction.title": "Solicitud de complemento",
|
||||
"plugins.interaction.openUrlTitle": "¿Abrir enlace externo?",
|
||||
"plugins.interaction.openUrlNote": "Este complemento solicita abrir la siguiente URL HTTPS en tu navegador predeterminado:",
|
||||
@@ -1412,10 +1407,7 @@ 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",
|
||||
"settings.plugins.market.installing": "Instalando...",
|
||||
"settings.plugins.market.update": "Actualizar",
|
||||
"settings.plugins.market.updating": "Actualizando...",
|
||||
"settings.plugins.market.install": "Instalar esta versión (desactivada)",
|
||||
"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.",
|
||||
@@ -1501,41 +1493,5 @@ Resalta el panel dividido enfocado:
|
||||
'plugins.hostActions.managedUnsupported': 'Los cambios de configuración SSH administrada requieren el editor de equipos de Vault.',
|
||||
'plugins.hostActions.failed': 'La solicitud caducó, se revocó o el equipo cambió. Selecciona el equipo de nuevo.',
|
||||
'plugins.hostActions.selectionLimit': 'Selecciona hasta 50 equipos actuales.',
|
||||
'settings.externalEditor.title': 'Editor remoto externo',
|
||||
'settings.externalEditor.desc': 'Abre proyectos y archivos SSH remotos directamente en editores locales como Zed, VS Code o Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Editor preferido',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Editor local predeterminado para el menú contextual de SFTP y las solicitudes desde el terminal.',
|
||||
'settings.externalEditor.executablePath': 'Ejecutable del editor',
|
||||
'settings.externalEditor.executablePath.desc': 'Déjalo vacío para detectarlo automáticamente o elige el binario local manualmente.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Detectar ruta del ejecutable automáticamente',
|
||||
'settings.externalEditor.status.configured': 'Ruta personalizada',
|
||||
'settings.externalEditor.status.detected': 'Detectado automáticamente',
|
||||
'settings.externalEditor.status.notFound': 'No detectado',
|
||||
'settings.externalEditor.browse': 'Examinar…',
|
||||
'settings.externalEditor.resetPath': 'Restablecer a detección automática',
|
||||
'settings.externalEditor.redetect': 'Volver a detectar editores instalados',
|
||||
'settings.externalEditor.customArgs': 'Argumentos personalizados',
|
||||
'settings.externalEditor.customArgs.desc': 'Argumentos separados por espacios (marcadores: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'Modo de conexión SSH',
|
||||
'settings.externalEditor.connectionMode.desc': 'El puente SSH de Netcatty reutiliza tu sesión autenticada activa sin exponer claves ni listas de equipos.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Puente SSH de Netcatty (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'OpenSSH directo (usuario@host:puerto)',
|
||||
'settings.externalEditor.sshBridge.title': 'Regla OpenSSH *.netcatty',
|
||||
'settings.externalEditor.sshBridge.desc': 'Añade un único bloque estático Host *.netcatty a tu configuración de OpenSSH sin escribir nombres de equipo, claves ni contraseñas.',
|
||||
'settings.externalEditor.sshBridge.install': 'Instalar regla',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Reinstalar regla',
|
||||
'settings.externalEditor.sshBridge.update': 'Actualizar regla',
|
||||
'settings.externalEditor.sshBridge.remove': 'Eliminar regla',
|
||||
'settings.externalEditor.terminalRequests': 'Permitir solicitudes desde el terminal (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Permite que las shells remotas abran rutas en tu editor local configurado mediante comandos como `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Habilitar comandos de editor remoto en sesiones de Netcatty',
|
||||
'settings.externalEditor.autoSetup.desc': 'Instala helpers `zed` / `ncedit` en ~/.netcatty/bin y los activa en el PATH solo para esta sesión de Netcatty, sin modificar ~/.bashrc ni ~/.zshrc (también configurable por equipo).',
|
||||
'settings.externalEditor.defaultTrust': 'Confianza predeterminada del equipo',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Política de permisos cuando un equipo remoto no reconocido solicita abrir un editor local.',
|
||||
'settings.externalEditor.trust.ask': 'Preguntar siempre',
|
||||
'settings.externalEditor.trust.allow': 'Permitir siempre',
|
||||
'settings.externalEditor.trust.deny': 'Denegar siempre',
|
||||
'settings.externalEditor.trustedHosts.host': 'Equipo',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Política',
|
||||
|
||||
};
|
||||
@@ -2,8 +2,6 @@ import type { Messages } from '../types';
|
||||
|
||||
export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio',
|
||||
'terminal.gitBranch.current': 'Rama de Git: {{value}}',
|
||||
'terminal.gitBranch.detached': 'HEAD separado: {{value}}',
|
||||
'terminal.directory.unknown': 'Directorio desconocido',
|
||||
'terminal.directory.search': 'Buscar subdirectorios...',
|
||||
'terminal.directory.directories': 'Directorios',
|
||||
@@ -17,8 +15,6 @@ 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.cygwinIntegrationUnavailable': 'Esperando que Bash de Cygwin vuelva a un indicador inactivo.',
|
||||
'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.',
|
||||
@@ -472,7 +468,6 @@ export const esTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Antes de la restauración',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} hosts, {keys} claves, {snippets} snippets, {notes} notas',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} chats de IA, {settings} ajustes',
|
||||
'cloudSync.localBackups.restore': 'Restaurar',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Copia de seguridad local restaurada.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Falló la restauración',
|
||||
@@ -623,10 +618,6 @@ export const esTerminalMessages: Messages = {
|
||||
'keychain.export.scriptPlaceholder': 'Script de exportación...',
|
||||
'keychain.export.missingCredentials':
|
||||
'El host no tiene contraseña ni clave guardadas. Primero agrega credenciales de contraseña al host.',
|
||||
'keychain.export.missingPublicKey':
|
||||
'Esta clave no tiene clave pública. Ábrela en Editar, pega la clave pública y vuelve a intentar Exportar y adjuntar.',
|
||||
'keychain.export.missingPublicKeyNote':
|
||||
'Esta clave no tiene clave pública. Pégala en el editor de claves antes de exportar.',
|
||||
'keychain.export.successTitle': 'Exportación exitosa',
|
||||
'keychain.export.successMessage': 'Clave pública exportada y adjuntada a {host}',
|
||||
'keychain.export.failedTitle': 'Falló la exportación',
|
||||
@@ -705,7 +696,6 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Registro:',
|
||||
'tabs.logLocal': 'Local',
|
||||
'tabs.copyTab': 'Copiar pestaña',
|
||||
'tabs.addSessionToWorkspace': 'Añadir sesión al espacio de trabajo',
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
@@ -999,12 +989,4 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'Mostrar en el navegador de todos los hosts.',
|
||||
'terminal.browser.downloadLocation': 'Guardado en la carpeta Descargas',
|
||||
'terminal.browser.saveAs': 'Guardar como…',
|
||||
'terminal.externalEditor.opened': 'Se abrió {path} en {editor}',
|
||||
'terminal.externalEditor.failed': 'No se pudo abrir en {editor}',
|
||||
'terminal.externalEditor.prompt.title': '¿Abrir en {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'El equipo remoto {host} solicitó abrir esta ruta remota en {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Denegar',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Permitir una vez',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Confiar siempre en este equipo',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Comandos de editor remoto configurados ({editor})',
|
||||
};
|
||||
@@ -1463,8 +1463,5 @@ export const esVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'Se eliminarán permanentemente {count} archivo(s) .webm grabados en este dispositivo.',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Se eliminaron {count} archivo(s) de grabación.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Las grabaciones se guardan solo localmente en este dispositivo y nunca se sincronizan en la nube. Los registros guardados están protegidos frente a la limpieza automática.',
|
||||
'sftp.context.openInExternalEditor': 'Abrir en {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Habilitar comandos de editor externo en esta sesión',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Activa `zed` / `ncedit` desde ~/.netcatty/bin solo para esta sesión de terminal de Netcatty (incluido tmux), sin modificar ~/.bashrc ni ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -228,25 +228,3 @@ test("AI tool output limit settings copy is localized across all five locales",
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
|
||||
test("LLM chat title settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.chatHistory.autoLlmTitle",
|
||||
"ai.chatHistory.autoLlmTitle.description",
|
||||
"ai.chatHistory.titleModel",
|
||||
"ai.chatHistory.titleModel.description",
|
||||
"ai.chatHistory.titleModel.none",
|
||||
"ai.chatHistory.titleModel.useCurrentCatty",
|
||||
"ai.chatHistory.titleModel.unavailable",
|
||||
"ai.chatHistory.titleModel.providerPlaceholder",
|
||||
"ai.chatHistory.titleModel.modelPlaceholder",
|
||||
] as const;
|
||||
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -628,19 +628,12 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': 'Выберите терминал или рабочее пространство…',
|
||||
'ai.chat.managerRebindHere': 'Текущая панель',
|
||||
'ai.chat.managerRebindDone': 'Чат «{title}» перемещён в {target}.',
|
||||
'ai.chat.managerToggleSelection': 'Выбрать чаты',
|
||||
'ai.chat.managerSelectAll': 'Выбрать все',
|
||||
'ai.chat.managerSelectedCount': 'Выбрано: {n}',
|
||||
'ai.chat.managerSelectRow': 'Выбрать этот чат',
|
||||
'ai.chat.managerRegenerateTitle': 'Пересоздать заголовок через ИИ',
|
||||
'ai.chat.managerExportOne': 'Экспортировать этот чат',
|
||||
'ai.chat.managerBadgeActive': 'Активен',
|
||||
'ai.chat.managerBadgeIdle': 'Простой',
|
||||
'ai.chat.managerMessagesCount': '{n} сообщений',
|
||||
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.justNow': 'Только что',
|
||||
'ai.chat.minutesAgo': '{n}м назад',
|
||||
'ai.chat.hoursAgo': '{n}ч назад',
|
||||
@@ -694,15 +687,6 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
|
||||
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
|
||||
'ai.chatHistory.messageCap.unit': 'сообщений',
|
||||
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
|
||||
'ai.chatHistory.titleModel': 'Модель для заголовков',
|
||||
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': 'Выбрать провайдер',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': 'Выбрать модель',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Обработчики главного процесса Codex ещё не загружены. Полностью перезапустите Netcatty или dev-процесс Electron и попробуйте снова.',
|
||||
|
||||
@@ -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 недоступна в этом сеансе.",
|
||||
@@ -430,8 +430,6 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': 'Показывать вкладку SFTP',
|
||||
'settings.vault.showSftpTabDesc': 'Показывать отдельный SFTP-вид в верхней панели вкладок. Если скрыто, используйте боковую панель SFTP внутри сессии.',
|
||||
'settings.vault.showHostTreeSidebar': 'Показывать боковую панель хостов',
|
||||
'settings.vault.removeTopTabsDragArea': 'Убрать верхнюю область перетаскивания окна',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': 'При включении удаляется область перетаскивания над вкладками, чтобы по верхнему краю можно было нажимать.',
|
||||
'settings.vault.showHostTreeSidebarDesc': 'Показывать список хостов и кнопку в верхней панели для вкладок терминала и редактора.',
|
||||
'settings.vault.autoImportSystemKnownHosts': 'Автоимпорт системного known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': 'При открытии хранилища тихо импортировать записи из OpenSSH known_hosts. Отключите, чтобы держать известные хосты Netcatty отдельно; кнопка «Сканировать систему» по-прежнему импортирует вручную.',
|
||||
@@ -1048,7 +1046,6 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': 'Открыть палитру команд',
|
||||
'settings.shortcuts.binding.quick-switch': 'Быстрое переключение',
|
||||
'settings.shortcuts.binding.new-workspace': 'Новая рабочая область',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': 'Добавить сессию в рабочую область',
|
||||
'settings.shortcuts.binding.snippets': 'Открыть сниппеты',
|
||||
'settings.shortcuts.binding.broadcast': 'Переключить режим трансляции',
|
||||
'settings.shortcuts.binding.toggle-opacity': 'Переключить прозрачность окна',
|
||||
@@ -1274,8 +1271,6 @@ export const ruCoreMessages: Messages = {
|
||||
"plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.",
|
||||
"plugins.sidebar.loading": "Загрузка страницы расширения…",
|
||||
"plugins.vault.loading": "Загрузка страницы плагина…",
|
||||
"plugins.vault.viewError": "Не удалось отобразить страницу плагина.",
|
||||
"plugins.vault.retry": "Повторить",
|
||||
"plugins.interaction.title": "Запрос плагина",
|
||||
"plugins.interaction.openUrlTitle": "Открыть внешнюю ссылку?",
|
||||
"plugins.interaction.openUrlNote": "Этот плагин запрашивает открытие следующего HTTPS-адреса в браузере по умолчанию:",
|
||||
@@ -1353,10 +1348,7 @@ export const ruCoreMessages: Messages = {
|
||||
"settings.plugins.market.title": "Каталог",
|
||||
"settings.plugins.market.note": "Отобранные плагины с открытым кодом. Проверка не гарантирует безопасность. Обновления выполняются вручную.",
|
||||
"settings.plugins.market.back": "Все плагины",
|
||||
"settings.plugins.market.install": "Установить",
|
||||
"settings.plugins.market.installing": "Установка...",
|
||||
"settings.plugins.market.update": "Обновить",
|
||||
"settings.plugins.market.updating": "Обновление...",
|
||||
"settings.plugins.market.install": "Установить эту версию (отключённой)",
|
||||
"settings.plugins.market.installNote": "Установленная версия будет заменена и остановлена. Проверьте разрешения перед включением.",
|
||||
"settings.plugins.market.sourceOnly": "Пример из этого проекта. Соберите локальной CLI и импортируйте .ncpkg; готовый пакет для скачивания не опубликован.",
|
||||
"settings.plugins.market.readmeNote": "Зафиксирован указанный коммит. HTML не выполняется, внешние изображения не загружаются. Текст автора плагина.",
|
||||
@@ -1442,40 +1434,4 @@ export const ruCoreMessages: Messages = {
|
||||
'plugins.hostActions.managedUnsupported': 'Изменяйте управляемые настройки SSH в редакторе хостов Vault.',
|
||||
'plugins.hostActions.failed': 'Запрос истёк, был отозван или хост изменился. Выберите хост заново.',
|
||||
'plugins.hostActions.selectionLimit': 'Выберите не более 50 текущих хостов.',
|
||||
'settings.externalEditor.title': 'Внешний удалённый редактор',
|
||||
'settings.externalEditor.desc': 'Открывайте удалённые SSH-проекты и файлы напрямую в локальных редакторах, таких как Zed, VS Code или Cursor.',
|
||||
'settings.externalEditor.preferredEditor': 'Предпочитаемый редактор',
|
||||
'settings.externalEditor.preferredEditor.desc': 'Локальный редактор по умолчанию для контекстного меню SFTP и запросов из терминала.',
|
||||
'settings.externalEditor.executablePath': 'Исполняемый файл редактора',
|
||||
'settings.externalEditor.executablePath.desc': 'Оставьте пустым для автоопределения или выберите локальный файл вручную.',
|
||||
'settings.externalEditor.executablePath.placeholder': 'Автоопределение пути к файлу',
|
||||
'settings.externalEditor.status.configured': 'Указан вручную',
|
||||
'settings.externalEditor.status.detected': 'Определён автоматически',
|
||||
'settings.externalEditor.status.notFound': 'Не найден',
|
||||
'settings.externalEditor.browse': 'Обзор…',
|
||||
'settings.externalEditor.resetPath': 'Сбросить на автоопределение',
|
||||
'settings.externalEditor.redetect': 'Повторить поиск редакторов',
|
||||
'settings.externalEditor.customArgs': 'Пользовательские аргументы',
|
||||
'settings.externalEditor.customArgs.desc': 'Аргументы через пробел (подстановки: {sshUri}, {sshTarget}, {remotePath}, {encodedPath}, {kind}).',
|
||||
'settings.externalEditor.connectionMode': 'Режим SSH-подключения',
|
||||
'settings.externalEditor.connectionMode.desc': 'SSH-мост Netcatty переиспользует активную аутентифицированную сессию без раскрытия ключей или списка хостов.',
|
||||
'settings.externalEditor.connectionMode.bridge': 'SSH-мост Netcatty (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': 'Прямой OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'Правило OpenSSH *.netcatty',
|
||||
'settings.externalEditor.sshBridge.desc': 'Добавляет один статический блок Host *.netcatty в конфиг OpenSSH без записи хостов, ключей и паролей.',
|
||||
'settings.externalEditor.sshBridge.install': 'Установить правило',
|
||||
'settings.externalEditor.sshBridge.reinstall': 'Переустановить правило',
|
||||
'settings.externalEditor.sshBridge.update': 'Обновить правило',
|
||||
'settings.externalEditor.sshBridge.remove': 'Удалить правило',
|
||||
'settings.externalEditor.terminalRequests': 'Разрешить запросы из терминала (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': 'Позволяет удалённой оболочке открывать пути в локальном редакторе командами вроде `zed .`.',
|
||||
'settings.externalEditor.autoSetup': 'Включить команды редактора только в сессиях Netcatty',
|
||||
'settings.externalEditor.autoSetup.desc': 'Устанавливает утилиты `zed` / `ncedit` в ~/.netcatty/bin и добавляет их в PATH только для этой сессии Netcatty, не изменяя ~/.bashrc и ~/.zshrc (можно задать отдельно для хоста).',
|
||||
'settings.externalEditor.defaultTrust': 'Доверие хостам по умолчанию',
|
||||
'settings.externalEditor.defaultTrust.desc': 'Политика разрешений, когда неизвестный удалённый хост запрашивает открытие локального редактора.',
|
||||
'settings.externalEditor.trust.ask': 'Спрашивать каждый раз',
|
||||
'settings.externalEditor.trust.allow': 'Всегда разрешать',
|
||||
'settings.externalEditor.trust.deny': 'Всегда запрещать',
|
||||
'settings.externalEditor.trustedHosts.host': 'Хост',
|
||||
'settings.externalEditor.trustedHosts.policy': 'Политика',
|
||||
};
|
||||
@@ -2,8 +2,6 @@ import type { Messages } from '../types';
|
||||
|
||||
export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
|
||||
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
|
||||
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
|
||||
'terminal.directory.unknown': 'Каталог неизвестен',
|
||||
'terminal.directory.search': 'Поиск подкаталогов...',
|
||||
'terminal.directory.directories': 'Каталоги',
|
||||
@@ -17,8 +15,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.integrationUnavailable': 'Интеграция каталогов PowerShell не готова. Проверьте параметры запуска и политику выполнения.',
|
||||
'terminal.directory.cmdIntegrationUnavailable': 'Ожидание данных о каталоге от исходного сеанса командной строки.',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': 'Ожидание доступного каталога исходного сеанса Git Bash.',
|
||||
'terminal.directory.wslIntegrationUnavailable': 'Ожидание готовности Bash в выбранном дистрибутиве WSL.',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': 'Ожидание готовности Bash в Cygwin.',
|
||||
'terminal.directory.nonFilesystem': 'Текущее расположение PowerShell не является каталогом файловой системы.',
|
||||
'terminal.directory.accessDenied': 'Нет разрешения на просмотр содержимого этого каталога.',
|
||||
'terminal.directory.busy': 'Дождитесь пустой командной строки.',
|
||||
@@ -492,7 +488,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': 'Перед восстановлением',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} хостов, {keys} ключей, {snippets} сниппетов, {notes} заметок',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} чатов ИИ, {settings} настроек',
|
||||
'cloudSync.localBackups.restore': 'Восстановить',
|
||||
'cloudSync.localBackups.restoreSuccess': 'Локальная резервная копия восстановлена.',
|
||||
'cloudSync.localBackups.restoreFailedTitle': 'Ошибка восстановления',
|
||||
@@ -640,8 +635,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'keychain.export.script': 'Скрипт *',
|
||||
'keychain.export.scriptPlaceholder': 'Скрипт экспорта...',
|
||||
'keychain.export.missingCredentials': 'У хоста нет сохранённого пароля или ключа. Сначала добавьте в хост учётные данные с паролем.',
|
||||
'keychain.export.missingPublicKey': 'У этого ключа нет публичного ключа. Откройте «Редактировать», вставьте публичный ключ и снова нажмите «Экспортировать и привязать».',
|
||||
'keychain.export.missingPublicKeyNote': 'У этого ключа нет публичного ключа. Вставьте его в редакторе ключа перед экспортом.',
|
||||
'keychain.export.successTitle': 'Экспорт выполнен успешно',
|
||||
'keychain.export.successMessage': 'Публичный ключ экспортирован и привязан к {host}',
|
||||
'keychain.export.failedTitle': 'Ошибка экспорта',
|
||||
@@ -718,7 +711,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': 'Журнал:',
|
||||
'tabs.logLocal': 'Локальный',
|
||||
'tabs.copyTab': 'Копировать вкладку',
|
||||
'tabs.addSessionToWorkspace': 'Добавить сессию в эту рабочую область',
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
@@ -1011,12 +1003,4 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': 'В браузерах всех хостов.',
|
||||
'terminal.browser.downloadLocation': 'Файлы сохраняются в папку «Загрузки»',
|
||||
'terminal.browser.saveAs': 'Сохранить как…',
|
||||
'terminal.externalEditor.opened': 'Открыто {path} в {editor}',
|
||||
'terminal.externalEditor.failed': 'Не удалось открыть в {editor}',
|
||||
'terminal.externalEditor.prompt.title': 'Открыть в {editor}?',
|
||||
'terminal.externalEditor.prompt.desc': 'Удалённый хост {host} запросил открытие этого пути в {editor}:',
|
||||
'terminal.externalEditor.prompt.deny': 'Отклонить',
|
||||
'terminal.externalEditor.prompt.allowOnce': 'Разрешить один раз',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': 'Всегда доверять хосту',
|
||||
'terminal.externalEditor.autoSetupConfigured': 'Команды удалённого редактора настроены ({editor})',
|
||||
};
|
||||
@@ -1482,8 +1482,5 @@ export const ruVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': 'С этого устройства будут безвозвратно удалены файлы .webm ({count}).',
|
||||
'settings.remoteDesktopRecordings.clearResult': 'Удалено файлов записей: {count}.',
|
||||
'settings.remoteDesktopRecordings.hint': 'Записи хранятся только локально на этом устройстве и не синхронизируются с облаком. Закреплённые журналы защищены от автоматической очистки.',
|
||||
'sftp.context.openInExternalEditor': 'Открыть в {editor}',
|
||||
'hostDetails.externalEditorShellIntegration': 'Включить команды внешнего редактора в этой сессии',
|
||||
'hostDetails.externalEditorShellIntegration.desc': 'Добавляет `zed` / `ncedit` из ~/.netcatty/bin в PATH только для этой сессии терминала Netcatty (включая tmux), не изменяя ~/.bashrc и ~/.zshrc.',
|
||||
|
||||
};
|
||||
@@ -629,19 +629,12 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': '选择目标终端或工作区…',
|
||||
'ai.chat.managerRebindHere': '当前面板',
|
||||
'ai.chat.managerRebindDone': '已将“{title}”移动到 {target}。',
|
||||
'ai.chat.managerToggleSelection': '选择会话',
|
||||
'ai.chat.managerSelectAll': '全选',
|
||||
'ai.chat.managerSelectedCount': '已选 {n} 个',
|
||||
'ai.chat.managerSelectRow': '选择此会话',
|
||||
'ai.chat.managerRegenerateTitle': '用 AI 重新生成标题',
|
||||
'ai.chat.managerExportOne': '导出此会话',
|
||||
'ai.chat.managerBadgeActive': '使用中',
|
||||
'ai.chat.managerBadgeIdle': '空闲',
|
||||
'ai.chat.managerMessagesCount': '{n} 条消息',
|
||||
'ai.chat.managerDeleteTitle': '删除此会话?',
|
||||
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
|
||||
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.justNow': '刚刚',
|
||||
'ai.chat.minutesAgo': '{n}分钟前',
|
||||
'ai.chat.hoursAgo': '{n}小时前',
|
||||
@@ -695,15 +688,6 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': '每个会话保留的消息数',
|
||||
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '条消息',
|
||||
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
|
||||
'ai.chatHistory.titleModel': '标题模型',
|
||||
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '不可用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '选择 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '选择模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主进程处理器尚未加载。请完全重启 Netcatty 或重启 Electron 开发进程,然后重试。',
|
||||
|
||||
@@ -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 安装插件。",
|
||||
@@ -438,8 +438,6 @@ export const zhCNCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '显示 SFTP 标签页',
|
||||
'settings.vault.showSftpTabDesc': '在顶部标签栏显示独立的 SFTP 视图。关闭后可改用会话内左侧的 SFTP 侧栏。',
|
||||
'settings.vault.showHostTreeSidebar': '显示主机列表侧栏',
|
||||
'settings.vault.removeTopTabsDragArea': '移除顶部窗口拖动区域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '开启后移除标签页上方的拖动空白区域,让顶部可用于点击标签页和窗口按钮。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在终端和编辑器标签页显示主机列表侧栏及顶部开关。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自动导入系统 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '打开主机库时静默导入 OpenSSH known_hosts 中的记录。关闭后,Netcatty 已知主机与系统信任库保持独立;仍可通过「扫描系统」手动导入。',
|
||||
@@ -1249,8 +1247,6 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"plugins.sidebar.selectTerminal": "请先选择已打开的终端。",
|
||||
"plugins.sidebar.loading": "正在加载扩展页面…",
|
||||
"plugins.vault.loading": "正在加载插件页面…",
|
||||
"plugins.vault.viewError": "插件页面渲染失败。",
|
||||
"plugins.vault.retry": "重试",
|
||||
"plugins.interaction.title": "插件请求",
|
||||
"plugins.interaction.openUrlTitle": "打开外部链接?",
|
||||
"plugins.interaction.openUrlNote": "此插件请求在默认浏览器中打开以下 HTTPS 链接:",
|
||||
@@ -1328,10 +1324,7 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
"settings.plugins.market.title": "插件市场",
|
||||
"settings.plugins.market.note": "精选开源插件。审核不代表安全认证,更新由你手动确认。",
|
||||
"settings.plugins.market.back": "所有插件",
|
||||
"settings.plugins.market.install": "安装",
|
||||
"settings.plugins.market.installing": "安装中...",
|
||||
"settings.plugins.market.update": "更新",
|
||||
"settings.plugins.market.updating": "更新中...",
|
||||
"settings.plugins.market.install": "安装此版本(保持停用)",
|
||||
"settings.plugins.market.installNote": "这会替换并停止已安装版本。请在已安装列表检查权限后再启用。",
|
||||
"settings.plugins.market.sourceOnly": "第一方源码示例。请用本地 CLI 构建并导入 .ncpkg;尚未发布可下载发行包。",
|
||||
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不执行,远程图片不加载。内容由插件作者提供。",
|
||||
@@ -1417,41 +1410,5 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'plugins.hostActions.managedUnsupported': '受管理的 SSH 配置变更需在 Vault 主机编辑器中完成。',
|
||||
'plugins.hostActions.failed': '请求已过期、被撤销或主机已改变。请重新选择主机。',
|
||||
'plugins.hostActions.selectionLimit': '最多选择 50 个当前主机。',
|
||||
'settings.externalEditor.title': '外部远程编辑器',
|
||||
'settings.externalEditor.desc': '直接在本地编辑器(如 Zed、VS Code 或 Cursor)中打开远程 SSH 项目和文件。',
|
||||
'settings.externalEditor.preferredEditor': '首选编辑器',
|
||||
'settings.externalEditor.preferredEditor.desc': 'SFTP 右键菜单和终端打开请求默认使用的本地编辑器。',
|
||||
'settings.externalEditor.executablePath': '编辑器可执行文件',
|
||||
'settings.externalEditor.executablePath.desc': '留空以自动检测,或手动选择本地程序路径。',
|
||||
'settings.externalEditor.executablePath.placeholder': '自动检测可执行文件路径',
|
||||
'settings.externalEditor.status.configured': '已自定义路径',
|
||||
'settings.externalEditor.status.detected': '已自动检测',
|
||||
'settings.externalEditor.status.notFound': '未检测到',
|
||||
'settings.externalEditor.browse': '浏览…',
|
||||
'settings.externalEditor.resetPath': '重置为自动检测',
|
||||
'settings.externalEditor.redetect': '重新检测已安装的编辑器',
|
||||
'settings.externalEditor.customArgs': '自定义参数',
|
||||
'settings.externalEditor.customArgs.desc': '以空格分隔的参数列表(支持占位符:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
|
||||
'settings.externalEditor.connectionMode': 'SSH 连接模式',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 桥接会直接复用当前已认证会话,无需向磁盘导出私钥或主机列表。',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 桥接 (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': '直连 OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 桥接规则',
|
||||
'settings.externalEditor.sshBridge.desc': '仅在 OpenSSH 配置中写入单个静态 Host *.netcatty 规则块,不包含任何主机名、私钥或密码。',
|
||||
'settings.externalEditor.sshBridge.install': '安装桥接规则',
|
||||
'settings.externalEditor.sshBridge.reinstall': '重新安装规则',
|
||||
'settings.externalEditor.sshBridge.update': '更新规则',
|
||||
'settings.externalEditor.sshBridge.remove': '移除规则',
|
||||
'settings.externalEditor.terminalRequests': '允许终端发起打开请求 (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': '允许远程 Shell 通过 `zed .` 等命令在本地编辑器中打开远程路径。',
|
||||
'settings.externalEditor.autoSetup': '仅在 Netcatty 会话中启用远程编辑器命令',
|
||||
'settings.externalEditor.autoSetup.desc': '将 `zed` / `ncedit` 脚本安装到 ~/.netcatty/bin,并仅在当前 Netcatty 终端会话的 PATH 中生效,不修改 ~/.bashrc 或 ~/.zshrc(也可按主机单独开关)。',
|
||||
'settings.externalEditor.defaultTrust': '默认主机信任策略',
|
||||
'settings.externalEditor.defaultTrust.desc': '未单独配置信任规则的远程主机发起打开编辑器请求时的处理方式。',
|
||||
'settings.externalEditor.trust.ask': '每次询问',
|
||||
'settings.externalEditor.trust.allow': '始终允许',
|
||||
'settings.externalEditor.trust.deny': '始终拒绝',
|
||||
'settings.externalEditor.trustedHosts.host': '主机',
|
||||
'settings.externalEditor.trustedHosts.policy': '策略',
|
||||
|
||||
};
|
||||
@@ -2,8 +2,6 @@ import type { Messages } from '../types';
|
||||
|
||||
export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '当前目录:{path}。更改目录',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
|
||||
'terminal.directory.unknown': '目录未知',
|
||||
'terminal.directory.search': '搜索当前目录下的文件夹…',
|
||||
'terminal.directory.directories': '目录',
|
||||
@@ -17,8 +15,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目录集成未就绪,启动参数或执行策略可能阻止了加载。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 会话报告当前目录。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 会话中的可访问目录。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所选 WSL 发行版中的 Bash 返回空闲提示符。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回空闲提示符。',
|
||||
'terminal.directory.nonFilesystem': '当前 PowerShell 位置不是文件系统目录。',
|
||||
'terminal.directory.accessDenied': '没有权限列出此目录。',
|
||||
'terminal.directory.busy': '请等待终端回到空命令提示符。',
|
||||
@@ -633,7 +629,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '打开命令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切换',
|
||||
'settings.shortcuts.binding.new-workspace': '新建工作区',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '添加会话到工作区',
|
||||
'settings.shortcuts.binding.snippets': '打开代码片段',
|
||||
'settings.shortcuts.binding.broadcast': '切换广播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切换窗口透明度',
|
||||
@@ -723,8 +718,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'keychain.export.script': '脚本 *',
|
||||
'keychain.export.scriptPlaceholder': '导出脚本...',
|
||||
'keychain.export.missingCredentials': '主机未保存密码或密钥。请先为该主机添加密码凭据。',
|
||||
'keychain.export.missingPublicKey': '此密钥没有公钥。请先在编辑页粘贴公钥,然后再试「导出并绑定」。',
|
||||
'keychain.export.missingPublicKeyNote': '此密钥没有公钥。请先在密钥编辑页粘贴公钥,然后再导出。',
|
||||
'keychain.export.successTitle': '导出成功',
|
||||
'keychain.export.successMessage': '已导出公钥并绑定到 {host}',
|
||||
'keychain.export.failedTitle': '导出失败',
|
||||
@@ -801,7 +794,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日志:',
|
||||
'tabs.logLocal': '本地',
|
||||
'tabs.copyTab': '复制标签页',
|
||||
'tabs.addSessionToWorkspace': '在此工作区添加会话',
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
@@ -1095,12 +1087,4 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': '在每台主机的浏览器中显示。',
|
||||
'terminal.browser.downloadLocation': '文件保存在系统“下载”文件夹',
|
||||
'terminal.browser.saveAs': '另存为…',
|
||||
'terminal.externalEditor.opened': '已在 {editor} 中打开 {path}',
|
||||
'terminal.externalEditor.failed': '无法在 {editor} 中打开',
|
||||
'terminal.externalEditor.prompt.title': '在 {editor} 中打开?',
|
||||
'terminal.externalEditor.prompt.desc': '远程主机 {host} 请求在 {editor} 中打开以下远程路径:',
|
||||
'terminal.externalEditor.prompt.deny': '拒绝',
|
||||
'terminal.externalEditor.prompt.allowOnce': '仅允许本次',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': '始终信任此主机',
|
||||
'terminal.externalEditor.autoSetupConfigured': '已配置远程编辑器命令 ({editor})',
|
||||
};
|
||||
@@ -848,7 +848,6 @@ export const zhCNVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': '恢复前',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} 台主机,{keys} 个密钥,{snippets} 个代码片段,{notes} 条笔记',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} 个 AI 会话,{settings} 项设置',
|
||||
'cloudSync.localBackups.restore': '恢复',
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢复本地备份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢复失败',
|
||||
@@ -1428,8 +1427,5 @@ export const zhCNVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '将从此设备永久删除 {count} 个 .webm 录屏文件。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已删除 {count} 个录屏文件。',
|
||||
'settings.remoteDesktopRecordings.hint': '录屏文件仅保存在本设备本地,绝不上传云同步;已收藏的连接日志录屏不会在自动清理中被删除。',
|
||||
'sftp.context.openInExternalEditor': '在 {editor} 中打开',
|
||||
'hostDetails.externalEditorShellIntegration': '在此会话中启用外部编辑器命令',
|
||||
'hostDetails.externalEditorShellIntegration.desc': '通过 ~/.netcatty/bin 仅在当前 Netcatty 终端会话中启用 `zed` / `ncedit`(支持 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
|
||||
|
||||
};
|
||||
@@ -628,19 +628,12 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.managerRebindPick': '選擇目標終端或工作區…',
|
||||
'ai.chat.managerRebindHere': '目前面板',
|
||||
'ai.chat.managerRebindDone': '已將「{title}」移動到 {target}。',
|
||||
'ai.chat.managerToggleSelection': '選擇工作階段',
|
||||
'ai.chat.managerSelectAll': '全選',
|
||||
'ai.chat.managerSelectedCount': '已選 {n} 個',
|
||||
'ai.chat.managerSelectRow': '選擇此工作階段',
|
||||
'ai.chat.managerRegenerateTitle': '用 AI 重新產生標題',
|
||||
'ai.chat.managerExportOne': '匯出此會話',
|
||||
'ai.chat.managerBadgeActive': '使用中',
|
||||
'ai.chat.managerBadgeIdle': '閒置',
|
||||
'ai.chat.managerMessagesCount': '{n} 則訊息',
|
||||
'ai.chat.managerDeleteTitle': '刪除此會話?',
|
||||
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
|
||||
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.justNow': '剛剛',
|
||||
'ai.chat.minutesAgo': '{n}分鐘前',
|
||||
'ai.chat.hoursAgo': '{n}小時前',
|
||||
@@ -694,15 +687,6 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
|
||||
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '則訊息',
|
||||
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
|
||||
'ai.chatHistory.titleModel': '標題模型',
|
||||
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '無法使用',
|
||||
'ai.chatHistory.titleModel.providerPlaceholder': '選擇 provider',
|
||||
'ai.chatHistory.titleModel.modelPlaceholder': '選擇模型',
|
||||
|
||||
// AI Error
|
||||
'ai.codex.bridgeError': 'Codex 主行程處理器尚未載入。請完全重新啟動 Netcatty 或重新啟動 Electron 開發行程,然後重試。',
|
||||
|
||||
@@ -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 安裝外掛。",
|
||||
@@ -438,8 +438,6 @@ export const zhTWCoreMessages: Messages = {
|
||||
'settings.vault.showSftpTab': '顯示 SFTP 分頁',
|
||||
'settings.vault.showSftpTabDesc': '在頂部分頁列顯示獨立的 SFTP 檢視。關閉後可改用工作階段內左側的 SFTP 側欄。',
|
||||
'settings.vault.showHostTreeSidebar': '顯示主機列表側欄',
|
||||
'settings.vault.removeTopTabsDragArea': '移除頂部視窗拖曳區域',
|
||||
'settings.vault.removeTopTabsDragAreaDesc': '開啟後移除分頁上方的拖曳空白區域,讓頂部可供點擊分頁與視窗按鈕。',
|
||||
'settings.vault.showHostTreeSidebarDesc': '在終端和編輯器分頁顯示主機列表側欄及頂部開關。',
|
||||
'settings.vault.autoImportSystemKnownHosts': '自動匯入系統 known_hosts',
|
||||
'settings.vault.autoImportSystemKnownHostsDesc': '開啟主機庫時靜默匯入 OpenSSH known_hosts 中的記錄。關閉後,Netcatty 已知主機與系統信任庫保持獨立;仍可透過「掃描系統」手動匯入。',
|
||||
@@ -1250,8 +1248,6 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。",
|
||||
"plugins.sidebar.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.loading": "正在載入擴充功能頁面…",
|
||||
"plugins.vault.viewError": "擴充功能頁面無法顯示。",
|
||||
"plugins.vault.retry": "重試",
|
||||
"plugins.interaction.title": "外掛請求",
|
||||
"plugins.interaction.openUrlTitle": "開啟外部連結?",
|
||||
"plugins.interaction.openUrlNote": "此外掛請求在預設瀏覽器中開啟以下 HTTPS 連結:",
|
||||
@@ -1358,10 +1354,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
"settings.plugins.market.title": "外掛市集",
|
||||
"settings.plugins.market.note": "精選開源外掛。審核不代表安全認證,更新由你手動確認。",
|
||||
"settings.plugins.market.back": "所有外掛",
|
||||
"settings.plugins.market.install": "安裝",
|
||||
"settings.plugins.market.installing": "安裝中...",
|
||||
"settings.plugins.market.update": "更新",
|
||||
"settings.plugins.market.updating": "更新中...",
|
||||
"settings.plugins.market.install": "安裝此版本(保持停用)",
|
||||
"settings.plugins.market.installNote": "這會替換並停止已安裝版本。請在已安裝列表檢查權限後再啟用。",
|
||||
"settings.plugins.market.sourceOnly": "第一方源碼示例。請用本地 CLI 構建並匯入 .ncpkg;尚未發佈可下載發行包。",
|
||||
"settings.plugins.market.readmeNote": "固定到上面的提交。HTML 不執行,遠端圖片不載入。內容由外掛作者提供。",
|
||||
@@ -1418,40 +1411,4 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'plugins.hostActions.managedUnsupported': '受管理的 SSH 設定變更需在 Vault 主機編輯器中完成。',
|
||||
'plugins.hostActions.failed': '請求已過期、被撤銷或主機已變更。請重新選擇主機。',
|
||||
'plugins.hostActions.selectionLimit': '最多選擇 50 部目前的主機。',
|
||||
'settings.externalEditor.title': '外部遠端編輯器',
|
||||
'settings.externalEditor.desc': '直接在本機編輯器(如 Zed、VS Code 或 Cursor)中開啟遠端 SSH 專案與檔案。',
|
||||
'settings.externalEditor.preferredEditor': '偏好編輯器',
|
||||
'settings.externalEditor.preferredEditor.desc': 'SFTP 右鍵選單與終端機開啟請求預設使用的本機編輯器。',
|
||||
'settings.externalEditor.executablePath': '編輯器執行檔',
|
||||
'settings.externalEditor.executablePath.desc': '留空以自動偵測,或手動選擇本機程式路徑。',
|
||||
'settings.externalEditor.executablePath.placeholder': '自動偵測執行檔路徑',
|
||||
'settings.externalEditor.status.configured': '已自訂路徑',
|
||||
'settings.externalEditor.status.detected': '已自動偵測',
|
||||
'settings.externalEditor.status.notFound': '未偵測到',
|
||||
'settings.externalEditor.browse': '瀏覽…',
|
||||
'settings.externalEditor.resetPath': '重設為自動偵測',
|
||||
'settings.externalEditor.redetect': '重新偵測已安裝的編輯器',
|
||||
'settings.externalEditor.customArgs': '自訂參數',
|
||||
'settings.externalEditor.customArgs.desc': '以空白分隔的參數清單(支援預留位置:{sshUri}、{sshTarget}、{remotePath}、{encodedPath}、{kind})。',
|
||||
'settings.externalEditor.connectionMode': 'SSH 連線模式',
|
||||
'settings.externalEditor.connectionMode.desc': 'Netcatty SSH 橋接會直接重複使用目前已完成驗證的連線,無需將私鑰或主機清單匯出至磁碟。',
|
||||
'settings.externalEditor.connectionMode.bridge': 'Netcatty SSH 橋接 (*.netcatty)',
|
||||
'settings.externalEditor.connectionMode.direct': '直連 OpenSSH (user@host:port)',
|
||||
'settings.externalEditor.sshBridge.title': 'OpenSSH *.netcatty 橋接規則',
|
||||
'settings.externalEditor.sshBridge.desc': '僅在 OpenSSH 設定中寫入單一靜態 Host *.netcatty 規則區塊,不包含任何主機名稱、私鑰或密碼。',
|
||||
'settings.externalEditor.sshBridge.install': '安裝橋接規則',
|
||||
'settings.externalEditor.sshBridge.reinstall': '重新安裝規則',
|
||||
'settings.externalEditor.sshBridge.update': '更新規則',
|
||||
'settings.externalEditor.sshBridge.remove': '移除規則',
|
||||
'settings.externalEditor.terminalRequests': '允許終端機發起開啟請求 (OSC 7337)',
|
||||
'settings.externalEditor.terminalRequests.desc': '允許遠端 Shell 透過 `zed .` 等指令在本機編輯器中開啟遠端路徑。',
|
||||
'settings.externalEditor.autoSetup': '僅在 Netcatty 工作階段啟用遠端編輯器指令',
|
||||
'settings.externalEditor.autoSetup.desc': '將 `zed` / `ncedit` 指令稿安裝至 ~/.netcatty/bin,並僅於目前 Netcatty 終端機工作階段的 PATH 生效,不修改 ~/.bashrc 或 ~/.zshrc(亦可依主機個別切換)。',
|
||||
'settings.externalEditor.defaultTrust': '預設主機信任原則',
|
||||
'settings.externalEditor.defaultTrust.desc': '尚未單獨設定信任原則的遠端主機請求開啟編輯器時的處理方式。',
|
||||
'settings.externalEditor.trust.ask': '每次詢問',
|
||||
'settings.externalEditor.trust.allow': '一律允許',
|
||||
'settings.externalEditor.trust.deny': '一律拒絕',
|
||||
'settings.externalEditor.trustedHosts.host': '主機',
|
||||
'settings.externalEditor.trustedHosts.policy': '原則',
|
||||
};
|
||||
@@ -2,8 +2,6 @@ import type { Messages } from '../types';
|
||||
|
||||
export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '目前目錄:{path}。變更目錄',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
|
||||
'terminal.directory.unknown': '目錄未知',
|
||||
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
|
||||
'terminal.directory.directories': '目錄',
|
||||
@@ -17,8 +15,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.integrationUnavailable': 'PowerShell 目錄整合尚未就緒,啟動參數或執行原則可能阻止載入。',
|
||||
'terminal.directory.cmdIntegrationUnavailable': '正在等待原 CMD 工作階段回報目前目錄。',
|
||||
'terminal.directory.gitBashIntegrationUnavailable': '正在等待原 Git Bash 工作階段中的可存取目錄。',
|
||||
'terminal.directory.wslIntegrationUnavailable': '正在等待所選 WSL 發行版本中的 Bash 返回閒置提示字元。',
|
||||
'terminal.directory.cygwinIntegrationUnavailable': '正在等待 Cygwin Bash 返回閒置提示字元。',
|
||||
'terminal.directory.nonFilesystem': '目前 PowerShell 位置不是檔案系統目錄。',
|
||||
'terminal.directory.accessDenied': '沒有權限列出此目錄。',
|
||||
'terminal.directory.busy': '請等待終端回到空白命令提示字元。',
|
||||
@@ -633,7 +629,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.binding.command-palette': '開啟指令面板',
|
||||
'settings.shortcuts.binding.quick-switch': '快速切換',
|
||||
'settings.shortcuts.binding.new-workspace': '新增工作區',
|
||||
'settings.shortcuts.binding.add-session-to-workspace': '新增工作階段至工作區',
|
||||
'settings.shortcuts.binding.snippets': '開啟程式碼片段',
|
||||
'settings.shortcuts.binding.broadcast': '切換廣播模式',
|
||||
'settings.shortcuts.binding.toggle-opacity': '切換視窗透明度',
|
||||
@@ -723,8 +718,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'keychain.export.script': '指令碼 *',
|
||||
'keychain.export.scriptPlaceholder': '匯出指令碼...',
|
||||
'keychain.export.missingCredentials': '主機未儲存密碼或金鑰。請先為該主機新增密碼憑證。',
|
||||
'keychain.export.missingPublicKey': '此金鑰沒有公鑰。請先在編輯頁貼上公鑰,然後再試「匯出並繫結」。',
|
||||
'keychain.export.missingPublicKeyNote': '此金鑰沒有公鑰。請先在金鑰編輯頁貼上公鑰,然後再匯出。',
|
||||
'keychain.export.successTitle': '匯出成功',
|
||||
'keychain.export.successMessage': '已匯出公鑰並繫結到 {host}',
|
||||
'keychain.export.failedTitle': '匯出失敗',
|
||||
@@ -801,7 +794,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.logPrefix': '日誌:',
|
||||
'tabs.logLocal': '本機',
|
||||
'tabs.copyTab': '複製分頁',
|
||||
'tabs.addSessionToWorkspace': '新增工作階段至此工作區',
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
@@ -1095,12 +1087,4 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.browser.allScopeHint': '在每台主機的瀏覽器中顯示。',
|
||||
'terminal.browser.downloadLocation': '檔案儲存在系統「下載項目」資料夾',
|
||||
'terminal.browser.saveAs': '另存新檔…',
|
||||
'terminal.externalEditor.opened': '已在 {editor} 中開啟 {path}',
|
||||
'terminal.externalEditor.failed': '無法在 {editor} 中開啟',
|
||||
'terminal.externalEditor.prompt.title': '在 {editor} 中開啟?',
|
||||
'terminal.externalEditor.prompt.desc': '遠端主機 {host} 請求在 {editor} 中開啟以下遠端路徑:',
|
||||
'terminal.externalEditor.prompt.deny': '拒絕',
|
||||
'terminal.externalEditor.prompt.allowOnce': '僅允許這次',
|
||||
'terminal.externalEditor.prompt.alwaysTrust': '一律信任此主機',
|
||||
'terminal.externalEditor.autoSetupConfigured': '已設定遠端編輯器指令 ({editor})',
|
||||
};
|
||||
@@ -848,7 +848,6 @@ export const zhTWVaultMessages: Messages = {
|
||||
'cloudSync.localBackups.reason.beforeRestore': '恢復前',
|
||||
'cloudSync.localBackups.versionChange': '{from} -> {to}',
|
||||
'cloudSync.localBackups.counts': '{hosts} 台主機,{keys} 個金鑰,{snippets} 個程式碼片段,{notes} 條筆記',
|
||||
'cloudSync.localBackups.aiCounts': '{sessions} 個 AI 工作階段,{settings} 項設定',
|
||||
'cloudSync.localBackups.restore': '恢復',
|
||||
'cloudSync.localBackups.restoreSuccess': '已恢復本機備份。',
|
||||
'cloudSync.localBackups.restoreFailedTitle': '恢復失敗',
|
||||
@@ -1428,8 +1427,5 @@ export const zhTWVaultMessages: Messages = {
|
||||
'settings.remoteDesktopRecordings.clearAllConfirmDesc': '將從此裝置永久刪除 {count} 個 .webm 錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.clearResult': '已刪除 {count} 個錄影檔案。',
|
||||
'settings.remoteDesktopRecordings.hint': '錄影檔案僅儲存在本裝置本機,絕不上傳雲端同步;已收藏的連線日誌錄影不會在自動清理中被刪除。',
|
||||
'sftp.context.openInExternalEditor': '在 {editor} 中開啟',
|
||||
'hostDetails.externalEditorShellIntegration': '於此工作階段啟用外部編輯器指令',
|
||||
'hostDetails.externalEditorShellIntegration.desc': '透過 ~/.netcatty/bin 僅於目前 Netcatty 終端機工作階段啟用 `zed` / `ncedit`(支援 tmux),不修改 ~/.bashrc 或 ~/.zshrc。',
|
||||
|
||||
};
|
||||
@@ -57,9 +57,6 @@ export interface LocalVaultBackupPreview {
|
||||
noteCount: number;
|
||||
identityCount: number;
|
||||
portForwardingRuleCount: number;
|
||||
/** Optional so backups written before these counters existed still load. */
|
||||
aiSessionCount?: number;
|
||||
settingCount?: number;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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', 'os']);
|
||||
assert.deepEqual(Object.keys(metadata), ['resourceId', 'revision', 'label', 'hostname', 'username', 'protocol', 'group', 'tags']);
|
||||
assert.equal(JSON.stringify(metadata).includes('synthetic-password'), false);
|
||||
resources.observe([first]);
|
||||
assert.equal(resources.resolve(first.id, metadata.revision), first);
|
||||
|
||||
@@ -65,409 +65,3 @@ test('inserting a child into an existing void element fails the view', async ()
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
});
|
||||
|
||||
test('duplicate insert of an existing id applies as a move or replace and keeps follow-up updates in sync', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
|
||||
// Inserting an existing id at a later sibling index replaces the existing node in place.
|
||||
const replaced = tree.apply([
|
||||
[3, 'a', 'class', 'stale'],
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(replaced, {
|
||||
children: [{ id: 'a', type: 1, element: 'span', attributes: { class: 'replaced' }, children: [] }],
|
||||
});
|
||||
|
||||
// Follow-up mutations must apply against the replaced live node (desync gate).
|
||||
const afterFollowUp = tree.apply([
|
||||
[3, 'a', 'class', 'after-sort'],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] }, 1],
|
||||
]);
|
||||
assert.deepEqual(afterFollowUp, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'after-sort' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'second' }] },
|
||||
],
|
||||
});
|
||||
|
||||
// Moving an existing sibling forward adjusts the insert index after detaching the old slot.
|
||||
const movedForward = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] }, 2],
|
||||
]);
|
||||
assert.deepEqual(movedForward.children.map((node) => node.id), ['b', 'a']);
|
||||
assert.deepEqual(movedForward.children[1], { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-end' }, children: [] });
|
||||
|
||||
// Moving an existing sibling backward preserves index 0 and keeps subsequent updates working.
|
||||
const movedBack = tree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'span', attributes: { class: 'moved-start' }, children: [] }, 0],
|
||||
]);
|
||||
assert.deepEqual(movedBack.children.map((node) => node.id), ['a', 'b']);
|
||||
const postMoveAttr = tree.apply([[2, 'b-text', 'updated-second'], [3, 'a', 'class', 'synced']]);
|
||||
assert.deepEqual(postMoveAttr, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'span', attributes: { class: 'synced' }, children: [] },
|
||||
{ id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'updated-second' }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('inserting a parent whose subtree re-includes an already-present child detaches the child and preserves later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', {
|
||||
id: 'old-parent',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'unsorted' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 0],
|
||||
]);
|
||||
|
||||
// Parent insertion repeats already-attached descendant IDs without a preceding remove.
|
||||
const reparented = tree.apply([
|
||||
[0, '~', {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
}, 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(reparented, {
|
||||
children: [
|
||||
{ id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] },
|
||||
{
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-asc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'alpha' }],
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// A subsequent sort-like incremental update on the moved child applies cleanly.
|
||||
const secondSort = tree.apply([
|
||||
[3, 'cell-1', 'class', 'sorted-desc'],
|
||||
[2, 'cell-text', 'omega'],
|
||||
]);
|
||||
assert.deepEqual(secondSort.children[1], {
|
||||
id: 'new-parent',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: {},
|
||||
children: [{
|
||||
id: 'cell-1',
|
||||
type: 1,
|
||||
element: 'span',
|
||||
attributes: { class: 'sorted-desc' },
|
||||
children: [{ id: 'cell-text', type: 3, data: 'omega' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Same-batch case: descendant inserted first, then a new parent serializing that descendant.
|
||||
const sameBatch = tree.apply([
|
||||
[0, 'old-parent', { id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }, 0],
|
||||
[0, '~', {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
}, 2],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(sameBatch.children[0], { id: 'old-parent', type: 1, element: 'div', attributes: {}, children: [] });
|
||||
assert.deepEqual(sameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'one' }] }],
|
||||
});
|
||||
const afterSameBatch = tree.apply([[2, 'child-2-text', 'two']]);
|
||||
assert.deepEqual(afterSameBatch.children[2], {
|
||||
id: 'wrapper',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'child-2', type: 1, element: 'span', attributes: {}, children: [{ id: 'child-2-text', type: 3, data: 'two' }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test('unrecoverable self-nesting duplicate throws without failing the tree or corrupting later updates', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[3, 'a', 'class', 'rejected'],
|
||||
[0, 'a', { id: 'a', type: 1, element: 'span', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Duplicate view node/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(tree.snapshot(), {
|
||||
children: [{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] }],
|
||||
});
|
||||
const updated = tree.apply([[0, '~', { id: 'b', type: 3, data: 'second' }, 1]]);
|
||||
assert.deepEqual(updated, {
|
||||
children: [
|
||||
{ id: 'a', type: 1, element: 'div', attributes: { class: 'first' }, children: [] },
|
||||
{ id: 'b', type: 3, data: 'second' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test('a duplicate id combined with a forbidden mutation still hard-fails the view', async () => {
|
||||
const { createPluginRemoteTree, isDuplicatePluginViewNodeError, assertDuplicateOnlyPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
// Mutation order matters for RemoteReceiver: the void-element child is applied first so the
|
||||
// projected tree actually contains both the policy violation and a later duplicate id.
|
||||
assert.throws(
|
||||
() => tree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 1],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(tree.isFailed(), true);
|
||||
assert.deepEqual(tree.snapshot(), { children: [] });
|
||||
|
||||
// Even when the duplicate node appears earlier in root order than the void-element violation,
|
||||
// unique-id revalidation must still hard-fail instead of rewriting the batch.
|
||||
const duplicateFirstTree = createPluginRemoteTree();
|
||||
duplicateFirstTree.apply([[0, '~', { id: 'input', type: 1, element: 'input', attributes: { type: 'text' }, children: [] }, 0]]);
|
||||
assert.throws(
|
||||
() => duplicateFirstTree.apply([
|
||||
[0, 'input', { id: 'child', type: 3, data: 'invalid' }, 0],
|
||||
[0, '~', { id: 'input', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
]),
|
||||
/Void view elements/,
|
||||
);
|
||||
assert.equal(duplicateFirstTree.isFailed(), true);
|
||||
assert.deepEqual(duplicateFirstTree.snapshot(), { children: [] });
|
||||
|
||||
// Defense in depth: if a projected tree already has both issues, unique-id revalidation
|
||||
// must still surface the void-element violation instead of treating it as recoverable.
|
||||
const mixed = {
|
||||
children: [
|
||||
{ id: 'input', type: 1 as const, element: 'input', attributes: { type: 'text' }, children: [{ id: 'child', type: 3 as const, data: 'invalid' }] },
|
||||
{ id: 'input', type: 1 as const, element: 'div', attributes: {}, children: [] },
|
||||
],
|
||||
};
|
||||
assert.equal(isDuplicatePluginViewNodeError(new TypeError('Duplicate view node')), true);
|
||||
assert.throws(() => assertDuplicateOnlyPluginRemoteTree(mixed), /Void view elements/);
|
||||
});
|
||||
|
||||
test('RemoteMutationObserver wrapping a sibling preserves kept siblings and follow-up text updates', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="remote"></div>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
|
||||
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] });
|
||||
}
|
||||
const { RemoteMutationObserver } = await import('@remote-dom/core/elements');
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const staged = createPluginRemoteTree();
|
||||
const batches: unknown[][][] = [];
|
||||
const observer = new RemoteMutationObserver({
|
||||
mutate(records) {
|
||||
const cloned = JSON.parse(JSON.stringify(records)) as unknown[][];
|
||||
batches.push(cloned);
|
||||
staged.apply(cloned);
|
||||
},
|
||||
call() { throw new Error('Host method calls are unavailable'); },
|
||||
});
|
||||
const container = document.getElementById('remote')!;
|
||||
observer.observe(container);
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
try {
|
||||
const a = document.createElement('div');
|
||||
a.id = 'a';
|
||||
const aText = document.createTextNode('Alpha');
|
||||
a.appendChild(aText);
|
||||
|
||||
const b = document.createElement('div');
|
||||
b.id = 'b';
|
||||
b.appendChild(document.createTextNode('Beta'));
|
||||
|
||||
container.appendChild(a);
|
||||
container.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
assert.equal(staged.snapshot().children.length, 2);
|
||||
|
||||
// Same-tick wrap: append wrapper and move b into it.
|
||||
const wrapper = document.createElement('section');
|
||||
wrapper.id = 'wrapper';
|
||||
container.appendChild(wrapper);
|
||||
wrapper.appendChild(b);
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterWrap = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterWrap.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const [aNode, wrapperNode] = afterWrap.children;
|
||||
assert.ok(aNode && aNode.type === 1, 'Expected sibling a first in host tree');
|
||||
assert.ok(wrapperNode && wrapperNode.type === 1, 'Expected wrapper second in host tree');
|
||||
assert.equal(aNode.children[0]?.type === 3 ? aNode.children[0].data : null, 'Alpha');
|
||||
assert.deepEqual(
|
||||
wrapperNode.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['b'],
|
||||
);
|
||||
const bNode = wrapperNode.children[0];
|
||||
assert.ok(bNode && bNode.type === 1, 'Expected b inside wrapper');
|
||||
assert.equal(bNode.children[0]?.type === 3 ? bNode.children[0].data : null, 'Beta');
|
||||
|
||||
// Desync gate: a subsequent text update to a must apply cleanly.
|
||||
aText.data = 'Alpha updated';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterText = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterText.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a', 'wrapper'],
|
||||
);
|
||||
const updatedANode = afterText.children[0];
|
||||
assert.ok(updatedANode && updatedANode.type === 1);
|
||||
assert.equal(updatedANode.children[0]?.type === 3 ? updatedANode.children[0].data : null, 'Alpha updated');
|
||||
|
||||
// Later turn: removing wrapper at index 1 must keep a and leave a updatable.
|
||||
wrapper.remove();
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemove = staged.snapshot();
|
||||
assert.deepEqual(
|
||||
afterRemove.children.map((node) => (node.type === 1 ? node.attributes.id : null)),
|
||||
['a'],
|
||||
);
|
||||
aText.data = 'Alpha after remove';
|
||||
await flush();
|
||||
|
||||
assert.equal(staged.isFailed(), false);
|
||||
const afterRemoveText = staged.snapshot();
|
||||
const survivingANode = afterRemoveText.children[0];
|
||||
assert.ok(survivingANode && survivingANode.type === 1);
|
||||
assert.equal(survivingANode.children[0]?.type === 3 ? survivingANode.children[0].data : null, 'Alpha after remove');
|
||||
assert.ok(batches.length >= 5);
|
||||
} finally {
|
||||
observer.disconnect();
|
||||
for (const [key, value] of saved) {
|
||||
if (value) Object.defineProperty(globalThis, key, value);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('rewriteDuplicateInsertBatch skips matched detaches and remaps subsequent producer removals', async () => {
|
||||
const { createPluginRemoteTree } = await import('./pluginRemoteTree');
|
||||
const tree = createPluginRemoteTree();
|
||||
tree.apply([
|
||||
[0, '~', { id: '0', type: 1, element: 'div', attributes: { id: 'a' }, children: [{ id: '1', type: 3, data: 'Alpha' }] }, 0],
|
||||
[0, '~', { id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }, 1],
|
||||
]);
|
||||
|
||||
// Exact mutation batch from RemoteMutationObserver when appending wrapper and moving b into it.
|
||||
const wrapped = tree.apply([
|
||||
[0, '~', {
|
||||
id: '4',
|
||||
type: 1,
|
||||
element: 'section',
|
||||
attributes: { id: 'wrapper' },
|
||||
children: [{ id: '2', type: 1, element: 'div', attributes: { id: 'b' }, children: [{ id: '3', type: 3, data: 'Beta' }] }],
|
||||
}, 0],
|
||||
[1, '~', 1],
|
||||
]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(wrapped.children.map((node) => node.id), ['0', '4']);
|
||||
const wrapperNode = wrapped.children[1];
|
||||
assert.equal(wrapperNode.type, 1);
|
||||
if (wrapperNode.type === 1) {
|
||||
assert.deepEqual(wrapperNode.children.map((node) => node.id), ['2']);
|
||||
}
|
||||
|
||||
// Subsequent text update to a must still apply.
|
||||
const updated = tree.apply([[2, '1', 'Alpha updated']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(updated.children[0], {
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha updated' }],
|
||||
});
|
||||
|
||||
// Later producer remove of wrapper at index 1 must remove wrapper and keep a alive.
|
||||
const afterRemove = tree.apply([[1, '~', 1]]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemove.children.map((node) => node.id), ['0']);
|
||||
const afterRemoveUpdate = tree.apply([[2, '1', 'Alpha after remove']]);
|
||||
assert.equal(tree.isFailed(), false);
|
||||
assert.deepEqual(afterRemoveUpdate, {
|
||||
children: [{
|
||||
id: '0',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { id: 'a' },
|
||||
children: [{ id: '1', type: 3, data: 'Alpha after remove' }],
|
||||
}],
|
||||
});
|
||||
|
||||
// Producer remove at a larger index after a rewrite detach at a smaller index remaps to the right sibling.
|
||||
const remapTree = createPluginRemoteTree();
|
||||
remapTree.apply([
|
||||
[0, '~', { id: 'a', type: 1, element: 'div', attributes: {}, children: [] }, 0],
|
||||
[0, '~', { id: 'b', type: 1, element: 'div', attributes: {}, children: [{ id: 'b-text', type: 3, data: 'keep' }] }, 1],
|
||||
[0, '~', { id: 'c', type: 1, element: 'div', attributes: {}, children: [] }, 2],
|
||||
]);
|
||||
const remapped = remapTree.apply([
|
||||
[0, '~', { id: 'wrap', type: 1, element: 'section', attributes: {}, children: [{ id: 'a', type: 1, element: 'div', attributes: {}, children: [] }] }, 3],
|
||||
// Producer removes c (original index 2) while a (index 0) was already detached by the rewrite.
|
||||
[1, '~', 2],
|
||||
// Producer then removes a at original index 0 (already detached -> skipped).
|
||||
[1, '~', 0],
|
||||
]);
|
||||
assert.equal(remapTree.isFailed(), false);
|
||||
assert.deepEqual(remapped.children.map((node) => node.id), ['b', 'wrap']);
|
||||
const followUp = remapTree.apply([[2, 'b-text', 'still-alive']]);
|
||||
assert.deepEqual(followUp.children[0], {
|
||||
id: 'b',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {},
|
||||
children: [{ id: 'b-text', type: 3, data: 'still-alive' }],
|
||||
});
|
||||
});
|
||||
@@ -12,174 +12,6 @@ export function isValidatedPluginRemoteTree(tree: unknown): boolean {
|
||||
return Boolean(tree && typeof tree === 'object' && validatedTrees.has(tree));
|
||||
}
|
||||
|
||||
export function isDuplicatePluginViewNodeError(error: unknown): error is TypeError {
|
||||
return error instanceof TypeError && error.message === 'Duplicate view node';
|
||||
}
|
||||
|
||||
function withUniqueViewIds(tree: WireTree): WireTree {
|
||||
let n = 0;
|
||||
const rewrite = (node: WireNode): WireNode => {
|
||||
const id = `n${n++}`;
|
||||
if (node.type === 3 || node.type === 8) return { id, type: node.type, data: node.data };
|
||||
return { id, type: 1, element: node.element, attributes: node.attributes, children: node.children.map(rewrite) };
|
||||
};
|
||||
return { children: tree.children.map(rewrite) };
|
||||
}
|
||||
|
||||
/** If a projected tree has duplicate IDs, still hard-fail when other policy violations exist. */
|
||||
export function assertDuplicateOnlyPluginRemoteTree(tree: WireTree): void {
|
||||
validatePluginRemoteTree(withUniqueViewIds(tree));
|
||||
}
|
||||
|
||||
type WorkingNode = {
|
||||
id: string;
|
||||
parentId: string | null;
|
||||
children: WorkingNode[];
|
||||
};
|
||||
|
||||
type RewriteDetach = {
|
||||
parentId: string;
|
||||
index: number;
|
||||
id: string;
|
||||
};
|
||||
|
||||
function collectSubtreeIds(node: WireNode, out: string[] = []): string[] {
|
||||
out.push(node.id);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) collectSubtreeIds(child, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildWorkingNode(node: WireNode, parentId: string, nodes: Map<string, WorkingNode>): WorkingNode {
|
||||
const working: WorkingNode = { id: node.id, parentId, children: [] };
|
||||
nodes.set(node.id, working);
|
||||
if (node.type === 1) {
|
||||
for (const child of node.children) {
|
||||
working.children.push(buildWorkingNode(child, node.id, nodes));
|
||||
}
|
||||
}
|
||||
return working;
|
||||
}
|
||||
|
||||
function detachWorkingSubtree(node: WorkingNode, nodes: Map<string, WorkingNode>): void {
|
||||
nodes.delete(node.id);
|
||||
node.parentId = null;
|
||||
for (const child of node.children) detachWorkingSubtree(child, nodes);
|
||||
}
|
||||
|
||||
function hasAncestorInSet(startId: string, ids: Set<string>, nodes: Map<string, WorkingNode>): boolean {
|
||||
let cursor: string | null = startId;
|
||||
while (cursor !== null) {
|
||||
if (ids.has(cursor)) return true;
|
||||
cursor = nodes.get(cursor)?.parentId ?? null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a duplicate-only mutation batch so inserts referencing IDs already
|
||||
* attached in the tree first emit explicit removals from their previous parents.
|
||||
* Returns null if an insert would detach its own destination parent (cycle).
|
||||
*/
|
||||
function rewriteDuplicateInsertBatch(current: WireTree, batch: unknown[][]): unknown[][] | null {
|
||||
const root: WorkingNode = { id: '~', parentId: null, children: [] };
|
||||
const nodes = new Map<string, WorkingNode>([['~', root]]);
|
||||
for (const child of current.children) {
|
||||
root.children.push(buildWorkingNode(child, '~', nodes));
|
||||
}
|
||||
|
||||
const rewritten: unknown[][] = [];
|
||||
const rewriteDetaches: RewriteDetach[] = [];
|
||||
for (const record of batch) {
|
||||
const type = record[0];
|
||||
if (type === 0) {
|
||||
const parentId = record[1] as string;
|
||||
const node = record[2] as WireNode;
|
||||
let insertIndex = record[3] as number;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
// Detached parent: RemoteReceiver drops this insert as a no-op.
|
||||
rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
|
||||
const subtreeIds = collectSubtreeIds(node);
|
||||
if (hasAncestorInSet(parentId, new Set(subtreeIds), nodes)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const existingId of subtreeIds) {
|
||||
const existing = nodes.get(existingId);
|
||||
if (!existing || existing.parentId === null) continue;
|
||||
const oldParent = nodes.get(existing.parentId);
|
||||
if (!oldParent) continue;
|
||||
const oldIndex = oldParent.children.indexOf(existing);
|
||||
if (oldIndex < 0) continue;
|
||||
|
||||
rewritten.push([1, oldParent.id, oldIndex]);
|
||||
rewriteDetaches.push({ parentId: oldParent.id, index: oldIndex, id: existing.id });
|
||||
oldParent.children.splice(oldIndex, 1);
|
||||
detachWorkingSubtree(existing, nodes);
|
||||
|
||||
if (oldParent.id === parentId) {
|
||||
if (oldIndex < insertIndex) {
|
||||
insertIndex -= 1;
|
||||
} else if (existing.id !== node.id && oldIndex > insertIndex) {
|
||||
insertIndex = oldIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rewritten.push(insertIndex === record[3] ? record : [0, parentId, node, insertIndex]);
|
||||
const inserted = buildWorkingNode(node, parentId, nodes);
|
||||
if (insertIndex >= parent.children.length) {
|
||||
parent.children.push(inserted);
|
||||
} else {
|
||||
parent.children.splice(insertIndex, 0, inserted);
|
||||
}
|
||||
} else if (type === 1) {
|
||||
const parentId = record[1] as string;
|
||||
const removeIndex = record[2] as number;
|
||||
const exactMatchIndex = rewriteDetaches.findIndex(
|
||||
(detach) => detach.parentId === parentId && detach.index === removeIndex,
|
||||
);
|
||||
if (exactMatchIndex !== -1) {
|
||||
rewriteDetaches.splice(exactMatchIndex, 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
let smallerCount = 0;
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index < removeIndex) {
|
||||
smallerCount += 1;
|
||||
}
|
||||
}
|
||||
const remappedIndex = removeIndex - smallerCount;
|
||||
const parent = nodes.get(parentId);
|
||||
if (!parent) {
|
||||
if (smallerCount === 0) rewritten.push(record);
|
||||
continue;
|
||||
}
|
||||
if (remappedIndex < 0 || remappedIndex >= parent.children.length) {
|
||||
continue;
|
||||
}
|
||||
rewritten.push(remappedIndex === removeIndex ? record : [1, parentId, remappedIndex]);
|
||||
const [removed] = parent.children.splice(remappedIndex, 1);
|
||||
if (removed) detachWorkingSubtree(removed, nodes);
|
||||
for (const detach of rewriteDetaches) {
|
||||
if (detach.parentId === parentId && detach.index > removeIndex) {
|
||||
detach.index -= 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
rewritten.push(record);
|
||||
}
|
||||
}
|
||||
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
/** Data-only staging area: untrusted changes are never applied directly to the host DOM. */
|
||||
export function createPluginRemoteTree() {
|
||||
const receiver = new RemoteReceiver();
|
||||
@@ -191,16 +23,6 @@ export function createPluginRemoteTree() {
|
||||
if (value.type === 3 || value.type === 8) return { id: value.id, type: value.type, data: value.data ?? '' };
|
||||
return { id: value.id, type: 1, element: value.element ?? '', attributes: Object.fromEntries(Object.entries(value.attributes ?? {}).filter(([, attribute]) => attribute !== null)), children: (value.children ?? []).map(project) };
|
||||
};
|
||||
const applyToScratch = (records: unknown[][]): WireTree => {
|
||||
const scratch = new RemoteReceiver();
|
||||
if (current.children.length > 0) {
|
||||
scratch.connection.mutate(
|
||||
current.children.map((child, index) => [0, '~', child, index]) as unknown as Parameters<typeof scratch.connection.mutate>[0],
|
||||
);
|
||||
}
|
||||
scratch.connection.mutate(records as unknown as Parameters<typeof scratch.connection.mutate>[0]);
|
||||
return { children: scratch.root.children.map(project) };
|
||||
};
|
||||
return {
|
||||
apply(input: unknown): WireTree {
|
||||
if (failed) throw new Error('Plugin view has been closed after an invalid update');
|
||||
@@ -209,35 +31,16 @@ export function createPluginRemoteTree() {
|
||||
// Ordinary DOM attribute mutations do not specify a channel. RemoteReceiver
|
||||
// defaults those to properties, so explicitly mark them as attributes.
|
||||
const batch = (input as unknown[][]).map((record) => record[0] === 3 && record.length === 4 ? [...record, 2] : record);
|
||||
let appliedBatch = batch;
|
||||
let next = applyToScratch(batch);
|
||||
try {
|
||||
validatePluginRemoteTree(next);
|
||||
} catch (error) {
|
||||
if (!isDuplicatePluginViewNodeError(error)) throw error;
|
||||
assertDuplicateOnlyPluginRemoteTree(next);
|
||||
const rewritten = rewriteDuplicateInsertBatch(current, batch);
|
||||
if (!rewritten) throw error;
|
||||
const rewrittenNext = applyToScratch(rewritten);
|
||||
try {
|
||||
validatePluginRemoteTree(rewrittenNext);
|
||||
} catch (rewrittenError) {
|
||||
if (isDuplicatePluginViewNodeError(rewrittenError)) assertDuplicateOnlyPluginRemoteTree(rewrittenNext);
|
||||
throw rewrittenError;
|
||||
}
|
||||
appliedBatch = rewritten;
|
||||
next = rewrittenNext;
|
||||
}
|
||||
receiver.connection.mutate(appliedBatch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
receiver.connection.mutate(batch as unknown as Parameters<typeof receiver.connection.mutate>[0]);
|
||||
const next = { children: receiver.root.children.map(project) };
|
||||
validatePluginRemoteTree(next);
|
||||
validatedTrees.add(next);
|
||||
current = next;
|
||||
return next;
|
||||
} catch (error) {
|
||||
if (!isDuplicatePluginViewNodeError(error)) {
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
}
|
||||
failed = true;
|
||||
current = { children: [] };
|
||||
validatedTrees.add(current);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -218,52 +218,3 @@ test('portForward.start surfaces live error status and message when tunnel start
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('views.open resolves visible contribution, triggers open without polluting context, and rejects missing/hidden views', async () => {
|
||||
const opened: Array<{ viewId: string; context?: Record<string, unknown>; params?: unknown }> = [];
|
||||
const queries: unknown[] = [];
|
||||
const ctx: PluginVaultDataContext = {
|
||||
...makeContext({}),
|
||||
viewOpenRuntime: {
|
||||
getPluginContributions: async (query) => {
|
||||
queries.push(query);
|
||||
return {
|
||||
locale: 'en',
|
||||
plugins: [{
|
||||
id: 'com.example.db',
|
||||
version: '1.0.0',
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: 'com.example.db.workbench', title: 'Database', location: 'vault-page', visible: true },
|
||||
{ id: 'com.example.db.hidden', title: 'Hidden', location: 'vault-page', visible: false },
|
||||
],
|
||||
}],
|
||||
};
|
||||
},
|
||||
requestOpenPluginView: (detail) => { opened.push(detail); },
|
||||
},
|
||||
};
|
||||
|
||||
const result = await handlePluginVaultDataRequest(
|
||||
'views.open',
|
||||
{ viewId: 'com.example.db.workbench', location: 'vault-page' },
|
||||
ctx,
|
||||
);
|
||||
assert.deepEqual(result, { opened: true, focused: true, location: 'vault-page' });
|
||||
assert.deepEqual(queries[0], { context: { 'netcatty.surface': 'vault-page' } });
|
||||
assert.deepEqual(opened, [{ viewId: 'com.example.db.workbench' }]);
|
||||
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.hidden', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
await assert.rejects(
|
||||
() => handlePluginVaultDataRequest('views.open', { viewId: 'com.example.db.missing', location: 'vault-page' }, ctx),
|
||||
/not available/,
|
||||
);
|
||||
assert.equal(opened.length, 1);
|
||||
});
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
import { requestOpenPluginView } from './usePluginViewLifecycle';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
@@ -37,16 +36,10 @@ export interface PluginPortForwardRuntimeDeps {
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export interface PluginViewOpenRuntimeDeps {
|
||||
getPluginContributions?: NonNullable<ReturnType<typeof netcattyBridge.get>>['getPluginContributions'];
|
||||
requestOpenPluginView?: typeof requestOpenPluginView;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
viewOpenRuntime?: PluginViewOpenRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
@@ -479,42 +472,6 @@ export async function handlePluginVaultDataRequest(
|
||||
return { focused: true };
|
||||
}
|
||||
|
||||
case 'views.open': {
|
||||
const viewId = typeof payload.viewId === 'string' ? payload.viewId : '';
|
||||
const location = typeof payload.location === 'string' ? payload.location : '';
|
||||
if (!viewId) throw new Error('Plugin view ID is required');
|
||||
const queryContext = location === 'vault-page'
|
||||
? { 'netcatty.surface': 'vault-page' }
|
||||
: location === 'terminal-sidebar'
|
||||
? { 'netcatty.surface': 'terminal-sidebar' }
|
||||
: { 'netcatty.surface': 'view' };
|
||||
const getContributions = ctx.viewOpenRuntime?.getPluginContributions ?? netcattyBridge.get()?.getPluginContributions;
|
||||
if (!getContributions) {
|
||||
throw new Error('Plugin contributions are unavailable');
|
||||
}
|
||||
const snapshot = await getContributions({ context: queryContext });
|
||||
const resolved = snapshot.plugins
|
||||
.flatMap((plugin) => plugin.views)
|
||||
.find((view) => view.id === viewId && view.visible);
|
||||
if (!resolved) {
|
||||
throw new Error(`Plugin view is not available: ${viewId}`);
|
||||
}
|
||||
if (resolved.location === 'terminal-sidebar') {
|
||||
const sessionRuntime = getAppSessionRuntime();
|
||||
const activeTabId = activeTabStore.getActiveTabId();
|
||||
const isTerminalTab = Boolean(
|
||||
sessionRuntime?.sessions.some((s) => s.id === activeTabId)
|
||||
|| sessionRuntime?.workspaces.some((w) => w.id === activeTabId),
|
||||
);
|
||||
if (!isTerminalTab) {
|
||||
throw new Error('An active terminal tab is required to open a terminal sidebar view');
|
||||
}
|
||||
}
|
||||
const openView = ctx.viewOpenRuntime?.requestOpenPluginView ?? requestOpenPluginView;
|
||||
openView({ viewId: resolved.id });
|
||||
return { opened: true, focused: true, location: resolved.location };
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported Vault data request: ${kind}`);
|
||||
}
|
||||
|
||||
@@ -60,320 +60,3 @@ test('empty first update holds loading briefly to prevent blank-frame flash then
|
||||
assert.equal(view.getSnapshot().loading, false, 'truly empty view finishes loading after grace window');
|
||||
store.dispose();
|
||||
});
|
||||
test('update and event failures warn concisely with error message before disposing without logging event payloads', async () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f1 = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view1 = store.acquire('bad-seq', f1.bridge, request);
|
||||
f1.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: f1.opened[0].instanceId, sequence: 99, css: '', mutations: [] });
|
||||
assert.equal(view1.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Invalid plugin update order/);
|
||||
assert.ok(warns[0][1] instanceof Error);
|
||||
|
||||
const f2 = fixture();
|
||||
f2.bridge.sendHostDrawnPluginViewEvent = async () => { throw new Error('IPC channel closed'); };
|
||||
const view2 = store.acquire('bad-send', f2.bridge, request);
|
||||
view2.send({ type: 'input', nodeId: 'field', value: 'secret@example.com' });
|
||||
await Promise.resolve();
|
||||
assert.equal(view2.getSnapshot().error, true);
|
||||
assert.equal(warns.length, 2);
|
||||
assert.match(String(warns[1][0]), /IPC channel closed/);
|
||||
assert.doesNotMatch(warns[1].map(String).join(' '), /secret@example\.com/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
test('recoverable duplicate node update applies as a move and publishes the new tree without warning', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-move', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Re-inserting an existing node (or wrapping it in a new parent without a remove)
|
||||
// is normalized as a move and published immediately with zero warnings.
|
||||
const movedNode = {
|
||||
id: 'group-1',
|
||||
type: 1 as const,
|
||||
element: 'section',
|
||||
attributes: { class: 'sorted' },
|
||||
children: [{
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
}],
|
||||
};
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.sorted{color:blue}',
|
||||
mutations: [[0, '~', movedNode, 1]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [movedNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-move'), view);
|
||||
|
||||
// A subsequent incremental update applies cleanly against the moved nodes.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 0);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{
|
||||
...movedNode,
|
||||
children: [{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] }],
|
||||
},
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
// Forbidden mutations still dispose the session.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('unrecoverable duplicate node update warns without failing the session and accepts subsequent valid updates', () => {
|
||||
const warns: unknown[][] = [];
|
||||
const originalWarn = console.warn;
|
||||
console.warn = (...args: unknown[]) => { warns.push(args); };
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('dup-recovery', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const initialNode = {
|
||||
id: 'row-1',
|
||||
type: 1 as const,
|
||||
element: 'div',
|
||||
attributes: { class: 'row' },
|
||||
children: [{ id: 'cell-1', type: 3 as const, data: 'alpha' }],
|
||||
};
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{display:flex}', mutations: [[0, '~', initialNode, 0]] });
|
||||
assert.equal(view.getSnapshot().loading, false);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
|
||||
// Self-nesting cycle cannot be rewritten as a move; last-resort fallback preserves last good tree.
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'div', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(warns.length, 1);
|
||||
assert.match(String(warns[0][0]), /Duplicate view node/);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [initialNode]);
|
||||
assert.equal(f.closes.length, 0);
|
||||
assert.equal(store.peek('dup-recovery'), view);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [
|
||||
[2, 'cell-1', 'beta'],
|
||||
[0, '~', { id: 'row-2', type: 3, data: 'second' }, 1],
|
||||
],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, [
|
||||
{ ...initialNode, children: [{ id: 'cell-1', type: 3, data: 'beta' }] },
|
||||
{ id: 'row-2', type: 3, data: 'second' },
|
||||
]);
|
||||
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'onclick', 'attack()']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.deepEqual(view.getSnapshot().tree.children, []);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('pending CSS from a rejected unrecoverable duplicate update is published on the next accepted update', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-pending', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'rejected update does not publish CSS immediately');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), true, 'next accepted update publishes the stashed CSS');
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('explicit CSS matching the last committed value supersedes pending CSS', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('css-supersede', f.bridge, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'row-1', type: 1 as const, element: 'div', attributes: { class: 'row' }, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.row{color:red}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 2,
|
||||
css: '.row{color:blue}',
|
||||
mutations: [[0, 'row-1', { id: 'row-1', type: 1, element: 'span', attributes: {}, children: [] }, 0]],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 3,
|
||||
css: '.row{color:red}',
|
||||
mutations: [[3, 'row-1', 'class', 'ready']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true, 'explicit red supersedes pending blue');
|
||||
f.update({
|
||||
kind: 'host-ui.update',
|
||||
viewId: request.viewId,
|
||||
instanceId: id,
|
||||
sequence: 4,
|
||||
css: '',
|
||||
cssUnchanged: true,
|
||||
mutations: [[3, 'row-1', 'class', 'again']],
|
||||
} as Update);
|
||||
assert.equal(view.getSnapshot().css.includes('red'), true);
|
||||
assert.equal(view.getSnapshot().css.includes('blue'), false);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
|
||||
const bridgeWithDiag = {
|
||||
...f.bridge,
|
||||
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
|
||||
diagnostics.push(payload);
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('diag-test', bridgeWithDiag, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
|
||||
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
|
||||
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
assert.equal(diagnostics.length, 1);
|
||||
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
|
||||
|
||||
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.equal(diagnostics.length, 2);
|
||||
assert.equal(diagnostics[1].source, 'plugin-view');
|
||||
assert.match(diagnostics[1].message, /Invalid plugin update order/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
@@ -1,11 +1,9 @@
|
||||
import { createPluginRemoteTree, isDuplicatePluginViewNodeError } from './pluginRemoteTree';
|
||||
import { createPluginRemoteTree } from './pluginRemoteTree';
|
||||
import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
|
||||
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
|
||||
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
|
||||
@@ -28,10 +26,7 @@ export class PluginViewSessions {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let loggedDuplicateNode = false;
|
||||
let lastRawCss: string | null = null;
|
||||
let pendingCss: string | null = null;
|
||||
let pendingRawCss: string | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let emptyFrameTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const listeners = new Set<() => void>();
|
||||
@@ -47,26 +42,14 @@ export class PluginViewSessions {
|
||||
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
|
||||
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
|
||||
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
|
||||
let stagedCss: string | null = null;
|
||||
let stagedRawCss: string | null = null;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
if (update.cssUnchanged || update.css === undefined) {
|
||||
// keep pending CSS, if any, for the nextCss fallback below
|
||||
} else if (lastRawCss !== null && update.css === lastRawCss) {
|
||||
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
} else {
|
||||
stagedCss = validatePluginStylesheet(update.css);
|
||||
stagedRawCss = update.css;
|
||||
}
|
||||
const nextCss = stagedCss ?? pendingCss ?? state.css;
|
||||
const nextCss = update.cssUnchanged
|
||||
? state.css
|
||||
: (lastRawCss !== null && update.css === lastRawCss)
|
||||
? state.css
|
||||
: ((lastRawCss = update.css), validatePluginStylesheet(update.css));
|
||||
const nextTree = tree.apply(update.mutations);
|
||||
if (stagedRawCss !== null) lastRawCss = stagedRawCss;
|
||||
else if (pendingRawCss !== null) lastRawCss = pendingRawCss;
|
||||
pendingCss = null;
|
||||
pendingRawCss = null;
|
||||
const settled = (update.acknowledgedEvent ?? 0) >= eventId;
|
||||
if (state.loading && !hasRenderableTreeContent(nextTree)) {
|
||||
// Hold the host loading surface briefly while an older SDK flushes its
|
||||
@@ -85,34 +68,7 @@ export class PluginViewSessions {
|
||||
emptyFrameTimer = undefined;
|
||||
}
|
||||
publish({ tree: nextTree, css: nextCss, loading: false, error: false, settled });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
|
||||
const duplicateNode = isDuplicatePluginViewNodeError(error);
|
||||
if (!duplicateNode || !loggedDuplicateNode) {
|
||||
if (duplicateNode) loggedDuplicateNode = true;
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to apply update for ${request.viewId}: ${message}`,
|
||||
extra: {
|
||||
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
|
||||
viewId: request.viewId,
|
||||
sequence: update.sequence,
|
||||
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
// Recoverable duplicate-only batches are normalized as moves in
|
||||
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
|
||||
if (duplicateNode) {
|
||||
if (stagedCss !== null && stagedRawCss !== null) {
|
||||
pendingCss = stagedCss;
|
||||
pendingRawCss = stagedRawCss;
|
||||
}
|
||||
return;
|
||||
}
|
||||
dispose(true);
|
||||
}
|
||||
} catch { dispose(true); }
|
||||
}));
|
||||
cleanup.push(bridge.onPluginViewClosed((event) => { if (event.instanceId === id) dispose(true); }));
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
@@ -144,18 +100,7 @@ export class PluginViewSessions {
|
||||
send: (event: HostDrawnViewEvent) => {
|
||||
if (disposed || users === 0) return;
|
||||
publish({ ...state, settled: false });
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
|
||||
if (!disposed) {
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to send event for ${request.viewId}: ${message}`,
|
||||
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
|
||||
}).catch(() => {});
|
||||
}
|
||||
dispose(true);
|
||||
});
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch(() => dispose(true));
|
||||
},
|
||||
dispose,
|
||||
};
|
||||
|
||||
@@ -25,7 +25,6 @@ export type SettingsChromeSnapshot = {
|
||||
windowOpacity: number;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
showRecentHosts: boolean;
|
||||
hostClickBehavior: HostClickBehavior;
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
@@ -60,7 +59,6 @@ export const DEFAULT_SETTINGS_CHROME_SNAPSHOT: SettingsChromeSnapshot = Object.f
|
||||
windowOpacity: 1,
|
||||
showSftpTab: true,
|
||||
showHostTreeSidebar: true,
|
||||
removeTopTabsDragArea: false,
|
||||
showRecentHosts: true,
|
||||
hostClickBehavior: 'connect',
|
||||
showOnlyUngroupedHostsInRoot: false,
|
||||
@@ -88,7 +86,6 @@ export function settingsChromeSnapshotsEqual(
|
||||
&& a.windowOpacity === b.windowOpacity
|
||||
&& a.showSftpTab === b.showSftpTab
|
||||
&& a.showHostTreeSidebar === b.showHostTreeSidebar
|
||||
&& a.removeTopTabsDragArea === b.removeTopTabsDragArea
|
||||
&& a.showRecentHosts === b.showRecentHosts
|
||||
&& a.hostClickBehavior === b.hostClickBehavior
|
||||
&& a.showOnlyUngroupedHostsInRoot === b.showOnlyUngroupedHostsInRoot
|
||||
|
||||
@@ -137,7 +137,6 @@ export type { HostClickBehavior } from '../../domain/hostClickBehavior';
|
||||
export const DEFAULT_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT = false;
|
||||
export const DEFAULT_SHOW_SFTP_TAB = true;
|
||||
export const DEFAULT_SHOW_HOST_TREE_SIDEBAR = true;
|
||||
export const DEFAULT_REMOVE_TOP_TABS_DRAG_AREA = false;
|
||||
export const DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS = false;
|
||||
export const DEFAULT_SHOW_TAB_NUMBER_BADGES = true;
|
||||
export const DEFAULT_DISABLE_TERMINAL_FONT_ZOOM = false;
|
||||
|
||||
@@ -35,7 +35,6 @@ import {
|
||||
STORAGE_KEY_HOST_CLICK_BEHAVIOR,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -137,7 +136,6 @@ interface UseSettingsStorageSyncParams {
|
||||
showOnlyUngroupedHostsInRoot: boolean;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
removeTopTabsDragArea: boolean;
|
||||
terminalSidePanelAutoOpen: boolean;
|
||||
terminalSidePanelAutoOpenTab: TerminalSidePanelAutoOpenTab;
|
||||
localShellSidePanelAutoOpen: boolean;
|
||||
@@ -196,7 +194,6 @@ interface UseSettingsStorageSyncParams {
|
||||
setShowOnlyUngroupedHostsInRootState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowSftpTabState: Dispatch<SetStateAction<boolean>>;
|
||||
setShowHostTreeSidebarState: Dispatch<SetStateAction<boolean>>;
|
||||
setRemoveTopTabsDragAreaState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
setTerminalSidePanelAutoOpenTabState: Dispatch<SetStateAction<TerminalSidePanelAutoOpenTab>>;
|
||||
setLocalShellSidePanelAutoOpenState: Dispatch<SetStateAction<boolean>>;
|
||||
@@ -241,7 +238,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -252,7 +249,7 @@ export function useSettingsStorageSync({
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState, setJmsDeepLinkEnabledState, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState,
|
||||
@@ -269,7 +266,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -281,7 +278,7 @@ export function useSettingsStorageSync({
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -551,12 +548,6 @@ export function useSettingsStorageSync({
|
||||
setShowHostTreeSidebarState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.removeTopTabsDragArea) {
|
||||
setRemoveTopTabsDragAreaState(newValue);
|
||||
}
|
||||
}
|
||||
if (e.key === STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN && e.newValue !== null) {
|
||||
const newValue = e.newValue === 'true';
|
||||
if (newValue !== s.terminalSidePanelAutoOpen) {
|
||||
@@ -710,7 +701,6 @@ export function useSettingsStorageSync({
|
||||
setSftpSkipUnchanged,
|
||||
setShowOnlyUngroupedHostsInRootState,
|
||||
setShowHostTreeSidebarState,
|
||||
setRemoveTopTabsDragAreaState,
|
||||
setTerminalSidePanelAutoOpenState,
|
||||
setTerminalSidePanelAutoOpenTabState,
|
||||
setLocalShellSidePanelAutoOpenState,
|
||||
|
||||
@@ -1,38 +1,21 @@
|
||||
import {
|
||||
buildSftpDownloadDialogDirectoryOptions,
|
||||
normalizeSftpDefaultDownloadDirectory,
|
||||
type SftpDownloadDialogDirectoryOptions,
|
||||
} from "../../../domain/sftpDownloadLocation";
|
||||
import {
|
||||
STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
} from "../../../infrastructure/config/storageKeys";
|
||||
import { STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR } from "../../../infrastructure/config/storageKeys";
|
||||
import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter";
|
||||
|
||||
/**
|
||||
* Read the device-local download folders at call time so every SFTP
|
||||
* Read the device-local default download folder at call time so every SFTP
|
||||
* surface (main view, terminal side panel, other windows) sees the latest
|
||||
* value without threading it through props.
|
||||
*/
|
||||
export const getSftpDownloadDialogDirectoryOptions = (): SftpDownloadDialogDirectoryOptions => {
|
||||
let stored: string | null = null;
|
||||
let lastUsed: string | null = null;
|
||||
try {
|
||||
stored = localStorageAdapter.readString(STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR);
|
||||
lastUsed = localStorageAdapter.readString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR);
|
||||
} catch {
|
||||
// Storage unavailable (non-browser host); fall back to system Downloads.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored, lastUsed);
|
||||
};
|
||||
|
||||
/** Remember a confirmed download destination without changing the setting. */
|
||||
export const rememberSftpDownloadDirectory = (directory: string): void => {
|
||||
const normalized = normalizeSftpDefaultDownloadDirectory(directory);
|
||||
if (!normalized) return;
|
||||
try {
|
||||
localStorageAdapter.writeString(STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR, normalized);
|
||||
} catch {
|
||||
// Unavailable storage must not interrupt the download.
|
||||
}
|
||||
return buildSftpDownloadDialogDirectoryOptions(stored);
|
||||
};
|
||||
@@ -1022,9 +1022,6 @@ export const useSftpConnections = ({
|
||||
id: connectionId,
|
||||
hostId: host.id,
|
||||
hostLabel: host.label,
|
||||
hostname: host.hostname,
|
||||
port: host.port,
|
||||
username: host.username,
|
||||
isLocal: false,
|
||||
status: "connecting",
|
||||
currentPath: normalizedCachedStartPath,
|
||||
|
||||
@@ -47,7 +47,6 @@ test('Win32 adapters confirm actual native cwd and reject stale revisions or for
|
||||
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
|
||||
});
|
||||
t.after(() => controller.dispose());
|
||||
assert.equal(await controller.refresh(), cwd);
|
||||
const revision = terminalCwdStore.getSessionRevision(id);
|
||||
terminalCwdStore.setCwd(id, 'C:\\other', 'backend-strict');
|
||||
terminalCwdStore.setCwd(id, 'C:\\base', 'backend-strict');
|
||||
@@ -208,7 +207,7 @@ for (const probe of ['fails', 'stalls'] as const) {
|
||||
t.after(() => controller.dispose());
|
||||
await controller.change('/next', new AbortController().signal, () => {});
|
||||
assert.deepEqual(writes, ["cd -- '/next'\r"]);
|
||||
assert.equal(controller.getConfirmedCwd(), '/next');
|
||||
assert.equal(controller.hasConfirmedCwd(), true);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DirectoryPickerError, directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
|
||||
import { isAbsoluteDirectoryPath, sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
|
||||
import { DirectoryPickerError, directoryChangeCommand, isDirectoryPath, COMPLETE_DIRECTORY_CAPABILITIES, type DirectoryCapabilities } from '../../domain/directoryPicker';
|
||||
import { sameDirectoryPath, type DirectoryTarget } from '../../domain/directoryPath';
|
||||
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
|
||||
@@ -16,33 +16,19 @@ export function createTerminalDirectoryController(options: {
|
||||
target?: DirectoryTarget;
|
||||
capabilities?: DirectoryCapabilities;
|
||||
buildChangeCommand?: (path: string) => string | null;
|
||||
trustOsc7?: boolean;
|
||||
localPosixSessionId?: string;
|
||||
}) {
|
||||
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 => isAbsoluteDirectoryPath(path, target.pathFlavor);
|
||||
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 verifiedCwd: string | null = null;
|
||||
const cwdListeners = new Set<() => void>();
|
||||
const notifyCwd = () => cwdListeners.forEach(listener => listener());
|
||||
let confirmed = false;
|
||||
let refreshing: Promise<string> | null = null;
|
||||
let refreshAgain = false;
|
||||
let cwdError: DirectoryPickerError | null = null;
|
||||
const lifetime = new AbortController();
|
||||
const current = () => !disposed && options.isCurrent();
|
||||
function getConfirmedCwd(): string | null {
|
||||
if (!current() || !capabilities.readCwd) return null;
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
const source = terminalCwdStore.getSource(options.sessionId);
|
||||
if (source === 'stale') return null;
|
||||
if (trustsOsc7 && source === 'osc7' && valid(cwd)) return cwd;
|
||||
if (options.trustOsc7 === false && target.pathFlavor === 'posix') return verifiedCwd;
|
||||
return verifiedCwd !== null && cwd === verifiedCwd ? verifiedCwd : null;
|
||||
}
|
||||
function check(signal?: AbortSignal) {
|
||||
if (!current() || signal?.aborted) throw new DirectoryPickerError('unavailable');
|
||||
}
|
||||
@@ -71,7 +57,7 @@ export function createTerminalDirectoryController(options: {
|
||||
if (!capabilities.readCwd) throw new DirectoryPickerError('unavailable');
|
||||
const activeShellCwd = () => {
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
&& (submittedRevision === undefined || terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision)
|
||||
? cwd : null;
|
||||
};
|
||||
@@ -80,7 +66,7 @@ export function createTerminalDirectoryController(options: {
|
||||
// events and picker remounts. Only a cd submission may probe past its own
|
||||
// pre-write report while waiting for fresh confirmation.
|
||||
const reported = activeShellCwd();
|
||||
if (reported) { cwdError = null; return reported; }
|
||||
if (reported) { confirmed = true; cwdError = null; return reported; }
|
||||
if (refreshing) {
|
||||
// Output may settle while a pre-cd query is still in flight. Keep one
|
||||
// follow-up query so that its older result cannot be the last update.
|
||||
@@ -93,24 +79,20 @@ export function createTerminalDirectoryController(options: {
|
||||
cwd = await bounded(options.io.cwd());
|
||||
if (!valid(cwd)) throw new DirectoryPickerError('unknown');
|
||||
} catch (error) {
|
||||
if (current() && !trustsOsc7) {
|
||||
verifiedCwd = null;
|
||||
if (current() && target.pathFlavor === 'win32') {
|
||||
confirmed = false;
|
||||
cwdError = error instanceof DirectoryPickerError ? error : new DirectoryPickerError('unknown');
|
||||
options.publish('');
|
||||
notifyCwd();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
check();
|
||||
const reported = activeShellCwd();
|
||||
const live = terminalCwdStore.getCwd(options.sessionId);
|
||||
const verifiedCwdChanged = verifiedCwd !== cwd;
|
||||
verifiedCwd = cwd;
|
||||
confirmed = true;
|
||||
cwdError = null;
|
||||
if (reported) return reported;
|
||||
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale'
|
||||
|| verifiedCwdChanged) options.publish(cwd);
|
||||
if (verifiedCwdChanged) notifyCwd();
|
||||
if (live !== cwd || terminalCwdStore.getSource(options.sessionId) === 'stale') options.publish(cwd);
|
||||
return cwd;
|
||||
})();
|
||||
refreshing = pending;
|
||||
@@ -137,7 +119,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 && getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
|
||||
if (expectedCwd && 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');
|
||||
@@ -145,7 +127,7 @@ export function createTerminalDirectoryController(options: {
|
||||
const deadline = Date.now() + (options.confirmationMs ?? 8000);
|
||||
const hasFreshOsc7 = () => {
|
||||
const cwd = terminalCwdStore.getCwd(options.sessionId);
|
||||
return trustsOsc7 && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
|
||||
return target.pathFlavor === 'posix' && valid(cwd) && terminalCwdStore.getSessionRevision(options.sessionId) !== submittedRevision
|
||||
&& terminalCwdStore.getSource(options.sessionId) === 'osc7'
|
||||
&& (same(cwd, path) || same(cwd, canonical));
|
||||
};
|
||||
@@ -183,23 +165,15 @@ export function createTerminalDirectoryController(options: {
|
||||
};
|
||||
await Promise.race([confirmFromProbe(), confirmFromOsc7()]);
|
||||
check(signal);
|
||||
confirmed = true;
|
||||
} finally { confirmationFinished = true; changing = false; }
|
||||
}
|
||||
return {
|
||||
target,
|
||||
localPosixSessionId: options.localPosixSessionId,
|
||||
capabilities,
|
||||
getConfirmedCwd,
|
||||
subscribeCwd(listener: () => void) {
|
||||
const unsubscribe = terminalCwdStore.subscribe(listener);
|
||||
cwdListeners.add(listener);
|
||||
return () => {
|
||||
unsubscribe();
|
||||
cwdListeners.delete(listener);
|
||||
};
|
||||
},
|
||||
getCwdError: () => cwdError?.code ?? null,
|
||||
refresh: () => refresh(),
|
||||
hasConfirmedCwd: () => confirmed,
|
||||
async home() {
|
||||
check();
|
||||
const result = await bounded(options.io.home?.() ?? Promise.resolve(null));
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { TerminalDirectoryController } from './terminalDirectoryController'
|
||||
|
||||
const sessions = new Map<string, TerminalDirectoryController>();
|
||||
const consumers = new Map<string, number>();
|
||||
const refreshListeners = new Map<string, Set<() => void>>();
|
||||
const scheduledRefreshes = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const OUTPUT_SETTLE_MS = 150;
|
||||
|
||||
@@ -37,24 +36,10 @@ export function observeTerminalDirectory(id: string) {
|
||||
else { consumers.delete(id); cancelScheduledRefresh(id); }
|
||||
};
|
||||
}
|
||||
export function subscribeTerminalDirectoryRefresh(id: string, listener: () => void) {
|
||||
const listeners = refreshListeners.get(id) ?? new Set<() => void>();
|
||||
listeners.add(listener);
|
||||
refreshListeners.set(id, listeners);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) refreshListeners.delete(id);
|
||||
};
|
||||
}
|
||||
|
||||
/** Called by the existing command completion path, only while chips are visible. */
|
||||
export function refreshObservedTerminalDirectory(id: string) {
|
||||
cancelScheduledRefresh(id);
|
||||
const controller = consumers.has(id) ? sessions.get(id) : undefined;
|
||||
if (!controller) return;
|
||||
void controller.refresh().then(() => {
|
||||
if (sessions.get(id) === controller) refreshListeners.get(id)?.forEach(listener => listener());
|
||||
}).catch(() => {});
|
||||
if (consumers.has(id)) void sessions.get(id)?.refresh().catch(() => {});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
@@ -19,8 +19,6 @@ import {
|
||||
STORAGE_KEY_AI_WEB_SEARCH,
|
||||
STORAGE_KEY_AI_QUICK_MESSAGES,
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type { AIQuickMessage } from '../../infrastructure/ai/quickMessages';
|
||||
import { sanitizeQuickMessages } from '../../infrastructure/ai/quickMessages';
|
||||
@@ -48,7 +46,6 @@ import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import type { TitleModelConfig } from '../../domain/aiSessionTitle';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -57,25 +54,6 @@ import {
|
||||
readCommandBlocklistSetting,
|
||||
} from './commandBlocklistSettings';
|
||||
|
||||
export type { TitleModelConfig };
|
||||
|
||||
function readTitleModelSetting(): TitleModelConfig | null {
|
||||
const stored = localStorageAdapter.read<unknown>(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
if (!stored || typeof stored !== 'object') return null;
|
||||
const providerId = (stored as TitleModelConfig).providerId;
|
||||
const modelId = (stored as TitleModelConfig).modelId;
|
||||
return typeof providerId === 'string' && providerId.trim()
|
||||
&& typeof modelId === 'string' && modelId.trim()
|
||||
? { providerId: providerId.trim(), modelId: modelId.trim() }
|
||||
: null;
|
||||
}
|
||||
|
||||
function readAgentStringMap(key: string): Record<string, string> {
|
||||
const stored = localStorageAdapter.read<unknown>(key);
|
||||
if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return {};
|
||||
return stored as Record<string, string>;
|
||||
}
|
||||
|
||||
function readPermissionMode(): AIPermissionMode {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE);
|
||||
if (stored === 'observer' || stored === 'confirm' || stored === 'auto') return stored;
|
||||
@@ -172,25 +150,6 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const [quickMessages, setQuickMessagesRaw] = useState<AIQuickMessage[]>(() =>
|
||||
sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)),
|
||||
);
|
||||
const [autoLlmTitle, setAutoLlmTitle] = useStoredBoolean(STORAGE_KEY_AI_AUTO_LLM_TITLE, true);
|
||||
const [titleModel, setTitleModelRaw] = useState<TitleModelConfig | null>(() =>
|
||||
readTitleModelSetting(),
|
||||
);
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
|
||||
const setTitleModel = useCallback((config: TitleModelConfig | null) => {
|
||||
const normalized = config
|
||||
&& typeof config.providerId === 'string' && config.providerId.trim()
|
||||
&& typeof config.modelId === 'string' && config.modelId.trim()
|
||||
? { providerId: config.providerId.trim(), modelId: config.modelId.trim() }
|
||||
: null;
|
||||
titleModelRef.current = normalized;
|
||||
setTitleModelRaw(normalized);
|
||||
if (normalized) localStorageAdapter.write(STORAGE_KEY_AI_TITLE_MODEL, normalized);
|
||||
else localStorageAdapter.remove(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_TITLE_MODEL);
|
||||
}, []);
|
||||
|
||||
const setProviders = useCallback((value: ProviderConfig[] | ((prev: ProviderConfig[]) => ProviderConfig[])) => {
|
||||
setProvidersRaw((prev) => {
|
||||
@@ -224,9 +183,6 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
localStorageAdapter.writeString(STORAGE_KEY_AI_ACTIVE_PROVIDER, '');
|
||||
return '';
|
||||
});
|
||||
if (titleModelRef.current?.providerId === id) {
|
||||
setTitleModel(null);
|
||||
}
|
||||
|
||||
if (onRemoveProvider) {
|
||||
onRemoveProvider(id);
|
||||
@@ -240,13 +196,11 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
const cleanup = removeProviderReferences(id, agentProviderMap, agentModelMap);
|
||||
if (cleanup.providerMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, cleanup.agentProviderMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
||||
}
|
||||
if (cleanup.modelMapChanged) {
|
||||
localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, cleanup.agentModelMap);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
||||
}
|
||||
}, [onRemoveProvider, setProviders, setTitleModel]);
|
||||
}, [onRemoveProvider, setProviders]);
|
||||
|
||||
const setActiveProviderId = useCallback((id: string) => {
|
||||
setActiveProviderIdRaw(id);
|
||||
@@ -421,9 +375,6 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
case STORAGE_KEY_AI_QUICK_MESSAGES:
|
||||
setQuickMessagesRaw(sanitizeQuickMessages(localStorageAdapter.read<unknown>(STORAGE_KEY_AI_QUICK_MESSAGES)));
|
||||
break;
|
||||
case STORAGE_KEY_AI_TITLE_MODEL:
|
||||
setTitleModelRaw(readTitleModelSetting());
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
@@ -487,10 +438,6 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
}), [
|
||||
providers,
|
||||
setProviders,
|
||||
@@ -524,10 +471,6 @@ export function useSharedAISettingsState(options?: SharedAISettingsStateOptions)
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -543,12 +486,6 @@ export function useAISettingsState() {
|
||||
STORAGE_KEY_AI_SHOW_TERMINAL_SELECTION_ACTION,
|
||||
true,
|
||||
);
|
||||
const [agentProviderMap, setAgentProviderMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP),
|
||||
);
|
||||
const [agentModelMap, setAgentModelMapRaw] = useState<Record<string, string>>(() =>
|
||||
readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP),
|
||||
);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
@@ -557,32 +494,23 @@ export function useAISettingsState() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const syncSettingsOnlyKey = (key: string | null) => {
|
||||
const syncMessageCap = (key: string | null) => {
|
||||
if (key !== STORAGE_KEY_AI_SESSION_MESSAGE_CAP) return;
|
||||
try {
|
||||
switch (key) {
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_PROVIDER_MAP:
|
||||
setAgentProviderMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_PROVIDER_MAP));
|
||||
break;
|
||||
case STORAGE_KEY_AI_AGENT_MODEL_MAP:
|
||||
setAgentModelMapRaw(readAgentStringMap(STORAGE_KEY_AI_AGENT_MODEL_MAP));
|
||||
break;
|
||||
}
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
?? DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn('[useAISettingsState] Failed to process AI settings storage change', key, err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleStorage = (event: StorageEvent) => syncSettingsOnlyKey(event.key);
|
||||
const handleStorage = (event: StorageEvent) => syncMessageCap(event.key);
|
||||
const handleLocalStateChanged = (event: Event) => {
|
||||
syncSettingsOnlyKey((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
syncMessageCap((event as CustomEvent<{ key?: string }>).detail?.key ?? null);
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorage);
|
||||
@@ -599,15 +527,11 @@ export function useAISettingsState() {
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}), [
|
||||
shared,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
showTerminalSelectionAIAction,
|
||||
setShowTerminalSelectionAIAction,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
]);
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
import type { AISession, ProviderConfig } from '../../infrastructure/ai/types.ts';
|
||||
import {
|
||||
STORAGE_KEY_AI_ACTIVE_PROVIDER,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AUTO_LLM_TITLE,
|
||||
STORAGE_KEY_AI_PROVIDERS,
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
|
||||
import { useAISessionsStore } from './aiSessionsStore.ts';
|
||||
import {
|
||||
__resetIdbPersistenceForTests,
|
||||
markAiSessionsHydrationComplete,
|
||||
setLatestAISessionsSnapshot,
|
||||
} from './aiStateSnapshots.ts';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
type Capture = {
|
||||
ai: ReturnType<typeof useAIState> | null;
|
||||
sessions: AISession[];
|
||||
};
|
||||
|
||||
function Harness({
|
||||
capture,
|
||||
options,
|
||||
}: {
|
||||
capture: Capture;
|
||||
options?: UseAIStateOptions;
|
||||
}) {
|
||||
capture.ai = useAIState(options);
|
||||
capture.sessions = useAISessionsStore().sessions as AISession[];
|
||||
return null;
|
||||
}
|
||||
|
||||
async function setupHook(options?: {
|
||||
sessions?: AISession[];
|
||||
providers?: ProviderConfig[];
|
||||
activeProviderId?: string;
|
||||
agentProviderMap?: Record<string, string>;
|
||||
agentModelMap?: Record<string, string>;
|
||||
autoLlmTitle?: boolean;
|
||||
titleModel?: { providerId: string; modelId: string } | null;
|
||||
generateSessionTitle?: UseAIStateOptions['generateSessionTitle'];
|
||||
}) {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
|
||||
const prevDescriptors = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of [
|
||||
['window', dom.window],
|
||||
['document', dom.window.document],
|
||||
['localStorage', dom.window.localStorage],
|
||||
['CustomEvent', dom.window.CustomEvent],
|
||||
['Event', dom.window.Event],
|
||||
['IS_REACT_ACT_ENVIRONMENT', true],
|
||||
] as const) {
|
||||
prevDescriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
|
||||
__resetIdbPersistenceForTests();
|
||||
markAiSessionsHydrationComplete();
|
||||
|
||||
if (options?.providers) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_PROVIDERS, JSON.stringify(options.providers));
|
||||
}
|
||||
if (options?.activeProviderId) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_ACTIVE_PROVIDER, options.activeProviderId);
|
||||
}
|
||||
if (options?.agentProviderMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify(options.agentProviderMap));
|
||||
}
|
||||
if (options?.agentModelMap) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify(options.agentModelMap));
|
||||
}
|
||||
if (options?.autoLlmTitle !== undefined) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_AUTO_LLM_TITLE, String(options.autoLlmTitle));
|
||||
}
|
||||
if (options?.titleModel) {
|
||||
dom.window.localStorage.setItem(STORAGE_KEY_AI_TITLE_MODEL, JSON.stringify(options.titleModel));
|
||||
}
|
||||
|
||||
const initialSessions = options?.sessions ?? [];
|
||||
setLatestAISessionsSnapshot(initialSessions);
|
||||
dom.window.localStorage.setItem('netcatty_ai_sessions_v1', JSON.stringify(initialSessions));
|
||||
|
||||
const container = dom.window.document.createElement('div');
|
||||
dom.window.document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const capture: Capture = { ai: null, sessions: [] };
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
React.createElement(Harness, {
|
||||
capture,
|
||||
options: { generateSessionTitle: options?.generateSessionTitle },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
capture,
|
||||
cleanup: async () => {
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
__resetIdbPersistenceForTests();
|
||||
for (const [key, desc] of prevDescriptors) {
|
||||
if (desc) Object.defineProperty(globalThis, key, desc);
|
||||
else delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const providerA: ProviderConfig = {
|
||||
id: 'p-catty',
|
||||
providerId: 'openai',
|
||||
name: 'Main OpenAI',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-5.4',
|
||||
};
|
||||
|
||||
const providerB: ProviderConfig = {
|
||||
id: 'p-title',
|
||||
providerId: 'openai',
|
||||
name: 'Cheap Title',
|
||||
enabled: true,
|
||||
defaultModel: 'gpt-4o-mini',
|
||||
};
|
||||
|
||||
const untitledSession = (id = 's-1'): AISession => ({
|
||||
id,
|
||||
title: 'New Chat',
|
||||
agentId: 'catty',
|
||||
scope: { type: 'terminal', targetId: 'term-1' },
|
||||
messages: [{ id: 'm-1', role: 'user', content: 'Check slow SSH handshake on prod', timestamp: 1 }],
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
});
|
||||
|
||||
test('autoTitleSession preserves a user rename that happens while LLM title generation is pending', async () => {
|
||||
const pending = deferred<string>();
|
||||
let capturedSignal: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession()],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
capturedSignal = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let titleTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
titleTask = capture.ai!.autoTitleSession('s-1', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
// Deterministic fallback landed immediately.
|
||||
assert.equal(capture.sessions[0].title, 'Check slow SSH handshake on prod');
|
||||
assert.equal(capturedSignal?.aborted, false);
|
||||
|
||||
// User renames the session (e.g. after closing & reopening the side panel).
|
||||
await act(async () => {
|
||||
capture.ai!.updateSessionTitle('s-1', 'Prod SSH Debug');
|
||||
});
|
||||
assert.equal(capturedSignal?.aborted, true, 'manual rename aborts pending LLM call');
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
|
||||
// Even if the LLM promise resolves with a generated title afterwards, it
|
||||
// must not overwrite the user's title.
|
||||
await act(async () => {
|
||||
pending.resolve('Slow SSH Handshake');
|
||||
await titleTask;
|
||||
});
|
||||
assert.equal(capture.sessions[0].title, 'Prod SSH Debug');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession promotes the LLM title when unrenamed and passes Catty or explicit titleModel config', async () => {
|
||||
const seenConfigs: Array<ProviderConfig | null | undefined> = [];
|
||||
const pending = deferred<string>();
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-catty'), untitledSession('s-explicit')],
|
||||
providers: [providerB, providerA],
|
||||
activeProviderId: providerB.id,
|
||||
agentProviderMap: { catty: providerA.id },
|
||||
agentModelMap: { catty: 'gpt-5.4-turbo' },
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
seenConfigs.push(opts.config);
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
let task!: Promise<void>;
|
||||
await act(async () => {
|
||||
task = capture.ai!.autoTitleSession('s-catty', 'Check slow SSH handshake on prod');
|
||||
});
|
||||
assert.equal(seenConfigs[0]?.id, providerA.id);
|
||||
assert.equal(seenConfigs[0]?.defaultModel, 'gpt-5.4-turbo');
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve('SSH Handshake Audit');
|
||||
await task;
|
||||
});
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-catty')?.title, 'SSH Handshake Audit');
|
||||
|
||||
// Explicit titleModel overrides Catty model.
|
||||
await act(async () => {
|
||||
capture.ai!.setTitleModel({ providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
});
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-explicit', 'Inspect nginx error logs');
|
||||
});
|
||||
assert.equal(seenConfigs[1]?.id, providerB.id);
|
||||
assert.equal(seenConfigs[1]?.defaultModel, 'gpt-4o-mini');
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-explicit')?.title, 'SSH Handshake Audit');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession aborts and ignores deleted sessions, deduplicates concurrent calls, and skips titled chats', async () => {
|
||||
const pending = deferred<string>();
|
||||
let calls = 0;
|
||||
let signalRef: AbortSignal | undefined;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [
|
||||
untitledSession('s-del'),
|
||||
untitledSession('s-dup'),
|
||||
{ ...untitledSession('s-titled'), title: 'Already named' },
|
||||
],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
calls += 1;
|
||||
signalRef = opts.signal;
|
||||
return pending.promise;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// Titled chat skips both fallback and LLM.
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-titled', 'New prompt text');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions.find((s) => s.id === 's-titled')?.title, 'Already named');
|
||||
|
||||
// Deleting a session aborts in-flight generation and never resurrects it.
|
||||
let delTask!: Promise<void>;
|
||||
await act(async () => {
|
||||
delTask = capture.ai!.autoTitleSession('s-del', 'Delete me mid-flight');
|
||||
});
|
||||
assert.equal(calls, 1);
|
||||
await act(async () => {
|
||||
capture.ai!.deleteSession('s-del');
|
||||
});
|
||||
assert.equal(signalRef?.aborted, true);
|
||||
await act(async () => {
|
||||
pending.resolve('Ghost title');
|
||||
await delTask;
|
||||
});
|
||||
assert.equal(capture.sessions.some((s) => s.id === 's-del'), false);
|
||||
|
||||
// Duplicate concurrent call for the same session only invokes LLM once.
|
||||
const pendingDup = deferred<string>();
|
||||
const dupHarness = await setupHook({
|
||||
sessions: [untitledSession('s-dup2')],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return pendingDup.promise;
|
||||
},
|
||||
});
|
||||
try {
|
||||
let t1!: Promise<void>;
|
||||
let t2!: Promise<void>;
|
||||
await act(async () => {
|
||||
t1 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'First call');
|
||||
t2 = dupHarness.capture.ai!.autoTitleSession('s-dup2', 'Second call');
|
||||
});
|
||||
assert.equal(calls, 2);
|
||||
await act(async () => {
|
||||
pendingDup.resolve('Single Title');
|
||||
await Promise.all([t1, t2]);
|
||||
});
|
||||
assert.equal(dupHarness.capture.sessions.find((s) => s.id === 's-dup2')?.title, 'Single Title');
|
||||
} finally {
|
||||
await dupHarness.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dangling titleModel', async () => {
|
||||
let calls = 0;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [untitledSession('s-off')],
|
||||
providers: [providerA, providerB],
|
||||
activeProviderId: providerA.id,
|
||||
autoLlmTitle: false,
|
||||
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
|
||||
generateSessionTitle: async () => {
|
||||
calls += 1;
|
||||
return 'Should not run';
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
await capture.ai!.autoTitleSession('s-off', 'Fallback only please');
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions[0].title, 'Fallback only please');
|
||||
|
||||
assert.deepEqual(capture.ai!.titleModel, { providerId: providerB.id, modelId: 'gpt-4o-mini' });
|
||||
await act(async () => {
|
||||
capture.ai!.removeProvider(providerB.id);
|
||||
});
|
||||
assert.equal(capture.ai!.titleModel, null);
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
@@ -98,20 +98,8 @@ import {
|
||||
buildUndoLastTurnBranch,
|
||||
type UndoLastTurnRestoredDraft,
|
||||
} from '../../domain/aiUndoLastTurn';
|
||||
import {
|
||||
applySessionTitleIfCurrent,
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveEffectiveTitleModelConfig,
|
||||
} from '../../domain/aiSessionTitle';
|
||||
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
|
||||
|
||||
export interface UseAIStateOptions {
|
||||
/** Optional test injection for one-shot LLM title generation. */
|
||||
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
|
||||
}
|
||||
|
||||
export function useAIState(options?: UseAIStateOptions) {
|
||||
export function useAIState() {
|
||||
const [hostPermissions, setHostPermissionsRaw] = useState<HostAIPermission[]>(() =>
|
||||
localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS) ?? []
|
||||
);
|
||||
@@ -414,35 +402,11 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
} = useSharedAISettingsState({
|
||||
ignoreInvalidPermissionModeOnStorage: true,
|
||||
onRemoveProvider: handleRemoveProviderReferences,
|
||||
});
|
||||
|
||||
const providersRef = useRef(providers);
|
||||
providersRef.current = providers;
|
||||
const activeProviderIdRef = useRef(activeProviderId);
|
||||
activeProviderIdRef.current = activeProviderId;
|
||||
const activeModelIdRef = useRef(activeModelId);
|
||||
activeModelIdRef.current = activeModelId;
|
||||
const autoLlmTitleRef = useRef(autoLlmTitle);
|
||||
autoLlmTitleRef.current = autoLlmTitle;
|
||||
const titleModelRef = useRef(titleModel);
|
||||
titleModelRef.current = titleModel;
|
||||
const generateSessionTitleRef = useRef(options?.generateSessionTitle);
|
||||
generateSessionTitleRef.current = options?.generateSessionTitle;
|
||||
const pendingCreatedSessionIdsRef = useRef<Set<string>>(new Set());
|
||||
const titleAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
|
||||
useEffect(() => {
|
||||
for (const session of sessions) {
|
||||
pendingCreatedSessionIdsRef.current.delete(session.id);
|
||||
}
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
}, [sessions]);
|
||||
@@ -760,14 +724,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
// Keep the source workspace name when the fork stays in that workspace;
|
||||
// a fork into a different/terminal scope must not inherit a stale name.
|
||||
if (
|
||||
source.workspaceNameSnapshot
|
||||
&& (!viewingScope || (viewingScope.type === 'workspace' && viewingScope.targetId === source.scope.targetId))
|
||||
) {
|
||||
fork.workspaceNameSnapshot = source.workspaceNameSnapshot;
|
||||
}
|
||||
if (plan.contextCompaction) {
|
||||
fork.contextCompaction = plan.contextCompaction;
|
||||
}
|
||||
@@ -783,25 +739,17 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
return fork;
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const createSession = useCallback((
|
||||
scope: AISessionScope,
|
||||
agentId?: string,
|
||||
workspaceNameSnapshot?: string,
|
||||
): AISession => {
|
||||
const createSession = useCallback((scope: AISessionScope, agentId?: string): AISession => {
|
||||
const now = Date.now();
|
||||
const session: AISession = {
|
||||
id: `ai_${now}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
title: 'New Chat',
|
||||
agentId: agentId || defaultAgentId,
|
||||
scope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
messages: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
pendingCreatedSessionIdsRef.current.add(session.id);
|
||||
setSessionsRaw(prev => {
|
||||
const next = [session, ...prev];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -848,12 +796,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
|
||||
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
|
||||
pendingCreatedSessionIdsRef.current.delete(sessionId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
cleanupDeletedAIChatSessions([sessionId]);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -896,14 +838,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
const removedSessionIds = sessionsRef.current
|
||||
.filter(s => s.scope.type === scopeType && s.scope.targetId === targetId)
|
||||
.map(s => s.id);
|
||||
for (const removedId of removedSessionIds) {
|
||||
pendingCreatedSessionIdsRef.current.delete(removedId);
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(removedId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(removedId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
}
|
||||
cleanupDeletedAIChatSessions(removedSessionIds);
|
||||
if (persistTimerRef.current) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
@@ -931,12 +865,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, [persistSessions]);
|
||||
|
||||
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
|
||||
// Manual rename supersedes any in-flight automatic title generation.
|
||||
const pendingTitleController = titleAbortControllersRef.current.get(sessionId);
|
||||
if (pendingTitleController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
@@ -945,182 +873,12 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
});
|
||||
}, [persistSessions]);
|
||||
|
||||
/**
|
||||
* Auto-title a session if it still carries the placeholder title. Writes a
|
||||
* deterministic fallback immediately, then (when enabled and a model is
|
||||
* configured) upgrades it with a one-shot LLM summary. Lives in application
|
||||
* state so panel close/reopen cannot break the in-flight lifecycle, and
|
||||
* compares against live state atomically so a user rename always wins.
|
||||
*/
|
||||
const autoTitleSession = useCallback(async (
|
||||
sessionId: string,
|
||||
text: string,
|
||||
callerSignal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
if (!sessionId) return;
|
||||
if (titleAbortControllersRef.current.has(sessionId)) return;
|
||||
|
||||
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const existing = snapshot.find((s) => s.id === sessionId);
|
||||
if (existing && !canAutoTitleSession(existing)) return;
|
||||
if (!existing && !pendingCreatedSessionIdsRef.current.has(sessionId)) return;
|
||||
|
||||
const fallback = buildFallbackTitle(text);
|
||||
|
||||
// Phase 1: Atomically apply the deterministic fallback while still untitled.
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
|
||||
if (!autoLlmTitleRef.current || callerSignal?.aborted) return;
|
||||
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
activeProviderId: activeProviderIdRef.current,
|
||||
activeModelId: activeModelIdRef.current,
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
|
||||
const requestController = new AbortController();
|
||||
titleAbortControllersRef.current.set(sessionId, requestController);
|
||||
const onCallerAbort = () => requestController.abort();
|
||||
if (callerSignal) {
|
||||
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
|
||||
}
|
||||
|
||||
try {
|
||||
const latestBeforeCall = (latestAISessionsSnapshot ?? sessionsRef.current)
|
||||
.find((s) => s.id === sessionId);
|
||||
if (
|
||||
latestBeforeCall
|
||||
&& !canAutoTitleSession(latestBeforeCall)
|
||||
&& latestBeforeCall.title !== fallback
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const sourceMessages = latestBeforeCall?.messages?.length
|
||||
? latestBeforeCall.messages
|
||||
: (text ? [{ role: 'user' as const, content: text }] : []);
|
||||
if (sourceMessages.length === 0) return;
|
||||
|
||||
const generateTitle = generateSessionTitleRef.current
|
||||
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
|
||||
|
||||
const generated = await generateTitle(
|
||||
{ messages: sourceMessages },
|
||||
{
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: requestController.signal,
|
||||
},
|
||||
);
|
||||
|
||||
if (requestController.signal.aborted || !generated || generated === fallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Phase 2: Atomically promote the LLM title only if the session still
|
||||
// exists and still holds the exact fallback title applied in Phase 1.
|
||||
if (mountedRef.current) {
|
||||
setSessionsRaw((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
} else {
|
||||
const current = latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot();
|
||||
const result = applySessionTitleIfCurrent(current, sessionId, generated, fallback);
|
||||
if (result.updated) {
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Generation never throws; fallback was already applied above.
|
||||
} finally {
|
||||
if (callerSignal) {
|
||||
callerSignal.removeEventListener('abort', onCallerAbort);
|
||||
}
|
||||
if (titleAbortControllersRef.current.get(sessionId) === requestController) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
/**
|
||||
* Explicitly regenerate an existing chat's title with the configured LLM
|
||||
* (session-history management: no placeholder gate). The old title is the
|
||||
* expected value, so a user rename during generation still wins.
|
||||
*/
|
||||
const regenerateSessionTitle = useCallback(async (sessionId: string): Promise<void> => {
|
||||
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) return;
|
||||
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const session = snapshot.find((s) => s.id === sessionId);
|
||||
if (!session || session.messages.length === 0) return;
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
activeProviderId: activeProviderIdRef.current,
|
||||
activeModelId: activeModelIdRef.current,
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
const controller = new AbortController();
|
||||
titleAbortControllersRef.current.set(sessionId, controller);
|
||||
try {
|
||||
const generateTitle = generateSessionTitleRef.current
|
||||
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
|
||||
const generated = await generateTitle(
|
||||
{ messages: session.messages },
|
||||
{
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: controller.signal,
|
||||
fallbackOnFailure: false,
|
||||
},
|
||||
);
|
||||
if (controller.signal.aborted || !generated || generated === session.title) return;
|
||||
const previousTitle = session.title;
|
||||
const commit = (sessions: AISession[]) => {
|
||||
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
|
||||
if (!result.updated) return sessions;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
};
|
||||
if (mountedRef.current) setSessionsRaw(commit);
|
||||
else {
|
||||
const result = commit(latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot());
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
void result;
|
||||
}
|
||||
} catch {
|
||||
// Title generation never throws; keep the existing title on failure.
|
||||
} finally {
|
||||
if (titleAbortControllersRef.current.get(sessionId) === controller) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
|
||||
// Issue #4015 R2: rebind a dangling chat to the panel's current scope.
|
||||
// Rewrites `scope`, clears the dangling marker and makes the chat the
|
||||
// active session of its new scope so it shows in the scoped history again.
|
||||
const rebindSessionScope = useCallback((
|
||||
sessionId: string,
|
||||
scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] },
|
||||
workspaceNameSnapshot?: string,
|
||||
) => {
|
||||
const scopeKey = `${scope.type}:${scope.targetId}`;
|
||||
// Capture the PRE-rebind active map before rebindActiveSessionMap drops the
|
||||
@@ -1145,15 +903,9 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
if (scope.hostIds && scope.hostIds.length > 0) {
|
||||
nextScope.hostIds = [...scope.hostIds];
|
||||
}
|
||||
// Snapshot follows the binding: keep it only for workspace scopes.
|
||||
// `rest` may still carry a stale snapshot from a previous workspace.
|
||||
const { workspaceNameSnapshot: _staleSnapshot, ...withoutSnapshot } = rest;
|
||||
return {
|
||||
...withoutSnapshot,
|
||||
...rest,
|
||||
scope: nextScope,
|
||||
...(scope.type === 'workspace' && workspaceNameSnapshot
|
||||
? { workspaceNameSnapshot }
|
||||
: {}),
|
||||
updatedAt: Date.now(),
|
||||
} as AISession;
|
||||
});
|
||||
@@ -1701,10 +1453,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
// sessions / activeSessionIdMap / draftsByScope / panelViewByScope live in
|
||||
// aiSessionsStore so streaming updates do not rebuild this config object.
|
||||
setActiveSessionId,
|
||||
@@ -1720,8 +1468,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -1776,10 +1522,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
setWebSearchConfig,
|
||||
quickMessages,
|
||||
setQuickMessages,
|
||||
autoLlmTitle,
|
||||
setAutoLlmTitle,
|
||||
titleModel,
|
||||
setTitleModel,
|
||||
setActiveSessionId,
|
||||
ensureDraftForScope,
|
||||
updateDraft,
|
||||
@@ -1793,8 +1535,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
deleteSession,
|
||||
deleteSessionsByTarget,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
|
||||
@@ -16,19 +16,5 @@ export const useClipboardBackend = () => {
|
||||
return await bridge.writeClipboardText(text) === true;
|
||||
}, []);
|
||||
|
||||
const readClipboardImagePng = useCallback(async (): Promise<Uint8Array | null> => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (bridge?.readClipboardImagePng) return await bridge.readClipboardImagePng();
|
||||
|
||||
// Browser fallback when the native clipboard bridge is unavailable.
|
||||
const items = await navigator.clipboard?.read();
|
||||
for (const item of items ?? []) {
|
||||
if (!item.types.includes("image/png")) continue;
|
||||
const blob = await item.getType("image/png");
|
||||
return new Uint8Array(await blob.arrayBuffer());
|
||||
}
|
||||
return null;
|
||||
}, []);
|
||||
|
||||
return { readClipboardText, writeClipboardText, readClipboardImagePng };
|
||||
return { readClipboardText, writeClipboardText };
|
||||
};
|
||||
@@ -63,8 +63,6 @@ interface CloudSyncRunOptions {
|
||||
conflictActionOverride?: CloudSyncConflictAction;
|
||||
applyConvergentPayload?: ConvergentPayloadApplier;
|
||||
signal?: AbortSignal;
|
||||
/** One-shot manual sync: skip convergent fan-out (single-provider only). */
|
||||
forceSingleProvider?: boolean;
|
||||
}
|
||||
|
||||
export interface CloudSyncHook {
|
||||
@@ -136,7 +134,7 @@ export interface CloudSyncHook {
|
||||
syncToProvider: (
|
||||
provider: CloudProvider,
|
||||
payload: SyncPayload,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
|
||||
) => Promise<SyncResult>;
|
||||
downloadFromProvider: (provider: CloudProvider) => Promise<RemoteSyncPayload | null>;
|
||||
commitRemoteInspection: (provider: CloudProvider, remoteFile: SyncedFile, payload: SyncPayload, opts?: { recordDownload?: boolean }) => Promise<void>;
|
||||
@@ -820,7 +818,7 @@ export const useCloudSync = (): CloudSyncHook => {
|
||||
const syncToProviderWithUnlock = useCallback(async (
|
||||
provider: CloudProvider,
|
||||
payload: SyncPayload,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal' | 'forceSingleProvider'>,
|
||||
opts?: Pick<CloudSyncRunOptions, 'overrideShrink' | 'applyConvergentPayload' | 'signal'>,
|
||||
) => {
|
||||
await ensureUnlocked();
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { DirectoryPickerError, filterDirectories, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
|
||||
import { parentDirectoryPath } from '../../domain/directoryPath';
|
||||
import { DirectoryPickerError, directoryParent, filterDirectories, isDirectoryPath, type DirectoryEntry, type DirectoryPickerErrorCode } from '../../domain/directoryPicker';
|
||||
import { resolveComposeDirectoryDisplay, type ComposeDirectoryDisplay } from '../../domain/composeDirectoryDisplay';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirectories } from './terminalDirectoryRegistry';
|
||||
@@ -8,9 +7,13 @@ import { getTerminalDirectory, observeTerminalDirectory, subscribeTerminalDirect
|
||||
export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const pathFlavor = controller?.target.pathFlavor ?? 'posix';
|
||||
const subscribeCwd = controller?.subscribeCwd ?? terminalCwdStore.subscribe;
|
||||
const getCurrentCwd = useCallback(() => controller?.getConfirmedCwd() ?? null, [controller]);
|
||||
const cwd = useSyncExternalStore(subscribeCwd, getCurrentCwd, () => null);
|
||||
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 cwd = controller && isDirectoryPath(observedCwd, pathFlavor)
|
||||
&& (confirmed || controller.hasConfirmedCwd() || (pathFlavor === 'posix' && terminalCwdStore.getSource(sessionId) === 'osc7'))
|
||||
? observedCwd : null;
|
||||
const [open, setOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [showHidden, setShowHidden] = useState(false);
|
||||
@@ -42,11 +45,11 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const stopObserving = observeTerminalDirectory(sessionId);
|
||||
lifetime.current = new AbortController();
|
||||
sending.current = false;
|
||||
setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
|
||||
setConfirmation(null); setOpen(false); setPending(false); setLoading(false); setHome(null); setError(null); setEntries([]);
|
||||
listingBase.current = null;
|
||||
listingRevision.current = null;
|
||||
if (controller) void Promise.all([controller.refresh(), controller.home()]).then(([, nextHome]) => {
|
||||
if (generation.current === id) setHome(nextHome);
|
||||
if (generation.current === id) { setConfirmation({ sessionId, controller }); setHome(nextHome); }
|
||||
}).catch(failure => { if (generation.current === id) report(failure, 'unknown'); });
|
||||
return () => {
|
||||
generation.current = id + 1;
|
||||
@@ -58,9 +61,9 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
if (!controller) { setError('unavailable'); return; }
|
||||
const id = generation.current;
|
||||
setError(null);
|
||||
try { await controller.refresh(); }
|
||||
try { await controller.refresh(); if (generation.current === id) setConfirmation({ sessionId, controller }); }
|
||||
catch (failure) { if (generation.current === id) report(failure, 'unknown'); }
|
||||
}, [controller, report]);
|
||||
}, [controller, report, sessionId]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!controller || !cwd) return;
|
||||
@@ -74,7 +77,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 || getCurrentCwd() !== cwd) return;
|
||||
if (task.signal.aborted || id !== generation.current || terminalCwdStore.getCwd(sessionId) !== cwd) return;
|
||||
if (terminalCwdStore.getSessionRevision(sessionId) !== revision) continue;
|
||||
listingBase.current = cwd; listingRevision.current = revision; setEntries(result.entries); setHome(result.home);
|
||||
return;
|
||||
@@ -83,7 +86,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, getCurrentCwd, report, sessionId, setHome]);
|
||||
}, [controller, cwd, report, sessionId, setHome]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!cwd) {
|
||||
@@ -99,8 +102,8 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
const change = useCallback(async (path: string) => {
|
||||
if (!controller) { setError('unavailable'); return; }
|
||||
if (sending.current) return;
|
||||
if (!cwd || getCurrentCwd() !== cwd
|
||||
|| (path !== parentDirectoryPath(cwd, pathFlavor) && (listingBase.current !== cwd
|
||||
if (!cwd || terminalCwdStore.getCwd(sessionId) !== cwd
|
||||
|| (path !== directoryParent(cwd, pathFlavor) && (listingBase.current !== cwd
|
||||
|| listingRevision.current !== terminalCwdStore.getSessionRevision(sessionId)))) { setError('unavailable'); return; }
|
||||
sending.current = true; setPending(true); setError(null);
|
||||
const id = generation.current;
|
||||
@@ -112,14 +115,14 @@ export function useComposeDirectoryPicker(sessionId: string) {
|
||||
finally {
|
||||
if (id === generation.current) { sending.current = false; setPending(false); }
|
||||
}
|
||||
}, [controller, report, cwd, sessionId, pathFlavor, getCurrentCwd]);
|
||||
}, [controller, report, cwd, sessionId, pathFlavor]);
|
||||
|
||||
const filtered = useMemo(() => filterDirectories(entries, query, showHidden), [entries, query, showHidden]);
|
||||
const cwdError = useSyncExternalStore(subscribeCwd, () => controller?.getCwdError() ?? null, () => null);
|
||||
const cwdError = controller?.getCwdError() ?? null;
|
||||
const waitsForCwd = error === 'unknown' || error === 'integrationUnavailable' || error === 'cmdIntegrationUnavailable'
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'wslIntegrationUnavailable' || error === 'cygwinIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
|| error === 'gitBashIntegrationUnavailable' || error === 'nonFilesystem';
|
||||
return { cwd, home, display, pathFlavor, open, setOpen, query, setQuery, showHidden, setShowHidden, entries: filtered,
|
||||
parent: cwd ? parentDirectoryPath(cwd, pathFlavor) : null, loading, pending,
|
||||
parent: cwd ? directoryParent(cwd, pathFlavor) : null, loading, pending,
|
||||
error: cwdError ?? (cwd && waitsForCwd ? null : error),
|
||||
available: !!controller?.capabilities.listDirectories && !!controller.capabilities.changeDirectory && !!controller.capabilities.confirmChange,
|
||||
refresh, reload: load, change };
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
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 type { TerminalGitHeadResult } from '../../domain/terminalGitHead';
|
||||
import { useComposeGitBranch } from './useComposeGitBranch';
|
||||
import { createTerminalDirectoryController } from './terminalDirectoryController';
|
||||
import { observeTerminalDirectory, refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
test('Git chip follows confirmed cwd and ignores an old worktree result', async t => {
|
||||
const id = 'git-chip-test';
|
||||
const calls: { id: string; cwd: string; resolve: (head: TerminalGitHeadResult) => void }[] = [];
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
|
||||
netcatty: { readLocalSessionGitHead: (backendId: string, cwd: string) => new Promise<TerminalGitHeadResult>(resolve => {
|
||||
calls.push({ id: backendId, cwd, resolve });
|
||||
}) },
|
||||
} });
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId: id, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => true,
|
||||
io: { cwd: async () => '/other', list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} },
|
||||
publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'),
|
||||
});
|
||||
const unregister = registerTerminalDirectory(id, controller);
|
||||
const stopObserving = observeTerminalDirectory(id);
|
||||
let root!: ReactTestRenderer;
|
||||
let head: ReturnType<typeof useComposeGitBranch>;
|
||||
function Harness() { head = useComposeGitBranch(id); return null; }
|
||||
const waitForCalls = async (count: number) => {
|
||||
for (let i = 0; calls.length < count && i < 100; i++) await new Promise(resolve => setTimeout(resolve, 10));
|
||||
assert.equal(calls.length, count);
|
||||
};
|
||||
t.after(async () => {
|
||||
await act(async () => { root?.unmount(); });
|
||||
stopObserving(); unregister(); terminalCwdStore.setCwd(id, null);
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, 'window');
|
||||
});
|
||||
terminalCwdStore.setCwd(id, '/old', 'inferred');
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
assert.equal(head!, null);
|
||||
assert.deepEqual(calls, []);
|
||||
await act(async () => { terminalCwdStore.setCwd(id, '/old', 'osc7'); });
|
||||
await waitForCalls(1);
|
||||
assert.equal(calls[0].id, 'local-pty');
|
||||
assert.equal(calls[0].cwd, '/old');
|
||||
await act(async () => { terminalCwdStore.setCwd(id, '/other', 'osc7'); });
|
||||
await waitForCalls(2);
|
||||
await act(async () => { calls[1].resolve({ kind: 'branch', name: 'current', worktreeRoot: '/other' }); });
|
||||
await act(async () => { calls[0].resolve({ kind: 'branch', name: 'old', worktreeRoot: '/old' }); });
|
||||
assert.deepEqual(head!, { kind: 'branch', name: 'current', worktreeRoot: '/other' });
|
||||
refreshObservedTerminalDirectory(id);
|
||||
await waitForCalls(3);
|
||||
await act(async () => { calls[2].resolve({ kind: 'detached', hash: '123abcd', worktreeRoot: '/other' }); });
|
||||
assert.deepEqual(head!, { kind: 'detached', hash: '123abcd', worktreeRoot: '/other' });
|
||||
await act(async () => { terminalCwdStore.setCwd(id, null); });
|
||||
assert.equal(head!, null);
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import type { TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
|
||||
const noCwd = () => null;
|
||||
const noSubscription = () => () => {};
|
||||
const REFRESH_DELAY_MS = 150;
|
||||
|
||||
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const backendId = controller?.localPosixSessionId;
|
||||
const cwd = useSyncExternalStore(
|
||||
backendId ? controller.subscribeCwd : noSubscription,
|
||||
backendId ? controller.getConfirmedCwd : noCwd,
|
||||
noCwd,
|
||||
);
|
||||
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
|
||||
let active = true;
|
||||
let pending = false;
|
||||
let refreshAgain = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const isCurrent = () => active && getTerminalDirectory(sessionId) === controller && controller.getConfirmedCwd() === cwd;
|
||||
|
||||
const read = async () => {
|
||||
if (!isCurrent()) return;
|
||||
pending = true;
|
||||
try {
|
||||
const next = await bridge.readLocalSessionGitHead?.(backendId, cwd);
|
||||
if (isCurrent() && !refreshAgain) {
|
||||
setResult({ controller, cwd, head: next?.kind === 'branch' || next?.kind === 'detached' ? next : null });
|
||||
}
|
||||
} catch {
|
||||
if (isCurrent() && !refreshAgain) setResult({ controller, cwd, head: null });
|
||||
} finally {
|
||||
pending = false;
|
||||
if (refreshAgain && active) {
|
||||
refreshAgain = false;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
if (pending) {
|
||||
refreshAgain = true;
|
||||
return;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => { void read(); }, REFRESH_DELAY_MS);
|
||||
};
|
||||
schedule();
|
||||
const unsubscribe = subscribeTerminalDirectoryRefresh(sessionId, schedule);
|
||||
return () => {
|
||||
active = false;
|
||||
clearTimeout(timer);
|
||||
unsubscribe();
|
||||
setResult(current => current?.controller === controller && current.cwd === cwd ? null : current);
|
||||
};
|
||||
}, [backendId, controller, cwd, sessionId]);
|
||||
|
||||
return result?.controller === controller && result.cwd === cwd ? result.head : null;
|
||||
}
|
||||
@@ -1,480 +0,0 @@
|
||||
/**
|
||||
* useExternalEditorSettings - Reactive store & launcher for External Editor integration
|
||||
*
|
||||
* Device-local (not cloud-synced because executable paths differ across machines).
|
||||
* Uses useSyncExternalStore + window `storage` events so the Settings window and
|
||||
* main Terminal/SFTP windows stay immediately in sync.
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import {
|
||||
buildDirectSshTarget,
|
||||
buildSshBridgeHostname,
|
||||
getHostKeyForExternalEditor,
|
||||
normalizeExternalEditorSettings,
|
||||
validateAndNormalizeRemotePath,
|
||||
type ExternalEditorConnectionMode,
|
||||
type ExternalEditorHostIdentity,
|
||||
type ExternalEditorHostTrustPolicy,
|
||||
type ExternalEditorPresetId,
|
||||
type ExternalEditorSettings,
|
||||
type ExternalEditorTargetKind,
|
||||
} from '../../domain/externalEditor';
|
||||
import { STORAGE_KEY_EXTERNAL_EDITOR } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import {
|
||||
netcattyBridge,
|
||||
type ExternalEditorBridgeConfigStatus,
|
||||
type ExternalEditorDetectEntry,
|
||||
type ExternalEditorOpenRemoteResult,
|
||||
} from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export type {
|
||||
ExternalEditorBridgeConfigStatus,
|
||||
ExternalEditorDetectEntry,
|
||||
ExternalEditorOpenRemoteResult,
|
||||
};
|
||||
|
||||
const subscribers = new Set<() => void>();
|
||||
|
||||
function hasBrowserStorage(): boolean {
|
||||
return typeof window !== 'undefined' && 'localStorage' in window;
|
||||
}
|
||||
|
||||
function loadExternalEditorSettings(): ExternalEditorSettings {
|
||||
if (!hasBrowserStorage()) {
|
||||
return normalizeExternalEditorSettings(undefined);
|
||||
}
|
||||
try {
|
||||
const stored = localStorageAdapter.read<Partial<ExternalEditorSettings>>(STORAGE_KEY_EXTERNAL_EDITOR);
|
||||
return normalizeExternalEditorSettings(stored);
|
||||
} catch {
|
||||
return normalizeExternalEditorSettings(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
let currentSettings: ExternalEditorSettings = loadExternalEditorSettings();
|
||||
let storageListenerAttached = false;
|
||||
|
||||
function ensureStorageListener() {
|
||||
if (storageListenerAttached || typeof window === 'undefined' || typeof window.addEventListener !== 'function') {
|
||||
return;
|
||||
}
|
||||
storageListenerAttached = true;
|
||||
window.addEventListener('storage', (event: StorageEvent) => {
|
||||
if (event.key === STORAGE_KEY_EXTERNAL_EDITOR) {
|
||||
writeSettings(loadExternalEditorSettings(), false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
ensureStorageListener();
|
||||
|
||||
function notifySubscribers() {
|
||||
subscribers.forEach((cb) => cb());
|
||||
}
|
||||
|
||||
function writeSettings(next: ExternalEditorSettings, persist = true) {
|
||||
currentSettings = normalizeExternalEditorSettings(next);
|
||||
if (persist && hasBrowserStorage()) {
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_EXTERNAL_EDITOR, currentSettings);
|
||||
} catch {
|
||||
// ignore storage write failures in restricted contexts
|
||||
}
|
||||
}
|
||||
notifySubscribers();
|
||||
}
|
||||
|
||||
function subscribe(callback: () => void) {
|
||||
subscribers.add(callback);
|
||||
return () => {
|
||||
subscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
export function getExternalEditorSettingsSnapshot(): ExternalEditorSettings {
|
||||
return currentSettings;
|
||||
}
|
||||
|
||||
export function updateExternalEditorSettings(
|
||||
updater: (prev: ExternalEditorSettings) => ExternalEditorSettings,
|
||||
): ExternalEditorSettings {
|
||||
const next = updater(currentSettings);
|
||||
writeSettings(next, true);
|
||||
return currentSettings;
|
||||
}
|
||||
|
||||
export function setExternalEditorHostTrust(
|
||||
host: ExternalEditorHostIdentity,
|
||||
policy: ExternalEditorHostTrustPolicy,
|
||||
): void {
|
||||
const hostKey = getHostKeyForExternalEditor(host);
|
||||
if (!hostKey) return;
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
trustedHosts: {
|
||||
...prev.trustedHosts,
|
||||
[hostKey]: policy,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function removeExternalEditorHostTrust(hostKey: string): void {
|
||||
updateExternalEditorSettings((prev) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(prev.trustedHosts, hostKey)) return prev;
|
||||
const nextTrusted = { ...prev.trustedHosts };
|
||||
delete nextTrusted[hostKey];
|
||||
return {
|
||||
...prev,
|
||||
trustedHosts: nextTrusted,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface LaunchRemoteExternalEditorParams {
|
||||
editorId?: ExternalEditorPresetId;
|
||||
host: ExternalEditorHostIdentity;
|
||||
remotePath: string;
|
||||
fallbackCwd?: string;
|
||||
kind?: ExternalEditorTargetKind;
|
||||
sessionId?: string;
|
||||
sftpId?: string;
|
||||
settings?: ExternalEditorSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared application-layer launcher invoked by both Terminal OSC 7337 handlers
|
||||
* and SFTP context menus.
|
||||
*/
|
||||
export async function launchRemoteExternalEditor(
|
||||
params: LaunchRemoteExternalEditorParams,
|
||||
): Promise<ExternalEditorOpenRemoteResult> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.openRemote) {
|
||||
throw new Error('External editor integration requires the desktop application.');
|
||||
}
|
||||
|
||||
const settings = params.settings ?? getExternalEditorSettingsSnapshot();
|
||||
const editorId = params.editorId ?? settings.defaultEditor;
|
||||
const editorConfig = settings.editors[editorId];
|
||||
|
||||
const validated = validateAndNormalizeRemotePath(params.remotePath, params.fallbackCwd);
|
||||
if (!validated.ok) {
|
||||
throw new Error('error' in validated ? validated.error : 'Invalid remote path');
|
||||
}
|
||||
|
||||
const connectionMode = settings.connectionMode;
|
||||
const bridgeHost = connectionMode === 'bridge'
|
||||
? buildSshBridgeHostname(params.host)
|
||||
: undefined;
|
||||
const directSshTarget = connectionMode === 'direct'
|
||||
? buildDirectSshTarget(params.host) ?? undefined
|
||||
: undefined;
|
||||
|
||||
if (connectionMode === 'direct' && !directSshTarget) {
|
||||
throw new Error('Cannot construct a valid OpenSSH target for this host.');
|
||||
}
|
||||
|
||||
return bridge.externalEditor.openRemote({
|
||||
editorId,
|
||||
executablePath: editorConfig?.executablePath || undefined,
|
||||
customArgs: editorId === 'custom' ? editorConfig?.customArgs : undefined,
|
||||
connectionMode,
|
||||
bridgeHost,
|
||||
directSshTarget,
|
||||
sessionId: params.sessionId,
|
||||
sftpId: params.sftpId,
|
||||
hostId: params.host.hostId,
|
||||
hostname: params.host.hostname,
|
||||
port: params.host.port,
|
||||
username: params.host.username,
|
||||
remotePath: validated.path,
|
||||
kind: params.kind ?? 'auto',
|
||||
});
|
||||
}
|
||||
|
||||
export async function detectInstalledExternalEditors(): Promise<Record<string, ExternalEditorDetectEntry>> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.detect) return {};
|
||||
return (await bridge.externalEditor.detect()) || {};
|
||||
}
|
||||
|
||||
export async function getExternalEditorBridgeConfigStatus(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.getBridgeConfigStatus) return null;
|
||||
return (await bridge.externalEditor.getBridgeConfigStatus()) || null;
|
||||
}
|
||||
|
||||
export async function installExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.installBridgeConfig) return null;
|
||||
return bridge.externalEditor.installBridgeConfig();
|
||||
}
|
||||
|
||||
export async function removeExternalEditorBridgeConfig(): Promise<ExternalEditorBridgeConfigStatus | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.externalEditor?.removeBridgeConfig) return null;
|
||||
return bridge.externalEditor.removeBridgeConfig();
|
||||
}
|
||||
|
||||
export async function selectExternalEditorApplication(): Promise<{ path: string; name?: string } | null> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.selectApplication) return null;
|
||||
return (await bridge.selectApplication()) || null;
|
||||
}
|
||||
|
||||
function getTerminalAutoSetupSnapshotKey(): string {
|
||||
const s = currentSettings;
|
||||
return `${s.terminalRequestsEnabled ? 1 : 0}:${s.autoSetupShellIntegration ? 1 : 0}:${s.defaultEditor}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow selector for Terminal panes so edits to unrelated External Editor settings
|
||||
* (executable paths, custom args, trust list, bridge mode) never re-render open terminals.
|
||||
*/
|
||||
export function useExternalEditorTerminalAutoSetupConfig(): {
|
||||
terminalRequestsEnabled: boolean;
|
||||
autoSetupShellIntegration: boolean;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
} {
|
||||
const key = useSyncExternalStore(
|
||||
subscribe,
|
||||
getTerminalAutoSetupSnapshotKey,
|
||||
getTerminalAutoSetupSnapshotKey,
|
||||
);
|
||||
useEffect(() => {
|
||||
ensureStorageListener();
|
||||
}, []);
|
||||
const [reqFlag, autoFlag, defaultEditor] = key.split(':');
|
||||
return {
|
||||
terminalRequestsEnabled: reqFlag === '1',
|
||||
autoSetupShellIntegration: autoFlag === '1',
|
||||
defaultEditor: defaultEditor as ExternalEditorPresetId,
|
||||
};
|
||||
}
|
||||
|
||||
export function useExternalEditorSettings() {
|
||||
const settings = useSyncExternalStore(
|
||||
subscribe,
|
||||
getExternalEditorSettingsSnapshot,
|
||||
getExternalEditorSettingsSnapshot,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ensureStorageListener();
|
||||
}, []);
|
||||
|
||||
const setDefaultEditor = useCallback((editorId: ExternalEditorPresetId) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
defaultEditor: editorId,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setEditorExecutablePath = useCallback((editorId: ExternalEditorPresetId, executablePath: string) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
[editorId]: {
|
||||
...prev.editors[editorId],
|
||||
executablePath,
|
||||
},
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setCustomEditorArgs = useCallback((customArgs: string[]) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
custom: {
|
||||
...prev.editors.custom,
|
||||
customArgs,
|
||||
},
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setTerminalRequestsEnabled = useCallback((enabled: boolean) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
terminalRequestsEnabled: enabled,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setAutoSetupShellIntegration = useCallback((enabled: boolean) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
autoSetupShellIntegration: enabled,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setDefaultTrustPolicy = useCallback((policy: ExternalEditorHostTrustPolicy) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
defaultTrustPolicy: policy,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setConnectionMode = useCallback((mode: ExternalEditorConnectionMode) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
connectionMode: mode,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const setHostTrustPolicy = useCallback((hostKey: string, policy: ExternalEditorHostTrustPolicy) => {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
trustedHosts: {
|
||||
...prev.trustedHosts,
|
||||
[hostKey]: policy,
|
||||
},
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const removeHostTrustPolicy = useCallback((hostKey: string) => {
|
||||
removeExternalEditorHostTrust(hostKey);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
settings,
|
||||
setDefaultEditor,
|
||||
setEditorExecutablePath,
|
||||
setCustomEditorArgs,
|
||||
setTerminalRequestsEnabled,
|
||||
setAutoSetupShellIntegration,
|
||||
setDefaultTrustPolicy,
|
||||
setConnectionMode,
|
||||
setHostTrustPolicy,
|
||||
removeHostTrustPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Application-state hook owning external editor detection, `~/.ssh/config` bridge
|
||||
* installation/removal, and application picker lifecycle so UI settings sections
|
||||
* stay presentation-only.
|
||||
*/
|
||||
export function useExternalEditorEnvironment() {
|
||||
const [detectedEditors, setDetectedEditors] = useState<Record<string, ExternalEditorDetectEntry>>({});
|
||||
const [detecting, setDetecting] = useState(false);
|
||||
const [selectingApp, setSelectingApp] = useState(false);
|
||||
const [bridgeStatus, setBridgeStatus] = useState<ExternalEditorBridgeConfigStatus | null>(null);
|
||||
const [bridgeBusy, setBridgeBusy] = useState(false);
|
||||
const [bridgeError, setBridgeError] = useState<string | null>(null);
|
||||
|
||||
const mountedRef = useRef(true);
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const refreshStatus = useCallback(async () => {
|
||||
setDetecting(true);
|
||||
try {
|
||||
const [detected, cfg] = await Promise.all([
|
||||
detectInstalledExternalEditors(),
|
||||
getExternalEditorBridgeConfigStatus(),
|
||||
]);
|
||||
if (!mountedRef.current) return;
|
||||
setDetectedEditors(detected);
|
||||
setBridgeStatus(cfg);
|
||||
setBridgeError(null);
|
||||
} catch (err) {
|
||||
if (!mountedRef.current) return;
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setDetecting(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshStatus();
|
||||
}, [refreshStatus]);
|
||||
|
||||
const browseExecutable = useCallback(async (editorId: ExternalEditorPresetId): Promise<string | null> => {
|
||||
setSelectingApp(true);
|
||||
try {
|
||||
const picked = await selectExternalEditorApplication();
|
||||
if (picked?.path) {
|
||||
updateExternalEditorSettings((prev) => ({
|
||||
...prev,
|
||||
editors: {
|
||||
...prev.editors,
|
||||
[editorId]: {
|
||||
...prev.editors[editorId],
|
||||
executablePath: picked.path,
|
||||
},
|
||||
},
|
||||
}));
|
||||
return picked.path;
|
||||
}
|
||||
return null;
|
||||
} catch (err) {
|
||||
console.error('[ExternalEditor] Failed to select executable:', err);
|
||||
return null;
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setSelectingApp(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const installBridgeConfig = useCallback(async () => {
|
||||
setBridgeBusy(true);
|
||||
setBridgeError(null);
|
||||
try {
|
||||
const status = await installExternalEditorBridgeConfig();
|
||||
if (mountedRef.current && status) {
|
||||
setBridgeStatus(status);
|
||||
}
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setBridgeBusy(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const removeBridgeConfig = useCallback(async () => {
|
||||
setBridgeBusy(true);
|
||||
setBridgeError(null);
|
||||
try {
|
||||
const status = await removeExternalEditorBridgeConfig();
|
||||
if (mountedRef.current && status) {
|
||||
setBridgeStatus(status);
|
||||
}
|
||||
} catch (err) {
|
||||
if (mountedRef.current) {
|
||||
setBridgeError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} finally {
|
||||
if (mountedRef.current) {
|
||||
setBridgeBusy(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
detectedEditors,
|
||||
detecting,
|
||||
selectingApp,
|
||||
bridgeStatus,
|
||||
bridgeBusy,
|
||||
bridgeError,
|
||||
refreshStatus,
|
||||
browseExecutable,
|
||||
installBridgeConfig,
|
||||
removeBridgeConfig,
|
||||
};
|
||||
}
|
||||
@@ -16,10 +16,7 @@ export const checkAppShortcut = (
|
||||
return null;
|
||||
};
|
||||
|
||||
// Get list of key bindings that should be handled at app level (not by terminal).
|
||||
// Conditional shortcuts that pass through to the terminal when unavailable
|
||||
// (like toggleHostTree and addSessionToWorkspace) stay out so an unconsumed
|
||||
// chord still gets full Kitty/Win32/broadcast handling in xterm.
|
||||
// Get list of key bindings that should be handled at app level (not by terminal)
|
||||
export const getAppLevelActions = (): Set<string> => {
|
||||
return new Set([
|
||||
'switchToTab',
|
||||
|
||||
@@ -39,11 +39,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const update = () => {
|
||||
const snapshot = session.getSnapshot();
|
||||
if (snapshot.error) sessionRef.current = null;
|
||||
setState({ key, snapshot, image: session.image });
|
||||
};
|
||||
const update = () => { const snapshot = session.getSnapshot(); setState({ key, snapshot, image: session.image }); if (snapshot.error) unavailableRef.current(); };
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
@@ -53,9 +49,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const hasCurrentState = active
|
||||
&& state.key === key
|
||||
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
|
||||
const hasCurrentState = active && state.key === key && cachedSession !== null && state.image === cachedSession.image;
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
? state.snapshot
|
||||
: cachedSession
|
||||
|
||||
@@ -2,28 +2,6 @@ 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;
|
||||
@@ -39,55 +17,3 @@ 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,32 +1,42 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { checkPluginUpdates, type PluginUpdateCandidate, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
|
||||
import { checkPluginUpdates, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
/** 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) {
|
||||
/** Manual catalog checks only; no scheduler, install or permission mutation. */
|
||||
export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]) {
|
||||
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]);
|
||||
const check = useCallback(async (options?: { silent?: boolean }) => {
|
||||
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 () => {
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
const current = generation.current;
|
||||
setBusy(true); setError(null); setUpdateError(null);
|
||||
if (!options?.silent) setResult(null);
|
||||
setBusy(true); setError(null); setResult(null);
|
||||
try {
|
||||
const value = await checkPluginUpdates(netcattyBridge.require());
|
||||
if (mounted.current && current === generation.current) setResult(value);
|
||||
@@ -38,52 +48,5 @@ export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]
|
||||
if (mounted.current) setBusy(false);
|
||||
}
|
||||
}, []);
|
||||
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 };
|
||||
return { result, error, busy, check };
|
||||
}
|
||||
@@ -26,7 +26,6 @@ export const OPEN_PLUGIN_VIEW_EVENT = 'netcatty:open-plugin-view';
|
||||
export interface OpenPluginViewDetail {
|
||||
viewId: string;
|
||||
context?: Record<string, unknown>;
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export type ResolvedPluginView = {
|
||||
|
||||
@@ -58,7 +58,6 @@ export const isAutoStartProxyReady = (
|
||||
host.proxyProfileId && !validProxyProfileIds.has(host.proxyProfileId),
|
||||
);
|
||||
const missingGroupProxyProfile = Boolean(
|
||||
!host.directProxy &&
|
||||
!host.proxyConfig &&
|
||||
!host.proxyProfileId &&
|
||||
rawGroupDefaults.proxyProfileId &&
|
||||
|
||||
@@ -88,7 +88,6 @@ import {
|
||||
STORAGE_KEY_SHOW_ONLY_UNGROUPED_HOSTS_IN_ROOT,
|
||||
STORAGE_KEY_SHOW_SFTP_TAB,
|
||||
STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR,
|
||||
STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN,
|
||||
STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB,
|
||||
STORAGE_KEY_LOCAL_SHELL_SIDE_PANEL_AUTO_OPEN,
|
||||
@@ -146,7 +145,6 @@ import {
|
||||
DEFAULT_HOST_CLICK_BEHAVIOR,
|
||||
DEFAULT_SHOW_SFTP_TAB,
|
||||
DEFAULT_SHOW_HOST_TREE_SIDEBAR,
|
||||
DEFAULT_REMOVE_TOP_TABS_DRAG_AREA,
|
||||
DEFAULT_SHELL_ONLY_TAB_NUMBER_SHORTCUTS,
|
||||
DEFAULT_SHOW_TAB_NUMBER_BADGES,
|
||||
DEFAULT_DISABLE_TERMINAL_FONT_ZOOM,
|
||||
@@ -474,10 +472,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
return stored ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR;
|
||||
});
|
||||
const [removeTopTabsDragArea, setRemoveTopTabsDragAreaState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
return stored ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA;
|
||||
});
|
||||
const [terminalSidePanelAutoOpen, setTerminalSidePanelAutoOpenState] = useState<boolean>(() => {
|
||||
const stored = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
return stored ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED;
|
||||
@@ -1192,8 +1186,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTabState(storedShowSftpTab ?? DEFAULT_SHOW_SFTP_TAB);
|
||||
const storedShowHostTreeSidebar = localStorageAdapter.readBoolean(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR);
|
||||
setShowHostTreeSidebarState(storedShowHostTreeSidebar ?? DEFAULT_SHOW_HOST_TREE_SIDEBAR);
|
||||
const storedRemoveTopTabsDragArea = localStorageAdapter.readBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
setRemoveTopTabsDragAreaState(storedRemoveTopTabsDragArea ?? DEFAULT_REMOVE_TOP_TABS_DRAG_AREA);
|
||||
const storedTerminalSidePanelAutoOpen = localStorageAdapter.readBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN);
|
||||
setTerminalSidePanelAutoOpenState(storedTerminalSidePanelAutoOpen ?? DEFAULT_TERMINAL_SIDE_PANEL_AUTO_OPEN_ENABLED);
|
||||
const storedTerminalSidePanelAutoOpenTab = readStoredString(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN_TAB);
|
||||
@@ -1497,7 +1489,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
terminalThemeId, followAppTerminalTheme, terminalFontFamilyId, terminalFontSize,
|
||||
sftpDoubleClickBehavior, sftpAutoSync, sftpShowHiddenFiles,
|
||||
sftpUseCompressedUpload, sftpSkipUnchanged, sftpAutoOpenSidebar, sftpFollowTerminalCwd, sftpDefaultViewMode,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, removeTopTabsDragArea, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
showRecentHosts, hostClickBehavior, showOnlyUngroupedHostsInRoot, showSftpTab, showHostTreeSidebar, terminalSidePanelAutoOpen, terminalSidePanelAutoOpenTab, localShellSidePanelAutoOpen, localShellSidePanelAutoOpenTab, shellOnlyTabNumberShortcuts, showTabNumberBadges, disableTerminalFontZoom, restorePreviousSession, restoreTerminalCwd, startupLanding,
|
||||
editorWordWrap, sessionLogsEnabled, sessionLogsDir, sessionLogsFormat, sessionLogsTimestampsEnabled,
|
||||
remoteDesktopAutoRecord, remoteDesktopRecordingFps, remoteDesktopRecordingIncludeAudio, remoteDesktopRecordingMaxMb, remoteDesktopRecordingRetentionDays,
|
||||
sshDebugLogsEnabled, sshDeepLinkEnabled, jmsDeepLinkEnabled, jumpServerRdpLaunchMode, explorerContextMenuEnabled,
|
||||
@@ -1509,7 +1501,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setFollowAppTerminalThemeState, setTerminalFontFamilyId, setTerminalFontSize: applyIncomingTerminalFontSize,
|
||||
setSftpDoubleClickBehavior, setSftpAutoSync, setSftpShowHiddenFiles,
|
||||
setSftpUseCompressedUpload, setSftpSkipUnchanged, setSftpAutoOpenSidebar, setSftpFollowTerminalCwd, setSftpDefaultViewMode,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setRemoveTopTabsDragAreaState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setShowRecentHostsState, setHostClickBehaviorState, setShowOnlyUngroupedHostsInRootState, setShowSftpTabState, setShowHostTreeSidebarState, setTerminalSidePanelAutoOpenState, setTerminalSidePanelAutoOpenTabState, setLocalShellSidePanelAutoOpenState, setLocalShellSidePanelAutoOpenTabState, setShellOnlyTabNumberShortcutsState, setShowTabNumberBadgesState, setDisableTerminalFontZoomState, setRestorePreviousSessionState, setRestoreTerminalCwdState, setStartupLandingState,
|
||||
setEditorWordWrapState, setSessionLogsEnabled, setSessionLogsDir, setSessionLogsFormat, setSessionLogsTimestampsEnabled,
|
||||
setRemoteDesktopAutoRecordState, setRemoteDesktopRecordingFpsState, setRemoteDesktopRecordingIncludeAudioState, setRemoteDesktopRecordingMaxMbState, setRemoteDesktopRecordingRetentionDaysState,
|
||||
setSshDebugLogsEnabled, setSshDeepLinkEnabledState: applyIncomingSshDeepLinkEnabled, setJmsDeepLinkEnabledState: applyIncomingJmsDeepLinkEnabled, setJumpServerRdpLaunchModeState, setExplorerContextMenuEnabledState: applyIncomingExplorerContextMenuEnabled,
|
||||
@@ -1655,13 +1647,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
notifySettingsChanged(STORAGE_KEY_SHOW_HOST_TREE_SIDEBAR, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setRemoveTopTabsDragArea = useCallback((enabled: boolean) => {
|
||||
setRemoveTopTabsDragAreaState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
if (!persistMountedRef.current) return;
|
||||
notifySettingsChanged(STORAGE_KEY_REMOVE_TOP_TABS_DRAG_AREA, enabled);
|
||||
}, [notifySettingsChanged]);
|
||||
|
||||
const setTerminalSidePanelAutoOpen = useCallback((enabled: boolean) => {
|
||||
setTerminalSidePanelAutoOpenState(enabled);
|
||||
localStorageAdapter.writeBoolean(STORAGE_KEY_TERMINAL_SIDE_PANEL_AUTO_OPEN, enabled);
|
||||
@@ -2196,7 +2181,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
windowOpacity,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showRecentHosts,
|
||||
hostClickBehavior,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
@@ -2221,7 +2205,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
restoreTerminalCwd,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
showHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
showOnlyUngroupedHostsInRoot,
|
||||
showRecentHosts,
|
||||
showSftpTab,
|
||||
@@ -2402,8 +2385,6 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setShowSftpTab,
|
||||
showHostTreeSidebar,
|
||||
setShowHostTreeSidebar,
|
||||
removeTopTabsDragArea,
|
||||
setRemoveTopTabsDragArea,
|
||||
terminalSidePanelAutoOpen,
|
||||
setTerminalSidePanelAutoOpen,
|
||||
terminalSidePanelAutoOpenTab,
|
||||
|
||||
@@ -11,11 +11,11 @@ type SessionProps = Parameters<typeof useTerminalDirectorySession>[0];
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo'], discoverShells?: NetcattyBridge['discoverShells']) {
|
||||
function installBridge(t: TestContext, getAppInfo?: NetcattyBridge['getAppInfo']) {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
let probes = 0; let lists = 0;
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: { netcatty: {
|
||||
getAppInfo, discoverShells,
|
||||
getAppInfo,
|
||||
getSessionPwd: async () => { probes++; return { success: true, cwd: '/actual' }; },
|
||||
listLocalDir: async () => { lists++; return []; },
|
||||
} } });
|
||||
@@ -55,19 +55,6 @@ for (const wrapper of ['wsl-Ubuntu', 'git-bash', 'cygwin']) {
|
||||
});
|
||||
}
|
||||
|
||||
test('a discovered Cygwin terminal registers its own POSIX directory controller', async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform: 'win32' }), async () => [
|
||||
{ id: 'cygwin', name: 'Cygwin', command: 'C:/cygwin64/bin/bash.exe', args: ['--login', '-i'], icon: 'cygwin' },
|
||||
]);
|
||||
const props = options('cygwin-tab');
|
||||
props.host = { ...props.host, localShell: 'cygwin' };
|
||||
function Harness() { useTerminalDirectorySession(props); return null; }
|
||||
let root!: ReactTestRenderer;
|
||||
await act(async () => { root = create(React.createElement(Harness)); });
|
||||
t.after(async () => { await act(async () => { root.unmount(); }); });
|
||||
assert.deepEqual(getTerminalDirectory(props.sessionId)?.target, { authority: 'cygwin:cygwin-tab', pathFlavor: 'posix' });
|
||||
});
|
||||
|
||||
for (const platform of ['linux', 'darwin']) {
|
||||
test(`local POSIX directory controller registers on ${platform}`, async t => {
|
||||
installBridge(t, async () => ({ name: 'Netcatty', version: 'test', platform }));
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createTerminalDirectoryController } from './terminalDirectoryController
|
||||
import { registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES, type WindowsDirectoryShell } from '../../domain/directoryPicker';
|
||||
import type { DirectoryPathFlavor } from '../../domain/directoryPath';
|
||||
import { isDiscoveredCygwin, isDiscoveredGitBash } from '../../lib/localShell';
|
||||
import { isDiscoveredGitBash } from '../../lib/localShell';
|
||||
|
||||
export function useTerminalDirectorySession(options: {
|
||||
sessionId: string;
|
||||
@@ -36,18 +36,15 @@ export function useTerminalDirectorySession(options: {
|
||||
let unregister = () => {};
|
||||
const register = (pathFlavor: DirectoryPathFlavor = 'posix', integration?: WindowsDirectoryShell) => {
|
||||
if (!isCurrent()) return;
|
||||
const sessionFilesystem = integration === 'wsl' || integration === 'cygwin';
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId,
|
||||
localPosixSessionId: local && !integration ? backendId : undefined,
|
||||
io: createTerminalDirectoryIO(bridge, backendId, {
|
||||
local, hostname: host.hostname, username: host.username || 'root', port: host.port,
|
||||
encoding: host.sftpEncoding,
|
||||
pathFlavor,
|
||||
windowsShell: integration,
|
||||
}, isCurrent),
|
||||
target: { authority: `${sessionFilesystem ? integration : local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
trustOsc7: !sessionFilesystem,
|
||||
target: { authority: `${local ? 'local' : 'ssh'}:${backendId}`, pathFlavor },
|
||||
capabilities: COMPLETE_DIRECTORY_CAPABILITIES,
|
||||
buildChangeCommand: path => directoryChangeCommand(path, integration ?? 'posix', pathFlavor),
|
||||
isCurrent,
|
||||
@@ -63,14 +60,8 @@ export function useTerminalDirectorySession(options: {
|
||||
if (windowsShell) register('win32', windowsShell);
|
||||
else if (shellType === 'posix' && host.localShell) {
|
||||
const shells = await bridge.discoverShells?.();
|
||||
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)) {
|
||||
if (isDiscoveredGitBash(host.localShell, shells?.find(item => item.id === 'git-bash')?.command)) {
|
||||
register('win32', 'git-bash');
|
||||
} else if (isDiscoveredCygwin(host.localShell, shells?.find(item => item.id === 'cygwin')?.command)) {
|
||||
register('posix', 'cygwin');
|
||||
}
|
||||
}
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX,
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
|
||||
} from '../../domain/externalEditor';
|
||||
import { createExternalEditorSessionProvisioner } from './useTerminalExternalEditor';
|
||||
|
||||
function flushMicrotasks(): Promise<void> {
|
||||
return new Promise((resolve) => setImmediate(resolve));
|
||||
}
|
||||
|
||||
test('provisions initial editor helpers and activates PATH once, then installs newly selected editor without re-injecting PATH', async () => {
|
||||
const execCalls: { sessionId: string; command: string }[] = [];
|
||||
const writeCalls: { sessionId: string; data: string; opts?: { automated?: boolean } }[] = [];
|
||||
const configuredLabels: string[] = [];
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (sessionId, command) => {
|
||||
execCalls.push({ sessionId, command });
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (sessionId, data, opts) => {
|
||||
writeCalls.push({ sessionId, data, opts });
|
||||
},
|
||||
getCurrentSessionId: () => 'sess-1',
|
||||
isReadyForCommandInjection: () => true,
|
||||
onConfigured: (label) => configuredLabels.push(label),
|
||||
});
|
||||
|
||||
// 1. Initial connection with Zed
|
||||
const cancelZed = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.match(execCalls[0].command, /write_bin '\\''zed'\\''/);
|
||||
assert.doesNotMatch(execCalls[0].command, /write_bin '\\''code'\\''/);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.match(writeCalls[0].data, /export PATH="\$HOME\/\.netcatty\/bin:\$PATH" NETCATTY_EXTERNAL_EDITOR=1/);
|
||||
assert.deepEqual(writeCalls[0].opts, { automated: true });
|
||||
assert.deepEqual(configuredLabels, ['Zed']);
|
||||
|
||||
// 2. Switching preferred editor to VS Code in the same live session installs `code`
|
||||
// without injecting a duplicate PATH activation command into the terminal.
|
||||
cancelZed();
|
||||
const cancelVscode = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'vscode' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.match(execCalls[1].command, /write_bin '\\''code'\\''/);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.deepEqual(configuredLabels, ['Zed', 'VS Code']);
|
||||
|
||||
// 3. Switching back to Zed in the same session is a no-op (already provisioned + activated).
|
||||
cancelVscode();
|
||||
const cancelZedAgain = provisioner.sync({ sessionId: 'sess-1', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
cancelZedAgain();
|
||||
});
|
||||
|
||||
test('polls until terminal prompt is ready and cancels cleanly if editor changes before prompt settles', async () => {
|
||||
const execCalls: string[] = [];
|
||||
const writeCalls: string[] = [];
|
||||
const timers = new Map<number, () => void>();
|
||||
let nextTimerId = 1;
|
||||
let ready = false;
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (_sessionId, command) => {
|
||||
execCalls.push(command);
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}fish\n${EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER}\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (_sessionId, data) => {
|
||||
writeCalls.push(data);
|
||||
},
|
||||
getCurrentSessionId: () => 'sess-2',
|
||||
isReadyForCommandInjection: () => ready,
|
||||
scheduleTimer: (fn) => {
|
||||
const id = nextTimerId++;
|
||||
timers.set(id, fn);
|
||||
return id as unknown as ReturnType<typeof setTimeout>;
|
||||
},
|
||||
clearTimer: (handle) => {
|
||||
timers.delete(handle as unknown as number);
|
||||
},
|
||||
});
|
||||
|
||||
// Start with Zed while prompt is still busy with MOTD.
|
||||
const cancelZed = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.equal(writeCalls.length, 0);
|
||||
assert.equal(timers.size, 1);
|
||||
|
||||
// Switch to Cursor before prompt becomes ready: old poll is cancelled, Cursor is provisioned.
|
||||
cancelZed();
|
||||
assert.equal(timers.size, 0);
|
||||
|
||||
const cancelCursor = provisioner.sync({ sessionId: 'sess-2', defaultEditor: 'cursor' });
|
||||
await flushMicrotasks();
|
||||
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.match(execCalls[1], /write_bin '\\''cursor'\\''/);
|
||||
assert.equal(writeCalls.length, 0);
|
||||
assert.equal(timers.size, 1);
|
||||
|
||||
// Prompt becomes ready -> fish PATH activation executes once.
|
||||
ready = true;
|
||||
const scheduled = [...timers.values()];
|
||||
timers.clear();
|
||||
scheduled.forEach((fn) => fn());
|
||||
|
||||
assert.equal(writeCalls.length, 1);
|
||||
assert.match(writeCalls[0], /set -gx PATH "\$HOME\/\.netcatty\/bin" \$PATH/);
|
||||
cancelCursor();
|
||||
});
|
||||
|
||||
test('resets per-session tracking on disconnect so reconnect re-activates PATH', async () => {
|
||||
let activeSessionId = 'sess-3';
|
||||
const execCalls: string[] = [];
|
||||
const writeCalls: string[] = [];
|
||||
|
||||
const provisioner = createExternalEditorSessionProvisioner({
|
||||
setupExec: async (sessionId) => {
|
||||
execCalls.push(sessionId);
|
||||
return {
|
||||
success: true,
|
||||
stdout: `${EXTERNAL_EDITOR_AUTO_SETUP_SHELL_PREFIX}posix\n`,
|
||||
};
|
||||
},
|
||||
writeToSession: (sessionId) => {
|
||||
writeCalls.push(sessionId);
|
||||
},
|
||||
getCurrentSessionId: () => activeSessionId,
|
||||
isReadyForCommandInjection: () => true,
|
||||
});
|
||||
|
||||
const cancelFirst = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 1);
|
||||
assert.equal(writeCalls.length, 1);
|
||||
cancelFirst();
|
||||
|
||||
// Disconnect resets session state even if the same sessionId reconnects.
|
||||
provisioner.reset();
|
||||
const cancelSecond = provisioner.sync({ sessionId: 'sess-3', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 2);
|
||||
assert.equal(writeCalls.length, 2);
|
||||
cancelSecond();
|
||||
|
||||
// New backend sessionId also provisions and activates fresh.
|
||||
activeSessionId = 'sess-4';
|
||||
const cancelThird = provisioner.sync({ sessionId: 'sess-4', defaultEditor: 'zed' });
|
||||
await flushMicrotasks();
|
||||
assert.equal(execCalls.length, 3);
|
||||
assert.equal(writeCalls.length, 3);
|
||||
cancelThird();
|
||||
});
|
||||
@@ -1,387 +0,0 @@
|
||||
/**
|
||||
* useTerminalExternalEditor - Application-state hook & session provisioner for
|
||||
* Terminal External Editor integration (OSC 7337 requests, per-host trust prompts,
|
||||
* and session-scoped ~/.netcatty/bin helper provisioning + one-time PATH activation).
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER,
|
||||
buildExternalEditorAutoSetupCommand,
|
||||
buildExternalEditorSessionActivateCommand,
|
||||
getExternalEditorLabel,
|
||||
parseExternalEditorAutoSetupShell,
|
||||
resolveExternalEditorTrustPolicy,
|
||||
shouldAutoSetupExternalEditorShell,
|
||||
validateAndNormalizeRemotePath,
|
||||
type ExternalEditorOscRequest,
|
||||
type ExternalEditorPresetId,
|
||||
type ExternalEditorTargetKind,
|
||||
} from '../../domain/externalEditor';
|
||||
import type { Host } from '../../domain/models';
|
||||
import { logger } from '../../lib/logger';
|
||||
import {
|
||||
getExternalEditorSettingsSnapshot,
|
||||
launchRemoteExternalEditor,
|
||||
setExternalEditorHostTrust,
|
||||
useExternalEditorTerminalAutoSetupConfig,
|
||||
} from './useExternalEditorSettings';
|
||||
|
||||
export interface PendingExternalEditorRequest {
|
||||
editorId: ExternalEditorPresetId;
|
||||
editorLabel: string;
|
||||
remotePath: string;
|
||||
kind: ExternalEditorTargetKind;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionSetupResult {
|
||||
success?: boolean;
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionProvisionerDeps {
|
||||
setupExec: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
|
||||
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
|
||||
getCurrentSessionId: () => string | null;
|
||||
isReadyForCommandInjection: () => boolean;
|
||||
onConfigured?: (editorLabel: string) => void;
|
||||
onWarn?: (message: string, detail?: unknown) => void;
|
||||
scheduleTimer?: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
|
||||
clearTimer?: (handle: ReturnType<typeof setTimeout>) => void;
|
||||
pollIntervalMs?: number;
|
||||
maxPollAttempts?: number;
|
||||
}
|
||||
|
||||
export interface ExternalEditorSessionProvisioner {
|
||||
reset: () => void;
|
||||
sync: (params: {
|
||||
sessionId: string;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
}) => () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stateful session helper provisioner separated from React so lifecycle
|
||||
* transitions (initial setup, preferred-editor switching without re-injecting
|
||||
* PATH, disconnect reset, and cancellation) can be tested deterministically.
|
||||
*/
|
||||
export function createExternalEditorSessionProvisioner(
|
||||
deps: ExternalEditorSessionProvisionerDeps,
|
||||
): ExternalEditorSessionProvisioner {
|
||||
const scheduleTimer = deps.scheduleTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
||||
const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
|
||||
const pollIntervalMs = deps.pollIntervalMs ?? 100;
|
||||
const maxPollAttempts = deps.maxPollAttempts ?? 60;
|
||||
|
||||
let trackedSessionId: string | null = null;
|
||||
let provisionedEditors = new Set<ExternalEditorPresetId>();
|
||||
let pathActivated = false;
|
||||
|
||||
const reset = () => {
|
||||
trackedSessionId = null;
|
||||
provisionedEditors = new Set();
|
||||
pathActivated = false;
|
||||
};
|
||||
|
||||
const sync = ({
|
||||
sessionId,
|
||||
defaultEditor,
|
||||
}: {
|
||||
sessionId: string;
|
||||
defaultEditor: ExternalEditorPresetId;
|
||||
}): (() => void) => {
|
||||
if (trackedSessionId !== sessionId) {
|
||||
trackedSessionId = sessionId;
|
||||
provisionedEditors = new Set();
|
||||
pathActivated = false;
|
||||
}
|
||||
|
||||
if (provisionedEditors.has(defaultEditor) && pathActivated) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const setupCmd = buildExternalEditorAutoSetupCommand(defaultEditor);
|
||||
|
||||
void deps.setupExec(sessionId, setupCmd).then((result) => {
|
||||
if (cancelled) return;
|
||||
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
|
||||
if (!result?.success) {
|
||||
deps.onWarn?.(
|
||||
'[Terminal] External editor session helper setup failed:',
|
||||
result?.error || result?.stderr,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
provisionedEditors.add(defaultEditor);
|
||||
const updated = typeof result.stdout === 'string'
|
||||
&& result.stdout.includes(EXTERNAL_EDITOR_AUTO_SETUP_UPDATED_MARKER);
|
||||
|
||||
// PATH is already active in this shell session (e.g. user changed preferred
|
||||
// editor while connected); the new wrapper in ~/.netcatty/bin is immediately
|
||||
// available without injecting another PATH command into the running terminal.
|
||||
if (pathActivated) {
|
||||
if (updated) {
|
||||
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const shellKind = parseExternalEditorAutoSetupShell(result.stdout);
|
||||
const activateCmd = buildExternalEditorSessionActivateCommand(shellKind);
|
||||
|
||||
let attempts = 0;
|
||||
const tryActivateInSession = () => {
|
||||
if (cancelled) return;
|
||||
if (trackedSessionId !== sessionId || deps.getCurrentSessionId() !== sessionId) return;
|
||||
if (pathActivated) return;
|
||||
|
||||
if (deps.isReadyForCommandInjection()) {
|
||||
pathActivated = true;
|
||||
deps.writeToSession(sessionId, activateCmd, { automated: true });
|
||||
if (updated) {
|
||||
deps.onConfigured?.(getExternalEditorLabel(defaultEditor));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
attempts += 1;
|
||||
if (attempts < maxPollAttempts) {
|
||||
pollTimer = scheduleTimer(tryActivateInSession, pollIntervalMs);
|
||||
}
|
||||
};
|
||||
|
||||
tryActivateInSession();
|
||||
}).catch((err) => {
|
||||
if (cancelled) return;
|
||||
deps.onWarn?.('[Terminal] External editor session helper setup error:', err);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (pollTimer !== null) {
|
||||
clearTimer(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
return { reset, sync };
|
||||
}
|
||||
|
||||
export interface UseTerminalExternalEditorOptions {
|
||||
sessionId: string;
|
||||
status: string;
|
||||
host: Pick<
|
||||
Host,
|
||||
'id' | 'hostname' | 'port' | 'username' | 'label' | 'protocol' | 'externalEditorShellIntegration'
|
||||
>;
|
||||
isLocalConnection: boolean;
|
||||
isSerialConnection: boolean;
|
||||
getBackendSessionId: () => string | null;
|
||||
isVisible: () => boolean;
|
||||
getFallbackCwd: () => string | undefined;
|
||||
isReadyForCommandInjection: () => boolean;
|
||||
setupOsc7Tracking?: (sessionId: string, command: string) => Promise<ExternalEditorSessionSetupResult>;
|
||||
writeToSession: (sessionId: string, data: string, opts?: { automated?: boolean }) => void;
|
||||
focusTerminal: () => void;
|
||||
onOpened: (editorLabel: string, remotePath: string) => void;
|
||||
onOpenFailed: (message: string) => void;
|
||||
formatFallbackOpenError: (editorLabel: string) => string;
|
||||
onAutoSetupConfigured: (editorLabel: string) => void;
|
||||
}
|
||||
|
||||
export function useTerminalExternalEditor(options: UseTerminalExternalEditorOptions) {
|
||||
const liveRef = useRef(options);
|
||||
liveRef.current = options;
|
||||
|
||||
const {
|
||||
sessionId,
|
||||
status,
|
||||
host,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
} = options;
|
||||
const hostProtocol = host.protocol || 'ssh';
|
||||
|
||||
const [pendingExternalEditorRequest, setPendingExternalEditorRequest] =
|
||||
useState<PendingExternalEditorRequest | null>(null);
|
||||
const pendingExternalEditorRequestRef = useRef(pendingExternalEditorRequest);
|
||||
pendingExternalEditorRequestRef.current = pendingExternalEditorRequest;
|
||||
const lastExternalEditorLaunchRef = useRef<{ key: string; at: number } | null>(null);
|
||||
|
||||
const executeExternalEditorLaunch = useCallback((req: PendingExternalEditorRequest) => {
|
||||
const launchKey = `${req.editorId}:${req.kind}:${req.remotePath}`;
|
||||
const now = Date.now();
|
||||
const prev = lastExternalEditorLaunchRef.current;
|
||||
if (prev && prev.key === launchKey && now - prev.at < 800) {
|
||||
return;
|
||||
}
|
||||
lastExternalEditorLaunchRef.current = { key: launchKey, at: now };
|
||||
|
||||
const current = liveRef.current;
|
||||
void launchRemoteExternalEditor({
|
||||
editorId: req.editorId,
|
||||
host: {
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
},
|
||||
remotePath: req.remotePath,
|
||||
kind: req.kind,
|
||||
sessionId: current.getBackendSessionId() ?? current.sessionId,
|
||||
}).then(() => {
|
||||
liveRef.current.onOpened(req.editorLabel, req.remotePath);
|
||||
}).catch((err) => {
|
||||
liveRef.current.onOpenFailed(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: liveRef.current.formatFallbackOpenError(req.editorLabel),
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleOscExternalEditorRequest = useCallback((request: ExternalEditorOscRequest) => {
|
||||
const current = liveRef.current;
|
||||
// Strictly scope OSC 7337 remote editor opens to live SSH sessions on visible tabs.
|
||||
if (current.isLocalConnection || current.isSerialConnection) return;
|
||||
if (!current.isVisible()) return;
|
||||
if ((current.host.protocol || 'ssh') !== 'ssh') return;
|
||||
|
||||
const settings = getExternalEditorSettingsSnapshot();
|
||||
if (!settings.terminalRequestsEnabled) return;
|
||||
|
||||
const fallbackCwd = current.getFallbackCwd();
|
||||
const normalized = validateAndNormalizeRemotePath(request.path, fallbackCwd);
|
||||
if (!normalized.ok) {
|
||||
logger.warn(
|
||||
'[Terminal] Rejected invalid OSC 7337 remote path:',
|
||||
'error' in normalized ? normalized.error : 'invalid path',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const editorId: ExternalEditorPresetId = request.editorId ?? settings.defaultEditor;
|
||||
const editorLabel = getExternalEditorLabel(editorId);
|
||||
const hostIdentity = {
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
};
|
||||
const trust = resolveExternalEditorTrustPolicy(settings, hostIdentity);
|
||||
if (trust === 'deny') {
|
||||
logger.debug('[Terminal] Ignored OSC 7337 external editor request (host denied)');
|
||||
return;
|
||||
}
|
||||
|
||||
const launchPayload: PendingExternalEditorRequest = {
|
||||
editorId,
|
||||
editorLabel,
|
||||
remotePath: normalized.path,
|
||||
kind: request.kind,
|
||||
};
|
||||
|
||||
if (trust === 'allow') {
|
||||
executeExternalEditorLaunch(launchPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
// Untrusted host: show explicit inline confirmation prompt (do not overwrite an active prompt).
|
||||
setPendingExternalEditorRequest((prev) => prev ?? launchPayload);
|
||||
}, [executeExternalEditorLaunch]);
|
||||
|
||||
const handleExternalEditorPromptResponse = useCallback((decision: 'deny' | 'once' | 'always') => {
|
||||
const currentRequest = pendingExternalEditorRequestRef.current;
|
||||
pendingExternalEditorRequestRef.current = null;
|
||||
setPendingExternalEditorRequest(null);
|
||||
if (currentRequest) {
|
||||
const current = liveRef.current;
|
||||
if (decision === 'always') {
|
||||
setExternalEditorHostTrust({
|
||||
hostId: current.host.id,
|
||||
hostname: current.host.hostname,
|
||||
port: current.host.port,
|
||||
username: current.host.username,
|
||||
label: current.host.label,
|
||||
}, 'allow');
|
||||
executeExternalEditorLaunch(currentRequest);
|
||||
} else if (decision === 'once') {
|
||||
executeExternalEditorLaunch(currentRequest);
|
||||
}
|
||||
}
|
||||
liveRef.current.focusTerminal();
|
||||
}, [executeExternalEditorLaunch]);
|
||||
|
||||
// Session-scoped external editor shell commands: install standalone helpers into
|
||||
// ~/.netcatty/bin over the silent exec channel (never modifying shell rc files)
|
||||
// and prepend ~/.netcatty/bin to PATH once per connected terminal session.
|
||||
const autoSetupConfig = useExternalEditorTerminalAutoSetupConfig();
|
||||
const shouldEnableSessionCommands = shouldAutoSetupExternalEditorShell(
|
||||
autoSetupConfig,
|
||||
{ externalEditorShellIntegration: host.externalEditorShellIntegration },
|
||||
);
|
||||
const defaultExternalEditor = autoSetupConfig.defaultEditor;
|
||||
|
||||
const provisionerRef = useRef<ExternalEditorSessionProvisioner | null>(null);
|
||||
if (!provisionerRef.current) {
|
||||
provisionerRef.current = createExternalEditorSessionProvisioner({
|
||||
setupExec: (activeSessionId, command) => {
|
||||
const fn = liveRef.current.setupOsc7Tracking;
|
||||
if (!fn) return Promise.resolve({ success: false, error: 'setupOsc7Tracking unavailable' });
|
||||
return fn(activeSessionId, command);
|
||||
},
|
||||
writeToSession: (activeSessionId, data, opts) => {
|
||||
liveRef.current.writeToSession(activeSessionId, data, opts);
|
||||
},
|
||||
getCurrentSessionId: () => liveRef.current.getBackendSessionId() ?? liveRef.current.sessionId,
|
||||
isReadyForCommandInjection: () => liveRef.current.isReadyForCommandInjection(),
|
||||
onConfigured: (editorLabel) => liveRef.current.onAutoSetupConfigured(editorLabel),
|
||||
onWarn: (message, detail) => logger.warn(message, detail),
|
||||
scheduleTimer: (fn, ms) => window.setTimeout(fn, ms) as unknown as ReturnType<typeof setTimeout>,
|
||||
clearTimer: (handle) => window.clearTimeout(handle as unknown as number),
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const provisioner = provisionerRef.current;
|
||||
if (!provisioner) return;
|
||||
|
||||
if (status !== 'connected') {
|
||||
provisioner.reset();
|
||||
return;
|
||||
}
|
||||
if (isLocalConnection || isSerialConnection) return;
|
||||
if (hostProtocol !== 'ssh') return;
|
||||
if (!shouldEnableSessionCommands) return;
|
||||
if (!liveRef.current.setupOsc7Tracking) return;
|
||||
|
||||
const activeSessionId = liveRef.current.getBackendSessionId() ?? sessionId;
|
||||
if (!activeSessionId) return;
|
||||
|
||||
return provisioner.sync({
|
||||
sessionId: activeSessionId,
|
||||
defaultEditor: defaultExternalEditor,
|
||||
});
|
||||
}, [
|
||||
status,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
hostProtocol,
|
||||
shouldEnableSessionCommands,
|
||||
defaultExternalEditor,
|
||||
sessionId,
|
||||
]);
|
||||
|
||||
return {
|
||||
pendingExternalEditorRequest,
|
||||
handleOscExternalEditorRequest,
|
||||
handleExternalEditorPromptResponse,
|
||||
};
|
||||
}
|
||||
@@ -4,8 +4,6 @@ import { JSDOM } from 'jsdom';
|
||||
|
||||
const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
|
||||
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
@@ -32,10 +30,9 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
@@ -86,7 +83,6 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = true;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -97,7 +93,6 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
coldRoot.render(<Fixture />);
|
||||
});
|
||||
@@ -127,125 +122,3 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('useVaultNavConfig preserves saved plugin order when settled with pluginsAvailable=false and restores slots once plugins become available', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
|
||||
OFFICIAL_DB_PLUGIN,
|
||||
OFFICIAL_MONITOR_PLUGIN,
|
||||
];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable: boolean | undefined = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
model.reorder(OFFICIAL_MONITOR_PLUGIN, 'hosts', 'after');
|
||||
model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
|
||||
const restartedRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN), false);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(model.config.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
const persistedUnavailable = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedUnavailable.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedUnavailable.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.deepEqual(persistedUnavailable.hidden, ['logs']);
|
||||
|
||||
pluginsAvailable = undefined;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
const persistedDefault = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedDefault.order[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(persistedDefault.order.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
restartedRoot.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_MONITOR_PLUGIN);
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
|
||||
await act(async () => {
|
||||
restartedRoot.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -28,8 +28,6 @@ export interface UseVaultNavConfigOptions {
|
||||
activePluginIds: readonly PluginVaultNavId[];
|
||||
/** Pass true while plugin contributions are still loading on cold start. */
|
||||
pluginsLoading?: boolean;
|
||||
/** Pass true once plugin contributions are available from the plugin runtime. */
|
||||
pluginsAvailable?: boolean;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
@@ -78,14 +76,13 @@ function writeStoredVaultNavConfig(config: VaultNavConfig): void {
|
||||
export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
pluginsAvailable = false,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
|
||||
const pruneMissingPlugins = !pluginsLoading;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
|
||||
@@ -440,43 +440,3 @@ test('changed remote transcript resets the local native SDK thread before contin
|
||||
assert.equal(getAISessionsSnapshot().sessions[0].messages.at(-1)?.content, 'Added on another device');
|
||||
delete (window as unknown as { netcatty?: unknown }).netcatty;
|
||||
});
|
||||
|
||||
test('cloud apply keeps receiver workspaceNameSnapshot when workspace binding is unchanged and drops it on rebind', async () => {
|
||||
const local: AISession = {
|
||||
...session(),
|
||||
id: 'ws-chat',
|
||||
scope: { type: 'workspace', targetId: 'ws-1', hostIds: ['h-1'] },
|
||||
workspaceNameSnapshot: 'Prod Cluster (this Mac)',
|
||||
updatedAt: 10,
|
||||
};
|
||||
save([local]);
|
||||
|
||||
// Never uploaded to cloud.
|
||||
const uploaded = await buildCloudSyncPayload(vault, [], { collectPluginSidecars: () => undefined });
|
||||
assert.equal(Object.hasOwn(uploaded.aiSessions?.[0] ?? {}, 'workspaceNameSnapshot'), false);
|
||||
|
||||
// Newer remote update on the same workspace (stripped by remote device, or even
|
||||
// carrying a foreign snapshot that must be stripped on apply) keeps local name.
|
||||
const remoteSameWs: AISession = {
|
||||
...local,
|
||||
updatedAt: 20,
|
||||
title: 'Updated title from peer',
|
||||
workspaceNameSnapshot: 'Peer stale name',
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteSameWs], syncedAt: 20 }, { importVaultData: () => undefined });
|
||||
const afterSameWs = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterSameWs?.title, 'Updated title from peer');
|
||||
assert.equal(afterSameWs?.workspaceNameSnapshot, 'Prod Cluster (this Mac)');
|
||||
|
||||
// Newer remote update that rebinds to another workspace drops the old local name.
|
||||
const remoteRebound: AISession = {
|
||||
...local,
|
||||
updatedAt: 30,
|
||||
scope: { type: 'workspace', targetId: 'ws-2', hostIds: ['h-2'] },
|
||||
workspaceNameSnapshot: undefined,
|
||||
};
|
||||
await applySyncPayload({ ...vault, aiSessions: [remoteRebound], syncedAt: 30 }, { importVaultData: () => undefined });
|
||||
const afterRebound = getAISessionsSnapshot().sessions.find((s) => s.id === 'ws-chat');
|
||||
assert.equal(afterRebound?.scope.targetId, 'ws-2');
|
||||
assert.equal(afterRebound?.workspaceNameSnapshot, undefined);
|
||||
});
|
||||
@@ -2422,17 +2422,13 @@ test('sync prepares header encryption once before importing and leaves input unc
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_PROVIDERS)!)[0].customHeaders, { 'X-Tenant': sealed });
|
||||
});
|
||||
|
||||
for (const key of [
|
||||
storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR,
|
||||
storageKeys.STORAGE_KEY_SFTP_LAST_DOWNLOAD_DIR,
|
||||
]) {
|
||||
test(`SFTP download folder ${key} stays device-local and is never synced`, async () => {
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
}
|
||||
test("SFTP default download folder stays device-local and is never synced", async () => {
|
||||
const key = storageKeys.STORAGE_KEY_SFTP_DEFAULT_DOWNLOAD_DIR;
|
||||
assert.equal((SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(key), false);
|
||||
localStorage.clear();
|
||||
localStorage.setItem(key, "/Users/me/server-files");
|
||||
const payload = buildSyncPayload(vault());
|
||||
assert.equal(JSON.stringify(payload).includes("/Users/me/server-files"), false);
|
||||
await applySyncPayload(payload, { importVaultData: () => {} });
|
||||
assert.equal(localStorage.getItem(key), "/Users/me/server-files");
|
||||
});
|
||||
@@ -1,265 +1,3 @@
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
Var /GLOBAL CreateDesktopShortcutPref
|
||||
!endif
|
||||
|
||||
!macro customHeader
|
||||
!ifndef BUILD_UNINSTALLER
|
||||
!ifdef LANG_ENGLISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ENGLISH} "Create &desktop shortcut"
|
||||
!endif
|
||||
!ifdef LANG_SIMPCHINESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SIMPCHINESE} "创建桌面快捷方式(&D)"
|
||||
!endif
|
||||
!ifdef LANG_TRADCHINESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TRADCHINESE} "建立桌面捷徑(&D)"
|
||||
!endif
|
||||
!ifdef LANG_RUSSIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_RUSSIAN} "Создать ярлык на &рабочем столе"
|
||||
!endif
|
||||
!ifdef LANG_JAPANESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_JAPANESE} "デスクトップにショートカットを作成する(&D)"
|
||||
!endif
|
||||
!ifdef LANG_KOREAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_KOREAN} "바탕 화면에 바로 가기 만들기(&D)"
|
||||
!endif
|
||||
!ifdef LANG_GERMAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_GERMAN} "&Desktopverknüpfung erstellen"
|
||||
!endif
|
||||
!ifdef LANG_FRENCH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FRENCH} "Créer un raccourci sur le &bureau"
|
||||
!endif
|
||||
!ifdef LANG_SPANISHINTERNATIONAL
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SPANISHINTERNATIONAL} "Crear acceso directo en el &escritorio"
|
||||
!endif
|
||||
!ifdef LANG_ITALIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ITALIAN} "Crea collegamento sul &desktop"
|
||||
!endif
|
||||
!ifdef LANG_DUTCH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DUTCH} "&Bureaublad-snelkoppeling maken"
|
||||
!endif
|
||||
!ifdef LANG_DANISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_DANISH} "Opret genvej på &skrivebordet"
|
||||
!endif
|
||||
!ifdef LANG_SWEDISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SWEDISH} "Skapa genväg på &skrivbordet"
|
||||
!endif
|
||||
!ifdef LANG_NORWEGIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_NORWEGIAN} "Opprett snarvei på &skrivebordet"
|
||||
!endif
|
||||
!ifdef LANG_FINNISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_FINNISH} "Luo pikakuvake &työpöydälle"
|
||||
!endif
|
||||
!ifdef LANG_PORTUGUESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESE} "Criar atalho na &área de trabalho"
|
||||
!endif
|
||||
!ifdef LANG_PORTUGUESEBR
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_PORTUGUESEBR} "Criar atalho na &Área de Trabalho"
|
||||
!endif
|
||||
!ifdef LANG_POLISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_POLISH} "Utwórz skrót na &pulpicie"
|
||||
!endif
|
||||
!ifdef LANG_UKRAINIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_UKRAINIAN} "Створити ярлик на &робочому столі"
|
||||
!endif
|
||||
!ifdef LANG_CZECH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_CZECH} "Vytvořit zástupce na &ploše"
|
||||
!endif
|
||||
!ifdef LANG_SLOVAK
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_SLOVAK} "Vytvoriť odkaz na &ploche"
|
||||
!endif
|
||||
!ifdef LANG_HUNGARIAN
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_HUNGARIAN} "Parancsikon létrehozása az &asztalon"
|
||||
!endif
|
||||
!ifdef LANG_ARABIC
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_ARABIC} "إنشاء اختصار على سطح ال&مكتب"
|
||||
!endif
|
||||
!ifdef LANG_TURKISH
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_TURKISH} "&Masaüstü kısayolu oluştur"
|
||||
!endif
|
||||
!ifdef LANG_THAI
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_THAI} "สร้างทางลัดบน&เดสก์ท็อป"
|
||||
!endif
|
||||
!ifdef LANG_VIETNAMESE
|
||||
LangString CREATE_DESKTOP_SHORTCUT_TEXT ${LANG_VIETNAMESE} "Tạo lối tắt trên &màn hình nền"
|
||||
!endif
|
||||
|
||||
; Determine whether the desktop shortcut should be checked/created.
|
||||
; Must run before uninstallOldVersion deletes the old registry key or shortcut.
|
||||
Function CaptureDesktopShortcutState
|
||||
${if} ${isNoDesktopShortcut}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
Return
|
||||
${endif}
|
||||
|
||||
!insertmacro setLinkVars
|
||||
|
||||
ReadRegStr $0 SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
|
||||
${if} $0 == "false"
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
|
||||
ReadRegStr $1 SHCTX "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $1 != ""
|
||||
; Existing install: only preserve the shortcut if it still exists on the desktop.
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
|
||||
; Migrating from per-user to all-users: inspect the previous per-user desktop shortcut.
|
||||
${if} $installMode == "all"
|
||||
ReadRegStr $2 HKCU "${INSTALL_REGISTRY_KEY}" InstallLocation
|
||||
${if} $2 != ""
|
||||
ReadRegStr $3 HKCU "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut
|
||||
SetShellVarContext current
|
||||
!insertmacro setLinkVars
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
${orIf} ${FileExists} "$oldDesktopLink"
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
${elseif} $3 == "false"
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
${endif}
|
||||
SetShellVarContext all
|
||||
!insertmacro setLinkVars
|
||||
Return
|
||||
${endif}
|
||||
${endif}
|
||||
|
||||
; Fresh installation: default to creating the desktop shortcut (user can uncheck on finish page).
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
FunctionEnd
|
||||
|
||||
Function InstFilesShowCaptureDesktopShortcut
|
||||
Call CaptureDesktopShortcutState
|
||||
FunctionEnd
|
||||
!endif
|
||||
!macroend
|
||||
|
||||
!macro ensureDesktopShortcut
|
||||
${if} $appExe == ""
|
||||
StrCpy $appExe "$INSTDIR\${APP_EXECUTABLE_FILENAME}"
|
||||
${endif}
|
||||
${if} $newDesktopLink == ""
|
||||
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
|
||||
${endif}
|
||||
|
||||
${if} $oldDesktopLink != ""
|
||||
${andIf} $oldDesktopLink != $newDesktopLink
|
||||
${andIf} ${FileExists} "$oldDesktopLink"
|
||||
Rename "$oldDesktopLink" "$newDesktopLink"
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${elseIfNot} ${FileExists} "$newDesktopLink"
|
||||
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
|
||||
ClearErrors
|
||||
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
!macroend
|
||||
|
||||
!macro removeDesktopShortcut
|
||||
${if} $newDesktopLink == ""
|
||||
StrCpy $newDesktopLink "$DESKTOP\${SHORTCUT_NAME}.lnk"
|
||||
${endif}
|
||||
|
||||
${if} ${FileExists} "$newDesktopLink"
|
||||
WinShell::UninstShortcut "$newDesktopLink"
|
||||
Delete "$newDesktopLink"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
${if} $oldDesktopLink != ""
|
||||
${andIf} $oldDesktopLink != $newDesktopLink
|
||||
${andIf} ${FileExists} "$oldDesktopLink"
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
Delete "$oldDesktopLink"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
!macroend
|
||||
|
||||
!macro customPageAfterChangeDir
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW InstFilesShowCaptureDesktopShortcut
|
||||
!macroend
|
||||
|
||||
!macro customFinishPage
|
||||
!ifndef HIDE_RUN_AFTER_FINISH
|
||||
Function StartApp
|
||||
${if} ${isUpdated}
|
||||
StrCpy $1 "--updated"
|
||||
${else}
|
||||
StrCpy $1 ""
|
||||
${endif}
|
||||
${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "$1"
|
||||
FunctionEnd
|
||||
|
||||
!define MUI_FINISHPAGE_RUN
|
||||
!define MUI_FINISHPAGE_RUN_FUNCTION "StartApp"
|
||||
!endif
|
||||
|
||||
!define MUI_FINISHPAGE_SHOWREADME ""
|
||||
!define MUI_FINISHPAGE_SHOWREADME_TEXT "$(CREATE_DESKTOP_SHORTCUT_TEXT)"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION "FinishDesktopShortcutNoop"
|
||||
!define MUI_FINISHPAGE_SHOWREADME_NOTCHECKED
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_SHOW FinishPageShow
|
||||
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE FinishPageLeave
|
||||
!insertmacro MUI_PAGE_FINISH
|
||||
|
||||
Function FinishPageShow
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${ifNot} ${RebootFlag}
|
||||
!endif
|
||||
${if} $CreateDesktopShortcutPref == "true"
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_CHECKED} 0
|
||||
${else}
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_SETCHECK} ${BST_UNCHECKED} 0
|
||||
${endif}
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${endif}
|
||||
!endif
|
||||
FunctionEnd
|
||||
|
||||
Function FinishPageLeave
|
||||
!ifndef MUI_FINISHPAGE_NOREBOOTSUPPORT
|
||||
${if} ${RebootFlag}
|
||||
${if} $CreateDesktopShortcutPref == "true"
|
||||
!insertmacro ensureDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
|
||||
${else}
|
||||
!insertmacro removeDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
|
||||
${endif}
|
||||
Return
|
||||
${endif}
|
||||
!endif
|
||||
|
||||
SendMessage $mui.FinishPage.ShowReadme ${BM_GETCHECK} 0 0 $0
|
||||
${if} $0 = ${BST_CHECKED}
|
||||
StrCpy $CreateDesktopShortcutPref "true"
|
||||
!insertmacro ensureDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "true"
|
||||
${else}
|
||||
StrCpy $CreateDesktopShortcutPref "false"
|
||||
!insertmacro removeDesktopShortcut
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "false"
|
||||
${endif}
|
||||
FunctionEnd
|
||||
|
||||
Function FinishDesktopShortcutNoop
|
||||
FunctionEnd
|
||||
!macroend
|
||||
|
||||
!macro customInit
|
||||
; #3946: external MCP hosts launch Netcatty.exe with ELECTRON_RUN_AS_NODE=1
|
||||
; via netcatty-external-mcp.cmd. Those processes can outlive the host UI as
|
||||
@@ -269,17 +7,9 @@
|
||||
; and /T would terminate the installer itself. Ignore a missing process.
|
||||
nsExec::ExecToLog "taskkill /F /IM Netcatty.exe"
|
||||
Pop $0
|
||||
Call CaptureDesktopShortcutState
|
||||
!macroend
|
||||
|
||||
!macro customInstall
|
||||
WriteRegStr SHCTX "${INSTALL_REGISTRY_KEY}" CreateDesktopShortcut "$CreateDesktopShortcutPref"
|
||||
${if} ${Silent}
|
||||
${andIf} $CreateDesktopShortcutPref == "true"
|
||||
${andIfNot} ${isNoDesktopShortcut}
|
||||
!insertmacro ensureDesktopShortcut
|
||||
${endif}
|
||||
|
||||
; Open a selected folder in a new Netcatty local terminal.
|
||||
; Args go after `--` so Electron/Chromium does not swallow them. Use
|
||||
; `--open-terminal-path="%1."` so paths with spaces stay one token and drive
|
||||
@@ -320,13 +50,6 @@
|
||||
!macroend
|
||||
|
||||
!macro customUnInstall
|
||||
; DO_NOT_CREATE_DESKTOP_SHORTCUT is set so electron-builder never auto-creates
|
||||
; the desktop shortcut; remove an existing shortcut here on real uninstall.
|
||||
${ifNot} ${isKeepShortcuts}
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
Delete "$oldDesktopLink"
|
||||
${endif}
|
||||
|
||||
DeleteRegKey SHCTX "Software\Classes\Directory\shell\Netcatty"
|
||||
DeleteRegKey SHCTX "Software\Classes\Directory\Background\shell\Netcatty"
|
||||
DeleteRegKey SHCTX "Software\Classes\Netcatty.SSH"
|
||||
|
||||
@@ -59,7 +59,6 @@ interface AIChatPanelContentProps {
|
||||
activeCompaction?: import('../application/state/useAgentCompactionUi').ActiveCompactionUi | null;
|
||||
contextUsage?: import('../application/state/useAgentCompactionUi').AgentContextUsage | null;
|
||||
inputValue: string;
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
@@ -172,7 +171,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
activeCompaction = null,
|
||||
contextUsage = null,
|
||||
inputValue,
|
||||
inputValueRevision,
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
@@ -570,7 +568,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
<ChatInput
|
||||
parked={parked}
|
||||
value={inputValue}
|
||||
valueRevision={inputValueRevision}
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import type { AISession } from '../infrastructure/ai/types';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { cn } from '../lib/utils';
|
||||
@@ -9,7 +9,6 @@ import { Input } from './ui/input';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
|
||||
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
|
||||
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
|
||||
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
@@ -53,7 +52,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
const { t } = useI18n();
|
||||
const [view, setView] = useState<'scoped' | 'global'>('scoped');
|
||||
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
|
||||
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
|
||||
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
@@ -72,22 +70,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
setRenderCount(SESSION_RENDER_BATCH);
|
||||
}, [sessions, searchQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== 'global' || !globalManager) {
|
||||
setGlobalSelectionMode(false);
|
||||
}
|
||||
}, [view, globalManager]);
|
||||
|
||||
const selectionContextValue = useMemo(
|
||||
() => ({
|
||||
selectionMode: globalSelectionMode,
|
||||
setSelectionMode: setGlobalSelectionMode,
|
||||
}),
|
||||
[globalSelectionMode],
|
||||
);
|
||||
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
|
||||
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
|
||||
|
||||
const displayedSessions = filteredSessions.slice(0, renderCount);
|
||||
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
|
||||
|
||||
@@ -150,7 +132,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{hasHeaderMenu && (
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
|
||||
<DropdownTrigger asChild>
|
||||
<button
|
||||
@@ -162,31 +144,6 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
|
||||
{canSelectGlobalChats && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setHeaderMenuOpen(false);
|
||||
setGlobalSelectionMode((prev) => !prev);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<CheckSquare
|
||||
size={12}
|
||||
className={cn(
|
||||
'shrink-0',
|
||||
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
<span>{t('ai.chat.managerToggleSelection')}</span>
|
||||
</button>
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
<div className="my-1 h-px bg-border/50" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{onImportSessions && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -227,9 +184,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
{view === 'global' && globalManager ? (
|
||||
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
|
||||
{globalManager}
|
||||
</GlobalSessionSelectionContext.Provider>
|
||||
globalManager
|
||||
) : (
|
||||
<>
|
||||
<div className="px-3 py-2 shrink-0 border-b border-border/30">
|
||||
|
||||
@@ -14,11 +14,6 @@ import type {
|
||||
ExternalAgentConfig,
|
||||
} from '../infrastructure/ai/types';
|
||||
import type { VaultNote } from '../domain/models';
|
||||
import {
|
||||
buildFallbackTitle,
|
||||
canAutoTitleSession,
|
||||
resolveCattyEffectiveModel,
|
||||
} from '../domain/aiSessionTitle';
|
||||
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
|
||||
import {
|
||||
DEFAULT_MAX_ITERATIONS,
|
||||
@@ -299,8 +294,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
undoLastTurnInSession,
|
||||
deleteSession,
|
||||
updateSessionTitle,
|
||||
autoTitleSession,
|
||||
regenerateSessionTitle,
|
||||
rebindSessionScope,
|
||||
exportSessionsBackup,
|
||||
importSessionsBackup,
|
||||
@@ -830,14 +823,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
showSessionView(scopeKey, sessionId);
|
||||
}, [scopeKey, showSessionView]);
|
||||
|
||||
const [composerValueRevision, setComposerValueRevision] = useState(0);
|
||||
|
||||
const discardPendingComposerText = useCallback(() => {
|
||||
pendingComposerTextRef.current = null;
|
||||
if (currentDraftRef.current) {
|
||||
currentDraftRef.current = { ...currentDraftRef.current, text: '' };
|
||||
}
|
||||
setComposerValueRevision((rev) => rev + 1);
|
||||
}, []);
|
||||
|
||||
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
|
||||
@@ -1051,16 +1038,26 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
[providers, activeProviderId],
|
||||
);
|
||||
|
||||
const { provider: cattyAgentProvider, modelId: cattyAgentModelId } = useMemo(
|
||||
() => resolveCattyEffectiveModel({
|
||||
providers,
|
||||
activeProviderId,
|
||||
activeModelId,
|
||||
agentProviderMap,
|
||||
agentModelMap,
|
||||
}),
|
||||
[providers, activeProviderId, activeModelId, agentProviderMap, agentModelMap],
|
||||
);
|
||||
const cattyAgentProvider = useMemo(() => {
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
if (overrideId) {
|
||||
const p = providers.find((cfg) => cfg.id === overrideId);
|
||||
if (p) return p;
|
||||
}
|
||||
return activeProvider;
|
||||
}, [agentProviderMap, providers, activeProvider]);
|
||||
|
||||
const cattyAgentModelId = useMemo(() => {
|
||||
const trim = (s: string | undefined | null): string => (s ?? '').trim();
|
||||
const overrideId = agentProviderMap['catty'];
|
||||
const overrideProvider = overrideId
|
||||
? providers.find((cfg) => cfg.id === overrideId)
|
||||
: undefined;
|
||||
if (overrideProvider) {
|
||||
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
|
||||
}
|
||||
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
|
||||
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
|
||||
|
||||
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
|
||||
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
|
||||
@@ -1683,10 +1680,18 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
}, [openSettingsWindow]);
|
||||
|
||||
|
||||
/** Ref to always access latest sessions inside async send callbacks. */
|
||||
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
|
||||
const sessionsRef = useRef(sessions);
|
||||
sessionsRef.current = sessions;
|
||||
|
||||
/** Auto-title a session from the first user message if untitled. */
|
||||
const autoTitleSession = useCallback((sessionId: string, text: string) => {
|
||||
const s = sessionsRef.current.find(x => x.id === sessionId);
|
||||
if (s && (!s.title || s.title === 'New Chat')) {
|
||||
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
|
||||
}
|
||||
}, [updateSessionTitle]);
|
||||
|
||||
const buildExecutorContextForScope = useCallback((scope: {
|
||||
type: 'terminal' | 'workspace' | 'global';
|
||||
targetId?: string;
|
||||
@@ -1870,7 +1875,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
let currentSession = currentSessionView ?? null;
|
||||
if (isDraftMode) {
|
||||
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
|
||||
const createdSession = createSession(scope, sendAgentId, scopeLabel);
|
||||
const createdSession = createSession(scope, sendAgentId);
|
||||
sessionId = createdSession.id;
|
||||
currentSession = createdSession;
|
||||
if (useDraftAttachments) clearScopeDraft({ keepPendingText: keepPendingAfterSend() });
|
||||
@@ -1978,6 +1983,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
|
||||
setStreamingForScope(sessionId, false);
|
||||
abortControllersRef.current.delete(sessionId);
|
||||
autoTitleSession(sessionId, titleText);
|
||||
} else {
|
||||
const toolScope = {
|
||||
type: scopeType,
|
||||
@@ -1999,23 +2005,12 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
terminalSessions,
|
||||
webSearchConfig,
|
||||
getExecutorContext: () => buildExecutorContextForScope(toolScope),
|
||||
// Title generation is triggered once, below, for both agent branches.
|
||||
autoTitleSession: () => {},
|
||||
autoTitleSession,
|
||||
selectedUserSkillSlugs: selectedSkillSlugs,
|
||||
titleText,
|
||||
pluginContext,
|
||||
}, modelAttachments.length > 0 ? modelAttachments : undefined);
|
||||
}
|
||||
// Single title-generation trigger for both agent branches. Pass the
|
||||
// signal explicitly: sendToCattyAgent's finally removes its controller.
|
||||
if (autoTitleSession) {
|
||||
void autoTitleSession(sessionId, titleText, abortController.signal);
|
||||
} else {
|
||||
const current = sessionsRef.current.find((s) => s.id === sessionId);
|
||||
if (canAutoTitleSession(current)) {
|
||||
updateSessionTitle(sessionId, buildFallbackTitle(titleText));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
endSendForKey(sendGateKey);
|
||||
@@ -2027,7 +2022,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
validateNoteMentions, loadCodexConfigModel,
|
||||
isStreaming, isUndoingLastTurn, activeProvider, effectiveActiveProvider, effectiveActiveModelId, selectedCattyThinking, scopeKey, currentAgentId,
|
||||
activeModelId, externalAgents,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage, updateSessionTitle,
|
||||
createSession, addMessageToSession, updateMessageById, updateLastMessage,
|
||||
setStreamingForScope,
|
||||
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
|
||||
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
|
||||
@@ -2435,23 +2430,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
deleteSession(sessionId);
|
||||
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
|
||||
|
||||
// Regeneration lives in useAIState so it can reuse the maintainer's
|
||||
// title-model resolution and atomic title-write helpers.
|
||||
const handleManagerRegenerateTitle = useCallback((sessionId: string) => {
|
||||
void regenerateSessionTitle?.(sessionId);
|
||||
}, [regenerateSessionTitle]);
|
||||
|
||||
const handleManagerDeleteMany = useCallback(async (sessionIds: string[]) => {
|
||||
for (const sessionId of sessionIds) {
|
||||
if (abortControllersRef.current.has(sessionId) || streamingSessionIds.has(sessionId)) {
|
||||
await stopStreamingForSession(sessionId);
|
||||
}
|
||||
// Each delete records an intentional tombstone so sync can propagate
|
||||
// the removal (the "decrease" side of session-history sync).
|
||||
deleteSession(sessionId);
|
||||
}
|
||||
}, [abortControllersRef, deleteSession, stopStreamingForSession, streamingSessionIds]);
|
||||
|
||||
const handleManagerExport = useCallback((sessionId: string) => {
|
||||
void exportSessionsBackup?.([sessionId]).then((filePath) => {
|
||||
if (filePath == null) {
|
||||
@@ -2486,8 +2464,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onRebind={handleManagerRebind}
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
|
||||
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
)
|
||||
@@ -2507,8 +2483,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
handleManagerRebind,
|
||||
handleRenameSession,
|
||||
handleManagerDelete,
|
||||
handleManagerDeleteMany,
|
||||
handleManagerRegenerateTitle,
|
||||
handleManagerExport,
|
||||
onFocusAIScopeTarget,
|
||||
]);
|
||||
@@ -2582,7 +2556,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
contextUsage={contextUsage}
|
||||
canCompact={canCompact}
|
||||
inputValue={inputValue}
|
||||
inputValueRevision={composerValueRevision}
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
@@ -2693,8 +2666,6 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
|
||||
'createSession',
|
||||
'deleteSession',
|
||||
'updateSessionTitle',
|
||||
'autoTitleSession',
|
||||
'regenerateSessionTitle',
|
||||
'rebindSessionScope',
|
||||
'exportSessionsBackup',
|
||||
'importSessionsBackup',
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface AIChatSidePanelProps {
|
||||
clearDraftForScope: (scopeKey: string) => void;
|
||||
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
|
||||
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
|
||||
createSession: (scope: AISessionScope, agentId?: string, workspaceNameSnapshot?: string) => AISession;
|
||||
createSession: (scope: AISessionScope, agentId?: string) => AISession;
|
||||
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
|
||||
undoLastTurnInSession?: (
|
||||
sessionId: string,
|
||||
@@ -44,9 +44,6 @@ export interface AIChatSidePanelProps {
|
||||
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
|
||||
deleteSession: (sessionId: string, scopeKey?: string) => void;
|
||||
updateSessionTitle: (sessionId: string, title: string) => void;
|
||||
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
|
||||
/** Explicitly regenerate an existing chat title with the configured LLM. */
|
||||
regenerateSessionTitle?: (sessionId: string) => void | Promise<void>;
|
||||
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
|
||||
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
|
||||
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
|
||||
|
||||
@@ -690,15 +690,11 @@ const SyncDashboard: React.FC<SyncDashboardProps> = ({
|
||||
if (!ensureSyncablePayload(payload)) return;
|
||||
const result = await sync.syncToProvider(provider, payload, {
|
||||
applyConvergentPayload: onApplyConvergentPayload,
|
||||
// A per-provider button must sync only that provider: skip the
|
||||
// convergent fan-out even when convergent mode is active.
|
||||
// Auto-sync / top-bar Sync Now still use syncAllProviders.
|
||||
forceSingleProvider: true,
|
||||
});
|
||||
|
||||
// The selected provider may still carry a newer joined replica
|
||||
// (e.g. written by another device); apply it locally before
|
||||
// reporting the result. This is per-provider only now.
|
||||
// Convergent sync fans out to every provider. Even if the
|
||||
// requested provider fails, another provider can verify a newer
|
||||
// joined replica that must be applied before reporting the error.
|
||||
if (result.mergedPayload && !result.mergedPayloadApplied && onApplyPayload) {
|
||||
const portableMerged = stripSyncPayloadEncryptedCredentials(result.mergedPayload);
|
||||
await Promise.resolve(onApplyPayload(portableMerged));
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
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,11 +33,6 @@ 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,7 +121,6 @@ export const hasGroupSshFields = (c: Partial<GroupConfig>): boolean => {
|
||||
return Boolean(
|
||||
c.proxyProfileId ||
|
||||
c.proxyConfig ||
|
||||
c.directProxy === true ||
|
||||
c.hostChain ||
|
||||
c.startupCommand ||
|
||||
c.startupCommandRunMode !== undefined,
|
||||
@@ -351,29 +350,23 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
|
||||
[form.proxyProfileId, proxyProfiles],
|
||||
);
|
||||
const hasMissingProxyProfile = Boolean(!form.directProxy && form.proxyProfileId && !selectedProxyProfile);
|
||||
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
|
||||
const hasProxyConfig = Boolean(
|
||||
form.directProxy || form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
|
||||
form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
|
||||
);
|
||||
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 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 update = <K extends keyof GroupConfig>(key: K, value: GroupConfig[K] | undefined) => {
|
||||
setForm((prev) => ({ ...prev, [key]: value }));
|
||||
@@ -470,7 +463,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
if (!hasAnyProtocol) {
|
||||
delete next.proxyProfileId;
|
||||
delete next.proxyConfig;
|
||||
delete next.directProxy;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -487,7 +479,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
if (!hasAnyProtocol) {
|
||||
delete next.proxyProfileId;
|
||||
delete next.proxyConfig;
|
||||
delete next.directProxy;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -503,7 +494,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
if (!hasAnyProtocol) {
|
||||
delete next.proxyProfileId;
|
||||
delete next.proxyConfig;
|
||||
delete next.directProxy;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -523,7 +513,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
if (!hasAnyProtocol) {
|
||||
delete next.proxyProfileId;
|
||||
delete next.proxyConfig;
|
||||
delete next.directProxy;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -536,7 +525,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
const updateProxyConfig = useCallback(
|
||||
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
|
||||
setForm((prev) => {
|
||||
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
|
||||
const { proxyProfileId: _proxyProfileId, ...rest } = prev;
|
||||
return {
|
||||
...rest,
|
||||
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
|
||||
@@ -548,26 +537,19 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
|
||||
const clearProxyConfig = useCallback(() => {
|
||||
setForm((prev) => {
|
||||
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
|
||||
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectProxyProfile = useCallback((profileId: string | undefined) => {
|
||||
setForm((prev) => {
|
||||
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
|
||||
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...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 || [];
|
||||
@@ -769,6 +751,7 @@ 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"));
|
||||
@@ -789,7 +772,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
|
||||
const anyProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled || telnetEnabled;
|
||||
const anyRoutingProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled;
|
||||
const proxySave = anyProtocolEnabled && !form.directProxy
|
||||
const proxySave = anyProtocolEnabled
|
||||
? prepareProxyConfigForSave({
|
||||
proxyConfig: form.proxyConfig,
|
||||
proxyProfileId: form.proxyProfileId,
|
||||
@@ -934,14 +917,10 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
|
||||
}),
|
||||
...(finalRdpConfig && { rdpConfig: finalRdpConfig }),
|
||||
...(finalVncConfig && { vncConfig: finalVncConfig }),
|
||||
...(anyProtocolEnabled && (
|
||||
form.directProxy === true
|
||||
? { directProxy: true }
|
||||
: {
|
||||
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
|
||||
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
|
||||
}
|
||||
)),
|
||||
...(anyProtocolEnabled && {
|
||||
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
|
||||
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
|
||||
}),
|
||||
...(anyRoutingProtocolEnabled && {
|
||||
...(form.hostChain !== undefined && { hostChain: form.hostChain }),
|
||||
}),
|
||||
@@ -975,10 +954,8 @@ 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}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { isRemoteDesktopProtocol } from "../domain/remoteDesktop";
|
||||
import React from "react";
|
||||
import { AlertTriangle, ChevronDown, Forward, Globe, HeartPulse, KeyRound, Link2, Palette, Plus, Router, ShieldAlert, TerminalSquare, Timer, Wifi, X, Variable } from "lucide-react";
|
||||
import { customThemeStore } from "../application/state/customThemeStore";
|
||||
import { useExternalEditorSettings } from "../application/state/useExternalEditorSettings";
|
||||
import { clearHostFontSizeOverride, clearHostThemeOverride } from "../domain/terminalAppearance";
|
||||
import { resolveSshAgentToggleUpdate } from "../domain/sshAuth";
|
||||
import { MAX_FONT_SIZE, MIN_FONT_SIZE } from "../infrastructure/config/fonts";
|
||||
@@ -64,11 +63,9 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
proxySummaryType,
|
||||
proxySummaryLabel,
|
||||
proxySummaryTooltip,
|
||||
displayDirectProxy = Boolean(form.directProxy),
|
||||
proxyInherited = false,
|
||||
clearProxyConfig,
|
||||
}) => {
|
||||
const { settings: externalEditorSettings } = useExternalEditorSettings();
|
||||
const inheritedDeviceType = effectiveGroupDefaults?.deviceType;
|
||||
const effectiveDeviceType = form.deviceType ?? inheritedDeviceType;
|
||||
const effectiveMoshEnabled = form.moshEnabled ?? effectiveGroupDefaults?.moshEnabled;
|
||||
@@ -552,39 +549,6 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
enabled={!!form.showLineTimestamps}
|
||||
onToggle={() => update("showLineTimestamps", !form.showLineTimestamps)}
|
||||
/>
|
||||
{isSshView && (
|
||||
<HostDetailsSettingRow
|
||||
label={t("hostDetails.externalEditorShellIntegration")}
|
||||
hint={t("hostDetails.externalEditorShellIntegration.desc")}
|
||||
>
|
||||
<Select
|
||||
value={
|
||||
form.externalEditorShellIntegration === true
|
||||
? "enabled"
|
||||
: form.externalEditorShellIntegration === false
|
||||
? "disabled"
|
||||
: "default"
|
||||
}
|
||||
onValueChange={(v) =>
|
||||
update(
|
||||
"externalEditorShellIntegration",
|
||||
v === "enabled" ? true : v === "disabled" ? false : undefined,
|
||||
)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-36 text-xs">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">
|
||||
{`${t("hostDetails.backspaceBehavior.default")} (${externalEditorSettings.autoSetupShellIntegration ? t("common.enabled") : t("common.disabled")})`}
|
||||
</SelectItem>
|
||||
<SelectItem value="enabled">{t("common.enabled")}</SelectItem>
|
||||
<SelectItem value="disabled">{t("common.disabled")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</HostDetailsSettingRow>
|
||||
)}
|
||||
{isSshView && !effectiveMoshEnabled && !effectiveEtEnabled && (
|
||||
<>
|
||||
<ToggleRow
|
||||
@@ -820,7 +784,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
|
||||
title={t("hostDetails.proxy")}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
{displayDirectProxy ? (
|
||||
{form.directProxy ? (
|
||||
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
@@ -832,10 +796,8 @@ 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"
|
||||
@@ -846,7 +808,6 @@ 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,34 +691,6 @@ 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,10 +517,8 @@ 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 = displayDirectProxy
|
||||
const displayProxyConfig = form.directProxy
|
||||
? undefined
|
||||
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
|
||||
const selectedProxyProfile = useMemo(
|
||||
@@ -529,7 +527,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
);
|
||||
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
|
||||
const proxyInherited = !hasHostProxyOverride && Boolean(
|
||||
displayDirectProxy || displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
|
||||
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
|
||||
);
|
||||
const proxySummaryType = hasMissingProxyProfile
|
||||
? t("hostDetails.proxyPanel.missing")
|
||||
@@ -1520,7 +1518,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
proxyProfiles={proxyProfiles}
|
||||
identities={identities}
|
||||
selectedProxyProfileId={displayProxyProfileId}
|
||||
directProxy={displayDirectProxy}
|
||||
directProxy={form.directProxy}
|
||||
allowClear={hasHostProxyOverride}
|
||||
onUpdateProxy={updateProxyConfig}
|
||||
onSelectProxyProfile={selectProxyProfile}
|
||||
@@ -1904,7 +1902,6 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
proxySummaryType={proxySummaryType}
|
||||
proxySummaryLabel={proxySummaryLabel}
|
||||
proxySummaryTooltip={proxySummaryTooltip}
|
||||
displayDirectProxy={displayDirectProxy}
|
||||
proxyInherited={proxyInherited}
|
||||
clearProxyConfig={clearProxyConfig}
|
||||
/>
|
||||
|
||||
@@ -2,11 +2,6 @@ import React from "react";
|
||||
import { ChevronRight, Info } from "lucide-react";
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from "../domain/groupConfig";
|
||||
import { sanitizeCredentialValue } from "../domain/credentials";
|
||||
import {
|
||||
getExportablePublicKey,
|
||||
hasExportablePublicKey,
|
||||
isKeychainExportDisabled,
|
||||
} from "../domain/keychainExport";
|
||||
import { hasBridgeSshCredentials, resolveBridgeKeyAuth, resolveBridgeSshAgentAuth, resolveHostAuth } from "../domain/sshAuth";
|
||||
import { resolveHostSshConnectionTimeouts } from "../domain/sshConnectionTimeouts";
|
||||
import { connectionTotpFields } from "../domain/totpConfig";
|
||||
@@ -46,15 +41,6 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
onSaveHost,
|
||||
closePanel,
|
||||
}) => {
|
||||
const hasPublicKey = hasExportablePublicKey(panel.key?.publicKey);
|
||||
const exportDisabled = isKeychainExportDisabled({
|
||||
exportHost,
|
||||
exportLocation,
|
||||
exportFilename,
|
||||
publicKey: panel.key?.publicKey,
|
||||
isExporting,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Key info card */}
|
||||
@@ -173,32 +159,17 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
|
||||
{!hasPublicKey && (
|
||||
<div className="flex items-start gap-2 p-3 bg-muted/50 border border-border/60 rounded-lg">
|
||||
<Info
|
||||
size={14}
|
||||
className="mt-0.5 text-muted-foreground shrink-0"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("keychain.export.missingPublicKeyNote")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Export button */}
|
||||
<Button
|
||||
className="w-full h-11"
|
||||
disabled={exportDisabled}
|
||||
disabled={
|
||||
!exportHost ||
|
||||
!exportLocation ||
|
||||
!exportFilename ||
|
||||
isExporting
|
||||
}
|
||||
onClick={async () => {
|
||||
if (!exportHost) return;
|
||||
const publicKey = getExportablePublicKey(panel.key?.publicKey);
|
||||
if (!publicKey) {
|
||||
toast.error(
|
||||
t("keychain.export.missingPublicKey"),
|
||||
t("keychain.export.failedTitle"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!exportHost || !panel.key.publicKey) return;
|
||||
|
||||
setIsExporting(true);
|
||||
|
||||
@@ -245,7 +216,7 @@ export const KeychainExportPanel: React.FC<KeychainExportPanelProps> = ({
|
||||
}
|
||||
|
||||
// Escape the public key for shell (single quotes, escape existing quotes)
|
||||
const escapedPublicKey = publicKey.replace(
|
||||
const escapedPublicKey = panel.key.publicKey.replace(
|
||||
/'/g,
|
||||
"'\\''",
|
||||
);
|
||||
|
||||
@@ -73,12 +73,8 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
await act(async () => { selectSection('plugin-vault:missing'); await settle(); });
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] }; changed?.(); await settle(); });
|
||||
await act(async () => { activeTabStore.setActiveTabId('terminal:synthetic'); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'terminal:synthetic');
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id, params: { connectionId: 'db-1' } }); await settle(); });
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault', 'opening a vault-page switches the active tab to vault');
|
||||
await act(async () => { requestOpenPluginView({ viewId: page.id }); await settle(); });
|
||||
assert.equal(opens.length, 2);
|
||||
assert.deepEqual(opens[1].context, { 'netcatty.surface': 'vault-page' }, 'activation params must not be merged into contribution context');
|
||||
await act(async () => { selectSection('hosts'); await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
} finally {
|
||||
@@ -86,91 +82,3 @@ test('Vault navigation mounts a real content slot, yields to host dialogs, and w
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
|
||||
test('Failed host-drawn view session stays on the plugin vault page with error and retry instead of falling back to Hosts', 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>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof Window] });
|
||||
}
|
||||
for (const [key, value] of Object.entries({ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
|
||||
requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window), IS_REACT_ACT_ENVIRONMENT: true })) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({ x: 200, y: 100, width: 640, height: 480, top: 100, left: 200, right: 840, bottom: 580, toJSON() {} });
|
||||
const { act, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginVaultPages } = await import('../application/state/usePluginVaultPages');
|
||||
const { PluginVaultNavigation, PluginVaultPage } = await import('./plugins/PluginVaultPages');
|
||||
const { activeTabStore } = await import('../application/state/activeTabStore');
|
||||
const { I18nProvider } = await import('../application/i18n/I18nProvider');
|
||||
const page = { id: 'com.example.page.main', title: 'Synthetic page', location: 'vault-page', visible: true };
|
||||
let snapshot = { locale: 'en', plugins: [{ id: 'com.example.page', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [page] }] };
|
||||
let changed: (() => void) | undefined;
|
||||
const listeners = new Set<(event: NetcattyPluginViewClosedEvent) => void>();
|
||||
const opens: NetcattyPluginViewOpenRequest[] = [], closes: string[] = [];
|
||||
Object.assign(dom.window, { netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return snapshot; },
|
||||
onPluginContributionsChanged(fn: () => void) { changed = fn; return () => { changed = undefined; }; },
|
||||
onPluginViewClosed(fn: (event: NetcattyPluginViewClosedEvent) => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
||||
onHostDrawnPluginViewUpdate() { return () => {}; },
|
||||
async openHostDrawnPluginView(payload: NetcattyPluginViewOpenRequest) { opens.push(payload); return { instanceId: payload.instanceId! }; },
|
||||
async closeHostDrawnPluginView(id: string) { closes.push(id); },
|
||||
} });
|
||||
function Fixture() {
|
||||
const [section, select] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
|
||||
const model = usePluginVaultPages({ locale: 'en', section, select });
|
||||
return <><aside><button data-plugin-vault-fallback onClick={() => select('hosts')}>Hosts</button><PluginVaultNavigation model={model} collapsed={false} /></aside>
|
||||
<main data-section="vault-main">{model.selected ? <PluginVaultPage key={model.selected.key} model={model} /> : <p>Built-in hosts</p>}</main></>;
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 35));
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await act(async () => { root.render(<I18nProvider locale="en"><Fixture /></I18nProvider>); await settle(); });
|
||||
await act(async () => {
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Synthetic page — Synthetic plugin"]')!.click();
|
||||
await import('./plugins/PluginHostDrawnPage');
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 1);
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'));
|
||||
|
||||
// Session fails while plugin contribution remains active.
|
||||
await act(async () => {
|
||||
for (const listener of listeners) {
|
||||
listener({ instanceId: opens[0].instanceId!, viewId: page.id, pluginId: 'com.example.page', reason: 'view-error' });
|
||||
}
|
||||
await settle();
|
||||
});
|
||||
assert.ok(document.querySelector('[data-plugin-vault-page]'), 'stays on the plugin vault page');
|
||||
assert.doesNotMatch(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
assert.equal(document.querySelector('[data-plugin-remote-surface]'), null, 'does not render an empty remote surface');
|
||||
const alert = document.querySelector('[data-plugin-vault-page] [role="alert"]');
|
||||
assert.ok(alert, 'renders in-page error alert');
|
||||
assert.equal(alert!.textContent, 'The plugin page failed to render.');
|
||||
|
||||
const retryButton = [...document.querySelectorAll<HTMLButtonElement>('[data-plugin-vault-page] button')]
|
||||
.find((btn) => btn.textContent === 'Retry');
|
||||
assert.ok(retryButton, 'renders Retry control');
|
||||
|
||||
await act(async () => {
|
||||
retryButton!.click();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(opens.length, 2, 'clicking Retry opens a new host-drawn plugin view session');
|
||||
assert.notEqual(opens[1].instanceId, opens[0].instanceId);
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page] [role="alert"]'), null);
|
||||
|
||||
// Removing the contribution still falls back to Hosts.
|
||||
await act(async () => { snapshot = { ...snapshot, plugins: [] }; changed?.(); await settle(); });
|
||||
await act(async () => { await settle(); });
|
||||
assert.equal(document.querySelector('[data-plugin-vault-page]'), null);
|
||||
assert.match(document.querySelector('main')!.textContent!, /Built-in hosts/);
|
||||
} finally {
|
||||
await act(async () => { root.unmount(); (await import('../application/state/pluginViewSession')).pluginViewSessions.dispose(); await settle(); }); dom.window.close();
|
||||
for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); }
|
||||
}
|
||||
});
|
||||
@@ -226,15 +226,3 @@ 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=""/);
|
||||
});
|
||||
@@ -258,12 +258,6 @@ const SettingsAITabContainer: React.FC = () => {
|
||||
setQuickMessages={aiState.setQuickMessages}
|
||||
showTerminalSelectionAIAction={aiState.showTerminalSelectionAIAction}
|
||||
setShowTerminalSelectionAIAction={aiState.setShowTerminalSelectionAIAction}
|
||||
autoLlmTitle={aiState.autoLlmTitle}
|
||||
setAutoLlmTitle={aiState.setAutoLlmTitle}
|
||||
titleModel={aiState.titleModel}
|
||||
setTitleModel={aiState.setTitleModel}
|
||||
agentProviderMap={aiState.agentProviderMap}
|
||||
agentModelMap={aiState.agentModelMap}
|
||||
/>
|
||||
</AITabErrorBoundary>
|
||||
);
|
||||
@@ -587,8 +581,6 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setShowSftpTab={settings.setShowSftpTab}
|
||||
showHostTreeSidebar={settings.showHostTreeSidebar}
|
||||
setShowHostTreeSidebar={settings.setShowHostTreeSidebar}
|
||||
removeTopTabsDragArea={settings.removeTopTabsDragArea}
|
||||
setRemoveTopTabsDragArea={settings.setRemoveTopTabsDragArea}
|
||||
windowOpacity={settings.windowOpacity}
|
||||
setWindowOpacity={settings.setWindowOpacity}
|
||||
windowBackgroundBlur={settings.windowBackgroundBlur}
|
||||
|
||||
+2
-30
@@ -1,5 +1,4 @@
|
||||
import { terminalCwdStore } from '../application/state/terminalCwdStore';
|
||||
import { useTerminalExternalEditor } from '../application/state/useTerminalExternalEditor';
|
||||
import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession';
|
||||
import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
|
||||
import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
|
||||
@@ -1412,32 +1411,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const osc52ReadResolverRef = useRef<((allowed: boolean) => void) | null>(null);
|
||||
const [osc7SetupOpen, setOsc7SetupOpen] = useState(false);
|
||||
const [osc7SetupRunning, setOsc7SetupRunning] = useState(false);
|
||||
|
||||
const {
|
||||
pendingExternalEditorRequest,
|
||||
handleOscExternalEditorRequest,
|
||||
handleExternalEditorPromptResponse,
|
||||
} = useTerminalExternalEditor({
|
||||
sessionId,
|
||||
status,
|
||||
host,
|
||||
isLocalConnection,
|
||||
isSerialConnection,
|
||||
getBackendSessionId: () => sessionRef.current ?? sessionId,
|
||||
isVisible: () => isVisibleRef.current,
|
||||
getFallbackCwd: () => terminalCwdTracker.getRendererCwd() ?? knownCwdRef.current ?? undefined,
|
||||
isReadyForCommandInjection: () => isTerminalReadyForCommandInjection(sessionId),
|
||||
setupOsc7Tracking: terminalBackend.setupOsc7Tracking,
|
||||
writeToSession: terminalBackend.writeToSession,
|
||||
focusTerminal: () => termRef.current?.focus(),
|
||||
onOpened: (editor, path) =>
|
||||
toast.success(t("terminal.externalEditor.opened", { editor, path })),
|
||||
onOpenFailed: (message) => toast.error(message),
|
||||
formatFallbackOpenError: (editor) =>
|
||||
t("terminal.externalEditor.failed", { editor }),
|
||||
onAutoSetupConfigured: (editor) =>
|
||||
toast.success(t("terminal.externalEditor.autoSetupConfigured", { editor })),
|
||||
});
|
||||
const handleOsc52ReadRequest = useCallback((): Promise<boolean> => {
|
||||
// Reject if terminal is not visible (background tab) — user can't see the prompt
|
||||
if (!isVisibleRef.current) return Promise.resolve(false);
|
||||
@@ -4839,7 +4812,6 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
});
|
||||
},
|
||||
onOsc52ReadRequest: handleOsc52ReadRequest,
|
||||
onOscExternalEditorRequest: handleOscExternalEditorRequest,
|
||||
onAutocompleteKeyEvent: (e: KeyboardEvent) => autocompleteKeyEventRef.current?.(e) ?? true,
|
||||
onAutocompleteInput: (data: string) => autocompleteInputRef.current?.(data),
|
||||
onAutocompleteReposition: () => autocompleteRepositionRef.current?.(),
|
||||
@@ -5106,11 +5078,11 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
onWake: wakeFromHibernateRuntime,
|
||||
});
|
||||
|
||||
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleOscExternalEditorRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
useTerminalEffects({ isPromptSecurityAlternateScreenActive, CONNECTION_TIMEOUT, Error, XTERM_PERFORMANCE_CONFIG, applyUserCursorPreference, applyUserCursorWidthPreference, shouldApplyUserCursorPreference, snapshotUserCursorPreference, auth, autocompleteCloseRef, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, captureTerminalLogData, chainHosts: resolvedChainHosts, chainProgress, clearTerminalCwd, commandBufferRef, connectionLogBufferRef, containerRef, createPromptLineBreakState, createReplaySafeTerminalLogSanitizer, createXTermRuntime, deferTerminalResizeRef, disableTerminalFontZoomRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippetCommand, finalizeTerminalLogData, fitAddonRef, fontFamilyId, fontSize, fontWeightFixupDoneRef, forceCloseHibernatedSession, forceSyncRenderAfterResize, handleOsc52ReadRequest, handleTerminalDataCaptureOnce, hasConnectedRef, hasRuntimeRef, host, hotkeySchemeRef, hibernatedRef, identities, inWorkspace, isBootActiveRef, bootEpochRef, isBroadcastEnabledRef, broadcastPasswordBypassRef, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isConnectionPastTcpDial, isWaitingForAutoReconnect, isFocusMode, isFocused, isLocalConnection, isNetworkDevice, isResizing: deferTerminalResize, isRestoringSelectionRef, isSearchOpen, isSerialConnection, isVisible, isVisibleRef, keyBindingsRef, keys, kittyKeyboardProtocolEnabledForSession, knownCwdRef, lastFittedSizeRef, lastToastedErrorRef, logger, mouseTrackingRef, needsHostKeyVerification, onBroadcastInputRef, onBroadcastInterruptPriorityChange, onCommandExecuted, onCommandSubmitted: cwdAwareOnCommandSubmitted, onCommandSettled: onCommandSubmitted, onHotkeyActionRef, onOpenExternalError, onOutputTriggerUserInputRef: noteOutputTriggerUserInputRef, onPluginRuntimeCwdChange: pluginAwareOnRuntimeCwdChange, onSnippetShortkeyRef, onSnippetExecutorChange, onTerminalCwdChange, onTerminalTitleChange, onTerminalBell, onTerminalFontSizeChange, paneLayoutKey, passwordPromptActiveRef, pendingAuthRef, pendingOutputScrollRef, pluginDecorationRefreshRef, pluginDecorationRules, pluginDecorationRulesRef, pluginTerminalLifecycle, pluginTerminalProviderRevision, isPluginTerminalProviderAvailable, requestPluginTerminalProviders, prepareRestoredReconnect, prepareInitialCwdIntent, prevIsResizingRef, promptLineBreakStateRef, resizeSession, resolveHostAuth, resolvedFontFamily, safeFit, scriptRecorderRef: recorderRef, searchAddonRef, serialConfig, serialLineBufferRef, serializeAddonRef, sessionId, sessionRef, sessionStarters, setError, setHasMouseTracking, setIsCancelling, setIsDisconnectedDialogDismissed, requestSearchFocus, setNeedsHostKeyVerification, setPendingHostKeyInfo, setPendingHostKeyRequestId, setProgressLogs, setProgressValue, setShowLogs, setStatus, setConnectionDeadlineAt, shellType, shouldEnableNativeUserInputAutoScroll, shouldProbeSessionCwd, shouldStartTerminalBackend, vaultInitialized, attachExistingSession, attachAuthorization, attachHomeWebContentsIdRef, snippetsRef, splitResizeActive: isResizing, status, statusRef, sudoAutofillRef, t, teardown, telnetLocalEchoRef, termRef, terminalAltKeyOptions, terminalBackend, terminalContextActionsRef, terminalCwdTracker, terminalDataCapturedRef, terminalLogSanitizerRef, terminalOutputHistory: terminalOutputHistoryRef.current, terminalSettings, terminalSettingsRef, terminalTitleRef, toHostKeyInfo, toast, updateStatus, useEffect, useLayoutEffect, workspaceId, xtermRuntimeRef, zmodem, zmodemToastedRef, restoreState });
|
||||
|
||||
return (
|
||||
<>
|
||||
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleExternalEditorPromptResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, pendingExternalEditorRequest, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
|
||||
<TerminalView ctx={{ Activity, ArrowDownToLine, ArrowUpFromLine, Button, Clock3, Copy, Cpu, HardDrive, HoverCard, HoverCardContent, HoverCardTrigger, Maximize2, MemoryStick, Radio, RefreshCcw, Sparkles, SquareArrowOutUpRight, Unplug, TerminalAutocomplete, TerminalComposeBar, TerminalConnectionDialog, TerminalContextMenu, TerminalSearchBar, Tooltip, TooltipContent, TooltipTrigger, ZmodemOverwriteDialog, ZmodemProgressIndicator, auth, autocompleteAcceptTextRef, autocompleteCloseRef, autocompleteHostOs, autocompleteInputRef, autocompleteKeyEventRef, autocompleteRepositionRef, autocompleteSettings, canUpdateHost: !!onUpdateHost, chainProgress, cn, compactToolbar, lineTimestampsAvailable, containerRef, effectiveFontSize, effectiveFontWeight, effectiveTheme, error, executeSnippet, executeSnippetCommand, handleAddSelectionToAI: onAddSelectionToAI ? handleAddSelectionToAI : undefined, handleCancelConnect, handleCloseDisconnectedSession, handleCloseSearch, handleDisconnect: (attachExistingSession || compactToolbar) ? undefined : handleDisconnect, handleDismissDisconnectedDialog, handleDragEnter, handleDragLeave, handleDragOver, handleDrop, handleFindNext, handleFindPrevious, handleHostKeyAddAndContinue, handleHostKeyClose, handleHostKeyContinue, handleOpenHostBrowser, handleOpenSFTP, handleOsc52ReadResponse, handleOsc7SetupConfirm, handleOsc7SetupOpenChange, handleReceiveYmodem, handleRetry, handleSearch, handleSendYmodem, handleTopOverlayMouseDownCapture, hasMouseTracking, host, hotkeyScheme, inWorkspace, isBroadcastEnabled, composeSendToAll, onToggleComposeSendTarget, isCancelling, isComposeBarOpen: effectiveComposeBarOpen, isConnectionAwaitingUserInput, isDraggingOver, isFocusMode, isFocusedPane, isLocalConnection, remoteDragDropUsesZmodem, isPluginTerminalProviderAvailable, isReconnectActive, isSerialConnection, isSearchOpen, isSupportedOs, isSystemSidebarEligible, isVisible, keyBindings, keys, identities, knownCwdRef, needsHostKeyVerification, onAddSelectionToAI, onBroadcastInput, onCloseSession, onDetach, onDetachDragEnd, onDetachDragStart, onDetachPointerDown, onEndSessionDrag, onExpandToFocus, onTogglePaneMagnification, onOpenSystem, onRename, onSplitHorizontal, onSplitVertical, onStartSessionDrag, onToggleBroadcast, onUpdateHost: handleUpdateHostFromTerminal, osc52ReadPromptVisible, osc7SetupOpen, osc7SetupRunning, passwordPromptActiveRef, pendingHostKeyInfo, progressLogs, progressValue, renderControls, resolvedFontFamily, restoreState, scrollToBottomAfterProgrammaticInput, searchMatchCount, searchFocusToken, scriptExecutionOverlay: activeScriptRun ? (
|
||||
<ScriptExecutionOverlay
|
||||
run={activeScriptRun}
|
||||
onPause={() => { void pauseScriptRun(activeScriptRun.runId); }}
|
||||
|
||||
@@ -137,10 +137,8 @@ import {
|
||||
} from '../domain/sidePanelLayout';
|
||||
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
|
||||
import {
|
||||
canMagnifyPaneSurface,
|
||||
pruneMagnifiedPanesByTab,
|
||||
isPaneMagnificationSelectionValid,
|
||||
resolvePaneMagnificationCandidate,
|
||||
setTabMagnifiedPane,
|
||||
type PaneMagnificationController,
|
||||
type PaneMagnificationTarget,
|
||||
} from '../domain/paneMagnification';
|
||||
@@ -320,11 +318,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
onRemoveSessionFromWorkspace,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const [magnifiedPanesByTab, setMagnifiedPanesByTab] = useState<
|
||||
ReadonlyMap<string, PaneMagnificationTarget>
|
||||
>(() => new Map());
|
||||
const magnifiedPanesByTabRef = useRef(magnifiedPanesByTab);
|
||||
magnifiedPanesByTabRef.current = magnifiedPanesByTab;
|
||||
const [magnifiedPane, setMagnifiedPane] = useState<{
|
||||
tabId: string;
|
||||
target: PaneMagnificationTarget;
|
||||
} | null>(null);
|
||||
const magnifiedPaneRef = useRef(magnifiedPane);
|
||||
magnifiedPaneRef.current = magnifiedPane;
|
||||
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.
|
||||
@@ -346,8 +345,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
setMagnifiedPanesByTab((current) => {
|
||||
if (current.size === 0) return current;
|
||||
setMagnifiedPane((current) => {
|
||||
if (!current) return current;
|
||||
const terminalPanes = sessions.map((session) => ({
|
||||
tabId: session.workspaceId ?? session.id,
|
||||
sessionId: session.id,
|
||||
@@ -355,7 +354,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const sidePanelPanes = Array.from(sidePanelLayouts.entries()).flatMap(([tabId, layout]) => (
|
||||
collectSidePanelPanes(layout.root).map((pane) => ({ tabId, paneId: pane.id }))
|
||||
));
|
||||
return pruneMagnifiedPanesByTab(current, terminalPanes, sidePanelPanes);
|
||||
return isPaneMagnificationSelectionValid(current, terminalPanes, sidePanelPanes)
|
||||
? current
|
||||
: null;
|
||||
});
|
||||
}, [sessions, sidePanelLayouts]);
|
||||
const terminalRendererCwdBySessionRef = useRef<Map<string, string>>(new Map());
|
||||
@@ -474,18 +475,11 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
|
||||
// Stable callback references for Terminal components
|
||||
const handleCloseSession = useCallback((sessionId: string) => {
|
||||
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;
|
||||
});
|
||||
setMagnifiedPane((current) => (
|
||||
current?.target.kind === 'terminal' && current.target.sessionId === sessionId
|
||||
? null
|
||||
: current
|
||||
));
|
||||
for (const [tabId, target] of lastInteractedPaneRef.current) {
|
||||
if (target.kind === 'terminal' && target.sessionId === sessionId) {
|
||||
lastInteractedPaneRef.current.delete(tabId);
|
||||
@@ -1497,9 +1491,6 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
if (!shouldProbeCommandCwd({
|
||||
restoreTerminalCwd,
|
||||
visibleSftpHost,
|
||||
latestVisibleSftpHost: visibleSftpHost
|
||||
? hostsRef.current.find((host) => host.id === visibleSftpHost.id)
|
||||
: undefined,
|
||||
sessionHost,
|
||||
globalSftpFollowTerminalCwd: sftpFollowTerminalCwdRef.current,
|
||||
restrictExtraSshChannels: hostRestrictsExtraSshChannels(sessionHost),
|
||||
@@ -1782,9 +1773,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const handleCloseSidePanel = useCallback(() => {
|
||||
const activeTabId = activeTabIdRef.current;
|
||||
if (!activeTabId) return;
|
||||
setMagnifiedPanesByTab((current) => (
|
||||
current.get(activeTabId)?.kind === 'side-panel'
|
||||
? setTabMagnifiedPane(current, activeTabId, null)
|
||||
setMagnifiedPane((current) => (
|
||||
current?.tabId === activeTabId && current.target.kind === 'side-panel'
|
||||
? null
|
||||
: current
|
||||
));
|
||||
const sessionIdToRefocus = getActiveTerminalSessionId();
|
||||
@@ -1915,27 +1906,14 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const handleMagnifyTerminalPane = useCallback((tabId: string, sessionId: string) => {
|
||||
const target: PaneMagnificationTarget = { kind: 'terminal', sessionId };
|
||||
lastInteractedPaneRef.current.set(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]);
|
||||
setMagnifiedPane((current) => (
|
||||
current?.tabId === tabId
|
||||
&& current.target.kind === 'terminal'
|
||||
&& current.target.sessionId === sessionId
|
||||
? null
|
||||
: { tabId, target }
|
||||
));
|
||||
}, []);
|
||||
|
||||
const handleMagnifySidePanelPane = useCallback((paneId: string) => {
|
||||
const tabId = activeTabIdRef.current;
|
||||
@@ -1951,19 +1929,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
tool: pane.tool,
|
||||
};
|
||||
lastInteractedPaneRef.current.set(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);
|
||||
});
|
||||
setMagnifiedPane((current) => (
|
||||
current?.tabId === tabId
|
||||
&& current.target.kind === 'side-panel'
|
||||
&& current.target.paneId === paneId
|
||||
? null
|
||||
: { tabId, target }
|
||||
));
|
||||
}, [sidePanelLayoutsRef]);
|
||||
|
||||
const handleRestoreMagnifiedPane = useCallback(() => {
|
||||
const tabId = activeTabIdRef.current;
|
||||
if (!tabId) return;
|
||||
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, tabId, null));
|
||||
setMagnifiedPane((current) => current?.tabId === tabId ? null : current);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -1972,8 +1949,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const tabId = activeTabStore.getActiveTabId();
|
||||
if (!tabId) return null;
|
||||
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
|
||||
const currentTarget = magnifiedPanesByTabRef.current.get(tabId);
|
||||
const hasCurrentMagnification = !!currentTarget;
|
||||
const hasCurrentMagnification = magnifiedPaneRef.current?.tabId === tabId;
|
||||
if (workspace?.viewMode === 'focus' && !hasCurrentMagnification) return null;
|
||||
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
|
||||
const standaloneSession = sessionsRef.current.find((candidate) => (
|
||||
@@ -1995,7 +1971,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
? [focusedSidePanelPane, ...sidePanelPanes.filter((pane) => pane !== focusedSidePanelPane)]
|
||||
: sidePanelPanes,
|
||||
lastTarget: lastInteractedPaneRef.current.get(tabId),
|
||||
current: currentTarget ? { tabId, target: currentTarget } : null,
|
||||
current: magnifiedPaneRef.current,
|
||||
});
|
||||
return candidate ? { tabId, ...candidate } : null;
|
||||
};
|
||||
@@ -2007,23 +1983,19 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
focus: () => {
|
||||
const target = getTarget();
|
||||
if (!target || target.focused) return false;
|
||||
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, target.target));
|
||||
setMagnifiedPane({ tabId: target.tabId, target: target.target });
|
||||
return true;
|
||||
},
|
||||
restore: () => {
|
||||
const target = getTarget();
|
||||
if (!target?.focused) return false;
|
||||
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, null));
|
||||
setMagnifiedPane(null);
|
||||
return true;
|
||||
},
|
||||
toggle: () => {
|
||||
const target = getTarget();
|
||||
if (!target) return false;
|
||||
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(
|
||||
current,
|
||||
target.tabId,
|
||||
target.focused ? null : target.target,
|
||||
));
|
||||
setMagnifiedPane(target.focused ? null : { tabId: target.tabId, target: target.target });
|
||||
return true;
|
||||
},
|
||||
};
|
||||
@@ -2057,12 +2029,13 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
const closingPane = layout
|
||||
? collectSidePanelPanes(layout.root).find((pane) => pane.id === paneId)
|
||||
: undefined;
|
||||
setMagnifiedPanesByTab((current) => {
|
||||
const existing = current.get(tabId);
|
||||
return existing?.kind === 'side-panel' && existing.paneId === paneId
|
||||
? setTabMagnifiedPane(current, tabId, null)
|
||||
: current;
|
||||
});
|
||||
setMagnifiedPane((current) => (
|
||||
current?.tabId === tabId
|
||||
&& current.target.kind === 'side-panel'
|
||||
&& current.target.paneId === paneId
|
||||
? null
|
||||
: current
|
||||
));
|
||||
const closesWholePanel = closeSidePanelPaneForTab(tabId, paneId);
|
||||
if (closesWholePanel) {
|
||||
handleCloseSidePanel();
|
||||
@@ -2090,12 +2063,8 @@ 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;
|
||||
setMagnifiedPanesByTab((current) => {
|
||||
const existing = current.get(tabId);
|
||||
return existing?.kind === 'side-panel' && existing.paneId === paneId
|
||||
? setTabMagnifiedPane(current, tabId, null)
|
||||
: current;
|
||||
});
|
||||
setMagnifiedPane((current) => current?.tabId === tabId && current.target.kind === 'side-panel'
|
||||
&& current.target.paneId === paneId ? null : current);
|
||||
closeSidePanelPaneForTab(tabId, paneId);
|
||||
}, [closeSidePanelPaneForTab, sidePanelLayoutsRef]);
|
||||
|
||||
@@ -2182,12 +2151,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false;
|
||||
tabId = terminal.id;
|
||||
}
|
||||
setMagnifiedPanesByTab((current) => {
|
||||
const existing = current.get(tabId);
|
||||
return existing && !(existing.kind === 'side-panel' && existing.tool === 'ai')
|
||||
? setTabMagnifiedPane(current, tabId, null)
|
||||
: current;
|
||||
});
|
||||
setMagnifiedPane((current) => (
|
||||
current?.tabId === tabId
|
||||
&& !(current.target.kind === 'side-panel' && current.target.tool === 'ai')
|
||||
? null
|
||||
: current
|
||||
));
|
||||
activeTabStore.setActiveTabId(tabId);
|
||||
if (prepareSidePanelTool(tabId, 'ai')) {
|
||||
startTransition(() => {
|
||||
@@ -2917,7 +2886,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
|
||||
lastSidePanelTabRef,
|
||||
mountedAiTabIds: aiMountedTabIds,
|
||||
mountedSftpTabIds,
|
||||
magnifiedPanesByTab,
|
||||
magnifiedPane,
|
||||
notesMountedTabIds,
|
||||
browserMountedTabIds,
|
||||
notesOpenNoteByTab,
|
||||
|
||||
@@ -659,7 +659,6 @@ function TerminalPopupPageInner({
|
||||
accentMode={settings.accentMode}
|
||||
customAccent={settings.customAccent}
|
||||
terminalSettings={settings.terminalSettings}
|
||||
shellType={config.sourceSession.shellType}
|
||||
vaultInitializedOverride={vaultInitialized}
|
||||
disableTerminalFontZoom={settings.disableTerminalFontZoom}
|
||||
sessionId={sessionId}
|
||||
|
||||
+2
-10
@@ -217,7 +217,6 @@ interface TopTabsProps {
|
||||
tabInsertionTarget?: { tabId: string; position: 'before' | 'after'; additionalTabIds?: readonly string[] },
|
||||
) => void;
|
||||
onAppendHostToWorkspace?: (workspaceId: string, hostId: string) => void;
|
||||
onRequestAddToWorkspace?: (workspaceId: string) => void;
|
||||
showSftpTab: boolean;
|
||||
showHostTreeSidebar: boolean;
|
||||
switchTabKeyBinding: Pick<KeyBinding, 'mac' | 'pc'> | null;
|
||||
@@ -271,7 +270,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onReorderTabs,
|
||||
onRemoveSessionFromWorkspace,
|
||||
onAppendHostToWorkspace,
|
||||
onRequestAddToWorkspace,
|
||||
showSftpTab,
|
||||
showHostTreeSidebar,
|
||||
switchTabKeyBinding,
|
||||
@@ -290,7 +288,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
const {
|
||||
hotkeyScheme,
|
||||
showTabNumberBadges,
|
||||
removeTopTabsDragArea,
|
||||
shellOnlyTabNumberShortcuts,
|
||||
} = useSettingsChromeStore();
|
||||
const switchTabKey = hotkeyScheme === 'mac'
|
||||
@@ -1034,7 +1031,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onTabDrop={handleTabDrop}
|
||||
onRenameWorkspace={onRenameWorkspace}
|
||||
onCopyWorkspace={onCopyWorkspace}
|
||||
onRequestAddToWorkspace={onRequestAddToWorkspace}
|
||||
onCloseWorkspace={onCloseWorkspace}
|
||||
onDetachSessionFromWorkspace={handleDetachSessionFromWorkspace}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
@@ -1091,7 +1087,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
<div
|
||||
data-top-tabs-root
|
||||
data-section="top-tabs"
|
||||
data-remove-top-tabs-drag-area={removeTopTabsDragArea ? 'true' : undefined}
|
||||
className="relative w-full bg-secondary app-drag"
|
||||
style={{
|
||||
...dragRegionNoSelect,
|
||||
@@ -1104,11 +1099,9 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
tabsContainerRef={tabsContainerRef}
|
||||
updateScrollState={updateScrollState}
|
||||
/>
|
||||
{!removeTopTabsDragArea && (
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
)}
|
||||
{/* Always-on drag stripe so the window can be moved even when tabs fill the bar */}
|
||||
<div className="absolute inset-x-0 top-0 h-1 app-drag pointer-events-auto z-10" style={dragRegionStyle} aria-hidden />
|
||||
<div
|
||||
data-section="top-tabs-toolbar-row"
|
||||
className="h-9 flex items-end gap-0 app-drag overflow-visible"
|
||||
style={{
|
||||
...dragRegionStyle,
|
||||
@@ -1394,7 +1387,6 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
prev.onRequestAddToWorkspace === next.onRequestAddToWorkspace &&
|
||||
prev.onCopyWorkspace === next.onCopyWorkspace &&
|
||||
prev.onOpenSettings === next.onOpenSettings &&
|
||||
prev.onLockApp === next.onLockApp &&
|
||||
|
||||
@@ -394,7 +394,6 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -412,17 +412,3 @@ test('renders vault note attachment chips with the note title', () => {
|
||||
assert.match(source, /file\.vaultNoteId \? \(/);
|
||||
assert.match(source, /\{file\.vaultNoteTitle \|\| file\.filename\}/);
|
||||
});
|
||||
|
||||
test('valueRevision clears the uncontrolled textarea even when value stays empty across renders', () => {
|
||||
const chatInputSource = readFileSync(new URL('./ChatInput.tsx', import.meta.url), 'utf8');
|
||||
const sidePanelSource = readFileSync(new URL('../AIChatSidePanel.tsx', import.meta.url), 'utf8');
|
||||
const contentSource = readFileSync(new URL('../AIChatPanelContent.tsx', import.meta.url), 'utf8');
|
||||
|
||||
assert.match(chatInputSource, /valueRevision\?: number/);
|
||||
assert.match(chatInputSource, /prev\.valueRevision === next\.valueRevision/);
|
||||
assert.match(chatInputSource, /const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
|
||||
assert.match(chatInputSource, /if \(!revisionChanged && value === pushedParentTextRef\.current\) return/);
|
||||
assert.match(sidePanelSource, /setComposerValueRevision\(\(rev\) => rev \+ 1\)/);
|
||||
assert.match(sidePanelSource, /inputValueRevision=\{composerValueRevision\}/);
|
||||
assert.match(contentSource, /valueRevision=\{inputValueRevision\}/);
|
||||
});
|
||||
@@ -207,12 +207,6 @@ const ComposerSendUi = React.memo(function ComposerSendUi({
|
||||
|
||||
interface ChatInputProps {
|
||||
value: string;
|
||||
/**
|
||||
* Monotonic revision bumped by the parent whenever an authoritative reset
|
||||
* (e.g. post-send draft clear) must be applied to the uncontrolled textarea
|
||||
* even when `value` stayed equal across renders (such as `""` -> `""`).
|
||||
*/
|
||||
valueRevision?: number;
|
||||
onChange: (value: string) => void;
|
||||
onSend: (textOverride?: string) => void;
|
||||
onCompact?: () => void;
|
||||
@@ -309,7 +303,6 @@ interface ChatInputProps {
|
||||
|
||||
const ChatInput: React.FC<ChatInputProps> = ({
|
||||
value,
|
||||
valueRevision = 0,
|
||||
onChange,
|
||||
onSend,
|
||||
onCompact,
|
||||
@@ -555,18 +548,15 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
textareaRef.current?.value ?? composerTextRef.current
|
||||
), []);
|
||||
|
||||
const lastValueRevisionRef = useRef(valueRevision);
|
||||
useEffect(() => {
|
||||
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
|
||||
lastValueRevisionRef.current = valueRevision;
|
||||
if (!revisionChanged && value === pushedParentTextRef.current) return;
|
||||
if (value === pushedParentTextRef.current) return;
|
||||
pushedParentTextRef.current = value;
|
||||
composerTextRef.current = value;
|
||||
if (textareaRef.current && textareaRef.current.value !== value) {
|
||||
textareaRef.current.value = value;
|
||||
}
|
||||
syncHasComposerText(value);
|
||||
}, [syncHasComposerText, value, valueRevision]);
|
||||
}, [syncHasComposerText, value]);
|
||||
|
||||
const commitComposerText = useCallback((next: string) => {
|
||||
composerTextRef.current = next;
|
||||
@@ -1987,7 +1977,6 @@ function contextUsageEqual(
|
||||
function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boolean {
|
||||
return (
|
||||
prev.value === next.value
|
||||
&& prev.valueRevision === next.valueRevision
|
||||
&& prev.onChange === next.onChange
|
||||
&& prev.onSend === next.onSend
|
||||
&& prev.onCompact === next.onCompact
|
||||
|
||||
@@ -52,8 +52,6 @@ function baseProps() {
|
||||
onRebind: (_sessionId: string, _target: { type: string; targetId: string; hostIds?: string[] }) => {},
|
||||
onRename: undefined as ((_sessionId: string, _title: string) => void) | undefined,
|
||||
onDelete: (_sessionId: string) => {},
|
||||
onDeleteMany: undefined as ((_ids: string[]) => void) | undefined,
|
||||
onRegenerateTitle: undefined as ((_sessionId: string) => void) | undefined,
|
||||
onExport: (_sessionId: string) => {},
|
||||
};
|
||||
}
|
||||
@@ -544,185 +542,3 @@ test("clicking an active-elsewhere chat falls back to opening locally when focus
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("subtitle styling keeps agent label emphasized and message count normal when scopeLabel is empty", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
try {
|
||||
const props = baseProps();
|
||||
props.sessions = [
|
||||
makeSession({ id: "no-scope-label", title: "Orphan chat", scope: { type: "terminal", targetId: "t-gone" } }),
|
||||
];
|
||||
const renderer = await renderManager(dom, props);
|
||||
const row = rows(renderer)[0];
|
||||
const spans = Array.from(row.querySelectorAll("span")).filter((el) => !el.getAttribute("aria-hidden"));
|
||||
const agentSpan = spans.find((el) => el.textContent === "Catty Agent");
|
||||
const countSpan = spans.find((el) => (el.textContent ?? "").includes("1"));
|
||||
assert.ok(agentSpan?.className.includes("font-medium"));
|
||||
assert.ok(!agentSpan?.className.includes("truncate"));
|
||||
assert.ok(countSpan);
|
||||
assert.ok(!countSpan.className.includes("font-medium"));
|
||||
} finally {
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const restoreGlobals = installRadixGlobals(dom);
|
||||
try {
|
||||
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
|
||||
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
|
||||
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("../ui/tooltip.tsx");
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
|
||||
const props = baseProps();
|
||||
props.sessions = [
|
||||
makeSession({ id: "s-a", title: "A" }),
|
||||
makeSession({ id: "s-b", title: "B" }),
|
||||
];
|
||||
const deletedMany: string[][] = [];
|
||||
const regenerated: string[] = [];
|
||||
const activated: string[] = [];
|
||||
props.onDeleteMany = (ids) => deletedMany.push(ids);
|
||||
props.onRegenerateTitle = (id) => regenerated.push(id);
|
||||
props.onSelect = (id) => activated.push(id);
|
||||
|
||||
await renderer.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<SessionHistoryDrawer
|
||||
sessions={props.sessions}
|
||||
activeSessionId="s-a"
|
||||
onSelect={() => {}}
|
||||
onDelete={() => {}}
|
||||
onExportSessions={() => {}}
|
||||
onClose={() => {}}
|
||||
globalManager={<GlobalAIChatSessionManager {...props} />}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const openHeaderMenu = async () => {
|
||||
const trigger = renderer.container.querySelector<HTMLButtonElement>(
|
||||
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
|
||||
);
|
||||
assert.ok(trigger, "drawer overflow trigger present");
|
||||
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
};
|
||||
|
||||
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
|
||||
await openHeaderMenu();
|
||||
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
|
||||
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
|
||||
// Close header menu before switching tabs.
|
||||
await openHeaderMenu();
|
||||
|
||||
// Switch to the "All chats" tab.
|
||||
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
|
||||
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
|
||||
// Search/filter bar must not contain an inline selection toggle button.
|
||||
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
|
||||
assert.equal(
|
||||
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
|
||||
null,
|
||||
"no standalone selection button in filter bar",
|
||||
);
|
||||
|
||||
// Trigger selection mode from the drawer's top-right overflow menu.
|
||||
await openHeaderMenu();
|
||||
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
|
||||
assert.ok(selectItem, "Select chats menu item present on All chats tab");
|
||||
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.ok(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
"selection action bar opens",
|
||||
);
|
||||
|
||||
// Clicking Cancel exits selection mode cleanly.
|
||||
const cancelBtn = Array.from(
|
||||
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.trim() === t("common.cancel"));
|
||||
assert.ok(cancelBtn, "Cancel button present in selection bar");
|
||||
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.equal(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"Cancel exits selection mode",
|
||||
);
|
||||
|
||||
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
|
||||
await openHeaderMenu();
|
||||
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
assert.equal(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"Escape exits selection mode",
|
||||
);
|
||||
|
||||
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
|
||||
await openHeaderMenu();
|
||||
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.ok(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
"selection bar open before tab switch",
|
||||
);
|
||||
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
|
||||
assert.equal(
|
||||
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"switching away from All chats resets selection mode",
|
||||
);
|
||||
|
||||
await openHeaderMenu();
|
||||
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
|
||||
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
|
||||
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
assert.deepEqual(activated, []);
|
||||
|
||||
const bulkRegen = Array.from(
|
||||
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
|
||||
assert.ok(bulkRegen, "bulk regenerate button present");
|
||||
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
|
||||
|
||||
// Bulk delete is confirm-gated.
|
||||
const bulkDelete = Array.from(
|
||||
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.includes(t("common.delete")));
|
||||
assert.ok(bulkDelete, "bulk delete button present");
|
||||
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
|
||||
|
||||
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
|
||||
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
|
||||
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
|
||||
assert.equal(
|
||||
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"selection mode exits after confirmed bulk delete",
|
||||
);
|
||||
} finally {
|
||||
restoreGlobals();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Download, FolderInput, MoreHorizontal, Pencil, Search, Trash2, X } from 'lucide-react';
|
||||
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { cn } from '../../lib/utils';
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
} from '../ui/select';
|
||||
import { ConfirmDialog } from '../ui/confirm-dialog';
|
||||
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
|
||||
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
|
||||
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
|
||||
import {
|
||||
buildGlobalManagerRows,
|
||||
@@ -57,13 +56,7 @@ interface GlobalAIChatSessionManagerProps {
|
||||
onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void;
|
||||
onRename?: (sessionId: string, title: string) => void;
|
||||
onDelete: (sessionId: string) => void;
|
||||
onDeleteMany?: (sessionIds: string[]) => void;
|
||||
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
|
||||
onRegenerateTitle?: (sessionId: string) => void;
|
||||
onExport: (sessionId: string) => void;
|
||||
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
|
||||
selectionMode?: boolean;
|
||||
onSelectionModeChange?: (active: boolean) => void;
|
||||
}
|
||||
|
||||
const MANAGER_RENDER_BATCH = 80;
|
||||
@@ -85,44 +78,19 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
onRebind,
|
||||
onRename,
|
||||
onDelete,
|
||||
onDeleteMany,
|
||||
onRegenerateTitle,
|
||||
onExport,
|
||||
selectionMode: controlledSelectionMode,
|
||||
onSelectionModeChange,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const selectionContext = useContext(GlobalSessionSelectionContext);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [agentFilter, setAgentFilter] = useState<string>('all');
|
||||
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
|
||||
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
|
||||
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
|
||||
const [moveSession, setMoveSession] = useState<AISession | null>(null);
|
||||
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
const [renameDraft, setRenameDraft] = useState('');
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const selectionMode =
|
||||
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
|
||||
const setSelectionMode = useCallback(
|
||||
(active: boolean) => {
|
||||
if (controlledSelectionMode !== undefined) {
|
||||
onSelectionModeChange?.(active);
|
||||
} else if (selectionContext) {
|
||||
selectionContext.setSelectionMode(active);
|
||||
onSelectionModeChange?.(active);
|
||||
} else {
|
||||
setUncontrolledSelectionMode(active);
|
||||
onSelectionModeChange?.(active);
|
||||
}
|
||||
},
|
||||
[controlledSelectionMode, onSelectionModeChange, selectionContext],
|
||||
);
|
||||
|
||||
const rows = useMemo(
|
||||
() => buildGlobalManagerRows({
|
||||
sessions,
|
||||
@@ -161,26 +129,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
if (renamingSessionId) renameInputRef.current?.focus();
|
||||
}, [renamingSessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode) {
|
||||
setSelectedIds(new Set());
|
||||
setBulkDeleteConfirmOpen(false);
|
||||
}
|
||||
}, [selectionMode]);
|
||||
|
||||
const rowSessionIds = useMemo(
|
||||
() => new Set(rows.map((row) => row.session.id)),
|
||||
[rows],
|
||||
);
|
||||
const activeSelectedIds = useMemo(() => {
|
||||
if (selectedIds.size === 0) return selectedIds;
|
||||
const next = new Set<string>();
|
||||
selectedIds.forEach((id) => {
|
||||
if (rowSessionIds.has(id)) next.add(id);
|
||||
});
|
||||
return next;
|
||||
}, [selectedIds, rowSessionIds]);
|
||||
|
||||
const displayedRows = filteredRows.slice(0, renderCount);
|
||||
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
|
||||
|
||||
@@ -204,50 +152,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
setRenameDraft('');
|
||||
};
|
||||
|
||||
const toggleSelected = (sessionId: string) => {
|
||||
setSelectedIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(sessionId)) next.delete(sessionId); else next.add(sessionId);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
const exitSelectionMode = useCallback(() => {
|
||||
setSelectionMode(false);
|
||||
setSelectedIds(new Set());
|
||||
setBulkDeleteConfirmOpen(false);
|
||||
}, [setSelectionMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
exitSelectionMode();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
const visibleIds = displayedRows.map((row) => row.session.id);
|
||||
setSelectedIds((prev) => {
|
||||
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => prev.has(id));
|
||||
return allSelected ? new Set() : new Set(visibleIds);
|
||||
});
|
||||
};
|
||||
const commitBulkDelete = () => {
|
||||
if (activeSelectedIds.size === 0) return;
|
||||
const ids = [...activeSelectedIds];
|
||||
if (onDeleteMany) onDeleteMany(ids);
|
||||
else ids.forEach((id) => onDelete(id));
|
||||
exitSelectionMode();
|
||||
};
|
||||
const commitBulkRegenerate = () => {
|
||||
if (!onRegenerateTitle || activeSelectedIds.size === 0) return;
|
||||
activeSelectedIds.forEach((id) => onRegenerateTitle(id));
|
||||
};
|
||||
|
||||
const getOtherMoveTargets = (session: AISession) =>
|
||||
rebindTargets.filter(
|
||||
(target) =>
|
||||
@@ -332,54 +236,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
{selectionMode && (
|
||||
<div
|
||||
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
|
||||
data-section="ai-global-session-selection-bar"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSelectAll}
|
||||
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
|
||||
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
|
||||
{t('ai.chat.managerSelectAll')}
|
||||
</button>
|
||||
<span className="text-muted-foreground/60 whitespace-nowrap">
|
||||
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{onRegenerateTitle && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={activeSelectedIds.size === 0}
|
||||
onClick={commitBulkRegenerate}
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
{t('ai.chat.managerRegenerateTitle')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={activeSelectedIds.size === 0}
|
||||
onClick={() => setBulkDeleteConfirmOpen(true)}
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={exitSelectionMode}
|
||||
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="px-3">
|
||||
{filteredRows.length === 0 ? (
|
||||
@@ -404,43 +260,28 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
const canMoveElsewhere = otherMoveTargets.length > 0;
|
||||
const isRenaming = renamingSessionId === row.session.id;
|
||||
const isMenuOpen = openMenuSessionId === row.session.id;
|
||||
const subtitleParts: Array<{ text: string; bold: boolean; truncate: boolean }> = [];
|
||||
if (row.scopeLabel) {
|
||||
subtitleParts.push({ text: row.scopeLabel, bold: true, truncate: true });
|
||||
}
|
||||
subtitleParts.push({ text: row.agentLabel, bold: true, truncate: false });
|
||||
const subtitleParts: string[] = [];
|
||||
if (row.scopeLabel) subtitleParts.push(row.scopeLabel);
|
||||
if (showAgentMeta) subtitleParts.push(row.agentLabel);
|
||||
if (row.messageCount > 0) {
|
||||
subtitleParts.push({
|
||||
text: t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
|
||||
bold: false,
|
||||
truncate: false,
|
||||
});
|
||||
subtitleParts.push(
|
||||
t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount)),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<React.Fragment key={row.session.id}>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={selectionMode || row.canActivate ? 0 : -1}
|
||||
tabIndex={row.canActivate ? 0 : -1}
|
||||
onClick={() => {
|
||||
if (selectionMode) {
|
||||
toggleSelected(row.session.id);
|
||||
return;
|
||||
}
|
||||
if (!isRenaming && row.canActivate) activateRow(row);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.target !== e.currentTarget) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
if (selectionMode) {
|
||||
e.preventDefault();
|
||||
toggleSelected(row.session.id);
|
||||
return;
|
||||
}
|
||||
if (!isRenaming && row.canActivate) {
|
||||
e.preventDefault();
|
||||
activateRow(row);
|
||||
}
|
||||
if (!isRenaming && row.canActivate && (e.key === 'Enter' || e.key === ' ')) {
|
||||
e.preventDefault();
|
||||
activateRow(row);
|
||||
}
|
||||
}}
|
||||
className={cn(
|
||||
@@ -448,91 +289,69 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
row.isCurrentActive
|
||||
? 'text-foreground'
|
||||
: 'text-foreground/75 hover:text-foreground',
|
||||
!selectionMode && !row.canActivate && 'cursor-default',
|
||||
!row.canActivate && 'cursor-default',
|
||||
)}
|
||||
data-session-id={row.session.id}
|
||||
data-scope-state={row.scopeState}
|
||||
>
|
||||
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
|
||||
{selectionMode && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('ai.chat.managerSelectRow')}
|
||||
aria-pressed={activeSelectedIds.has(row.session.id)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleSelected(row.session.id);
|
||||
}}
|
||||
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
|
||||
>
|
||||
{activeSelectedIds.has(row.session.id)
|
||||
? <CheckSquare size={14} className="text-primary" />
|
||||
: <Square size={14} />}
|
||||
</button>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{row.isCurrentActive && (
|
||||
<span
|
||||
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
|
||||
aria-hidden
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{row.isCurrentActive && (
|
||||
<span
|
||||
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
|
||||
{isRenaming ? (
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
type="text"
|
||||
value={renameDraft}
|
||||
aria-label={t('ai.chat.renameChat')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
className="h-6 text-[12px]"
|
||||
/>
|
||||
) : (
|
||||
row.title
|
||||
)}
|
||||
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
|
||||
{isRenaming ? (
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
type="text"
|
||||
value={renameDraft}
|
||||
aria-label={t('ai.chat.renameChat')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
className="h-6 text-[12px]"
|
||||
/>
|
||||
) : (
|
||||
row.title
|
||||
)}
|
||||
</span>
|
||||
{row.isActiveElsewhere && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
|
||||
{t('ai.chat.managerBadgeActive')}
|
||||
</span>
|
||||
{row.isActiveElsewhere && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
|
||||
{t('ai.chat.managerBadgeActive')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{subtitleParts.length > 0 && (
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
|
||||
{subtitleParts.map((part, index) => (
|
||||
<React.Fragment key={`${row.session.id}-meta-${index}`}>
|
||||
{index > 0 && <span aria-hidden>·</span>}
|
||||
<span className={cn(
|
||||
part.truncate ? 'truncate' : 'shrink-0',
|
||||
part.bold && 'font-medium',
|
||||
)}>
|
||||
{part.text}
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{subtitleParts.length > 0 && (
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/50 min-w-0">
|
||||
{subtitleParts.map((part, index) => (
|
||||
<React.Fragment key={`${row.session.id}-meta-${index}`}>
|
||||
{index > 0 && <span aria-hidden>·</span>}
|
||||
<span className={index === 0 ? 'truncate' : 'shrink-0'}>
|
||||
{part}
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
|
||||
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
|
||||
{formatRelativeTime(new Date(row.session.updatedAt), t)}
|
||||
</span>
|
||||
{!selectionMode && (
|
||||
<Dropdown
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
|
||||
@@ -568,20 +387,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
<span>{t('ai.chat.renameChat')}</span>
|
||||
</button>
|
||||
)}
|
||||
{onRegenerateTitle && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setOpenMenuSessionId(null);
|
||||
onRegenerateTitle(row.session.id);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<RefreshCw size={12} className="shrink-0 text-muted-foreground" />
|
||||
<span>{t('ai.chat.managerRegenerateTitle')}</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
@@ -625,7 +430,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
</button>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{moveSession?.id === row.session.id && (
|
||||
@@ -686,17 +490,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
}}
|
||||
onConfirm={commitDelete}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
|
||||
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
|
||||
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
|
||||
confirmLabel={t('common.delete')}
|
||||
destructive
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setBulkDeleteConfirmOpen(false);
|
||||
}}
|
||||
onConfirm={commitBulkDelete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -96,39 +96,6 @@ test("global rows cover every scope: live terminal, other terminal, workspace, c
|
||||
assert.equal(byId.get("s-global")!.scopeLabel, t("ai.chat.chatsScopeGlobal"));
|
||||
});
|
||||
|
||||
test("workspace name snapshot is the fallback for a dangling workspace, but live title wins", () => {
|
||||
const input = {
|
||||
...baseInput(),
|
||||
hosts: [{ id: "h-old", label: "old-host", hostname: "10.0.0.5" }],
|
||||
};
|
||||
input.sessions = [
|
||||
// Workspace gone: the captured name wins over the host fallback.
|
||||
baseSession({
|
||||
id: "s-snap",
|
||||
scope: { type: "workspace", targetId: "w-gone", hostIds: ["h-old"] },
|
||||
workspaceNameSnapshot: "Prod (old)",
|
||||
}),
|
||||
// Workspace still live: the live title wins even if a stale snapshot exists.
|
||||
baseSession({
|
||||
id: "s-live",
|
||||
scope: { type: "workspace", targetId: "w-1" },
|
||||
workspaceNameSnapshot: "Stale name",
|
||||
}),
|
||||
// Dangling flag with a live workspace present still falls back to the snapshot.
|
||||
baseSession({
|
||||
id: "s-flagged",
|
||||
scope: { type: "workspace", targetId: "w-1" },
|
||||
scopeDangling: true,
|
||||
workspaceNameSnapshot: "Prod (archived)",
|
||||
}),
|
||||
];
|
||||
const byId = new Map(buildGlobalManagerRows(input).map((row) => [row.session.id, row]));
|
||||
assert.equal(byId.get("s-snap")!.scopeLabel, "Prod (old)");
|
||||
assert.equal(byId.get("s-snap")!.scopeState, "dangling");
|
||||
assert.equal(byId.get("s-live")!.scopeLabel, "Prod");
|
||||
assert.equal(byId.get("s-flagged")!.scopeLabel, "Prod (archived)");
|
||||
});
|
||||
|
||||
test("active marker distinguishes current panel active chat vs active elsewhere", () => {
|
||||
const input = baseInput();
|
||||
input.sessions = [
|
||||
|
||||
@@ -165,14 +165,10 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
|
||||
if (session.scope.type === 'workspace') {
|
||||
const title = workspaceTitles.get(session.scope.targetId ?? '');
|
||||
if (title != null && !session.scopeDangling) {
|
||||
// Live title wins so a rename is reflected immediately.
|
||||
scopeLabel = title;
|
||||
isDangling = false;
|
||||
} else {
|
||||
// Workspace is gone/dangling: prefer the name captured at bind time,
|
||||
// then fall back to the historical host labels.
|
||||
scopeLabel = session.workspaceNameSnapshot
|
||||
|| resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
|
||||
scopeLabel = resolveHistoricalHostLabel(session.scope.hostIds, hostNamesById);
|
||||
isDangling = true;
|
||||
}
|
||||
} else if (session.scope.type === 'terminal') {
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export interface GlobalSessionSelectionContextValue {
|
||||
selectionMode: boolean;
|
||||
setSelectionMode: (active: boolean) => void;
|
||||
}
|
||||
|
||||
export const GlobalSessionSelectionContext =
|
||||
createContext<GlobalSessionSelectionContextValue | null>(null);
|
||||
@@ -345,14 +345,6 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
|
||||
notes: String(backup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(backup.preview.aiSessionCount ?? 0),
|
||||
settings: String(backup.preview.settingCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
{restoreAllowed && (
|
||||
<Button
|
||||
@@ -451,14 +443,6 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
|
||||
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
|
||||
<div className="text-muted-foreground mt-0.5">
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
|
||||
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
|
||||
@@ -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 = directProxy ? undefined : (selectedProfile?.config ?? proxyConfig);
|
||||
const effectiveProxyConfig = 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 (!directProxy && (hasInvalidManualProxyPort || hasInvalidIdentity)) return;
|
||||
if (hasInvalidManualProxyPort || hasInvalidIdentity) return;
|
||||
onBack();
|
||||
}, [directProxy, hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
|
||||
}, [hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
|
||||
|
||||
return (
|
||||
<AsidePanel
|
||||
@@ -153,7 +153,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
|
||||
{t('hostDetails.proxyPanel.missingSaved')}
|
||||
</div>
|
||||
)}
|
||||
{isUsingProfile && selectedProfile && (
|
||||
{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>
|
||||
)}
|
||||
{isUsingProfile && selectedProfile && hasMissingIdentity && (
|
||||
{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>
|
||||
)}
|
||||
{isUsingProfile && selectedProfile && hasIncompleteIdentity && (
|
||||
{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>
|
||||
)}
|
||||
{isUsingProfile && selectedProfile && hasUnreadableIdentity && (
|
||||
{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>
|
||||
|
||||
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user