diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 374a16279..86456d833 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -44,7 +44,7 @@ jobs: - name: Verify generated Catty tool specs run: | npm run generate:capability-tools - git diff --exit-code infrastructure/ai/harness/generated/cattyToolSpecs.json + git diff --exit-code infrastructure/ai/harness/generated/cattyToolSpecs.json infrastructure/ai/harness/generated/globalAgentToolSpecs.json - name: Verify Codex App Server schema run: npm run check:codex-app-server-schema @@ -54,7 +54,6 @@ jobs: npm run check:plugin-contract npm run test:plugin-runtime npm run test:plugin-examples - node --test --import tsx components/settings/tabs/Plugin*.test.tsx - name: Test run: npm test diff --git a/.gitignore b/.gitignore index 09d013c17..00196c568 100755 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,6 @@ !CODE_OF_CONDUCT.md !CODE_SIGNING_POLICY.md !CONTRIBUTING.md -!ET_INTEGRATION_CHECKLIST.md !LICENSE !PRIVACY.md !README.ja-JP.md @@ -38,7 +37,6 @@ !index.css !index.html !index.tsx -!metadata.json !package-lock.json !package.json !tsconfig.json diff --git a/CLAUDE.md b/CLAUDE.md index bc23d850b..ba8bad7b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,7 @@ Netcatty is an Electron + React desktop app (SSH manager, terminal, SFTP browser ### Electron Main Process (`electron/`) - **`main.cjs`** — entry point; wires crash logging, process error guards, and delegates to `main/registerBridges.cjs` - **`bridges/`** — one `.cjs` file per capability domain (sshBridge, sftpBridge, terminalBridge, portForwardingBridge, aiBridge, etc.). Each bridge exposes IPC handlers via `ipcMain`. Tests live alongside the bridge file (`*.test.cjs`). -- **`preload.cjs`** — exposes a typed `window.electron` API to the renderer via `contextBridge`. Uses `preload/api.cjs` for the generated API surface. +- **`preload.cjs`** — exposes a typed `window.netcatty` API to the renderer via `contextBridge`. Uses `preload/api.cjs` for the generated API surface. - **`cli/`** — `netcatty-tool-cli.cjs` is a separate internal binary for tool/MCP integration; treat as internal surface only. ### Renderer Process (React + Vite) @@ -52,7 +52,7 @@ Three-layer architecture (see `AGENTS.md` for full detail): - **`components/`** — presentation only. `App.tsx` wires hooks to components; no business logic in components. ### IPC Pattern -UI calls `window.electron.*` (preload API) → IPC → bridge handler in main process. Never call `ipcRenderer` directly from components. +UI calls `window.netcatty.*` (via `infrastructure/services/netcattyBridge.ts`) → IPC → bridge handler in main process. Never call `ipcRenderer` directly from components. ### Key Conventions - All storage reads/writes go through `localStorageAdapter`; storage keys are in `infrastructure/config/storageKeys.ts`. diff --git a/ET_INTEGRATION_CHECKLIST.md b/ET_INTEGRATION_CHECKLIST.md deleted file mode 100644 index 3a8bcda34..000000000 --- a/ET_INTEGRATION_CHECKLIST.md +++ /dev/null @@ -1,219 +0,0 @@ -# EternalTerminal (ET) 集成清单 — 按 Mosh 方式重做 - -> 目标:在上游最新架构(分支 `feat/et-history-reapply`,基于 `031bf0ee`)上, -> **完全照搬 Mosh 的方式**重新集成 EternalTerminal: -> 1. **打包客户端** —— 像 `mosh-client` 那样,把 `et` 客户端二进制构建 + 下载 + -> 捆绑进安装包,运行时只用捆绑的二进制(不依赖系统安装的 et)。 -> 2. **接入协议** —— 把旧分支 `feat/eternal-terminal`(tip `67e81616`)里的 ET -> 后端 + UI 重新落到上游重构后的目录结构上,并让它启动**捆绑的** `et`。 -> -> 旧实现参考:`git show 67e81616`(共 7 个 ET 提交,见 `feat/eternal-terminal`)。 -> Mosh 模板参考(**仅 MoshCatty 纯二进制路径**):`resources/mosh/README.md`、 -> `scripts/fetch-mosh-binaries.cjs`、`scripts/resolve-mosh-bin-release.cjs`、 -> `scripts/mosh-extra-resources.cjs`、`electron/bridges/terminalBridge/moshSession.cjs`。 -> 客户端本体在独立仓库 [binaricat/MoshCatty](https://github.com/binaricat/MoshCatty) -> (`moshcatty-*` releases);Netcatty 内已无 Cygwin 构建流水线 / FluentTerminal 回退。 - -## 关键设计差异(ET vs Mosh) - -- **协议**:Mosh 需要 Node 做 SSH bootstrap + 抓 `MOSH CONNECT` + 换 PTY - (`moshHandshake` + `moshSession`)。**ET 不需要** —— `et` 客户端自己完成 SSH - 引导 + 协议握手,我们只要把 `et` 当作普通 PTY 进程 `pty.spawn` 即可。所以**没有** - `etHandshake.cjs`。 -- **凭证注入**:Mosh 自己驱动 ssh、直接往 PTY 里敲密码;ET 内部驱动 ssh,需用 - **SSH_ASKPASS + 临时 ~/.ssh 环境**把保存的密码/密钥/跳板/算法喂给 et 内部的 ssh - (旧实现 `prepareEtSshEnvironment` 已完整实现,直接搬运)。 -- **纯二进制**:MoshCatty 与理想 ET 打包都是「每平台一个客户端文件」。Mosh 侧已 - 无 terminfo / Cygwin DLL 袋;`et` 同样本地不渲染终端。Windows 若动态链 CRT - 才考虑可选 DLL 目录,否则只放 `et[.exe]`。 -- **构建系统**:Mosh 客户端在 **MoshCatty** 仓库用 Rust 构建并发布;Netcatty 只 - `fetch`。**ET** 用 CMake + Ninja + vcpkg - (`cmake -DDISABLE_TELEMETRY=ON -GNinja -DCMAKE_BUILD_TYPE=RelWithDebInfo`), - 产物是单个 `et`(Windows `et.exe`),由 `scripts/build-et/` + `build-et-binaries.yml` 发布。 - -## 命名约定(镜像 Mosh / MoshCatty) - -| Mosh (MoshCatty) | ET | -|------|----| -| `resources/mosh//mosh-client[.exe]` | `resources/et//et[.exe]` | -| 打包后 `/mosh/mosh-client` | 打包后 `/et/et` | -| 上游构建:`binaricat/MoshCatty` CI releases | `scripts/build-et/` + `build-et-binaries.yml` | -| `scripts/fetch-mosh-binaries.cjs` | `scripts/fetch-et-binaries.cjs` | -| `scripts/resolve-mosh-bin-release.cjs` | `scripts/resolve-et-bin-release.cjs` | -| `scripts/mosh-extra-resources.cjs` | `scripts/et-extra-resources.cjs` | -| env `MOSH_BIN_RELEASE` / 仓库 `MoshCatty` / tag `moshcatty-*` | env `ET_BIN_RELEASE` / 仓库 `Netcatty-et-bin` / tag `et-bin-*` | -| `npm run fetch:mosh[:dev]` | `npm run fetch:et[:dev]` | -| `bundledMoshClient()` / `resolveBareMoshClient()` | `bundledEtClient()` / `resolveBareEtClient()` | - ---- - -## Phase 1 — 打包基础设施(构建/下载/捆绑) - -- [x] **1.1** `resources/et/README.md` —— 镜像 `resources/mosh/README.md`:说明 - 二进制来源、`Netcatty-et-bin` 发布仓库、`et-bin-*` tag、许可证(ET 为 - Apache-2.0,与 GPL-3.0 兼容)、可复现构建命令。 -- [x] **1.2** `.gitignore` —— 追加 ET 段(镜像 mosh 段): - `/resources/et/*/et`、`/resources/et/*/et.exe`、`/resources/et/*/*.dll`、 - `/resources/et/*/et-win32-*-dlls/`。保留 `resources/et/README.md`。 -- [x] **1.3** `scripts/build-et/build-linux.sh` —— manylinux2014 + vcpkg 静态三元组 - 构建 `et`(x64/arm64),产物 `et-linux-.tar.gz`(+.sha256),内含单个 `et`。 - 校验非系统动态库(ldd 白名单)。 -- [x] **1.4** `scripts/build-et/build-macos.sh` —— arm64 + x86_64 分别构建后 `lipo` - 成 universal,`MACOSX_DEPLOYMENT_TARGET=11.0`,产物 `et-darwin-universal.tar.gz`。 -- [x] **1.5** `scripts/build-et/build-windows.ps1`(或 `.sh`)—— MSVC + vcpkg - `x64-windows-static`,产物 `et-win32-x64.tar.gz`(含 `et.exe`;若动态链接 CRT - 则随附 DLL 目录 `et-win32-x64-dlls/`,否则纯静态无 DLL)。 -- [x] **1.6** `scripts/et-extra-resources.cjs` —— 镜像 `mosh-extra-resources.cjs`: - 按平台/arch 仅当 `resources/et//et[.exe]` 存在时才产出 extraResources - 指令(`to: "et/"`);Windows 额外处理可选 DLL 目录。纯客户端文件为主。 -- [x] **1.7** `scripts/resolve-et-bin-release.cjs` —— 镜像 `resolve-mosh-bin-release.cjs`: - `TAG_RE=/^et-bin-.../`,默认仓库 `Netcatty-et-bin`,env `ET_BIN_RELEASE` 优先。 -- [x] **1.8** `scripts/fetch-et-binaries.cjs` —— 镜像 `fetch-mosh-binaries.cjs`: - `TARGETS` 四项(linux-x64/arm64、darwin-universal、win32-x64),全部 tar.gz; - SHA256SUMS 校验;解包到 `resources/et//`。**Windows 用自建产物**。 -- [x] **1.9** 单元测试:`scripts/fetch-et-binaries.test.cjs`、 - `scripts/resolve-et-bin-release.test.cjs`、`scripts/et-extra-resources.test.cjs` - (镜像对应 mosh 测试,改名/改路径)。 -- [x] **1.10** `package.json` scripts:新增 - `"fetch:et": "node scripts/fetch-et-binaries.cjs"`、 - `"fetch:et:dev": "node scripts/fetch-et-binaries.cjs --host --resolve-release"`; - 把 `dev` 脚本改成先 `fetch:mosh:dev && fetch:et:dev`;`test` glob 已覆盖 - `scripts/*.test.cjs`(确认即可)。 -- [x] **1.11** `electron-builder.config.cjs`:引入 `etExtraResources`,在 darwin/win32/ - linux 三处把 `etExtraResources(plat)` 合并进 `extraResources`(与 mosh 数组拼接)。 -- [x] **1.12** `.github/workflows/build-et-binaries.yml` —— 四个构建 job + 一个 - `release` job(dispatch 且 `release_tag` 非空时发布到 `Netcatty-et-bin`,附 - `SHA256SUMS`)。`paths` 过滤指向 `scripts/build-et/**`、`scripts/fetch-et-binaries.cjs`、 - `scripts/et-extra-resources.cjs`。env 用 `ET_REF`(默认 ET release tag,如 `et-v6.2.x`)。 - > 注:实际二进制由用户手动 `workflow_dispatch` 触发产出;本地/CI 未设 - > `ET_BIN_RELEASE` 时 fetch 步骤安静跳过(同 mosh 的 `MOSH_BIN_RELEASE`)。 - -## Phase 2 — 运行时定位捆绑客户端 - -- [x] **2.1** `electron/bridges/terminalBridge.cjs` 新增 `bundledEtClient(opts)` - —— 镜像 `bundledMoshClient`:打包路径 `/et/et[.exe]`;dev 回退 - `/resources/et//et[.exe]`;导出到 module.exports。 - -## Phase 3 — ET 协议后端(搬运旧实现到新架构) - -- [x] **3.1** 新建 `electron/bridges/terminalBridge/etSession.cjs` —— 用上游 - `moshSession.cjs` 的 `createXxxSessionApi(ctx)` + `with(ctx)` 工厂模式,封装: - `ET_ASKPASS_SCRIPT`、`writeSecureFile`、`prepareEtSshEnvironment`、 - `createEtAskpassArtifacts`、`cleanupStaleEtTempDirs`、 - `cleanupSessionExternalAuthArtifacts`、`execOnEtSession`、`startEtSession`。 - **改动点**:`etCmd` 由 `findExecutable('et')` 改为 `resolveBareEtClient()` - (取捆绑二进制);找不到时抛错(同 mosh:提示跑 `npm run fetch:et:dev`)。 - Windows 若有动态链接 DLL 目录,可把该目录加进 PATH(MoshCatty 路径已无此需求)。 -- [x] **3.2** `terminalBridge.cjs` 接线 `createEtSessionApi(ctx)`(镜像 moshSessionApi - 的 ctx),传入 `bundledEtClient`、`tempDirBridge`、`execFile/execFileSync` 等; - 解构出 `startEtSession`、`execOnEtSession`、`cleanupStaleEtTempDirs`、 - `cleanupSessionExternalAuthArtifacts`、`resolveBareEtClient`。 -- [x] **3.3** `init()` 调 `cleanupStaleEtTempDirs()`;`registerHandlers` 加 - `ipcMain.handle("netcatty:et:start", startEtSession)`;`closeSession` 与 - `cleanupAllSessions` 调 `cleanupSessionExternalAuthArtifacts(session)`; - `module.exports` 导出 `startEtSession`、`execOnEtSession`、`bundledEtClient`。 -- [x] **3.4** 测试:`terminalBridge.bundledEt.test.cjs`(路径解析)+ - `terminalBridge/etSession.test.cjs`(prepareEtSshEnvironment 的端口/密钥/ - askpass/跳板/legacy 算法分支)。可参考旧分支是否已有 ET 测试并搬运。 - -## Phase 4 — domain / 类型 / preload 接口面 - -- [x] **4.1** `domain/models.ts`:`HostProtocol` 加 `'et'`;`ProtocolConfig.etPort?`; - `Host`/`GroupConfig` 加 `etEnabled?`/`etPort?`/`etTerminalPath?`; - `TerminalSession.etEnabled?`;`ConnectionLog.protocol` 加 `'et'`。 - (照搬 `git show 794eecdf -- domain/models.ts`) -- [x] **4.2** `domain/groupConfig.ts`:加 `etEnabled` 默认项(照搬旧 diff)。 -- [x] **4.3** `global.d.ts`:`NetcattyBridge` 加 `startEtSession?(options): Promise<...>` - 及相关 options 类型(照搬 `git show 794eecdf -- global.d.ts`,并补齐后续 ET 提交 - 新增的 etPort/terminalPath/jumpHosts/legacyAlgorithms 字段)。 -- [x] **4.4** `electron/preload/api.cjs`:加 `startEtSession`(镜像第 26 行的 - `startMoshSession`)→ `ipcRenderer.invoke("netcatty:et:start", options)`。 - **注意**:上游已把 preload 重构成 `createPreloadApi`,落点在 `preload/api.cjs`, - 不是旧的 `preload.cjs` 内联对象。 - -## Phase 5 — 渲染层 + UI + i18n - -- [x] **5.1** `application/state/useTerminalBackend.ts`:加 `etAvailable`(查 - `bridge?.startEtSession`)+ `startEtSession`,并在返回对象/依赖数组里登记 - (镜像 mosh 的第 10/42/198/205 行处)。 -- [x] **5.2** `application/state/useSessionState.ts`:路由 ET 会话(照搬旧 diff,+6 行)。 -- [x] **5.3** `components/terminal/runtime/createTerminalSessionStarters.ts`:加 - `startEt(term)`(镜像 `startMosh`,组装 options:etPort/terminalPath/ - jumpHosts/legacyAlgorithms/凭证/identityFilePaths)。 - **注意**:上游把它从旧的 `infrastructure/runtime/` 移到了 - `components/terminal/runtime/` —— 落点以上游为准。 -- [x] **5.4** UI 组件(照搬 `git show b1a306f8 6c0d5bf3 55caa268` 的相应文件, - 映射到上游同名组件): - - [ ] `components/ProtocolSelectDialog.tsx` —— 新增 ET 选项 - - [ ] `components/QuickConnectWizard.tsx` - - [ ] `components/HostDetailsPanel.tsx` —— ET 设置(启用、ET 端口、etterminal 路径) - - [ ] `components/GroupDetailsPanel.tsx` - - [ ] `components/VaultView.tsx` - - [ ] `components/Terminal.tsx` / `components/TerminalLayer.tsx` - - [ ] `components/terminal/TerminalConnectionDialog.tsx` / `TerminalToolbar.tsx` - - [ ] `App.tsx` -- [x] **5.5** i18n:`application/i18n/locales/en.ts` 与 `zh-CN.ts` 加 ET 文案 - (照搬旧 diff,键名对齐上游现有 mosh 文案结构)。 - -## Phase 6 — 校验 - -- [x] **6.1** `npm run lint`(确保新 .cjs 在 scripts/ 下不受 ESLint 限制, - 或按需加 eslint-disable,与 mosh 脚本一致)。 -- [x] **6.2** `npm test`(新增的 fetch/resolve/extra-resources/etSession 测试全绿)。 -- [x] **6.3** `npm run build`(渲染层 TS 编译通过,无类型错误)。 -- [ ] **6.4** 手动冒烟(需先有发布的二进制): - `ET_BIN_RELEASE=et-bin-... npm run fetch:et` → `npm run start` → - 新建 ET 会话连一台装了 etserver 的主机,验证连接/输入/退出/凭证注入。 - ---- - -## 进度记录 - -- 状态:**Phase 1–5 已完成并通过校验**(仅余 1 个可选项 + CI 产二进制) -- 验证结果: - - `npx eslint <所有改动文件>` → 干净(0 错 0 警) - - `npx tsc --noEmit` → 我的改动 **0 个新增类型错误** - (`TerminalConnectionDialog` 里 `case 'mosh'` 的 TS2678 是既有问题,行号因我插入 ET 早返回从 60→64,非新增) - - `node --test`(ET 相关)→ etSession/bundledEt/3 个脚本测试 **全绿** - - `npm test` → 1383 通过 / 16 失败,**16 个全是既有的 Windows 环境失败** - (mosh 打包测试的 GNU-tar `C:` 问题、`isExecutableFile` 无 x 位、ACP execPath、SKILL.md 权限、Comware DH 等;均在我未改动的文件里) - - `npm run build`(Vite)→ **构建成功**(8.55s),渲染层打包通过 - -### 已完成 -- **Phase 1**:`scripts/et-extra-resources.cjs` / `resolve-et-bin-release.cjs` / - `fetch-et-binaries.cjs`(+3 测试,27 通过)、`scripts/build-et/{build-linux.sh, - build-macos.sh,build-windows.ps1}`、`.github/workflows/build-et-binaries.yml`、 - `resources/et/README.md`、`.gitignore`、`package.json`、`electron-builder.config.cjs`。 -- **Phase 2**:`terminalBridge.cjs` 新增并导出 `bundledEtClient`。 -- **Phase 3**:`terminalBridge/etSession.cjs`(startEtSession + prepareEtSshEnvironment + - SSH_ASKPASS 机制 + execOnEtSession + 清理),接线进 terminalBridge.cjs(ctx/IPC - `netcatty:et:start`/init 清理/close/quit 清理/导出),+2 测试(13 通过)。 - **et 指向捆绑二进制**(resolveBareEtClient→bundledEtClient),找不到则报错。 -- **Phase 4**:domain `connection.ts`/`history.ts`/`terminal.ts`、`groupConfig.ts`、 - `types/global/netcatty-bridge-session.d.ts`(startEtSession + NetcattyJumpHost[])、 - `electron/preload/api.cjs`、`domain/vaultImport.ts`(排除 'et' 导入协议)。 -- **Phase 5**: - - 启动派发:`useTerminalEffects.ts`、`Terminal.tsx`(×3) → `startEt` - - 运行时 starter:`createTerminalSessionStarters.ts` 新增 `startEt`(含单跳板/凭证/ - legacy 算法/askpass 路径),`.types.ts` 加 `etAvailable`/`startEtSession` - - 后端 hook:`useTerminalBackend.ts`(etAvailable + startEtSession) - - 会话透传 etEnabled:`sessionFactories.ts`、`useSessionState.ts`(×6)、 - `TerminalLayer.tsx`(×3)、`TerminalLayerSupport.tsx`、`AppHandlers.ts`(协议解析/日志/选择) - - UI:`HostDetailsAdvancedSections.tsx`(ET 开关+端口+etterminal 路径,与 Mosh 互斥)、 - `HostDetailsPanel.tsx`、`ProtocolSelectDialog.tsx`(ET 选项)、 - `TerminalConnectionDialog.tsx`(ET 标签)、`TerminalToolbar.tsx`(编码菜单门控)、 - `GroupSshSettingsSection.tsx` + `GroupDetailsPanel.tsx`(组级 ET)、`VaultView.tsx` - - i18n:en/zh-CN 的 `hostDetails.section.et`、`hostDetails.et.*`、 - `terminal.connection.protocol.et`、`terminal.et.*` - -### 剩余(可选 / 非阻塞) -- [ ] **QuickConnectWizard.tsx**:把 ET 加为“快速连接”协议按钮(type/端口/建主机映射 + - UI 按钮)。当前快速连接未列 ET;保存主机后开启 ET 再连即可,故仅为便利项。 -- [ ] **产出二进制**:手动 `workflow_dispatch` 跑 `build-et-binaries.yml`(带 - `release_tag=et-bin--1`)发布到 `Netcatty-et-bin`,并配 `ET_BIN_RELEASE_TOKEN` - secret。之后 `ET_BIN_RELEASE=... npm run fetch:et` 即可本地/打包捆绑 `et`。 - build-et 脚本本机无法编译 C++,需在 CI 验证。 -- [ ] **端到端冒烟**:有二进制后 `npm run dev`,对装有 etserver 的主机建 ET 会话验证。 - -- 当前分支:`feat/et-history-reapply`(基于上游 `031bf0ee`) -- 旧 ET 实现参考分支:`feat/eternal-terminal`(tip `67e81616`,7 个 ET 提交) diff --git a/application/app/AppFollowTerminalTheme.test.ts b/application/app/AppFollowTerminalTheme.test.ts deleted file mode 100644 index 70ef941da..000000000 --- a/application/app/AppFollowTerminalTheme.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const appSideEffectsSource = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8"); -const terminalHostSource = readFileSync(new URL("./hosts/TerminalHost.tsx", import.meta.url), "utf8"); -const appViewSource = readFileSync(new URL("./AppView.tsx", import.meta.url), "utf8"); -const runtimeSource = readFileSync(new URL("../state/useThemeRuntime.ts", import.meta.url), "utf8"); -const settingsSource = readFileSync(new URL("../state/useSettingsState.ts", import.meta.url), "utf8"); - -test("follow-app terminal theme selection updates the matching UI theme via ThemeRuntime", () => { - assert.match(runtimeSource, /getFollowAppTerminalThemeSelectionUpdate\(themeId\)/); - assert.match(runtimeSource, /setDarkUiThemeId\(update\.uiThemeId\)/); - assert.match(runtimeSource, /setLightUiThemeId\(update\.uiThemeId\)/); - assert.match(runtimeSource, /setTheme\(update\.appTheme\)/); - assert.doesNotMatch(runtimeSource, /isFollowAppIntentSettled\(userIntent\.themeId/); - assert.match(terminalHostSource, /useThemeRuntime\(/); - assert.match(terminalHostSource, /pickTerminalTheme\(themeId\)/); - assert.match(terminalHostSource, /pickTheme: pickTerminalTheme/); - // Theme members are listed field-by-field on the TerminalHost bag (not themeRuntime bag). - assert.match(terminalHostSource, /clearThemeIntent,/); - assert.match(terminalHostSource, /settleManualThemeIntent,/); - assert.match(terminalHostSource, /pickTerminalTheme,/); - assert.match(terminalHostSource, /resolveSessionAppearance: resolveFocusedAppearance/); - assert.doesNotMatch( - terminalHostSource, - /followAppTerminalTheme, themeRuntime, handleConnectSerial/, - ); - // Terminal domain must not thrash on whole settings bag identity. - assert.match(terminalHostSource, /sshDebugLogsEnabled:/); - assert.doesNotMatch( - terminalHostSource, - /splitSessionWithCurrentShell, settings, terminalFontFamilyId/, - ); - // Hotkey path must not depend on whole settings/sessions for callback identity. - assert.match(appSideEffectsSource, /showSftpTab: showSftpTabRef\.current/); - assert.match(appSideEffectsSource, /sessions: sessionsRef\.current/); - assert.match(appSideEffectsSource, /connectionLogs: connectionLogsRef\.current/); - assert.match(terminalHostSource, /useTerminalAppearanceInjection/); - assert.match(terminalHostSource, /includeChromeSurfaces: followAppTerminalTheme/); - assert.match(terminalHostSource, /useTerminalAppearanceInjection\(accentedGlobalAppearance/); - assert.match(terminalHostSource, /clearThemeIntent\(\)/); - assert.match(runtimeSource, /injectTerminalAppearanceVars\(appearance\.theme, \{ includeChromeSurfaces \}\)/); - assert.doesNotMatch(settingsSource, /pendingFollowAppTerminalThemeId/); - assert.doesNotMatch(settingsSource, /applyFollowAppTerminalThemePick/); - assert.match(settingsSource, /appearanceTransitionModeRef\.current = 'instant'/); - assert.match(appViewSource, /data-terminal-appearance-root/); - assert.match(appViewSource, /pickTerminalTheme=\{ctx\.pickTerminalTheme\}/); -}); - -test("default terminal theme selection persists via TerminalHost", () => { - // Product path lives on TerminalHost; AppSideEffects no longer owns this handler. - assert.match(terminalHostSource, /const handleDefaultTerminalThemeChange = useCallback\(\(themeId: string\) => \{/); - assert.match(terminalHostSource, /setTerminalThemeId\(themeId\)/); - assert.match(terminalHostSource, /TERMINAL_THEME_AUTO/); - assert.match(appViewSource, /onUpdateTerminalThemeId=\{handleDefaultTerminalThemeChange\}/); -}); diff --git a/application/app/AppSideEffects.appLock.test.ts b/application/app/AppSideEffects.appLock.test.ts deleted file mode 100644 index 4eeae53a5..000000000 --- a/application/app/AppSideEffects.appLock.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8"); - -test("open-terminal requests wait behind App Lock and resume after unlock", () => { - const handlerStart = source.indexOf("const _handleOpenTerminalPath"); - const handlerEnd = source.indexOf("useEffect(() =>", handlerStart); - const handlerSource = source.slice(handlerStart, handlerEnd); - const drainStart = source.indexOf("const pending = pendingDeepLinksWhileLockedRef.current.splice(0)"); - const drainEnd = source.indexOf("}, [appLockLocked]);", drainStart); - const drainSource = source.slice(drainStart, drainEnd); - - assert.match(handlerSource, /shouldDeferExternalActionWhileAppLocked/); - assert.match(handlerSource, /kind: 'open-terminal-path'/); - assert.match(drainSource, /_processOpenTerminalPath\(item\.payload\)/); - - const processStart = source.indexOf("const _processOpenTerminalPath"); - const processSource = source.slice(processStart, handlerStart); - assert.match(processSource, /handleCreateLocalTerminal\(undefined, \{ localStartDir \}\)/); - assert.match(processSource, /resolveShellSetting\(shellSetting, shells\)/); - assert.match(source, /const openTerminalQueueRef = useRef\(createOpenTerminalQueue\(\)\)/); - const enqueueAt = processSource.indexOf("openTerminalQueueRef.current.enqueue(() => {"); - const createAt = processSource.indexOf("handleCreateLocalTerminal"); - assert.ok(enqueueAt >= 0 && createAt > enqueueAt); - assert.match(processSource, /await ensureDiscoveredShells\(\)/); -}); diff --git a/application/app/AppSideEffects.deepLinkTabName.test.ts b/application/app/AppSideEffects.deepLinkTabName.test.ts deleted file mode 100644 index 68f649e87..000000000 --- a/application/app/AppSideEffects.deepLinkTabName.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8"); - -test("deep-link tab names are applied to terminal sessions", () => { - assert.match(source, /type DeepLinkPayload = \{[\s\S]*tabName\?: string/); - assert.match(source, /const handleConnectToHostWithTabName = useCallback/); - assert.match(source, /renameSessionInline\(sessionId, tabName\)/); - assert.match(source, /handleConnectToHostWithTabName\(ephemeralHost, tabName\)/); - assert.match( - source, - /handleConnectToHostWithTabName\(buildSshDeepLinkConnectionHost\(originalHost\), tabName\)/, - ); - assert.match( - source, - /handleConnectToHostWithTabName\(buildTelnetDeepLinkConnectionHost\(matchedEffectiveHost\), tabName\)/, - ); - assert.match(source, /label: tabName/); -}); diff --git a/application/app/AppSideEffects.paneMagnification.test.ts b/application/app/AppSideEffects.paneMagnification.test.ts deleted file mode 100644 index 7e50fbe95..000000000 --- a/application/app/AppSideEffects.paneMagnification.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8'); - -test('quick-switcher Escape handling stays in the bubble phase', () => { - const effectStart = source.indexOf('const onKeyDown = (e: KeyboardEvent) => {\n _handleEscapeKeyDown(e);'); - const effectEnd = source.indexOf('}, [appLockLocked]);', effectStart); - const effectSource = source.slice(effectStart, effectEnd); - - assert.notEqual(effectStart, -1); - assert.match(effectSource, /window\.addEventListener\('keydown', onKeyDown\)/); - assert.match(effectSource, /window\.removeEventListener\('keydown', onKeyDown\)/); - assert.doesNotMatch(source, /onCaptureKeyDown/); -}); diff --git a/application/app/AppSideEffects.snippetsDelete.test.ts b/application/app/AppSideEffects.snippetsDelete.test.ts deleted file mode 100644 index 5c8238396..000000000 --- a/application/app/AppSideEffects.snippetsDelete.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8"); - -test("snippets delete handler cleans host bindings via deleteSelectedSnippets", () => { - assert.match(source, /collectSnippetDeleteIds/); - assert.match(source, /deleteSelectedSnippets/); - assert.match( - source, - /netcatty:snippets:delete[\s\S]*void deleteSelectedSnippets\(ids\)/, - ); - assert.doesNotMatch( - source, - /updateSnippets\(snippets\.filter\(\(s\) => !ids\.has\(s\.id\)\)\)/, - ); -}); - -test("snippets delete handler uses vault live snapshot instead of component refs", () => { - // Component-level snippetsRef/hostsRef lag concurrent vault mutations that - // already advanced useVaultState refs before React re-renders AppSideEffects. - // Deletion must go through the vault hook's atomic live-snapshot path. - assert.match(source, /deleteSelectedSnippets,/); - assert.doesNotMatch(source, /snippetsRef\.current\s*=\s*snippets/); - assert.doesNotMatch( - source, - /deleteSelectedSnippetsFromVault\(\s*snippetsRef\.current/, - ); -}); diff --git a/application/app/AppSideEffects.temporaryConnectionSettings.test.ts b/application/app/AppSideEffects.temporaryConnectionSettings.test.ts deleted file mode 100644 index a284468c9..000000000 --- a/application/app/AppSideEffects.temporaryConnectionSettings.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./AppSideEffects.tsx", import.meta.url), "utf8"); - -test("handleConnectToHost reads temporary connection settings at call time", () => { - assert.match(source, /const temporaryConnectionSettingsRef = useRef\(terminalSettings\)/); - assert.match(source, /temporaryConnectionSettingsRef\.current = terminalSettings/); - - const handlerStart = source.indexOf("const handleConnectToHost = useCallback"); - const handlerEnd = source.indexOf("const handleConnectToHostWithTabName"); - assert.ok(handlerStart >= 0 && handlerEnd > handlerStart); - const handler = source.slice(handlerStart, handlerEnd); - - assert.match(handler, /temporaryConnectionSettingsRef\.current/); - assert.match(handler, /temporaryConnectionPrepareOptions\(liveTerminalSettings\)/); - assert.match(handler, /terminalSettings: liveTerminalSettings/); - assert.doesNotMatch(handler, /terminalSettings\.temporaryConnections/); - assert.doesNotMatch(handler, /\[addConnectionLog, connectToHost, resolveEffectiveHost, identities, keys, discoveredShells, terminalSettings\]/); -}); diff --git a/application/app/AppSideEffects.terminalKeyboardFocus.test.ts b/application/app/AppSideEffects.terminalKeyboardFocus.test.ts deleted file mode 100644 index 0f5e266b2..000000000 --- a/application/app/AppSideEffects.terminalKeyboardFocus.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import test from 'node:test'; - -const here = dirname(fileURLToPath(import.meta.url)); -const appSideEffectsSource = readFileSync(join(here, 'AppSideEffects.tsx'), 'utf8'); - -test('terminal keyboard focus tracking is always published to the main process', () => { - assert.match( - appSideEffectsSource, - /useTerminalKeyboardFocus\(\s*\)/, - 'the terminal keyboard focus signal must be unconditional', - ); -}); - -test('terminal keyboard focus is not gated on hotkey scheme or font zoom settings', () => { - // When the signal is turned off, the main process falls back to window zoom - // for Ctrl+= / Ctrl+- / Ctrl+0 while the user is typing in a terminal, so - // "disable terminal zoom" and per-binding overrides stop having any effect - // on those chords (#3327). - assert.doesNotMatch(appSideEffectsSource, /useTerminalKeyboardFocus\(\s*hotkeyScheme/); - assert.doesNotMatch( - appSideEffectsSource, - /useTerminalKeyboardFocus\(\s*[^)\s][^)]*disableTerminalFontZoom/, - ); -}); diff --git a/application/app/AppView.activeTabIsolation.test.ts b/application/app/AppView.activeTabIsolation.test.ts deleted file mode 100644 index 28aef6166..000000000 --- a/application/app/AppView.activeTabIsolation.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const appViewSource = readFileSync(new URL("./AppView.tsx", import.meta.url), "utf8"); -const pluginHostSource = readFileSync(new URL("./AppPluginKeybindingHost.tsx", import.meta.url), "utf8"); -const editorSurfaceSource = readFileSync(new URL("./AppHostEditorSurface.tsx", import.meta.url), "utf8"); - -test("AppView shell does not subscribe to useActiveTabId", () => { - // Top-tab switches must not rebuild the AppView shell. Leaves own the subscription. - assert.doesNotMatch(appViewSource, /useActiveTabId\s*\(/); - assert.doesNotMatch(appViewSource, /useActiveTabId/); - // Still uses activeTabStore for imperative tab close / neighbor activation. - assert.match(appViewSource, /activeTabStore/); -}); - -test("plugin keybindings and host-editor surface subscribe as leaves", () => { - assert.match(pluginHostSource, /useActiveTabId/); - assert.match(pluginHostSource, /resolveActivePluginKeybindingContext/); - assert.match(editorSurfaceSource, /useWorkSurfaceVisible/); - assert.match(editorSurfaceSource, /useActiveTabId/); - assert.match(appViewSource, /AppPluginKeybindingHost/); -}); diff --git a/application/app/AppView.workspaceHostAppend.test.ts b/application/app/AppView.workspaceHostAppend.test.ts deleted file mode 100644 index 34e06a924..000000000 --- a/application/app/AppView.workspaceHostAppend.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./AppView.tsx', import.meta.url), 'utf8'); - -test('workspace append resolves group defaults before creating host sessions', () => { - assert.match(source, /resolveEffectiveTerminalHost\(\{/); - assert.match(source, /groupConfigs,/); - assert.match(source, /proxyProfiles,/); - assert.match( - source, - /appendHostToWorkspace\(workspaceId, resolveWorkspaceAppendHost\(host\), rootDir\)/, - ); - assert.match( - source, - /appendHostToWorkspace\([\s\S]*?resolveWorkspaceAppendHost\(target\.host\),[\s\S]*?rootDir/, - ); -}); diff --git a/application/app/QuickSwitcherOverlay.tsx b/application/app/QuickSwitcherOverlay.tsx index 0f9c9842e..aa15b8b31 100644 --- a/application/app/QuickSwitcherOverlay.tsx +++ b/application/app/QuickSwitcherOverlay.tsx @@ -2,7 +2,7 @@ import React, { Suspense, lazy, useMemo, useState } from 'react'; import type { QuickSwitcherProps } from '../../components/QuickSwitcher'; import { LazyLoadBoundary } from '../../components/ui/lazy-load-boundary'; -import { getHostSearchMatch } from '../../lib/searchMatcher'; +import { getHostSearchMatch } from '../../domain/searchMatcher'; import type { Host } from '../../types'; const LazyQuickSwitcher = lazy(() => diff --git a/application/app/appShellPropsStore.ts b/application/app/appShellPropsStore.ts index 9b0bae4d0..c0a8a35ec 100644 --- a/application/app/appShellPropsStore.ts +++ b/application/app/appShellPropsStore.ts @@ -84,10 +84,6 @@ class AppShellPropsStore { export const appShellPropsStore = new AppShellPropsStore(); -export function publishAppShellDomains(domains: AppViewDomains): void { - appShellPropsStore.setDomains(domains); -} - export function publishAppShellDomainSlice( key: K, slice: AppViewDomains[K], diff --git a/application/app/strictModeIdempotency.test.ts b/application/app/strictModeIdempotency.test.ts deleted file mode 100644 index beb821ea4..000000000 --- a/application/app/strictModeIdempotency.test.ts +++ /dev/null @@ -1,279 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const appSource = readFileSync(new URL('../../App.tsx', import.meta.url), 'utf8'); -const appSideEffectsSource = readFileSync( - new URL('./AppSideEffects.tsx', import.meta.url), - 'utf8', -); -const indexSource = readFileSync(new URL('../../index.tsx', import.meta.url), 'utf8'); -const startupEffectsSource = readFileSync( - new URL('./useAppStartupEffects.ts', import.meta.url), - 'utf8', -); -const updateCheckSource = readFileSync( - new URL('../state/useUpdateCheck.ts', import.meta.url), - 'utf8', -); -const portForwardingAutoStartSource = readFileSync( - new URL('../state/usePortForwardingAutoStart.ts', import.meta.url), - 'utf8', -); -const appLockBridgeSource = readFileSync( - new URL('../state/useAppLockBridge.ts', import.meta.url), - 'utf8', -); - -test('every renderer root mounts under StrictMode', () => { - assert.match(indexSource, /import \{ StrictMode, Suspense, lazy \} from 'react'/); - - const renderCalls = indexSource.match(/root\.render\(/g) ?? []; - assert.equal(renderCalls.length, 5, 'main, settings, tray, terminal-popup and editor-window roots'); - - let cursor = 0; - for (let index = 0; index < renderCalls.length; index += 1) { - const renderAt = indexSource.indexOf('root.render(', cursor); - assert.notEqual(renderAt, -1); - const opener = indexSource.slice(renderAt, renderAt + 60); - assert.match(opener, /root\.render\(\s*/, `root.render #${index + 1} lacks StrictMode`); - cursor = renderAt + 'root.render('.length; - } -}); - -test('clone-session payload is consumed once even if the effect re-runs', () => { - const effectStart = appSideEffectsSource.indexOf('consumedNewWindowSessionRef'); - assert.notEqual(effectStart, -1, 'clone-session effect must latch on payload identity'); - const effectEnd = appSideEffectsSource.indexOf( - '}, [createSessionFromCloneSource, isVaultInitialized, pendingNewWindowSession]);', - effectStart, - ); - assert.notEqual(effectEnd, -1); - const body = appSideEffectsSource.slice(effectStart, effectEnd); - - // A ref comparison is required: clearing the state only lands on the next - // render, so a re-invoked effect still closes over the same payload. - assert.match(body, /if \(consumedNewWindowSessionRef\.current === pendingNewWindowSession\) return;/); - assert.ok( - body.indexOf('consumedNewWindowSessionRef.current = pending') - < body.indexOf('createSessionFromCloneSource(pending.sourceSession'), - 'payload must be marked consumed before the clone is created', - ); -}); - -test('rendererReady is notified once per renderer process', () => { - assert.match(appLockBridgeSource, /^let rendererReadySent = false;$/m); - const guardAt = appLockBridgeSource.indexOf('if (rendererReadySent) return;'); - assert.notEqual(guardAt, -1); - const guarded = appLockBridgeSource.slice(guardAt, guardAt + 200); - assert.match(guarded, /rendererReadySent = true;/); - assert.match(guarded, /netcattyBridge\.get\(\)\?\.rendererReady\?\.\(\)/); - assert.ok( - guarded.indexOf('rendererReadySent = true;') - < guarded.indexOf('netcattyBridge.get()?.rendererReady?.()'), - 'the latch must be set before the IPC call so a re-entrant effect is blocked', - ); -}); - -test('update-available toast latches on the release version', () => { - const latchAt = startupEffectsSource.indexOf('toastedUpdateVersionRef'); - assert.notEqual(latchAt, -1); - assert.match(startupEffectsSource, /const toastedUpdateVersionRef = useRef\(null\)/); - assert.match(startupEffectsSource, /if \(toastedUpdateVersionRef\.current === version\) return;/); - - const guardAt = startupEffectsSource.indexOf('if (toastedUpdateVersionRef.current === version) return;'); - const toastAt = startupEffectsSource.indexOf('toast.info(', guardAt); - assert.notEqual(toastAt, -1); - assert.ok(guardAt < toastAt, 'the version latch must gate the toast call'); -}); - -test('port-forward auto-start runs once across a StrictMode double effect', () => { - assert.match( - portForwardingAutoStartSource, - /const autoStartExecutedRef = useRef\(false\);/, - 'the launch auto-start needs a module-render latch, not just an effect dep list', - ); - - const effectStart = portForwardingAutoStartSource.indexOf('if (autoStartExecutedRef.current) return;'); - assert.notEqual(effectStart, -1, 'the effect must bail out when the latch is already set'); - const effectEnd = portForwardingAutoStartSource.indexOf( - '}, [\n enabled,\n isVaultInitialized,\n runAutoStart,\n ]);', - effectStart, - ); - assert.notEqual(effectEnd, -1, 'auto-start effect dep list moved; update this contract'); - const body = portForwardingAutoStartSource.slice(effectStart, effectEnd); - - // StrictMode invokes the effect twice with the same render's closure, so the - // latch has to be written before the async run is kicked off — awaiting or - // deferring the write would let the second invoke start a duplicate tunnel. - const latchAt = body.indexOf('autoStartExecutedRef.current = true;'); - const runAt = body.indexOf('void runAutoStart();'); - assert.notEqual(latchAt, -1); - assert.notEqual(runAt, -1); - assert.ok(latchAt < runAt, 'the latch must be set before runAutoStart() is called'); - - // The vault gate must also sit before the latch: latching on a pre-hydration - // invoke would permanently suppress the real auto-start. - assert.ok( - body.indexOf('if (!isVaultInitialized) return;') < latchAt, - 'the vault gate must precede the latch write', - ); -}); - -test('cancelled startup update check resets its latch instead of skipping forever', () => { - const scheduleAt = updateCheckSource.indexOf('let checkArmed = true;'); - assert.notEqual(scheduleAt, -1); - const tail = updateCheckSource.slice(scheduleAt); - - // The latch is only meaningful once the timer actually fires; a cleanup that - // cancels it beforehand must let the next effect schedule again. - assert.match(tail, /startupCheckTimeoutRef\.current = setTimeout\(async \(\) => \{\s*\n\s*checkArmed = false;/); - assert.match(tail, /if \(checkArmed\) \{\s*\n\s*hasCheckedOnStartupRef\.current = false;\s*\n\s*\}/); -}); - -test('terminal popup config survives StrictMode unsubscribe/resubscribe', () => { - const preloadSource = readFileSync(new URL('../../electron/preload.cjs', import.meta.url), 'utf8'); - const apiSource = readFileSync(new URL('../../electron/preload/api.cjs', import.meta.url), 'utf8'); - - assert.match(preloadSource, /lastPayload:\s*null/); - assert.match( - preloadSource, - /terminalPopupConfigState\.lastPayload = payload/, - 'incoming popup config must be retained beyond the one-shot pending slot', - ); - - const subscribeAt = apiSource.indexOf('onTerminalPopupConfig:'); - assert.notEqual(subscribeAt, -1); - const subscribe = apiSource.slice(subscribeAt, subscribeAt + 700); - assert.match( - subscribe, - /terminalPopupConfigState\.pending \?\? terminalPopupConfigState\.lastPayload/, - 'resubscribe must replay lastPayload after pending was drained', - ); - assert.match(subscribe, /terminalPopupConfigState\.pending = null/); - assert.doesNotMatch( - subscribe, - /terminalPopupConfigState\.lastPayload = null/, - 'StrictMode remount must not clear lastPayload on subscribe', - ); -}); - -test('vault init cancels the superseded StrictMode effect before publishing ready', () => { - const vaultSource = readFileSync( - new URL('../state/useVaultState.ts', import.meta.url), - 'utf8', - ); - const initAt = vaultSource.indexOf('let cancelled = false;'); - assert.notEqual(initAt, -1, 'vault init must track cancellation'); - const initSlice = vaultSource.slice(initAt, initAt + 20000); - assert.match( - initSlice, - /return \(\) => \{\s*\n\s*cancelled = true;\s*\n\s*resolveTerminalDataReady\(\);\s*\n\s*\};/, - 'StrictMode cleanup cancels init and unblocks the terminal-data ready promise', - ); - assert.match( - initSlice, - /if \(!cancelled\) \{\s*\n\s*setIsInitialized\(true\);\s*\n\s*setVaultInitialized\(true\);\s*\n\s*\}/, - 'only the surviving init may mark the vault ready', - ); - assert.match(initSlice, /if \(cancelled\) return;/); -}); - -test('global hotkey registration cleans up across StrictMode remount', () => { - const systemEffectsSource = readFileSync( - new URL('../state/systemSettingsEffects.ts', import.meta.url), - 'utf8', - ); - const hotkeyAt = systemEffectsSource.indexOf('Persist and sync toggle window hotkey setting'); - assert.notEqual(hotkeyAt, -1); - const hotkeyEffect = systemEffectsSource.slice(hotkeyAt, hotkeyAt + 2200); - assert.match(hotkeyEffect, /let cancelled = false;/); - assert.match(hotkeyEffect, /if \(cancelled\) return;/); - assert.match( - hotkeyEffect, - /if \(didRegister\) \{\s*\n\s*bridge\?\.unregisterGlobalHotkey/, - 'cleanup must unregister a registration started by this effect', - ); - // Early return before notify must not skip returning the cleanup function. - assert.doesNotMatch( - hotkeyEffect, - /if \(!persistMountedRef\.current\) return;\s*\n\s*notifySettingsChanged/, - ); -}); - -test('settings persistMountedRef resets on StrictMode cleanup', () => { - const settingsSource = readFileSync( - new URL('../state/useSettingsState.ts', import.meta.url), - 'utf8', - ); - const markAt = settingsSource.indexOf('Mark persist effects mounted AFTER all persist useEffects'); - assert.notEqual(markAt, -1); - const markEffect = settingsSource.slice(markAt, markAt + 500); - assert.match(markEffect, /persistMountedRef\.current = true;/); - assert.match( - markEffect, - /return \(\) => \{\s*\n\s*persistMountedRef\.current = false;\s*\n\s*\};/, - 'remount must treat boot as a fresh mount, not a settings change', - ); -}); - -test('tray panel connect flush latches against StrictMode double invoke', () => { - const sideEffectsSource = readFileSync( - new URL('./AppSideEffects.tsx', import.meta.url), - 'utf8', - ); - assert.match(sideEffectsSource, /pendingTrayConnectFlushKeyRef/); - assert.match( - sideEffectsSource, - /if \(pendingTrayConnectFlushKeyRef\.current === flushKey\) return;/, - ); -}); - -test('ssh transport idle TTL notify latches against StrictMode double invoke', () => { - const settingsSource = readFileSync( - new URL('../state/useSettingsState.ts', import.meta.url), - 'utf8', - ); - assert.match(settingsSource, /lastPushedSshTransportIdleTtlRef/); - assert.match( - settingsSource, - /if \(lastPushedSshTransportIdleTtlRef\.current === sshTransportIdleTtlMs\) return;/, - ); - assert.match( - settingsSource, - /lastPushedSshTransportIdleTtlRef\.current = sshTransportIdleTtlMs;/, - ); -}); - -test('terminal selection Ask-AI payload is consumed once under StrictMode', () => { - const hostSource = readFileSync( - new URL('../../components/terminalLayer/TerminalLayerSupport.tsx', import.meta.url), - 'utf8', - ); - assert.match(hostSource, /consumedTerminalSelectionRequestIds/); - assert.doesNotMatch( - hostSource, - /consumedTerminalSelectionRequestIdRef/, - 'component refs reset on StrictMode remount; use a module Set', - ); - assert.match( - hostSource, - /if \(consumedTerminalSelectionRequestIds\.has\(pendingTerminalSelection\.requestId\)\)/, - ); - const latchAt = hostSource.indexOf('markTerminalSelectionRequestConsumed(pendingTerminalSelection.requestId)'); - const draftAt = hostSource.indexOf('updateDraft(scopeKey, defaultAgentId'); - assert.ok(latchAt > 0 && draftAt > latchAt, 'must latch before mutating the draft'); -}); - -test('Codex App Server interaction bridge is app-singleton like MCP approvals', () => { - assert.match(appSource, /setupCodexAppServerInteractionBridge/); - const panelSource = readFileSync( - new URL('../../components/AIChatSidePanel.tsx', import.meta.url), - 'utf8', - ); - assert.doesNotMatch( - panelSource, - /setupCodexAppServerInteractionBridge/, - 'per-panel Codex IPC listeners fan out approvals under retained multi-tab mounts', - ); -}); diff --git a/application/app/topTabsChromeTheme.test.ts b/application/app/topTabsChromeTheme.test.ts deleted file mode 100644 index 171317826..000000000 --- a/application/app/topTabsChromeTheme.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { readFileSync } from "node:fs"; - -test("active chrome theme applies top tab vars and clears them before vault restore transition", () => { - const chromeThemeSource = readFileSync(new URL("../state/useActiveChromeTheme.ts", import.meta.url), "utf8"); - const syncSource = readFileSync(new URL("../state/activeChromeThemeSync.ts", import.meta.url), "utf8"); - const effectsSource = readFileSync(new URL("../../components/terminalLayer/useTerminalLayerEffects.ts", import.meta.url), "utf8"); - - assert.match(chromeThemeSource, /applyTopTabsChromeThemeVars\(theme\)/); - assert.match(chromeThemeSource, /resolveReadableForegroundForHsl\(cursor\)/); - const restoreBlock = chromeThemeSource.match( - /clearTopTabsChromeThemeVars\(\);\s*runThemeTransition\(\(\) => \{\s*removeActiveChromeTheme\(\);/, - )?.[0] ?? ""; - assert.notEqual(restoreBlock, "", "top tab vars must clear before the vault restore transition starts"); - assert.match(syncSource, /activeTabId === 'vault' \|\| activeTabId === 'sftp'\)[\s\S]*clearTopTabsChromeThemeVars\(\)/); - assert.match(effectsSource, /if \(!isTerminalLayerVisible\) \{[\s\S]*clearTopTabsPreviewVars\(\)/); -}); - -test("top tabs chrome theme keeps accent foreground in sync", () => { - const source = readFileSync(new URL("./topTabsChromeTheme.ts", import.meta.url), "utf8"); - const supportSource = readFileSync(new URL("../../components/terminalLayer/TerminalLayerSupport.tsx", import.meta.url), "utf8"); - - assert.match(source, /--primary-foreground/); - assert.match(source, /--accent-foreground/); - assert.match(source, /resolveReadableForegroundForHsl\(accent\)/); - assert.match(supportSource, /removeStylePropertyIfSet\(tabsRoot, '--primary-foreground'\)/); - assert.match(supportSource, /removeStylePropertyIfSet\(tabsRoot, '--accent-foreground'\)/); -}); diff --git a/application/convergentSyncMigration.ts b/application/convergentSyncMigration.ts index 3b2aa79df..c02a27acc 100644 --- a/application/convergentSyncMigration.ts +++ b/application/convergentSyncMigration.ts @@ -7,7 +7,6 @@ import type { import { cloudSyncPayloadsEqual, convergentConflictAddressKey, - materializeSyncPayloadFromConvergentState, planConvergentSyncMigration, refreshConvergentSyncMigrationPlan, resolveConvergentFieldConflict, @@ -238,12 +237,3 @@ export async function initializePreparedConvergentMigration(options: { }); return prepared.plan.preview; } - -export async function prepareConvergentSyncDowngrade( - manager: CloudSyncManager = getCloudSyncManager(), - now = Date.now(), -): Promise { - const replica = await manager.loadConvergentReplica(); - if (!replica) throw new Error('No convergent sync replica is available to downgrade'); - return materializeSyncPayloadFromConvergentState(replica.state, { syncedAt: now }); -} diff --git a/application/i18n/locales/cattyIterationLimitLocales.test.ts b/application/i18n/locales/cattyIterationLimitLocales.test.ts deleted file mode 100644 index afb16bd72..000000000 --- a/application/i18n/locales/cattyIterationLimitLocales.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { enAiMessages } from './en/ai'; -import { esAiMessages } from './es/ai'; -import { ruAiMessages } from './ru/ai'; -import { zhCNAiMessages } from './zh-CN/ai'; -import { zhTWAiMessages } from './zh-TW/ai'; - -for (const [locale, messages] of Object.entries({ - en: enAiMessages, es: esAiMessages, ru: ruAiMessages, - 'zh-CN': zhCNAiMessages, 'zh-TW': zhTWAiMessages, -})) { - test(`${locale} translates the Catty iteration limit notice and Continue action`, () => { - assert.ok(messages['ai.chat.iterationLimitReached']); - assert.match(messages['ai.chat.iterationLimitReached'], /\{limit\}/); - assert.ok(messages['ai.chat.continue']); - }); -} diff --git a/application/i18n/locales/cloudSyncConvergentLocales.test.ts b/application/i18n/locales/cloudSyncConvergentLocales.test.ts deleted file mode 100644 index ceefe6169..000000000 --- a/application/i18n/locales/cloudSyncConvergentLocales.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; - -import en from '../locales/en.ts'; -import ru from '../locales/ru.ts'; -import es from '../locales/es.ts'; -import zhCN from '../locales/zh-CN.ts'; -import zhTW from '../locales/zh-TW.ts'; - -const keys = [ - 'cloudSync.convergent.title', - 'cloudSync.convergent.experimental', - 'cloudSync.convergent.desc', - 'cloudSync.convergent.active', - 'cloudSync.convergent.paused', - 'cloudSync.convergent.enabled', - 'cloudSync.convergent.preview.title', - 'cloudSync.convergent.preview.entities', - 'cloudSync.convergent.preview.providers', - 'cloudSync.convergent.preview.conflicts', - 'cloudSync.convergent.preview.compatibility', - 'cloudSync.convergent.preview.confirm', - 'cloudSync.convergent.preview.status.ready', - 'cloudSync.convergent.preview.status.empty', - 'cloudSync.convergent.preview.status.unavailable', - 'cloudSync.convergent.preview.status.blocked', - 'cloudSync.convergent.preview.schema', - 'cloudSync.convergent.field.presence', - 'cloudSync.convergent.field.position', - 'cloudSync.convergent.conflicts.title', - 'cloudSync.convergent.conflict.empty', - 'cloudSync.convergent.conflict.secretSet', - 'cloudSync.convergent.conflict.current', - 'cloudSync.convergent.conflict.choose', - 'cloudSync.convergent.conflict.resolved', - 'cloudSync.convergent.downgrade.desc', - 'cloudSync.convergent.downgrade.button', - 'cloudSync.convergent.downgrade.confirm', - 'cloudSync.convergent.downgrade.done', -] as const; - -test('convergent sync copy exists in every bundled locale', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - for (const key of keys) { - assert.equal(typeof messages[key], 'string', `${locale} is missing ${key}`); - assert.notEqual(messages[key], '', `${locale} has empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/cloudSyncDisconnectLocales.test.ts b/application/i18n/locales/cloudSyncDisconnectLocales.test.ts deleted file mode 100644 index b641e65d7..000000000 --- a/application/i18n/locales/cloudSyncDisconnectLocales.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; - -import en from '../locales/en.ts'; -import ru from '../locales/ru.ts'; -import es from '../locales/es.ts'; -import zhCN from '../locales/zh-CN.ts'; -import zhTW from '../locales/zh-TW.ts'; - -const keys = [ - 'cloudSync.provider.disconnect', - 'cloudSync.provider.disconnect.confirmTitle', - 'cloudSync.provider.disconnect.confirmMessage', - 'cloudSync.provider.disconnect.confirmAction', - 'cloudSync.provider.disconnect.toastTitle', - 'cloudSync.provider.disconnect.cloudRemains', - 'cloudSync.provider.disconnect.failed', -] as const; - -test('disconnect copy exists in every bundled locale', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - for (const key of keys) { - assert.equal(typeof messages[key], 'string', `${locale} is missing ${key}`); - assert.notEqual(messages[key], '', `${locale} has empty ${key}`); - } - } -}); - -test('disconnect confirm copy states that saved provider credentials are removed', () => { - // The confirm dialog must explain the data consequence of disconnecting: - // locally saved endpoint + credentials removal, not just "stops syncing". - const expected = [ - [en, 'will be removed'], - [es, 'eliminarán'], - [ru, 'будут удалены'], - [zhCN, '删除'], - [zhTW, '刪除'], - ] as const; - for (const [messages, fragment] of expected) { - assert.ok( - (messages['cloudSync.provider.disconnect.confirmMessage'] as string).includes(fragment), - `confirmMessage should mention credential removal: ${fragment}`, - ); - } -}); - -test('disconnect toast copy explains the cloud copy is retained', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - assert.ok( - (messages['cloudSync.provider.disconnect.cloudRemains'] as string).includes( - '{name}', - ), - `${locale} cloudRemains hint should reference the provider name`, - ); - } -}); - -test('disconnect copy distinguishes login cleanup from retained local data', () => { - assert.match(en['cloudSync.provider.disconnect.confirmMessage'], /backup history and sync encryption password stay here/); - assert.doesNotMatch(en['cloudSync.provider.disconnect.cloudRemains'], /change.*password/); - for (const messages of [en, ru, es, zhCN, zhTW]) { - assert.ok(messages['cloudSync.provider.disconnect.failed'].includes('{name}')); - } -}); diff --git a/application/i18n/locales/cloudSyncStrategyLocales.test.ts b/application/i18n/locales/cloudSyncStrategyLocales.test.ts deleted file mode 100644 index 203cb5e8a..000000000 --- a/application/i18n/locales/cloudSyncStrategyLocales.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import en from "../locales/en.ts"; -import ru from "../locales/ru.ts"; -import es from "../locales/es.ts"; -import zhCN from "../locales/zh-CN.ts"; - -const strategyKeys = [ - "cloudSync.strategy.title", - "cloudSync.strategy.desc", - "cloudSync.strategy.smartMerge", - "cloudSync.strategy.smartMergeDesc", - "cloudSync.strategy.smartMergePreserve", - "cloudSync.strategy.smartMergePreserveDesc", - "cloudSync.strategy.preferCloud", - "cloudSync.strategy.preferCloudDesc", - "cloudSync.strategy.preferLocal", - "cloudSync.strategy.preferLocalDesc", - "cloudSync.aiSessions.title", - "cloudSync.aiSessions.desc", - "cloudSync.aiSessions.compatibility", - "cloudSync.aiSessions.enableFailed", -] as const; - -test("cloud sync strategy copy exists in every bundled locale", () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN })) { - for (const key of strategyKeys) { - assert.equal( - typeof messages[key], - "string", - `${locale} is missing ${key}`, - ); - assert.notEqual(messages[key], "", `${locale} has empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/codexSteerLocales.test.ts b/application/i18n/locales/codexSteerLocales.test.ts deleted file mode 100644 index 94441b2a7..000000000 --- a/application/i18n/locales/codexSteerLocales.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en.ts'; -import ru from './ru.ts'; -import es from './es.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const STEER_KEYS = [ - 'ai.codex.steer.addInstruction', - 'ai.codex.steer.sending', - 'ai.codex.steer.placeholder', - 'ai.codex.steer.notSteerableReview', - 'ai.codex.steer.notSteerableCompact', - 'ai.codex.steer.busy', - 'ai.codex.steer.inactive', - 'ai.codex.steer.unsupported', - 'ai.codex.steer.failed', -] as const; - -test('Codex steering UI is localized in every supported locale', () => { - for (const [name, messages] of Object.entries({ en, es, 'zh-CN': zhCN, 'zh-TW': zhTW, ru })) { - const missing = STEER_KEYS.filter(key => !messages[key]); - assert.deepEqual(missing, [], `${name} is missing Codex steering labels`); - } -}); diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index e2d5cf7fc..b2c6eaf62 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -748,9 +748,6 @@ export const enAiMessages: Messages = { 'terminal.layer.theme': 'Theme', 'terminal.layer.notes': 'Notes', 'terminal.layer.aiChat': 'AI Chat', - 'terminal.layer.movePanelLeft': 'Move panel to left', - 'terminal.layer.movePanelRight': 'Move panel to right', - 'terminal.layer.movePanelBottom': 'Move panel to bottom', 'terminal.layer.choosePanelPosition': 'Change position', 'terminal.layer.dockLeft': 'Left', 'terminal.layer.dockRight': 'Right', @@ -784,19 +781,15 @@ export const enAiMessages: Messages = { 'terminal.layer.hostTree.details.protocol': 'Protocol', 'terminal.layer.hostTree.details.group': 'Group', 'terminal.layer.hostTree.details.tags': 'Tags', - 'terminal.layer.hostTree.details.lastConnected': 'Last connected', 'topTabs.openQuickSwitcher': 'Open quick switcher', 'topTabs.moreTabs': 'More tabs', 'topTabs.aiAssistant': 'AI Assistant', - 'topTabs.newLocalTerminal': 'New Local Terminal', 'topTabs.controlPanel': 'Quick controls', 'topTabs.controlPanel.externalMcp': 'External MCP', 'topTabs.controlPanel.theme': 'Theme', 'topTabs.controlPanel.theme.light': 'Light', 'topTabs.controlPanel.theme.dark': 'Dark', 'topTabs.controlPanel.theme.system': 'System', - 'topTabs.externalMcp.enable': 'Enable External MCP', - 'topTabs.externalMcp.disable': 'Disable External MCP', 'topTabs.windowOpacity': 'Window opacity', 'topTabs.openSettings': 'Open Settings', 'ai.chat.sessionHistory': 'Session history', diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index 089f7d268..36e41b050 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -84,7 +84,6 @@ export const enCoreMessages: Messages = { 'common.edit': 'Edit', 'common.clear': 'Clear', 'common.optional': 'Optional', - 'common.selectPlaceholder': 'Select...', 'common.add': 'Add', 'common.rename': 'Rename', 'common.refresh': 'Refresh', @@ -124,11 +123,9 @@ export const enCoreMessages: Messages = { 'field.label': 'Label', 'field.type': 'Type', 'auth.keyType': 'Type {type}', - 'auth.showAllKeys': 'Show all keys', // Dialogs / prompts 'confirm.deleteHost': 'Delete Host "{name}"?', - 'confirm.deleteIdentity': 'Delete Identity "{name}"?', 'confirm.removeProvider': 'Remove provider "{name}"?', 'confirm.closeBusyTerminal.title': 'Confirm close', 'confirm.closeBusyTerminal.message': 'Process "{command}" is still running and will be terminated.', @@ -401,7 +398,6 @@ export const enCoreMessages: Messages = { 'tray.status.inactive': 'Inactive', 'tray.status.error': 'Error', 'tray.status.unknown': 'Unknown', - 'tray.recentHosts': 'Recent Hosts', 'tray.empty.title': 'Nothing here yet', 'tray.empty.subtitle': 'Go connect to a server, they miss you 🚀', 'tray.quit': 'Quit Netcatty', @@ -460,9 +456,6 @@ export const enCoreMessages: Messages = { 'update.downloadFailed.message': 'Failed to download update. You can download it manually.', 'update.needsSave.title': 'Unsaved Changes', 'update.needsSave.message': 'Save your open editors first, then click Restart Now again to install the update.', - 'update.openReleases': 'Open Releases', - 'update.remindLater': 'Remind Later', - 'update.skipVersion': 'Skip This Version', // Settings > Appearance 'settings.appearance.uiTheme': 'UI Theme', @@ -1083,8 +1076,6 @@ Highlight the focused split pane: 'settings.shortcuts.binding.sftp-navigate-to': 'Navigate to Selected Directory', // Context menus / common actions - 'action.newHost': 'New Host', - 'action.newSubfolder': 'New Subfolder', 'action.copyPublicKey': 'Copy Public Key', 'action.keyExport': 'Key Export', 'action.edit': 'Edit', @@ -1319,12 +1310,9 @@ Highlight the focused split pane: "settings.plugins.manager.remove": "Uninstall", "settings.plugins.manager.removeNote": "Uninstall removes package code and local KV data. User-owned settings, secrets and sync sidecars are retained.", "settings.plugins.permissions.statusUnknown": "Status unknown", - "plugins.sidebar.extensions": "Extension pages", "plugins.sidebar.selectTerminal": "Select an open terminal first.", "plugins.sidebar.loading": "Loading extension page…", "plugins.vault.loading": "Loading plugin page…", - "plugins.vault.extensions": "Extensions", - "plugins.vault.back": "Back to hosts", "plugins.interaction.title": "Plugin request", "plugins.interaction.sharing": "Text you share becomes available to this plugin and its granted capabilities, including network access. Reading does not approve a new network destination.", "plugins.interaction.input": "Input text", diff --git a/application/i18n/locales/en/scripts.ts b/application/i18n/locales/en/scripts.ts index 453e75ec7..1011cc266 100644 --- a/application/i18n/locales/en/scripts.ts +++ b/application/i18n/locales/en/scripts.ts @@ -1,6 +1,5 @@ export const enScriptsMessages = { 'scripts.meta.name': 'Name', - 'scripts.meta.language': 'Language', 'scripts.meta.description': 'Description', 'scripts.meta.descriptionPlaceholder': 'Optional notes about this script', 'scripts.meta.trigger': 'Trigger', @@ -15,7 +14,6 @@ export const enScriptsMessages = { 'scripts.actions.openEditor': 'Open editor', 'scripts.actions.openEditorHint': 'Edit script in a larger window', 'scripts.editor.modalTitle': 'Script editor', - 'scripts.editor.modalSubtitle': 'Edit metadata and script code in a larger workspace.', 'scripts.editor.lineCount': '{count} lines', 'scripts.editor.resize': 'Resize editor', 'scripts.targets.hint': 'Selected groups are resolved dynamically, so hosts added later are included automatically.', @@ -86,17 +84,13 @@ export const enScriptsMessages = { 'scripts.dialog.retry': 'Retry', 'scripts.dialog.skip': 'Skip', 'scripts.dialog.abort': 'Abort', - 'scripts.running.stepProgress': 'Step {current} / {total}', 'scripts.running.determinateProgress': '{label} {current}/{total}', 'scripts.running.progressFallback': 'Progress', 'scripts.running.operationsCount': '{count} operations', 'scripts.running.opsPrefix': '', 'scripts.running.opsSuffix': ' operations', - 'scripts.running.elapsedLabel': 'Elapsed', 'scripts.running.lastSentLabel': 'Sent:', 'scripts.running.elapsed': '{elapsed}', - 'scripts.running.completedSummary': 'Completed · {count} operations · {elapsed}', - 'scripts.running.dismissHint': 'Tap close to dismiss', 'scripts.running.dismiss': 'Close', 'scripts.running.viewLogs': 'View logs', 'scripts.running.logTitle': '{name} · Run log', @@ -111,26 +105,12 @@ export const enScriptsMessages = { 'vault.nav.scripts': 'Scripts', 'snippets.action.newScript': 'New automation script', 'hostDetails.section.automation': 'Automation', - 'hostDetails.automation.loginScript': 'Login script', - 'hostDetails.automation.loginScriptPlaceholder': 'Select a script', - 'hostDetails.automation.none': 'None', - 'hostDetails.automation.outputTriggers': 'Output triggers', - 'hostDetails.automation.addTrigger': 'Add trigger', - 'hostDetails.automation.triggerPatternPlaceholder': 'Regex pattern', - 'hostDetails.automation.linkedScripts': 'Linked scripts', - 'hostDetails.automation.linkedScriptsEmpty': 'No scripts linked to this host yet.', - 'hostDetails.automation.linkScriptPlaceholder': 'Link existing script…', - 'hostDetails.automation.unlink': 'Unlink', - 'hostDetails.automation.equivalenceHint': 'Links add this host to the script\'s target list in Scripts. Both views stay in sync.', 'hostDetails.automation.queueHint': 'Scripts run in order when this host connects. Global scripts run first, then this queue.', 'hostDetails.automation.globalScripts': 'Global connect scripts', 'hostDetails.automation.globalScriptsHint': 'Runs first on every connect. Reorder in Scripts library sort order.', 'hostDetails.automation.connectQueue': 'This host\'s run queue', 'hostDetails.automation.connectQueueEmpty': 'No connect scripts queued for this host yet.', 'hostDetails.automation.addToQueuePlaceholder': 'Add script to queue…', - 'hostDetails.automation.moveUp': 'Move up', - 'hostDetails.automation.moveDown': 'Move down', 'hostDetails.automation.removeFromQueue': 'Remove from queue', 'hostDetails.automation.dragHandle': 'Drag to reorder', - 'hostDetails.automation.queueDragHint': 'Drag items to reorder the connect queue.', }; diff --git a/application/i18n/locales/en/systemManager.ts b/application/i18n/locales/en/systemManager.ts index 3e76071a3..3e9828b0c 100644 --- a/application/i18n/locales/en/systemManager.ts +++ b/application/i18n/locales/en/systemManager.ts @@ -14,13 +14,11 @@ export const enSystemManagerMessages: Messages = { 'systemManager.tabs.docker': 'Docker', 'systemManager.tabs.gpu': 'GPU', 'systemManager.tabs.ariaLabel': 'System manager sections', - 'systemManager.popup.loading': 'Opening terminal…', 'systemManager.popup.startupFailed': 'The startup command did not complete successfully. Check that the target is still available and try again.', 'systemManager.errors.loadProcesses': 'Failed to load processes', 'systemManager.errors.loadTmux': 'Failed to load tmux sessions', 'systemManager.errors.loadTmuxWindows': 'Failed to load tmux windows', - 'systemManager.errors.loadTmuxPanes': 'Failed to load tmux panes', 'systemManager.errors.loadTmuxClients': 'Failed to load tmux clients', 'systemManager.errors.actionFailed': 'Action failed', 'systemManager.errors.loadDocker': 'Failed to load containers', @@ -31,7 +29,6 @@ export const enSystemManagerMessages: Messages = { 'systemManager.errors.nerdctlUnreachable': "nerdctl can't reach containerd", 'systemManager.errors.clusterUnreachable': "Can't reach the cluster for context {{context}}", 'systemManager.errors.clusterUnreachableGeneric': "Can't reach the cluster", - 'systemManager.errors.loadOverview': 'Failed to load system overview', 'systemManager.errors.loadGpu': 'Failed to load GPU / NPU stats', 'systemManager.errors.loadPorts': 'Failed to load listening ports', 'systemManager.errors.loadServices': 'Failed to load systemd services', @@ -65,13 +62,10 @@ export const enSystemManagerMessages: Messages = { 'systemManager.overview.noTopProcesses': 'No process data', 'systemManager.processes.search': 'Search processes…', - 'systemManager.processes.command': 'Command', - 'systemManager.processes.user': 'User', 'systemManager.processes.term': 'Terminate', 'systemManager.processes.kill': 'Kill', 'systemManager.processes.stop': 'Stop (SIGSTOP)', 'systemManager.processes.cont': 'Continue (SIGCONT)', - 'systemManager.processes.hup': 'Hang up (SIGHUP)', 'systemManager.processes.renice': 'Renice', 'systemManager.processes.renicePrompt': 'Nice value (-20 to 19)', 'systemManager.processes.reniceInvalid': 'Nice value must be between -20 and 19', @@ -86,7 +80,6 @@ export const enSystemManagerMessages: Messages = { 'systemManager.processes.stat': 'State', 'systemManager.processes.meta': '{{count}} process(es)', 'systemManager.processes.loading': 'Loading processes…', - 'systemManager.processes.loadingMore': 'Loading more processes…', 'systemManager.processes.state.running': 'Running', 'systemManager.processes.state.sleeping': 'Sleeping', 'systemManager.processes.state.stopped': 'Stopped', @@ -124,12 +117,9 @@ export const enSystemManagerMessages: Messages = { 'systemManager.tmux.attached': 'Attached', 'systemManager.tmux.detached': 'Detached', 'systemManager.tmux.windows': '{{count}} window(s)', - 'systemManager.tmux.created': 'Created', - 'systemManager.tmux.activity': 'Activity', 'systemManager.tmux.rename': 'Rename', 'systemManager.tmux.detach': 'Detach all', 'systemManager.tmux.killSession': 'Kill session', - 'systemManager.tmux.killServer': 'Kill server', 'systemManager.tmux.loadingDetails': 'Loading details…', 'systemManager.tmux.clients': 'Attached clients', 'systemManager.tmux.windowList': 'Windows', @@ -140,31 +130,17 @@ export const enSystemManagerMessages: Messages = { 'systemManager.docker.unavailable': 'No container runtime (Docker, Podman, nerdctl, or kubectl) was detected on this host', 'systemManager.tmux.windowsMismatch': 'Session reports {{count}} window(s) but list-windows returned none', 'systemManager.tmux.lastCommand': 'last command: {{command}}', - 'systemManager.tmux.noPanes': 'No panes', - 'systemManager.tmux.panes': '{{count}} pane(s)', - 'systemManager.tmux.active': 'active', 'systemManager.tmux.unnamedWindow': 'Unnamed window', - 'systemManager.tmux.unnamedPane': 'Unnamed pane', 'systemManager.tmux.attachWindow': 'Attach to window', - 'systemManager.tmux.selectWindow': 'Select window', 'systemManager.tmux.killWindow': 'Kill window', - 'systemManager.tmux.killPane': 'Kill pane', - 'systemManager.tmux.splitHorizontal': 'Split horizontal', - 'systemManager.tmux.splitVertical': 'Split vertical', - 'systemManager.tmux.sendKeys': 'Send keys', - 'systemManager.tmux.sendKeysTo': 'Send keys to window {{window}} pane {{pane}}', - 'systemManager.tmux.sendKeysPlaceholder': 'Command or text…', 'systemManager.tmux.renameSessionPrompt': 'Rename session', 'systemManager.tmux.renameWindowPrompt': 'Rename window', 'systemManager.tmux.windowName': 'Window name', 'systemManager.tmux.confirmKillSession': 'Kill tmux session "{{name}}"?', 'systemManager.tmux.confirmDetachSession': 'Detach all clients from "{{name}}"?', 'systemManager.tmux.confirmKillWindow': 'Kill window "{{name}}"?', - 'systemManager.tmux.confirmKillPane': 'Kill pane #{{index}}?', - 'systemManager.tmux.confirmKillServer': 'Kill tmux server? All sessions will be terminated.', 'systemManager.tmux.meta': '{{count}} session(s)', - 'systemManager.docker.title': 'Containers', 'systemManager.docker.subTabs.containers': 'Containers', 'systemManager.docker.subTabs.images': 'Images', 'systemManager.docker.empty': 'No containers found', @@ -177,7 +153,6 @@ export const enSystemManagerMessages: Messages = { 'systemManager.docker.filter.paused': 'Paused', 'systemManager.docker.shell': 'Shell', 'systemManager.docker.logs': 'Logs', - 'systemManager.docker.details': 'Details', 'systemManager.docker.inspect': 'Inspect', 'systemManager.docker.imageInspect': 'Image inspect', 'systemManager.docker.confirmRemove': 'Remove this container?', diff --git a/application/i18n/locales/en/terminal.ts b/application/i18n/locales/en/terminal.ts index c15608506..edcf132ec 100644 --- a/application/i18n/locales/en/terminal.ts +++ b/application/i18n/locales/en/terminal.ts @@ -53,7 +53,6 @@ export const enTerminalMessages: Messages = { 'terminal.toolbar.availableAfterConnect': 'Available after connect', 'terminal.toolbar.sendYmodem': 'Send with YMODEM', 'terminal.toolbar.receiveYmodem': 'Receive with YMODEM', - 'terminal.toolbar.sftp': 'SFTP', 'terminal.toolbar.more': 'More actions', 'terminal.toolbar.scripts': 'Scripts', 'terminal.toolbar.history': 'Command history', @@ -101,7 +100,6 @@ export const enTerminalMessages: Messages = { 'terminal.composeBar.resize': 'Resize compose bar height', 'terminal.composeBar.manageSnippets': 'Manage quick snippets', 'terminal.composeBar.searchSnippets': 'Search snippets...', - 'terminal.composeBar.noPinnedSnippets': 'Pin snippets with + for quick access', 'terminal.composeBar.noMatchingSnippets': 'No matching snippets', 'terminal.composeBar.pinnedCount': '{count} pinned', 'terminal.composeBar.unpinSnippet': 'Remove {label} from quick bar', @@ -195,7 +193,6 @@ export const enTerminalMessages: Messages = { 'terminal.osc7Setup.title': 'Configure directory tracking', 'terminal.osc7Setup.desc': 'Netcatty will add OSC 7 prompt hooks for the current remote user. This helps SFTP follow the terminal directory after sudo or su.', 'terminal.osc7Setup.targets': 'Possible files to update', - 'terminal.osc7Setup.command': 'Command to run', 'terminal.osc7Setup.run': 'Run setup', 'terminal.osc7Setup.running': 'Configuring...', 'terminal.osc7Setup.configured': 'Directory tracking configured', @@ -279,9 +276,6 @@ export const enTerminalMessages: Messages = { 'terminal.themeModal.themeType': '{type} theme', 'terminal.hiddenTheme.title': 'Current hidden theme', 'terminal.hiddenTheme.desc': 'This theme is hidden from manual picks and will be replaced when you choose another theme.', - 'topTabs.toggleTheme.systemExitTitle': 'System theme is active', - 'topTabs.toggleTheme.systemExitMessage': 'Open Settings to choose a fixed Light or Dark theme.', - 'topTabs.toggleTheme.openSettings': 'Open Settings', // Custom Themes 'terminal.customTheme.section': 'Custom Themes', @@ -294,7 +288,6 @@ export const enTerminalMessages: Messages = { 'terminal.customTheme.importDesc': 'Import from iTerm2 color scheme file', 'terminal.customTheme.importError': 'Failed to parse the selected file. Please ensure it is a valid .itermcolors XML file.', 'terminal.customTheme.delete': 'Delete Theme', - 'terminal.customTheme.confirmDelete': 'Confirm Delete', 'terminal.customTheme.name': 'Name', 'terminal.customTheme.namePlaceholder': 'My Custom Theme', 'terminal.customTheme.type': 'Type', @@ -354,10 +347,7 @@ export const enTerminalMessages: Messages = { 'cloudSync.provider.disconnect.cloudRemains': 'Encrypted sync copies may still exist in your {name} storage. To remove them, delete the sync files there. Disconnecting does not clear this device for handover.', 'cloudSync.provider.disconnect.failed': 'Could not finish disconnecting from {name}. Saved connection details may remain. Please try again.', 'cloudSync.provider.webdav': 'WebDAV', - 'cloudSync.provider.webdav.desc': 'Connect to a self-hosted WebDAV endpoint', 'cloudSync.provider.s3': 'S3 Compatible', - 'cloudSync.provider.s3.desc': 'Connect to S3-compatible object storage', - 'cloudSync.provider.comingSoon': 'Coming soon', 'cloudSync.webdav.title': 'WebDAV Settings', 'cloudSync.webdav.desc': 'Configure a WebDAV endpoint for encrypted sync.', 'cloudSync.webdav.endpoint': 'Endpoint URL', @@ -386,20 +376,6 @@ export const enTerminalMessages: Messages = { 'cloudSync.s3.allowInsecure': 'Allow insecure connection (ignore certificate errors)', 'cloudSync.s3.showSecret': 'Show secrets', 'cloudSync.s3.validation.required': 'Endpoint, region, bucket, access key, and secret are required.', - 'cloudSync.smb.title': 'SMB Settings', - 'cloudSync.smb.desc': 'Connect to an SMB/CIFS file share for encrypted sync.', - 'cloudSync.smb.share': 'Share Path', - 'cloudSync.smb.username': 'Username', - 'cloudSync.smb.password': 'Password', - 'cloudSync.smb.domain': 'Domain (optional)', - 'cloudSync.smb.domainPlaceholder': 'e.g., WORKGROUP', - 'cloudSync.smb.port': 'Port (optional)', - 'cloudSync.smb.showSecret': 'Show password', - 'cloudSync.smb.validation.share': 'Share path is required.', - 'cloudSync.smb.validation.port': 'Port must be a number between 1 and 65535.', - 'cloudSync.connect.smb.success': 'SMB connected successfully', - 'cloudSync.connect.smb.failedTitle': 'SMB connection failed', - 'cloudSync.provider.smb': 'SMB Share', 'cloudSync.connect.webdav.success': 'WebDAV connected successfully', 'cloudSync.connect.webdav.failedTitle': 'WebDAV connection failed', 'cloudSync.connect.s3.success': 'S3 connected successfully', @@ -416,7 +392,6 @@ export const enTerminalMessages: Messages = { 'cloudSync.lastSync.minutesAgo': '{minutes} min ago', 'cloudSync.changeKey': 'Change Key', 'cloudSync.providers.title': 'Cloud Providers', - 'cloudSync.syncAll': 'Sync All Connected Providers', 'cloudSync.autoSync.title': 'Auto-sync', 'cloudSync.autoSync.desc': 'Automatically sync when changes are made', 'cloudSync.strategy.title': 'Sync strategy', @@ -481,7 +456,6 @@ export const enTerminalMessages: Messages = { 'cloudSync.localBackups.folderWarning': 'This folder alone is not a complete, portable backup. Deleting or wiping the app profile (userData) may make these restore points unreadable.', 'cloudSync.localBackups.retentionTitle': 'Backup Retention', 'cloudSync.localBackups.retentionDesc': 'Choose how many local backups Netcatty should keep.', - 'cloudSync.localBackups.maxCount': 'Max backups', 'cloudSync.localBackups.maxSaved': 'Saved backup retention: {count}', 'cloudSync.localBackups.maxInvalid': 'Please enter a number between 1 and 100.', 'cloudSync.localBackups.empty': 'No local backups yet.', @@ -604,10 +578,7 @@ export const enTerminalMessages: Messages = { 'cloudSync.clearLocal.toast.desc': 'Local version reset to 0. Sync to download from cloud.', // Keychain - 'keychain.filter.key': 'KEY', - 'keychain.filter.certificate': 'CERTIFICATE', 'keychain.action.generateKey': 'Generate Key', - 'keychain.action.importKey': 'Import Key', 'keychain.action.newIdentity': 'New Identity', 'keychain.action.importCertificate': 'Import Certificate', 'keychain.view.grid': 'Grid', @@ -651,20 +622,8 @@ export const enTerminalMessages: Messages = { 'keychain.export.exporting': 'Exporting...', 'keychain.export.exportAndAttach': 'Export and Attach', 'keychain.export.title': 'Key export', - 'keychain.export.exportToRequired': 'Export to *', - 'keychain.export.selectHostPlaceholder': 'Select a host...', - 'keychain.export.locationLabel': 'Location ~ $1 *', - 'keychain.export.filenameLabel': 'Filename ~ $2 *', - 'keychain.export.advanced': 'Advanced', - 'keychain.export.note.supportsOnly': 'Key export currently supports only', - 'keychain.export.note.systems': 'systems.', - 'keychain.export.note.use': 'Use', - 'keychain.export.note.customize': 'section to customize the export script.', - 'keychain.export.scriptRequired': 'Script *', 'keychain.export.exportToHost': 'Export to host', - 'keychain.export.failedGeneric': 'Export failed: {message}', 'keychain.field.label': 'Label', - 'keychain.field.labelRequired': 'Label *', 'keychain.field.labelPlaceholder': 'Key label', 'keychain.field.privateKeyRequired': 'Private key *', 'keychain.field.publicKey': 'Public key', @@ -700,13 +659,9 @@ export const enTerminalMessages: Messages = { "fido.recovery.usePassword": "Use configured password", "fido.recovery.passwordFallback": "Trying the password configured for this host", "fido.prompt.cancelled": "Security key authentication cancelled.", - 'fido.prompt.touchDone': 'I touched it', 'fido.prompt.timeout': 'FIDO prompt timed out. Try connecting again.', - 'fido.error.opensshMissing': 'OpenSSH with FIDO/libfido2 is required. On macOS: brew install openssh libfido2.', - 'fido.error.agentUnavailable': 'Could not start a FIDO-capable SSH agent.', 'keychain.generate.resident': 'Store credentials on the key', 'keychain.generate.verifyRequired': 'Verify PIN each time', - 'keychain.action.loadResident': 'Load resident keys from security key', 'keychain.generate.keySize': 'Key size', 'keychain.generate.labelPlaceholder': 'Key label', 'keychain.generate.passphrasePlaceholder': 'Passphrase (optional)', @@ -716,7 +671,6 @@ export const enTerminalMessages: Messages = { 'keychain.import.dropHint': 'Drop a key file here', 'keychain.import.importFromFile': 'Import from file', 'keychain.import.saveKey': 'Save Key', - 'keychain.import.importedKeyLabel': 'Imported Key', 'keychain.identity.usernameRequired': 'Username *', 'keychain.identity.method.passwordOnly': 'Password', 'keychain.identity.summary.password': 'Auth password', @@ -725,14 +679,8 @@ export const enTerminalMessages: Messages = { 'keychain.identity.summary.passwordAndKey': 'Auth password and key', 'keychain.identity.summary.passwordAndCertificate': 'Auth password and certificate', 'keychain.identity.summary.none': 'No credentials', - 'keychain.identity.selectCredential': 'Select {kind}', 'keychain.identity.save': 'Save', 'keychain.identity.update': 'Update', - 'keychain.keyDialog.newTitle': 'New Key', - 'keychain.keyDialog.newDesc': 'Add a new SSH key', - 'keychain.keyDialog.editTitle': 'Edit Key', - 'keychain.keyDialog.editDesc': 'Update this SSH key', - 'keychain.keyDialog.updateKey': 'Update Key', // Tabs 'tabs.closeSessionAria': 'Close session', @@ -807,8 +755,6 @@ export const enTerminalMessages: Messages = { 'snippets.search.noResults.desc': 'No scripts or script packages match "{query}". Try a different search term or clear the search to browse.', 'snippets.section.packages': 'Script Packages', 'snippets.section.snippets': 'Scripts', - 'snippets.kind.codeSnippet': 'Code snippet', - 'snippets.kind.automationScript': 'Automation script', 'snippets.package.count': '{count} script(s)', 'snippets.commandFallback': 'Command', 'snippets.view.grid': 'Grid', @@ -840,9 +786,6 @@ export const enTerminalMessages: Messages = { 'snippets.import.modal.multipleFiles': '{count} files selected', 'snippets.import.modal.parsedSummary': '{files} file(s), {total} script(s), {packages} script package(s), {conflicts} duplicate command(s). Host bindings are ignored.', 'snippets.import.modal.confirm': 'Confirm import', - 'snippets.import.conflict.title': 'Import snippets?', - 'snippets.import.conflict.desc': '{file} contains {total} snippet(s). {conflicts} duplicate command(s) already exist.', - 'snippets.import.conflict.hostBindingsNote': 'Host bindings are not imported or exported with snippets.', 'snippets.import.conflict.skip': 'Skip duplicates', 'snippets.import.conflict.overwrite': 'Overwrite duplicates', 'snippets.packageDialog.title': 'New Script Package', @@ -901,9 +844,6 @@ export const enTerminalMessages: Messages = { 'serial.field.customPort': 'Custom Port Path', 'serial.field.namedPipeHint': 'Windows VM console: enter \\\\.\\pipe\\name. The VM must create the pipe as a server. Baud rate and framing are ignored.', 'serial.field.customPortPlaceholder': 'e.g. /dev/ttys001 or COM1', - 'serial.type.hardware': 'Hardware', - 'serial.type.pseudo': 'Pseudo Terminal', - 'serial.type.custom': 'Custom', 'serial.parity.none': 'None', 'serial.parity.even': 'Even', 'serial.parity.odd': 'Odd', @@ -924,7 +864,6 @@ export const enTerminalMessages: Messages = { 'serial.backspace.default': 'Default (DEL, 0x7F)', 'serial.backspace.ctrlH': 'Ctrl+H (BS, 0x08)', 'serial.field.charset': 'Charset', - 'serial.connectionError': 'Failed to connect to serial port', 'serial.field.baudRatePlaceholder': 'Select or enter baud rate...', 'serial.field.baudRateEmpty': 'Enter a custom baud rate', 'serial.field.customBaudRate': 'Using custom baud rate', @@ -943,10 +882,7 @@ export const enTerminalMessages: Messages = { 'keyboard.interactive.title': 'Authentication Required', 'keyboard.interactive.desc': 'The server requires additional authentication.', 'keyboard.interactive.descWithHost': 'The server {hostname} requires additional authentication.', - 'keyboard.interactive.response': 'Response', 'keyboard.interactive.verificationCode': 'Verification code', - 'keyboard.interactive.enterCode': 'Enter verification code', - 'keyboard.interactive.enterResponse': 'Enter response', 'keyboard.interactive.submit': 'Submit', 'keyboard.interactive.verifying': 'Verifying...', 'keyboard.interactive.savePassword': 'Save password', diff --git a/application/i18n/locales/en/vault.ts b/application/i18n/locales/en/vault.ts index 7f1cf9533..0fade0454 100644 --- a/application/i18n/locales/en/vault.ts +++ b/application/i18n/locales/en/vault.ts @@ -19,14 +19,6 @@ export const enVaultMessages: Messages = { 'notes.export.toast.failed': 'Failed to export notes.', 'notes.codeBlock.copied': 'Copied', 'notes.codeBlock.copyFailed': 'Failed to copy code block.', - 'notes.group.prompt': 'Folder path', - 'notes.group.all': 'Notebook', - 'notes.group.ungrouped': 'Ungrouped', - 'notes.section.notebooks': 'Notebook', - 'notes.section.notes': 'Notes', - 'notes.mode.edit': 'Edit', - 'notes.mode.split': 'Split', - 'notes.mode.preview': 'Preview', 'notes.title.placeholder': 'Note title', 'notes.editor.placeholder': 'Write Markdown notes here...', 'notes.editor.unrenderableMarkdown': 'This note contains Markdown the rich editor cannot display (for example unbalanced text). Showing the raw Markdown source instead — the content is intact.', @@ -72,25 +64,18 @@ export const enVaultMessages: Messages = { 'notes.toolbar.divider': 'Divider', 'notes.toolbar.link': 'Insert Link', 'notes.toolbar.image': 'Insert Image', - 'notes.action.pin': 'Pin Note', - 'notes.action.unpin': 'Unpin Note', 'notes.tag.remove': 'Remove tag', 'notes.tag.placeholder': 'Tag name...', 'notes.tag.add': 'Add tag', 'notes.outline.title': 'Table of Contents', - 'notes.outline.titleWithCount': 'Table of Contents ({count})', 'notes.outline.empty': 'No outline headings', 'notes.outline.emptyHint': 'Use # and ## in Markdown to create headings', 'notes.export.share': 'Export & Share', 'notes.export.currentNote': 'Current Note', 'notes.export.exportMarkdown': 'Export as Markdown (.md)', - 'notes.export.exportHtml': 'Export as HTML (.html)', 'notes.export.copyMarkdown': 'Copy Markdown Source', 'notes.export.allNotes': 'All Notes', 'notes.export.exportAllZip': 'Export All as ZIP Archive', - 'notes.export.toast.markdownSuccess': 'Markdown file exported', - 'notes.export.toast.htmlSuccess': 'HTML file exported', - 'notes.export.toast.zipSuccess': 'All notes exported as ZIP backup', // Vault import 'vault.import.title': 'Add data to your vault', @@ -261,7 +246,6 @@ export const enVaultMessages: Messages = { 'pf.tooltip.localDesc': 'Local port forwarding: Access remote services through SSH tunnel', 'pf.tooltip.remoteDesc': 'Remote port forwarding: Expose local services to remote host', 'pf.tooltip.dynamicDesc': 'Dynamic SOCKS proxy: Route traffic through SSH tunnel', - 'pf.deleteActive.title': 'Delete Active Port Forwarding?', 'pf.deleteActive.desc': 'This port forwarding rule "{label}" is currently active. Deleting it will stop the tunnel first.', 'pf.deleteActive.confirm': 'Stop and Delete', 'pf.form.autoStart': 'Auto Start', @@ -295,13 +279,9 @@ export const enVaultMessages: Messages = { 'sftp.columns.actions': 'Actions', 'sftp.sort.directoriesFirst': 'Folders first', 'sftp.emptyDirectory': 'Empty directory', - 'sftp.nav.up': 'Go up', - 'sftp.nav.home': 'Go to home', - 'sftp.nav.refresh': 'Refresh', 'sftp.upload': 'Upload', 'sftp.uploadFiles': 'Upload files', 'sftp.uploadFolder': 'Upload folder', - 'sftp.dragDropToUpload': 'Drag and drop files here to upload', 'sftp.retry': 'Retry', 'sftp.context.open': 'Open', 'sftp.context.navigateTo': 'Navigate to', @@ -340,28 +320,21 @@ export const enVaultMessages: Messages = { 'sftp.copyCurrentPath': 'Copy current path', 'sftp.copyCurrentPath.success': 'Current path copied', 'sftp.copyCurrentPath.error': 'Could not copy current path', - 'sftp.viewMode.label': 'View mode', 'sftp.viewMode.list': 'List view', 'sftp.viewMode.tree': 'Tree view', 'sftp.viewMode.switchToList': 'Switch to list view', 'sftp.viewMode.switchToTree': 'Switch to tree view', - 'sftp.listDensity.compact': 'Compact list', - 'sftp.listDensity.comfortable': 'Comfortable list', 'sftp.listDensity.switchToCompact': 'Switch to compact list', 'sftp.listDensity.switchToComfortable': 'Switch to comfortable list', 'sftp.tree.loadError': 'Failed to load directory', 'sftp.tree.loading': 'Loading...', 'sftp.kind.folder': 'Folder', - 'sftp.context.rename': 'Rename', 'sftp.context.permissions': 'Permissions', - 'sftp.context.delete': 'Delete', 'sftp.context.refresh': 'Refresh', 'sftp.context.uploadFiles': 'Upload File(s)...', 'sftp.context.uploadFilesHere': 'Upload File(s) Here...', 'sftp.context.uploadFolder': 'Upload Folder...', 'sftp.context.uploadFolderHere': 'Upload Folder Here...', - 'sftp.context.downloadSelected': 'Download selected ({count})', - 'sftp.context.deleteSelected': 'Delete selected ({count})', 'sftp.dropFilesHere': 'Drop files here', 'sftp.itemsCount': '{count} items', 'sftp.selectedCount': '{count} selected', @@ -370,8 +343,6 @@ export const enVaultMessages: Messages = { 'sftp.task.waiting': 'Waiting...', 'sftp.transfer.preparing': 'preparing...', 'sftp.status.loading': 'Loading...', - 'sftp.status.uploading': 'Uploading...', - 'sftp.status.ready': 'Ready', 'sftp.transfers': 'Transfers', 'sftp.transfers.active': '{count} active', 'sftp.transfers.clearCompleted': 'Clear completed', @@ -435,7 +406,6 @@ export const enVaultMessages: Messages = { 'sftp.transferCenter.applyAll': 'Apply to all', 'sftp.transfers.resizeNameColumn': 'Resize file name column', 'sftp.transfers.dragToResize': 'Drag to resize', - 'sftp.goUp': 'Go up', 'sftp.goToTerminalCwd': 'Go to terminal directory', 'sftp.locatePathInTerminal': 'Open path in terminal', 'sftp.followTerminalCwd': 'Follow terminal directory', @@ -451,29 +421,22 @@ export const enVaultMessages: Messages = { 'sftp.folderName.placeholder': 'Enter folder name', 'sftp.fileName': 'File name', 'sftp.fileName.placeholder': 'Enter file name', - 'sftp.prompt.newFolderName': 'New folder name?', 'sftp.rename.title': 'Rename', 'sftp.rename.newName': 'New name', 'sftp.rename.placeholder': 'Enter new name', - 'sftp.confirm.deleteOne': 'Delete "{name}"?', - 'sftp.deleteConfirm.single': 'Delete "{name}"?', 'sftp.deleteConfirm.title': 'Delete {count} item(s)?', 'sftp.deleteConfirm.desc': 'This action cannot be undone. The following will be deleted:', 'sftp.deleteConfirm.descSingle': 'This action cannot be undone.', 'sftp.deleteConfirm.host': 'Host', 'sftp.deleteConfirm.path': 'Path', - 'sftp.error.loadFailed': 'Failed to load directory', 'sftp.error.downloadFailed': 'Download failed', 'sftp.error.uploadFailed': 'Upload failed', 'sftp.error.deleteFailed': 'Delete failed', - 'sftp.error.createFolderFailed': 'Failed to create folder', - 'sftp.error.createFileFailed': 'Failed to create file', 'sftp.error.invalidFileName': 'Filename contains invalid characters: {chars}', 'sftp.error.reservedName': 'This filename is reserved by the system', 'sftp.overwrite.title': 'File Already Exists', 'sftp.overwrite.desc': 'A file named "{name}" already exists. Do you want to replace it?', 'sftp.overwrite.confirm': 'Replace', - 'sftp.error.renameFailed': 'Failed to rename', 'sftp.picker.title': 'Select Host', 'sftp.picker.desc': 'Pick a host for the {side} pane', 'sftp.picker.searchPlaceholder': 'Search hosts...', @@ -481,8 +444,6 @@ export const enVaultMessages: Messages = { 'sftp.picker.local.desc': 'Browse local files', 'sftp.picker.local.badge': 'Local', 'sftp.picker.connected.section': 'Connected', - 'sftp.picker.connected.badge': 'Live', - 'sftp.picker.connected.connecting': 'Connecting', 'sftp.picker.noMatch': 'No matching hosts', 'sftp.permissions.title': 'Edit Permissions', 'sftp.permissions.owner': 'Owner', @@ -490,16 +451,12 @@ export const enVaultMessages: Messages = { 'sftp.permissions.others': 'Others', 'sftp.permissions.octal': 'Octal', 'sftp.permissions.symbolic': 'Symbolic', - 'sftp.permissions.success': 'Permissions updated successfully', - 'sftp.permissions.failed': 'Failed to update permissions', 'sftp.pane.local': 'Local', 'sftp.pane.remote': 'Remote', 'sftp.pane.selectHost': 'Select host', 'sftp.pane.selectHostToStart': 'Select a host to start', 'sftp.pane.chooseFilesystem': 'Choose a local or remote filesystem to browse', 'sftp.tabs.addTab': 'Add new tab', - 'sftp.tabs.closeTab': 'Close tab', - 'sftp.tabs.newTab': 'New Tab', 'sftp.tabs.copyDefaultPath': 'Copy tab (default path)', 'sftp.tabs.copyCurrentPath': 'Copy and go to current path', 'sftp.conflict.title': 'File Conflict', @@ -525,47 +482,24 @@ export const enVaultMessages: Messages = { 'sftp.conflict.action.replace': 'Replace', // SFTP Upload Phases - 'sftp.upload.phase.compressing': 'Compressing', - 'sftp.upload.phase.uploading': 'Uploading', - 'sftp.upload.phase.extracting': 'Extracting', - 'sftp.upload.phase.compressed': 'Compressed', // SFTP File Opener 'sftp.context.copyPath': 'Copy file path', 'sftp.context.openWithDefault': 'Open with system default', 'sftp.context.openWith': 'Open with...', 'sftp.context.edit': 'Edit', - 'sftp.context.preview': 'Preview', 'sftp.opener.title': 'Open with', - 'sftp.opener.desc': 'Choose an application to open this file', 'sftp.opener.builtInEditor': 'Built-in Editor', 'sftp.opener.editDescription': 'Edit text files', - 'sftp.opener.builtInImageViewer': 'Built-in Image Viewer', - 'sftp.opener.previewDescription': 'Preview images', 'sftp.opener.systemApp': 'Choose Application...', 'sftp.opener.systemAppDescription': 'Select an application from your computer', - 'sftp.opener.onlySystemApp': 'This file can only be opened with an external application', - 'sftp.opener.noAppsAvailable': 'No applications available', 'sftp.opener.noExtension': 'files without extension', 'sftp.opener.setDefault': 'Always use this for {ext} files', - 'sftp.opener.confirmTitle': 'Set as Default?', - 'sftp.opener.confirmDescription': 'Do you want to always use {app} for {ext} files?', - 'sftp.opener.yesRemember': 'Yes, remember this choice', - 'sftp.opener.justOnce': 'Just this once', - 'sftp.opener.confirm.title': 'Set Default Application', - 'sftp.opener.confirm.desc': 'Do you want to always open .{ext} files with this application?', - 'sftp.editor.title': 'Text Editor', 'sftp.editor.save': 'Save to Remote', 'sftp.editor.saving': 'Saving...', 'sftp.editor.saved': 'Saved successfully', 'sftp.editor.saveFailed': 'Failed to save file', - 'sftp.editor.unsavedChanges': 'You have unsaved changes. Close anyway?', 'sftp.editor.syntaxHighlight': 'Syntax Highlighting', - 'sftp.preview.title': 'Image Preview', - 'sftp.preview.zoomIn': 'Zoom In', - 'sftp.preview.zoomOut': 'Zoom Out', - 'sftp.preview.resetZoom': 'Reset Zoom', - 'sftp.preview.fitToWindow': 'Fit to Window', // Settings > SFTP File Associations 'settings.tab.sftpFileAssociations': 'SFTP', @@ -644,28 +578,16 @@ export const enVaultMessages: Messages = { 'sftp.autoSync.error': 'Failed to sync file: {error}', // SFTP Folder Upload Progress - 'sftp.upload.progress': 'Uploading {current} of {total} files...', - 'sftp.upload.uploading': 'Uploading...', - 'sftp.upload.compressing': 'Compressing...', - 'sftp.upload.extracting': 'Extracting...', - 'sftp.upload.scanning': 'Scanning files...', - 'sftp.upload.completed': 'Completed', - 'sftp.upload.compressed': 'Compressed Transfer', - 'sftp.upload.currentFile': 'Current: {fileName}', 'sftp.upload.cancelled': 'Upload cancelled', 'sftp.upload.noFiles': 'No files to upload', 'sftp.upload.partialSuccess': 'Uploaded {success} file(s); {failed} failed', 'sftp.upload.cancel': 'Cancel', - 'sftp.upload.completedToPath': 'Uploaded to {path}', // SFTP Download - 'sftp.download.completed': 'Downloaded', - 'sftp.download.cancelled': 'Download cancelled', // SFTP Reconnecting 'sftp.reconnecting.title': 'Reconnecting...', 'sftp.reconnecting.desc': 'Connection lost, attempting to reconnect', - 'sftp.reconnected': 'Connection restored', 'sftp.error.reconnectFailed': 'Failed to reconnect. Please try again.', 'sftp.error.connectionLostManual': 'Connection lost. Please reconnect manually.', 'sftp.error.connectionLostReconnecting': 'Connection lost. Reconnecting...', @@ -741,12 +663,6 @@ export const enVaultMessages: Messages = { 'hostDetails.saveAria': 'Save', // Host connection test 'hostConnectionTest.title': 'Test Connection', - 'hostConnectionTest.test': 'Test', - 'hostConnectionTest.chainOf': 'Chain {current} of {total}', - 'hostConnectionTest.success': 'Connection successful', - 'hostConnectionTest.successHint': 'The host accepted your credentials. You can close this window.', - 'hostConnectionTest.connecting': 'Connecting… timeout in {seconds}s', - 'hostConnectionTest.failed': 'Connection failed.', 'hostConnectionTest.retry': 'Retry', 'hostConnectionTest.credentialsUnavailable': 'Saved credentials cannot be decrypted on this device. Re-enter them below.', 'hostDetails.section.address': 'Address', @@ -783,11 +699,8 @@ export const enVaultMessages: Messages = { 'hostDetails.notes.toggle.show': 'Show notes editor', 'hostDetails.notes.toggle.hide': 'Hide notes editor', 'hostDetails.group.placeholder': 'Parent Group', - 'hostDetails.section.credentials': 'Credentials', 'hostDetails.section.portCredentials': 'Port & Credentials', 'hostDetails.section.appearance': 'Appearance', - 'hostDetails.distro.title': 'Linux Distribution', - 'hostDetails.distro.desc': 'Auto-detect on connect, or override the distro icon manually.', 'hostDetails.icon.title': 'Host Icon', 'hostDetails.icon.sectionTitle': 'Color & Icon', 'hostDetails.icon.desc': 'Choose the icon source and color for this host.', @@ -799,7 +712,6 @@ export const enVaultMessages: Messages = { 'hostDetails.icon.mode.custom': 'Custom', 'hostDetails.icon.reset': 'Reset host icon', 'hostDetails.icon.colorLabel': 'Icon color', - 'hostDetails.icon.colorDefault': 'Default', 'hostDetails.icon.colorAuto': 'Automatic', 'hostDetails.icon.colorManual': 'Manual', 'hostDetails.icon.colorChoice': 'Color', @@ -850,7 +762,6 @@ export const enVaultMessages: Messages = { 'hostDetails.distro.mode.auto': 'Auto-detect', 'hostDetails.distro.mode.manual': 'Manual override', 'hostDetails.distro.detectedLabel': 'Current', - 'hostDetails.distro.manualLabel': 'Override', 'hostDetails.distro.pending': 'Detect after first connection', 'hostDetails.distro.unknown': 'Unknown', 'hostDetails.distro.option.linux': 'Generic Linux', @@ -901,7 +812,6 @@ export const enVaultMessages: Messages = { 'hostDetails.auth.mfaFirst': 'Prefer interactive auth', 'hostDetails.auth.mfaFirst.desc': 'For servers that require password and MFA through keyboard-interactive.', 'hostDetails.totp.title': 'Authenticator (TOTP)', - 'hostDetails.totp.enable': 'Save a TOTP secret for this host', 'hostDetails.totp.setup': 'Set up…', 'hostDetails.totp.edit': 'Edit', 'hostDetails.totp.modalTitle': 'Set up authenticator', @@ -1004,10 +914,8 @@ export const enVaultMessages: Messages = { 'hostDetails.jumpHosts.direct': 'Direct', 'hostDetails.jumpHosts.configure': 'Configure Proxy Hosts', 'hostDetails.proxy': 'Proxy via HTTP/SOCKS5/Command', - 'hostDetails.proxy.none': 'None', 'hostDetails.proxy.direct': 'Direct (no proxy)', 'hostDetails.proxy.directHint': 'Does not use a group or global default proxy', - 'hostDetails.proxy.edit': 'Edit Proxy', 'hostDetails.proxy.configure': 'Configure Proxy', 'hostDetails.proxyPanel.title': 'Proxy via HTTP/SOCKS5/Command', 'hostDetails.proxyPanel.hostPlaceholder': 'Proxy host', @@ -1017,7 +925,6 @@ export const enVaultMessages: Messages = { 'hostDetails.proxyPanel.credentials': 'Credentials', 'hostDetails.proxyPanel.usernamePlaceholder': 'Username', 'hostDetails.proxyPanel.passwordPlaceholder': 'Password', - 'hostDetails.proxyPanel.identities': 'Identities', 'hostDetails.proxyPanel.keychainIdentity': 'Keychain identity', 'hostDetails.proxyPanel.manualCredentials': 'Manual credentials', 'hostDetails.proxyPanel.remove': 'Remove Proxy', @@ -1041,8 +948,6 @@ export const enVaultMessages: Messages = { 'hostDetails.envVars.newVariable': 'New Variable', 'hostDetails.envVars.variableName': 'Variable name', 'hostDetails.chain.title': 'Edit Chain', - 'hostDetails.chain.desc': 'Adding another host will create a connection to {host}.', - 'hostDetails.chain.addHost': 'Add a Host', 'hostDetails.chain.target': 'Target', 'hostDetails.chain.availableHosts': 'Available Hosts', 'hostDetails.chain.clear': 'Clear', @@ -1108,28 +1013,14 @@ export const enVaultMessages: Messages = { 'hostDetails.plugin.useSsh': 'Use SSH instead', // Host form (legacy modal) - 'hostForm.title.edit': 'Edit Host', - 'hostForm.title.new': 'New Host', - 'hostForm.desc.edit': 'Update connection details for this host', - 'hostForm.desc.new': 'Create a new SSH host entry', 'hostForm.field.label': 'Label', - 'hostForm.placeholder.label': 'My Production Server', 'hostForm.field.hostname': 'Hostname / IP', - 'hostForm.placeholder.hostname': '192.168.1.1', 'hostForm.field.port': 'Port', 'hostForm.field.username': 'Username', 'hostForm.field.osType': 'OS Type', - 'hostForm.placeholder.selectOs': 'Select OS', 'hostForm.field.group': 'Group', - 'hostForm.placeholder.group': 'e.g. AWS, DigitalOcean', 'hostForm.field.tags': 'Tags', - 'hostForm.placeholder.addTag': 'Add a tag...', - 'hostForm.auth.method': 'Authentication Method', - 'hostForm.auth.password': 'Password', - 'hostForm.auth.sshKey': 'SSH Key', 'hostForm.auth.selectKey': 'Select an SSH Key', - 'hostForm.auth.noKeys': 'No keys available', - 'hostForm.auth.noKeysHint': 'No SSH keys found in Keychain. Please create one first.', 'hostForm.saveHost': 'Save Host', // Connection logs @@ -1148,7 +1039,6 @@ export const enVaultMessages: Messages = { 'logs.action.delete': 'Delete', // Log view - 'logView.customizeAppearance': 'Customize appearance', 'logView.appearance': 'Appearance', 'logView.readOnly': 'Read-only', 'logView.export': 'Export', diff --git a/application/i18n/locales/es/ai.ts b/application/i18n/locales/es/ai.ts index a4ea52551..f63dedc61 100644 --- a/application/i18n/locales/es/ai.ts +++ b/application/i18n/locales/es/ai.ts @@ -748,9 +748,6 @@ export const esAiMessages: Messages = { 'terminal.layer.theme': 'Tema', 'terminal.layer.notes': 'Notas', 'terminal.layer.aiChat': 'Chat de IA', - 'terminal.layer.movePanelLeft': 'Mover panel a la izquierda', - 'terminal.layer.movePanelRight': 'Mover panel a la derecha', - 'terminal.layer.movePanelBottom': 'Mover panel a la parte inferior', 'terminal.layer.choosePanelPosition': 'Cambiar posición', 'terminal.layer.dockLeft': 'Izquierda', 'terminal.layer.dockRight': 'Derecha', @@ -784,19 +781,15 @@ export const esAiMessages: Messages = { 'terminal.layer.hostTree.details.protocol': 'Protocolo', 'terminal.layer.hostTree.details.group': 'Grupo', 'terminal.layer.hostTree.details.tags': 'Etiquetas', - 'terminal.layer.hostTree.details.lastConnected': 'Última conexión', 'topTabs.openQuickSwitcher': 'Abrir selector rápido', 'topTabs.moreTabs': 'Más pestañas', 'topTabs.aiAssistant': 'Asistente de IA', - 'topTabs.newLocalTerminal': 'Nueva terminal local', 'topTabs.controlPanel': 'Controles rápidos', 'topTabs.controlPanel.externalMcp': 'MCP externo', 'topTabs.controlPanel.theme': 'Tema', 'topTabs.controlPanel.theme.light': 'Claro', 'topTabs.controlPanel.theme.dark': 'Oscuro', 'topTabs.controlPanel.theme.system': 'Sistema', - 'topTabs.externalMcp.enable': 'Habilitar MCP externo', - 'topTabs.externalMcp.disable': 'Desactivar MCP externo', 'topTabs.windowOpacity': 'Opacidad de la ventana', 'topTabs.openSettings': 'Abrir Configuración', 'ai.chat.sessionHistory': 'Historial de sesiones', diff --git a/application/i18n/locales/es/core.ts b/application/i18n/locales/es/core.ts index ea23976f2..cc7118fa2 100644 --- a/application/i18n/locales/es/core.ts +++ b/application/i18n/locales/es/core.ts @@ -84,7 +84,6 @@ export const esCoreMessages: Messages = { 'common.edit': 'Editar', 'common.clear': 'Limpiar', 'common.optional': 'Opcional', - 'common.selectPlaceholder': 'Seleccionar...', 'common.add': 'Agregar', 'common.rename': 'Renombrar', 'common.refresh': 'Actualizar', @@ -124,11 +123,9 @@ export const esCoreMessages: Messages = { 'field.label': 'Etiqueta', 'field.type': 'Tipo', 'auth.keyType': 'Tipo {type}', - 'auth.showAllKeys': 'Mostrar todas las claves', // Dialogs / prompts 'confirm.deleteHost': '¿Eliminar el host "{name}"?', - 'confirm.deleteIdentity': '¿Eliminar la identidad "{name}"?', 'confirm.removeProvider': '¿Quitar el proveedor "{name}"?', 'confirm.closeBusyTerminal.title': 'Confirmar cierre', 'confirm.closeBusyTerminal.message': 'El proceso "{command}" aún se está ejecutando y se terminará.', @@ -401,7 +398,6 @@ export const esCoreMessages: Messages = { 'tray.status.inactive': 'Inactivo', 'tray.status.error': 'Error', 'tray.status.unknown': 'Desconocido', - 'tray.recentHosts': 'Hosts recientes', 'tray.empty.title': 'Nada por aquí todavía', 'tray.empty.subtitle': 'Ve a conectarte a un servidor, te extrañan 🚀', 'tray.quit': 'Salir de Netcatty', @@ -460,9 +456,6 @@ export const esCoreMessages: Messages = { 'update.downloadFailed.message': 'No se pudo descargar la actualización. Puedes descargarla manualmente.', 'update.needsSave.title': 'Cambios sin guardar', 'update.needsSave.message': 'Primero guarda los editores abiertos y luego haz clic en Reiniciar ahora de nuevo para instalar la actualización.', - 'update.openReleases': 'Abrir versiones', - 'update.remindLater': 'Recordarme después', - 'update.skipVersion': 'Omitir esta versión', // Settings > Appearance 'settings.appearance.uiTheme': 'Tema de la interfaz', @@ -1083,8 +1076,6 @@ Resalta el panel dividido enfocado: 'settings.shortcuts.binding.sftp-navigate-to': 'Ir al directorio seleccionado', // Context menus / common actions - 'action.newHost': 'Nuevo host', - 'action.newSubfolder': 'Nueva subcarpeta', 'action.copyPublicKey': 'Copiar clave pública', 'action.keyExport': 'Exportar clave', 'action.edit': 'Editar', @@ -1319,12 +1310,9 @@ Resalta el panel dividido enfocado: "settings.plugins.manager.remove": "Desinstalar", "settings.plugins.manager.removeNote": "La desinstalación elimina el código y los datos KV locales. Se conservan los ajustes del usuario, los secretos y los datos auxiliares de sincronización.", "settings.plugins.permissions.statusUnknown": "Estado desconocido", - "plugins.sidebar.extensions": "Páginas de extensiones", "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.extensions": "Extensiones", - "plugins.vault.back": "Volver a hosts", "plugins.interaction.title": "Solicitud de complemento", "plugins.interaction.sharing": "El texto compartido estará disponible para este complemento y sus capacidades autorizadas, incluida la red. Leer no autoriza un nuevo destino de red.", "plugins.interaction.input": "Introducir texto", diff --git a/application/i18n/locales/es/scripts.ts b/application/i18n/locales/es/scripts.ts index d452a6b2d..397339079 100644 --- a/application/i18n/locales/es/scripts.ts +++ b/application/i18n/locales/es/scripts.ts @@ -1,6 +1,5 @@ export const esScriptsMessages = { 'scripts.meta.name': 'Nombre', - 'scripts.meta.language': 'Lenguaje', 'scripts.meta.description': 'Descripción', 'scripts.meta.descriptionPlaceholder': 'Notas opcionales sobre este script', 'scripts.meta.trigger': 'Disparador', @@ -15,7 +14,6 @@ export const esScriptsMessages = { 'scripts.actions.openEditor': 'Abrir editor', 'scripts.actions.openEditorHint': 'Editar el script en una ventana más grande', 'scripts.editor.modalTitle': 'Editor de scripts', - 'scripts.editor.modalSubtitle': 'Edita los metadatos y el código del script en un espacio de trabajo más amplio.', 'scripts.editor.lineCount': '{count} líneas', 'scripts.editor.resize': 'Redimensionar el editor', 'scripts.targets.hint': 'Los grupos seleccionados se resuelven dinámicamente, por lo que los hosts agregados después se incluyen automáticamente.', @@ -86,17 +84,13 @@ export const esScriptsMessages = { 'scripts.dialog.retry': 'Reintentar', 'scripts.dialog.skip': 'Omitir', 'scripts.dialog.abort': 'Abortar', - 'scripts.running.stepProgress': 'Paso {current} / {total}', 'scripts.running.determinateProgress': '{label} {current}/{total}', 'scripts.running.progressFallback': 'Progreso', 'scripts.running.operationsCount': '{count} operaciones', 'scripts.running.opsPrefix': '', 'scripts.running.opsSuffix': ' operaciones', - 'scripts.running.elapsedLabel': 'Transcurrido', 'scripts.running.lastSentLabel': 'Enviado:', 'scripts.running.elapsed': '{elapsed}', - 'scripts.running.completedSummary': 'Completado · {count} operaciones · {elapsed}', - 'scripts.running.dismissHint': 'Toca cerrar para descartar', 'scripts.running.dismiss': 'Cerrar', 'scripts.running.viewLogs': 'Ver registros', 'scripts.running.logTitle': '{name} · Registro de ejecución', @@ -111,26 +105,12 @@ export const esScriptsMessages = { 'vault.nav.scripts': 'Scripts', 'snippets.action.newScript': 'Nuevo script de automatización', 'hostDetails.section.automation': 'Automatización', - 'hostDetails.automation.loginScript': 'Script de inicio de sesión', - 'hostDetails.automation.loginScriptPlaceholder': 'Selecciona un script', - 'hostDetails.automation.none': 'Ninguno', - 'hostDetails.automation.outputTriggers': 'Disparadores de salida', - 'hostDetails.automation.addTrigger': 'Agregar disparador', - 'hostDetails.automation.triggerPatternPlaceholder': 'Patrón de regex', - 'hostDetails.automation.linkedScripts': 'Scripts vinculados', - 'hostDetails.automation.linkedScriptsEmpty': 'Aún no hay scripts vinculados a este host.', - 'hostDetails.automation.linkScriptPlaceholder': 'Vincular script existente…', - 'hostDetails.automation.unlink': 'Desvincular', - 'hostDetails.automation.equivalenceHint': 'Los vínculos agregan este host a la lista de destinos del script en Scripts. Ambas vistas se mantienen sincronizadas.', 'hostDetails.automation.queueHint': 'Los scripts se ejecutan en orden cuando este host se conecta. Los scripts globales se ejecutan primero, luego esta cola.', 'hostDetails.automation.globalScripts': 'Scripts de conexión globales', 'hostDetails.automation.globalScriptsHint': 'Se ejecutan primero en cada conexión. Reordena según el orden de clasificación de la biblioteca de Scripts.', 'hostDetails.automation.connectQueue': 'Cola de ejecución de este host', 'hostDetails.automation.connectQueueEmpty': 'Aún no hay scripts de conexión en cola para este host.', 'hostDetails.automation.addToQueuePlaceholder': 'Agregar script a la cola…', - 'hostDetails.automation.moveUp': 'Subir', - 'hostDetails.automation.moveDown': 'Bajar', 'hostDetails.automation.removeFromQueue': 'Quitar de la cola', 'hostDetails.automation.dragHandle': 'Arrastra para reordenar', - 'hostDetails.automation.queueDragHint': 'Arrastra los elementos para reordenar la cola de conexión.', }; \ No newline at end of file diff --git a/application/i18n/locales/es/systemManager.ts b/application/i18n/locales/es/systemManager.ts index 5e60acf44..f332993f8 100644 --- a/application/i18n/locales/es/systemManager.ts +++ b/application/i18n/locales/es/systemManager.ts @@ -14,13 +14,11 @@ export const esSystemManagerMessages: Messages = { 'systemManager.tabs.docker': 'Docker', 'systemManager.tabs.gpu': 'GPU', 'systemManager.tabs.ariaLabel': 'Secciones del administrador del sistema', - 'systemManager.popup.loading': 'Abriendo terminal…', 'systemManager.popup.startupFailed': 'El comando de inicio no se completó correctamente. Verifica que el destino siga disponible e inténtalo de nuevo.', 'systemManager.errors.loadProcesses': 'No se pudieron cargar los procesos', 'systemManager.errors.loadTmux': 'No se pudieron cargar las sesiones de tmux', 'systemManager.errors.loadTmuxWindows': 'No se pudieron cargar las ventanas de tmux', - 'systemManager.errors.loadTmuxPanes': 'No se pudieron cargar los paneles de tmux', 'systemManager.errors.loadTmuxClients': 'No se pudieron cargar los clientes de tmux', 'systemManager.errors.actionFailed': 'La acción falló', 'systemManager.errors.loadDocker': 'No se pudieron cargar los contenedores', @@ -28,7 +26,6 @@ export const esSystemManagerMessages: Messages = { 'systemManager.errors.loadDockerImages': 'No se pudieron cargar las imágenes', 'systemManager.errors.loadKubernetes': 'No se pudieron cargar los recursos de Kubernetes', 'systemManager.errors.loadPods': 'No se pudieron cargar los pods', - 'systemManager.errors.loadOverview': 'No se pudo cargar el resumen del sistema', 'systemManager.errors.loadGpu': 'No se pudieron cargar las estadísticas de GPU / NPU', 'systemManager.errors.loadPorts': 'No se pudieron cargar los puertos en escucha', 'systemManager.errors.loadServices': 'No se pudieron cargar los servicios de systemd', @@ -65,13 +62,10 @@ export const esSystemManagerMessages: Messages = { 'systemManager.overview.noTopProcesses': 'Sin datos de procesos', 'systemManager.processes.search': 'Buscar procesos…', - 'systemManager.processes.command': 'Comando', - 'systemManager.processes.user': 'Usuario', 'systemManager.processes.term': 'Terminar', 'systemManager.processes.kill': 'Forzar cierre', 'systemManager.processes.stop': 'Detener (SIGSTOP)', 'systemManager.processes.cont': 'Continuar (SIGCONT)', - 'systemManager.processes.hup': 'Colgar (SIGHUP)', 'systemManager.processes.renice': 'Renice', 'systemManager.processes.renicePrompt': 'Valor de nice (-20 a 19)', 'systemManager.processes.reniceInvalid': 'El valor de nice debe estar entre -20 y 19', @@ -86,7 +80,6 @@ export const esSystemManagerMessages: Messages = { 'systemManager.processes.stat': 'Estado', 'systemManager.processes.meta': '{{count}} proceso(s)', 'systemManager.processes.loading': 'Cargando procesos…', - 'systemManager.processes.loadingMore': 'Cargando más procesos…', 'systemManager.processes.state.running': 'En ejecución', 'systemManager.processes.state.sleeping': 'En reposo', 'systemManager.processes.state.stopped': 'Detenido', @@ -124,12 +117,9 @@ export const esSystemManagerMessages: Messages = { 'systemManager.tmux.attached': 'Conectada', 'systemManager.tmux.detached': 'Desacoplada', 'systemManager.tmux.windows': '{{count}} ventana(s)', - 'systemManager.tmux.created': 'Creada', - 'systemManager.tmux.activity': 'Actividad', 'systemManager.tmux.rename': 'Renombrar', 'systemManager.tmux.detach': 'Desacoplar todo', 'systemManager.tmux.killSession': 'Terminar sesión', - 'systemManager.tmux.killServer': 'Terminar servidor', 'systemManager.tmux.loadingDetails': 'Cargando detalles…', 'systemManager.tmux.clients': 'Clientes conectados', 'systemManager.tmux.windowList': 'Ventanas', @@ -140,31 +130,17 @@ export const esSystemManagerMessages: Messages = { 'systemManager.docker.unavailable': 'No se detectó ningún runtime de contenedores (Docker, Podman, nerdctl o kubectl) en este host', 'systemManager.tmux.windowsMismatch': 'La sesión reporta {{count}} ventana(s), pero list-windows no devolvió ninguna', 'systemManager.tmux.lastCommand': 'último comando: {{command}}', - 'systemManager.tmux.noPanes': 'No hay paneles', - 'systemManager.tmux.panes': '{{count}} panel(es)', - 'systemManager.tmux.active': 'activo', 'systemManager.tmux.unnamedWindow': 'Ventana sin nombre', - 'systemManager.tmux.unnamedPane': 'Panel sin nombre', 'systemManager.tmux.attachWindow': 'Conectar a la ventana', - 'systemManager.tmux.selectWindow': 'Seleccionar ventana', 'systemManager.tmux.killWindow': 'Terminar ventana', - 'systemManager.tmux.killPane': 'Terminar panel', - 'systemManager.tmux.splitHorizontal': 'Dividir horizontal', - 'systemManager.tmux.splitVertical': 'Dividir vertical', - 'systemManager.tmux.sendKeys': 'Enviar teclas', - 'systemManager.tmux.sendKeysTo': 'Enviar teclas a la ventana {{window}} panel {{pane}}', - 'systemManager.tmux.sendKeysPlaceholder': 'Comando o texto…', 'systemManager.tmux.renameSessionPrompt': 'Renombrar sesión', 'systemManager.tmux.renameWindowPrompt': 'Renombrar ventana', 'systemManager.tmux.windowName': 'Nombre de la ventana', 'systemManager.tmux.confirmKillSession': '¿Terminar la sesión de tmux "{{name}}"?', 'systemManager.tmux.confirmDetachSession': '¿Desacoplar todos los clientes de "{{name}}"?', 'systemManager.tmux.confirmKillWindow': '¿Terminar la ventana "{{name}}"?', - 'systemManager.tmux.confirmKillPane': '¿Terminar el panel #{{index}}?', - 'systemManager.tmux.confirmKillServer': '¿Terminar el servidor de tmux? Se terminarán todas las sesiones.', 'systemManager.tmux.meta': '{{count}} sesión(es)', - 'systemManager.docker.title': 'Contenedores', 'systemManager.docker.subTabs.containers': 'Contenedores', 'systemManager.docker.subTabs.images': 'Imágenes', 'systemManager.docker.empty': 'No se encontraron contenedores', @@ -177,7 +153,6 @@ export const esSystemManagerMessages: Messages = { 'systemManager.docker.filter.paused': 'En pausa', 'systemManager.docker.shell': 'Shell', 'systemManager.docker.logs': 'Registros', - 'systemManager.docker.details': 'Detalles', 'systemManager.docker.inspect': 'Inspeccionar', 'systemManager.docker.imageInspect': 'Inspección de imagen', 'systemManager.docker.confirmRemove': '¿Eliminar este contenedor?', diff --git a/application/i18n/locales/es/terminal.ts b/application/i18n/locales/es/terminal.ts index be1b05dc1..fb3b9f9e5 100644 --- a/application/i18n/locales/es/terminal.ts +++ b/application/i18n/locales/es/terminal.ts @@ -53,7 +53,6 @@ export const esTerminalMessages: Messages = { 'terminal.toolbar.availableAfterConnect': 'Disponible después de conectar', 'terminal.toolbar.sendYmodem': 'Enviar con YMODEM', 'terminal.toolbar.receiveYmodem': 'Recibir con YMODEM', - 'terminal.toolbar.sftp': 'SFTP', 'terminal.toolbar.more': 'Más acciones', 'terminal.toolbar.scripts': 'Scripts', 'terminal.toolbar.history': 'Historial de comandos', @@ -101,7 +100,6 @@ export const esTerminalMessages: Messages = { 'terminal.composeBar.resize': 'Cambiar la altura de la barra de redacción', 'terminal.composeBar.manageSnippets': 'Administrar snippets rápidos', 'terminal.composeBar.searchSnippets': 'Buscar snippets...', - 'terminal.composeBar.noPinnedSnippets': 'Fija snippets con + para acceso rápido', 'terminal.composeBar.noMatchingSnippets': 'No hay snippets que coincidan', 'terminal.composeBar.pinnedCount': '{count} fijados', 'terminal.composeBar.unpinSnippet': 'Quitar {label} de la barra rápida', @@ -195,7 +193,6 @@ export const esTerminalMessages: Messages = { 'terminal.osc7Setup.title': 'Configurar seguimiento de directorio', 'terminal.osc7Setup.desc': 'Netcatty agregará hooks de prompt OSC 7 para el usuario remoto actual. Esto ayuda a que SFTP siga el directorio de la terminal después de sudo o su.', 'terminal.osc7Setup.targets': 'Posibles archivos a actualizar', - 'terminal.osc7Setup.command': 'Comando a ejecutar', 'terminal.osc7Setup.run': 'Ejecutar configuración', 'terminal.osc7Setup.running': 'Configurando...', 'terminal.osc7Setup.configured': 'Seguimiento de directorio configurado', @@ -279,9 +276,6 @@ export const esTerminalMessages: Messages = { 'terminal.themeModal.themeType': 'Tema {type}', 'terminal.hiddenTheme.title': 'Tema oculto actual', 'terminal.hiddenTheme.desc': 'Este tema está oculto de la selección manual y se reemplazará cuando elijas otro tema.', - 'topTabs.toggleTheme.systemExitTitle': 'El tema del sistema está activo', - 'topTabs.toggleTheme.systemExitMessage': 'Abre Configuración para elegir un tema fijo de Claro u Oscuro.', - 'topTabs.toggleTheme.openSettings': 'Abrir Configuración', // Custom Themes 'terminal.customTheme.section': 'Temas personalizados', @@ -294,7 +288,6 @@ export const esTerminalMessages: Messages = { 'terminal.customTheme.importDesc': 'Importar desde archivo de esquema de color de iTerm2', 'terminal.customTheme.importError': 'No se pudo analizar el archivo seleccionado. Asegúrate de que sea un archivo XML .itermcolors válido.', 'terminal.customTheme.delete': 'Eliminar tema', - 'terminal.customTheme.confirmDelete': 'Confirmar eliminación', 'terminal.customTheme.name': 'Nombre', 'terminal.customTheme.namePlaceholder': 'Mi tema personalizado', 'terminal.customTheme.type': 'Tipo', @@ -354,10 +347,7 @@ export const esTerminalMessages: Messages = { 'cloudSync.provider.disconnect.cloudRemains': 'Las copias de sincronización cifradas pueden seguir en tu almacenamiento de {name}. Para eliminarlas, borra los archivos de sincronización allí. Desconectar no prepara este dispositivo para entregarlo a otra persona.', 'cloudSync.provider.disconnect.failed': 'No se pudo completar la desconexión de {name}. Los datos de conexión guardados podrían permanecer. Inténtalo de nuevo.', 'cloudSync.provider.webdav': 'WebDAV', - 'cloudSync.provider.webdav.desc': 'Conectar a un endpoint WebDAV autoalojado', 'cloudSync.provider.s3': 'Compatible con S3', - 'cloudSync.provider.s3.desc': 'Conectar a almacenamiento de objetos compatible con S3', - 'cloudSync.provider.comingSoon': 'Próximamente', 'cloudSync.webdav.title': 'Configuración de WebDAV', 'cloudSync.webdav.desc': 'Configura un endpoint WebDAV para la sincronización cifrada.', 'cloudSync.webdav.endpoint': 'URL del endpoint', @@ -386,20 +376,6 @@ export const esTerminalMessages: Messages = { 'cloudSync.s3.allowInsecure': 'Permitir conexión insegura (ignorar errores de certificado)', 'cloudSync.s3.showSecret': 'Mostrar secretos', 'cloudSync.s3.validation.required': 'Endpoint, región, bucket, clave de acceso y secreto son obligatorios.', - 'cloudSync.smb.title': 'Configuración de SMB', - 'cloudSync.smb.desc': 'Conéctate a un recurso compartido de archivos SMB/CIFS para la sincronización cifrada.', - 'cloudSync.smb.share': 'Ruta del recurso compartido', - 'cloudSync.smb.username': 'Nombre de usuario', - 'cloudSync.smb.password': 'Contraseña', - 'cloudSync.smb.domain': 'Dominio (opcional)', - 'cloudSync.smb.domainPlaceholder': 'p. ej., WORKGROUP', - 'cloudSync.smb.port': 'Puerto (opcional)', - 'cloudSync.smb.showSecret': 'Mostrar contraseña', - 'cloudSync.smb.validation.share': 'La ruta del recurso compartido es obligatoria.', - 'cloudSync.smb.validation.port': 'El puerto debe ser un número entre 1 y 65535.', - 'cloudSync.connect.smb.success': 'SMB se conectó correctamente', - 'cloudSync.connect.smb.failedTitle': 'Falló la conexión a SMB', - 'cloudSync.provider.smb': 'Recurso compartido SMB', 'cloudSync.connect.webdav.success': 'WebDAV se conectó correctamente', 'cloudSync.connect.webdav.failedTitle': 'Falló la conexión a WebDAV', 'cloudSync.connect.s3.success': 'S3 se conectó correctamente', @@ -416,7 +392,6 @@ export const esTerminalMessages: Messages = { 'cloudSync.lastSync.minutesAgo': 'Hace {minutes} min', 'cloudSync.changeKey': 'Cambiar clave', 'cloudSync.providers.title': 'Proveedores de nube', - 'cloudSync.syncAll': 'Sincronizar todos los proveedores conectados', 'cloudSync.autoSync.title': 'Sincronización automática', 'cloudSync.autoSync.desc': 'Sincronizar automáticamente cuando se realicen cambios', 'cloudSync.strategy.title': 'Estrategia de sincronización', @@ -481,7 +456,6 @@ export const esTerminalMessages: Messages = { 'cloudSync.localBackups.folderWarning': 'Esta carpeta por sí sola no es una copia de seguridad completa y portátil. Eliminar o vaciar el perfil de la aplicación (userData) puede impedir la lectura de estos puntos de restauración.', 'cloudSync.localBackups.retentionTitle': 'Retención de copias de seguridad', 'cloudSync.localBackups.retentionDesc': 'Elige cuántas copias de seguridad locales debe conservar Netcatty.', - 'cloudSync.localBackups.maxCount': 'Copias máximas', 'cloudSync.localBackups.maxSaved': 'Retención de copia guardada: {count}', 'cloudSync.localBackups.maxInvalid': 'Ingresa un número entre 1 y 100.', 'cloudSync.localBackups.empty': 'Aún no hay copias de seguridad locales.', @@ -604,10 +578,7 @@ export const esTerminalMessages: Messages = { 'cloudSync.clearLocal.toast.desc': 'Versión local restablecida a 0. Sincroniza para descargar desde la nube.', // Keychain - 'keychain.filter.key': 'CLAVE', - 'keychain.filter.certificate': 'CERTIFICADO', 'keychain.action.generateKey': 'Generar clave', - 'keychain.action.importKey': 'Importar clave', 'keychain.action.newIdentity': 'Nueva identidad', 'keychain.action.importCertificate': 'Importar certificado', 'keychain.view.grid': 'Cuadrícula', @@ -651,20 +622,8 @@ export const esTerminalMessages: Messages = { 'keychain.export.exporting': 'Exportando...', 'keychain.export.exportAndAttach': 'Exportar y adjuntar', 'keychain.export.title': 'Exportación de clave', - 'keychain.export.exportToRequired': 'Exportar a *', - 'keychain.export.selectHostPlaceholder': 'Selecciona un host...', - 'keychain.export.locationLabel': 'Ubicación ~ $1 *', - 'keychain.export.filenameLabel': 'Nombre de archivo ~ $2 *', - 'keychain.export.advanced': 'Avanzado', - 'keychain.export.note.supportsOnly': 'La exportación de claves actualmente solo admite', - 'keychain.export.note.systems': 'sistemas.', - 'keychain.export.note.use': 'Usa la', - 'keychain.export.note.customize': 'sección para personalizar el script de exportación.', - 'keychain.export.scriptRequired': 'Script *', 'keychain.export.exportToHost': 'Exportar al host', - 'keychain.export.failedGeneric': 'Falló la exportación: {message}', 'keychain.field.label': 'Etiqueta', - 'keychain.field.labelRequired': 'Etiqueta *', 'keychain.field.labelPlaceholder': 'Etiqueta de la clave', 'keychain.field.privateKeyRequired': 'Clave privada *', 'keychain.field.publicKey': 'Clave pública', @@ -679,7 +638,6 @@ export const esTerminalMessages: Messages = { 'keychain.import.dropHint': 'Suelta un archivo de clave aquí', 'keychain.import.importFromFile': 'Importar desde archivo', 'keychain.import.saveKey': 'Guardar clave', - 'keychain.import.importedKeyLabel': 'Clave importada', 'keychain.identity.usernameRequired': 'Nombre de usuario *', 'keychain.identity.method.passwordOnly': 'Contraseña', 'keychain.identity.summary.password': 'Contraseña de autenticación', @@ -688,14 +646,8 @@ export const esTerminalMessages: Messages = { 'keychain.identity.summary.passwordAndKey': 'Contraseña y clave de autenticación', 'keychain.identity.summary.passwordAndCertificate': 'Contraseña y certificado de autenticación', 'keychain.identity.summary.none': 'Sin credenciales', - 'keychain.identity.selectCredential': 'Seleccionar {kind}', 'keychain.identity.save': 'Guardar', 'keychain.identity.update': 'Actualizar', - 'keychain.keyDialog.newTitle': 'Nueva clave', - 'keychain.keyDialog.newDesc': 'Agregar una nueva clave SSH', - 'keychain.keyDialog.editTitle': 'Editar clave', - 'keychain.keyDialog.editDesc': 'Actualizar esta clave SSH', - 'keychain.keyDialog.updateKey': 'Actualizar clave', 'keychain.generate.standardKeys': 'Claves estándar', 'keychain.generate.securityKeys': 'Llaves de seguridad · FIDO2', 'keychain.generate.residentDesc': 'Permite recuperar las credenciales desde esta llave de seguridad.', @@ -704,7 +656,6 @@ export const esTerminalMessages: Messages = { 'keychain.generate.fidoHint': 'Conecta una llave de seguridad FIDO2. Es posible que se te solicite su PIN o un toque.', 'keychain.generate.resident': 'Guardar las credenciales en la llave', 'keychain.generate.verifyRequired': 'Verificar el PIN cada vez', - 'keychain.action.loadResident': 'Cargar claves residentes desde la llave de seguridad', // FIDO2 security key prompts and recovery states 'fido.prompt.pinTouchDesc': 'Ingresa tu PIN y luego toca la llave para confirmar.', @@ -720,7 +671,6 @@ export const esTerminalMessages: Messages = { 'fido.prompt.touchWaiting': 'Esperando tu llave…', 'fido.prompt.touchAutomatic': 'Continúa automáticamente después de que la toques', 'fido.prompt.cancelled': 'Se canceló la autenticación con llave de seguridad.', - 'fido.prompt.touchDone': 'Ya la toqué', 'fido.prompt.timeout': 'El aviso de FIDO agotó el tiempo de espera. Intenta conectarte de nuevo.', 'fido.recovery.device-unavailable.title': 'Conecta la llave de seguridad correspondiente', 'fido.recovery.device-unavailable.desc': 'Conecta el dispositivo que contiene la credencial de esta llave y vuelve a intentarlo.', @@ -733,8 +683,6 @@ export const esTerminalMessages: Messages = { 'fido.recovery.retry': 'Reintentar verificación', 'fido.recovery.usePassword': 'Usar la contraseña configurada', 'fido.recovery.passwordFallback': 'Probando la contraseña configurada para este host', - 'fido.error.opensshMissing': 'Se requiere OpenSSH con FIDO/libfido2. En macOS: brew install openssh libfido2.', - 'fido.error.agentUnavailable': 'No se pudo iniciar un agente SSH compatible con FIDO.', // Tabs 'tabs.closeSessionAria': 'Cerrar sesión', @@ -809,8 +757,6 @@ export const esTerminalMessages: Messages = { 'snippets.search.noResults.desc': 'Ningún script o paquete de scripts coincide con "{query}". Prueba con otro término de búsqueda o limpia la búsqueda para explorar.', 'snippets.section.packages': 'Paquetes de scripts', 'snippets.section.snippets': 'Scripts', - 'snippets.kind.codeSnippet': 'Snippet de código', - 'snippets.kind.automationScript': 'Script de automatización', 'snippets.package.count': '{count} script(s)', 'snippets.commandFallback': 'Comando', 'snippets.view.grid': 'Cuadrícula', @@ -842,9 +788,6 @@ export const esTerminalMessages: Messages = { 'snippets.import.modal.multipleFiles': '{count} archivos seleccionados', 'snippets.import.modal.parsedSummary': '{files} archivo(s), {total} script(s), {packages} paquete(s) de scripts, {conflicts} comando(s) duplicado(s). Las vinculaciones de host se ignoran.', 'snippets.import.modal.confirm': 'Confirmar importación', - 'snippets.import.conflict.title': '¿Importar snippets?', - 'snippets.import.conflict.desc': '{file} contiene {total} snippet(s). Ya existen {conflicts} comando(s) duplicado(s).', - 'snippets.import.conflict.hostBindingsNote': 'Las vinculaciones de host no se importan ni se exportan con los snippets.', 'snippets.import.conflict.skip': 'Omitir duplicados', 'snippets.import.conflict.overwrite': 'Sobrescribir duplicados', 'snippets.packageDialog.title': 'Nuevo paquete de scripts', @@ -903,9 +846,6 @@ export const esTerminalMessages: Messages = { 'serial.field.customPort': 'Ruta de puerto personalizada', 'serial.field.namedPipeHint': 'Consola de VM en Windows: introduce \\\\.\\pipe\\name. La VM debe crear la canalización como servidor. Se ignoran la velocidad y la trama.', 'serial.field.customPortPlaceholder': 'p. ej., /dev/ttys001 o COM1', - 'serial.type.hardware': 'Hardware', - 'serial.type.pseudo': 'Pseudoterminal', - 'serial.type.custom': 'Personalizado', 'serial.parity.none': 'Ninguna', 'serial.parity.even': 'Par', 'serial.parity.odd': 'Impar', @@ -926,7 +866,6 @@ export const esTerminalMessages: Messages = { 'serial.backspace.default': 'Predeterminado (DEL, 0x7F)', 'serial.backspace.ctrlH': 'Ctrl+H (BS, 0x08)', 'serial.field.charset': 'Codificación de caracteres', - 'serial.connectionError': 'No se pudo conectar al puerto serial', 'serial.field.baudRatePlaceholder': 'Selecciona o ingresa la velocidad de baudios...', 'serial.field.baudRateEmpty': 'Ingresa una velocidad de baudios personalizada', 'serial.field.customBaudRate': 'Usando velocidad de baudios personalizada', @@ -945,10 +884,7 @@ export const esTerminalMessages: Messages = { 'keyboard.interactive.title': 'Se requiere autenticación', 'keyboard.interactive.desc': 'El servidor requiere autenticación adicional.', 'keyboard.interactive.descWithHost': 'El servidor {hostname} requiere autenticación adicional.', - 'keyboard.interactive.response': 'Respuesta', 'keyboard.interactive.verificationCode': 'Código de verificación', - 'keyboard.interactive.enterCode': 'Ingresa el código de verificación', - 'keyboard.interactive.enterResponse': 'Ingresa la respuesta', 'keyboard.interactive.submit': 'Enviar', 'keyboard.interactive.verifying': 'Verificando...', 'keyboard.interactive.savePassword': 'Guardar contraseña', diff --git a/application/i18n/locales/es/vault.ts b/application/i18n/locales/es/vault.ts index 7becd503d..3f5438b37 100644 --- a/application/i18n/locales/es/vault.ts +++ b/application/i18n/locales/es/vault.ts @@ -19,14 +19,6 @@ export const esVaultMessages: Messages = { 'notes.export.toast.failed': 'No se pudieron exportar las notas.', 'notes.codeBlock.copied': 'Copiado', 'notes.codeBlock.copyFailed': 'No se pudo copiar el bloque de código.', - 'notes.group.prompt': 'Ruta de la carpeta', - 'notes.group.all': 'Cuaderno', - 'notes.group.ungrouped': 'Sin grupo', - 'notes.section.notebooks': 'Cuaderno', - 'notes.section.notes': 'Notas', - 'notes.mode.edit': 'Editar', - 'notes.mode.split': 'Dividir', - 'notes.mode.preview': 'Vista previa', 'notes.title.placeholder': 'Título de la nota', 'notes.editor.placeholder': 'Escribe notas Markdown aquí...', 'notes.editor.unrenderableMarkdown': 'Esta nota contiene Markdown que el editor enriquecido no puede mostrar (por ejemplo, etiquetas sin cerrar como ). Se muestra el origen Markdown sin cambios: el contenido está intacto.', @@ -72,25 +64,18 @@ export const esVaultMessages: Messages = { 'notes.toolbar.divider': 'Línea divisoria', 'notes.toolbar.link': 'Insertar enlace', 'notes.toolbar.image': 'Insertar imagen', - 'notes.action.pin': 'Fijar nota', - 'notes.action.unpin': 'Desfijar nota', 'notes.tag.remove': 'Eliminar etiqueta', 'notes.tag.placeholder': 'Nombre de etiqueta...', 'notes.tag.add': 'Añadir etiqueta', 'notes.outline.title': 'Índice de contenido', - 'notes.outline.titleWithCount': 'Índice de contenido ({count})', 'notes.outline.empty': 'Sin encabezados de esquema', 'notes.outline.emptyHint': 'Use # y ## en Markdown para crear encabezados', 'notes.export.share': 'Exportar y compartir', 'notes.export.currentNote': 'Nota actual', 'notes.export.exportMarkdown': 'Exportar como Markdown (.md)', - 'notes.export.exportHtml': 'Exportar como HTML (.html)', 'notes.export.copyMarkdown': 'Copiar código Markdown', 'notes.export.allNotes': 'Todas las notas', 'notes.export.exportAllZip': 'Exportar todo como archivo ZIP', - 'notes.export.toast.markdownSuccess': 'Archivo Markdown exportado', - 'notes.export.toast.htmlSuccess': 'Archivo HTML exportado', - 'notes.export.toast.zipSuccess': 'Todas las notas exportadas como copia de seguridad ZIP', // Vault import 'vault.import.title': 'Agrega datos a tu Vault', @@ -261,7 +246,6 @@ export const esVaultMessages: Messages = { 'pf.tooltip.localDesc': 'Reenvío de puerto local: accede a servicios remotos a través del túnel SSH', 'pf.tooltip.remoteDesc': 'Reenvío de puerto remoto: expone servicios locales al host remoto', 'pf.tooltip.dynamicDesc': 'Proxy SOCKS dinámico: enruta el tráfico a través del túnel SSH', - 'pf.deleteActive.title': '¿Eliminar el reenvío de puertos activo?', 'pf.deleteActive.desc': 'Esta regla de reenvío de puertos "{label}" está activa actualmente. Eliminarla primero detendrá el túnel.', 'pf.deleteActive.confirm': 'Detener y eliminar', 'pf.form.autoStart': 'Inicio automático', @@ -295,13 +279,9 @@ export const esVaultMessages: Messages = { 'sftp.columns.actions': 'Acciones', 'sftp.sort.directoriesFirst': 'Carpetas primero', 'sftp.emptyDirectory': 'Directorio vacío', - 'sftp.nav.up': 'Subir un nivel', - 'sftp.nav.home': 'Ir al inicio', - 'sftp.nav.refresh': 'Actualizar', 'sftp.upload': 'Subir', 'sftp.uploadFiles': 'Subir archivos', 'sftp.uploadFolder': 'Subir carpeta', - 'sftp.dragDropToUpload': 'Arrastra y suelta archivos aquí para subirlos', 'sftp.retry': 'Reintentar', 'sftp.context.open': 'Abrir', 'sftp.context.navigateTo': 'Navegar a', @@ -340,28 +320,21 @@ export const esVaultMessages: Messages = { 'sftp.copyCurrentPath': 'Copiar ruta actual', 'sftp.copyCurrentPath.success': 'Ruta actual copiada', 'sftp.copyCurrentPath.error': 'No se pudo copiar la ruta actual', - 'sftp.viewMode.label': 'Modo de vista', 'sftp.viewMode.list': 'Vista de lista', 'sftp.viewMode.tree': 'Vista de árbol', 'sftp.viewMode.switchToList': 'Cambiar a vista de lista', 'sftp.viewMode.switchToTree': 'Cambiar a vista de árbol', - 'sftp.listDensity.compact': 'Lista compacta', - 'sftp.listDensity.comfortable': 'Lista cómoda', 'sftp.listDensity.switchToCompact': 'Cambiar a lista compacta', 'sftp.listDensity.switchToComfortable': 'Cambiar a lista cómoda', 'sftp.tree.loadError': 'No se pudo cargar el directorio', 'sftp.tree.loading': 'Cargando...', 'sftp.kind.folder': 'Carpeta', - 'sftp.context.rename': 'Renombrar', 'sftp.context.permissions': 'Permisos', - 'sftp.context.delete': 'Eliminar', 'sftp.context.refresh': 'Actualizar', 'sftp.context.uploadFiles': 'Subir archivo(s)...', 'sftp.context.uploadFilesHere': 'Subir archivo(s) aquí...', 'sftp.context.uploadFolder': 'Subir carpeta...', 'sftp.context.uploadFolderHere': 'Subir carpeta aquí...', - 'sftp.context.downloadSelected': 'Descargar seleccionados ({count})', - 'sftp.context.deleteSelected': 'Eliminar seleccionados ({count})', 'sftp.dropFilesHere': 'Suelta los archivos aquí', 'sftp.itemsCount': '{count} elementos', 'sftp.selectedCount': '{count} seleccionados', @@ -370,8 +343,6 @@ export const esVaultMessages: Messages = { 'sftp.task.waiting': 'Esperando...', 'sftp.transfer.preparing': 'preparando...', 'sftp.status.loading': 'Cargando...', - 'sftp.status.uploading': 'Subiendo...', - 'sftp.status.ready': 'Listo', 'sftp.transfers': 'Transferencias', 'sftp.transfers.active': '{count} activas', 'sftp.transfers.clearCompleted': 'Limpiar completadas', @@ -435,7 +406,6 @@ export const esVaultMessages: Messages = { 'sftp.transferCenter.applyAll': 'Aplicar a todas', 'sftp.transfers.resizeNameColumn': 'Redimensionar la columna de nombre de archivo', 'sftp.transfers.dragToResize': 'Arrastra para redimensionar', - 'sftp.goUp': 'Subir un nivel', 'sftp.goToTerminalCwd': 'Ir al directorio de la terminal', 'sftp.locatePathInTerminal': 'Abrir ruta en la terminal', 'sftp.followTerminalCwd': 'Seguir el directorio de la terminal', @@ -451,29 +421,22 @@ export const esVaultMessages: Messages = { 'sftp.folderName.placeholder': 'Ingresa el nombre de la carpeta', 'sftp.fileName': 'Nombre del archivo', 'sftp.fileName.placeholder': 'Ingresa el nombre del archivo', - 'sftp.prompt.newFolderName': '¿Nombre de la carpeta nueva?', 'sftp.rename.title': 'Renombrar', 'sftp.rename.newName': 'Nombre nuevo', 'sftp.rename.placeholder': 'Ingresa el nombre nuevo', - 'sftp.confirm.deleteOne': '¿Eliminar "{name}"?', - 'sftp.deleteConfirm.single': '¿Eliminar "{name}"?', 'sftp.deleteConfirm.title': '¿Eliminar {count} elemento(s)?', 'sftp.deleteConfirm.desc': 'Esta acción no se puede deshacer. Se eliminará lo siguiente:', 'sftp.deleteConfirm.descSingle': 'Esta acción no se puede deshacer.', 'sftp.deleteConfirm.host': 'Host', 'sftp.deleteConfirm.path': 'Ruta', - 'sftp.error.loadFailed': 'No se pudo cargar el directorio', 'sftp.error.downloadFailed': 'No se pudo descargar', 'sftp.error.uploadFailed': 'No se pudo subir', 'sftp.error.deleteFailed': 'No se pudo eliminar', - 'sftp.error.createFolderFailed': 'No se pudo crear la carpeta', - 'sftp.error.createFileFailed': 'No se pudo crear el archivo', 'sftp.error.invalidFileName': 'El nombre de archivo contiene caracteres no válidos: {chars}', 'sftp.error.reservedName': 'Este nombre de archivo está reservado por el sistema', 'sftp.overwrite.title': 'El archivo ya existe', 'sftp.overwrite.desc': 'Ya existe un archivo llamado "{name}". ¿Quieres reemplazarlo?', 'sftp.overwrite.confirm': 'Reemplazar', - 'sftp.error.renameFailed': 'No se pudo renombrar', 'sftp.picker.title': 'Seleccionar host', 'sftp.picker.desc': 'Elige un host para el panel {side}', 'sftp.picker.searchPlaceholder': 'Buscar hosts...', @@ -481,8 +444,6 @@ export const esVaultMessages: Messages = { 'sftp.picker.local.desc': 'Explorar archivos locales', 'sftp.picker.local.badge': 'Local', 'sftp.picker.connected.section': 'Conectados', - 'sftp.picker.connected.badge': 'En vivo', - 'sftp.picker.connected.connecting': 'Conectando', 'sftp.picker.noMatch': 'No hay hosts que coincidan', 'sftp.permissions.title': 'Editar permisos', 'sftp.permissions.owner': 'Propietario', @@ -490,16 +451,12 @@ export const esVaultMessages: Messages = { 'sftp.permissions.others': 'Otros', 'sftp.permissions.octal': 'Octal', 'sftp.permissions.symbolic': 'Simbólico', - 'sftp.permissions.success': 'Permisos actualizados correctamente', - 'sftp.permissions.failed': 'No se pudieron actualizar los permisos', 'sftp.pane.local': 'Local', 'sftp.pane.remote': 'Remoto', 'sftp.pane.selectHost': 'Seleccionar host', 'sftp.pane.selectHostToStart': 'Selecciona un host para comenzar', 'sftp.pane.chooseFilesystem': 'Elige un sistema de archivos local o remoto para explorar', 'sftp.tabs.addTab': 'Agregar pestaña nueva', - 'sftp.tabs.closeTab': 'Cerrar pestaña', - 'sftp.tabs.newTab': 'Pestaña nueva', 'sftp.tabs.copyDefaultPath': 'Copiar pestaña (ruta predeterminada)', 'sftp.tabs.copyCurrentPath': 'Copiar e ir a la ruta actual', 'sftp.conflict.title': 'Conflicto de archivos', @@ -525,47 +482,24 @@ export const esVaultMessages: Messages = { 'sftp.conflict.action.replace': 'Reemplazar', // SFTP Upload Phases - 'sftp.upload.phase.compressing': 'Comprimiendo', - 'sftp.upload.phase.uploading': 'Subiendo', - 'sftp.upload.phase.extracting': 'Extrayendo', - 'sftp.upload.phase.compressed': 'Comprimido', // SFTP File Opener 'sftp.context.copyPath': 'Copiar ruta del archivo', 'sftp.context.openWithDefault': 'Abrir con la aplicación predeterminada del sistema', 'sftp.context.openWith': 'Abrir con...', 'sftp.context.edit': 'Editar', - 'sftp.context.preview': 'Vista previa', 'sftp.opener.title': 'Abrir con', - 'sftp.opener.desc': 'Elige una aplicación para abrir este archivo', 'sftp.opener.builtInEditor': 'Editor integrado', 'sftp.opener.editDescription': 'Editar archivos de texto', - 'sftp.opener.builtInImageViewer': 'Visor de imágenes integrado', - 'sftp.opener.previewDescription': 'Previsualizar imágenes', 'sftp.opener.systemApp': 'Elegir aplicación...', 'sftp.opener.systemAppDescription': 'Selecciona una aplicación de tu computadora', - 'sftp.opener.onlySystemApp': 'Este archivo solo se puede abrir con una aplicación externa', - 'sftp.opener.noAppsAvailable': 'No hay aplicaciones disponibles', 'sftp.opener.noExtension': 'archivos sin extensión', 'sftp.opener.setDefault': 'Usar siempre esto para archivos {ext}', - 'sftp.opener.confirmTitle': '¿Establecer como predeterminado?', - 'sftp.opener.confirmDescription': '¿Quieres usar siempre {app} para archivos {ext}?', - 'sftp.opener.yesRemember': 'Sí, recordar esta elección', - 'sftp.opener.justOnce': 'Solo esta vez', - 'sftp.opener.confirm.title': 'Establecer aplicación predeterminada', - 'sftp.opener.confirm.desc': '¿Quieres abrir siempre los archivos .{ext} con esta aplicación?', - 'sftp.editor.title': 'Editor de texto', 'sftp.editor.save': 'Guardar en remoto', 'sftp.editor.saving': 'Guardando...', 'sftp.editor.saved': 'Guardado correctamente', 'sftp.editor.saveFailed': 'No se pudo guardar el archivo', - 'sftp.editor.unsavedChanges': 'Tienes cambios sin guardar. ¿Cerrar de todos modos?', 'sftp.editor.syntaxHighlight': 'Resaltado de sintaxis', - 'sftp.preview.title': 'Vista previa de imagen', - 'sftp.preview.zoomIn': 'Acercar', - 'sftp.preview.zoomOut': 'Alejar', - 'sftp.preview.resetZoom': 'Restablecer zoom', - 'sftp.preview.fitToWindow': 'Ajustar a la ventana', // Settings > SFTP File Associations 'settings.tab.sftpFileAssociations': 'SFTP', @@ -644,28 +578,16 @@ export const esVaultMessages: Messages = { 'sftp.autoSync.error': 'No se pudo sincronizar el archivo: {error}', // SFTP Folder Upload Progress - 'sftp.upload.progress': 'Subiendo {current} de {total} archivos...', - 'sftp.upload.uploading': 'Subiendo...', - 'sftp.upload.compressing': 'Comprimiendo...', - 'sftp.upload.extracting': 'Extrayendo...', - 'sftp.upload.scanning': 'Escaneando archivos...', - 'sftp.upload.completed': 'Completado', - 'sftp.upload.compressed': 'Transferencia comprimida', - 'sftp.upload.currentFile': 'Actual: {fileName}', 'sftp.upload.cancelled': 'Subida cancelada', 'sftp.upload.noFiles': 'No hay archivos para subir', 'sftp.upload.partialSuccess': 'Se subieron {success} archivo(s); {failed} fallaron', 'sftp.upload.cancel': 'Cancelar', - 'sftp.upload.completedToPath': 'Subido a {path}', // SFTP Download - 'sftp.download.completed': 'Descargado', - 'sftp.download.cancelled': 'Descarga cancelada', // SFTP Reconnecting 'sftp.reconnecting.title': 'Reconectando...', 'sftp.reconnecting.desc': 'Se perdió la conexión, intentando reconectar', - 'sftp.reconnected': 'Conexión restablecida', 'sftp.error.reconnectFailed': 'No se pudo reconectar. Inténtalo de nuevo.', 'sftp.error.connectionLostManual': 'Se perdió la conexión. Vuelve a conectar manualmente.', 'sftp.error.connectionLostReconnecting': 'Se perdió la conexión. Reconectando...', @@ -773,11 +695,8 @@ export const esVaultMessages: Messages = { 'hostDetails.notes.toggle.show': 'Mostrar el editor de notas', 'hostDetails.notes.toggle.hide': 'Ocultar el editor de notas', 'hostDetails.group.placeholder': 'Grupo padre', - 'hostDetails.section.credentials': 'Credenciales', 'hostDetails.section.portCredentials': 'Puerto y credenciales', 'hostDetails.section.appearance': 'Apariencia', - 'hostDetails.distro.title': 'Distribución de Linux', - 'hostDetails.distro.desc': 'Detecta automáticamente al conectar, o anula el ícono de la distro manualmente.', 'hostDetails.icon.title': 'Ícono del host', 'hostDetails.icon.sectionTitle': 'Color e ícono', 'hostDetails.icon.desc': 'Elige la fuente y el color del ícono para este host.', @@ -789,7 +708,6 @@ export const esVaultMessages: Messages = { 'hostDetails.icon.mode.custom': 'Personalizado', 'hostDetails.icon.reset': 'Restablecer el ícono del host', 'hostDetails.icon.colorLabel': 'Color del ícono', - 'hostDetails.icon.colorDefault': 'Predeterminado', 'hostDetails.icon.colorAuto': 'Automático', 'hostDetails.icon.colorManual': 'Manual', 'hostDetails.icon.colorChoice': 'Color', @@ -840,7 +758,6 @@ export const esVaultMessages: Messages = { 'hostDetails.distro.mode.auto': 'Detección automática', 'hostDetails.distro.mode.manual': 'Anulación manual', 'hostDetails.distro.detectedLabel': 'Actual', - 'hostDetails.distro.manualLabel': 'Anulación', 'hostDetails.distro.pending': 'Detectar después de la primera conexión', 'hostDetails.distro.unknown': 'Desconocido', 'hostDetails.distro.option.linux': 'Linux genérico', @@ -891,7 +808,6 @@ export const esVaultMessages: Messages = { 'hostDetails.auth.mfaFirst': 'Preferir autenticación interactiva', 'hostDetails.auth.mfaFirst.desc': 'Para servidores que requieren contraseña y MFA a través de keyboard-interactive.', 'hostDetails.totp.title': 'Autenticador (TOTP)', - 'hostDetails.totp.enable': 'Guardar un secreto TOTP para este host', 'hostDetails.totp.setup': 'Configurar…', 'hostDetails.totp.edit': 'Editar', 'hostDetails.totp.modalTitle': 'Configurar autenticador', @@ -994,10 +910,8 @@ export const esVaultMessages: Messages = { 'hostDetails.jumpHosts.direct': 'Directo', 'hostDetails.jumpHosts.configure': 'Configurar hosts proxy', 'hostDetails.proxy': 'Proxy mediante HTTP/SOCKS5/Comando', - 'hostDetails.proxy.none': 'Ninguno', 'hostDetails.proxy.direct': 'Directo (sin proxy)', 'hostDetails.proxy.directHint': 'No usa el proxy del grupo ni el predeterminado global', - 'hostDetails.proxy.edit': 'Editar proxy', 'hostDetails.proxy.configure': 'Configurar proxy', 'hostDetails.proxyPanel.title': 'Proxy mediante HTTP/SOCKS5/Comando', 'hostDetails.proxyPanel.hostPlaceholder': 'Host del proxy', @@ -1007,7 +921,6 @@ export const esVaultMessages: Messages = { 'hostDetails.proxyPanel.credentials': 'Credenciales', 'hostDetails.proxyPanel.usernamePlaceholder': 'Nombre de usuario', 'hostDetails.proxyPanel.passwordPlaceholder': 'Contraseña', - 'hostDetails.proxyPanel.identities': 'Identidades', 'hostDetails.proxyPanel.keychainIdentity': 'Identidad del llavero', 'hostDetails.proxyPanel.manualCredentials': 'Credenciales manuales', 'hostDetails.proxyPanel.remove': 'Quitar proxy', @@ -1031,8 +944,6 @@ export const esVaultMessages: Messages = { 'hostDetails.envVars.newVariable': 'Variable nueva', 'hostDetails.envVars.variableName': 'Nombre de la variable', 'hostDetails.chain.title': 'Editar cadena', - 'hostDetails.chain.desc': 'Agregar otro host creará una conexión a {host}.', - 'hostDetails.chain.addHost': 'Agregar un host', 'hostDetails.chain.target': 'Destino', 'hostDetails.chain.availableHosts': 'Hosts disponibles', 'hostDetails.chain.clear': 'Limpiar', @@ -1069,12 +980,6 @@ export const esVaultMessages: Messages = { // Host connection test 'hostConnectionTest.title': 'Probar conexión', - 'hostConnectionTest.test': 'Probar', - 'hostConnectionTest.chainOf': 'Cadena {current} de {total}', - 'hostConnectionTest.success': 'Conexión correcta', - 'hostConnectionTest.successHint': 'El host aceptó tus credenciales. Puedes cerrar esta ventana.', - 'hostConnectionTest.connecting': 'Conectando… tiempo de espera en {seconds}s', - 'hostConnectionTest.failed': 'No se pudo conectar.', 'hostConnectionTest.retry': 'Reintentar', 'hostConnectionTest.credentialsUnavailable': 'Las credenciales guardadas no se pueden descifrar en este dispositivo. Vuelve a ingresarlas abajo.', @@ -1110,28 +1015,14 @@ export const esVaultMessages: Messages = { 'hostDetails.plugin.useSsh': 'Usar SSH en su lugar', // Host form (legacy modal) - 'hostForm.title.edit': 'Editar host', - 'hostForm.title.new': 'Host nuevo', - 'hostForm.desc.edit': 'Actualiza los detalles de conexión de este host', - 'hostForm.desc.new': 'Crea una nueva entrada de host SSH', 'hostForm.field.label': 'Etiqueta', - 'hostForm.placeholder.label': 'Mi servidor de producción', 'hostForm.field.hostname': 'Nombre de host / IP', - 'hostForm.placeholder.hostname': '192.168.1.1', 'hostForm.field.port': 'Puerto', 'hostForm.field.username': 'Nombre de usuario', 'hostForm.field.osType': 'Tipo de SO', - 'hostForm.placeholder.selectOs': 'Seleccionar SO', 'hostForm.field.group': 'Grupo', - 'hostForm.placeholder.group': 'p. ej., AWS, DigitalOcean', 'hostForm.field.tags': 'Etiquetas', - 'hostForm.placeholder.addTag': 'Agregar una etiqueta...', - 'hostForm.auth.method': 'Método de autenticación', - 'hostForm.auth.password': 'Contraseña', - 'hostForm.auth.sshKey': 'Clave SSH', 'hostForm.auth.selectKey': 'Seleccionar una clave SSH', - 'hostForm.auth.noKeys': 'No hay claves disponibles', - 'hostForm.auth.noKeysHint': 'No se encontraron claves SSH en el llavero. Crea una primero.', 'hostForm.saveHost': 'Guardar host', // Connection logs @@ -1150,7 +1041,6 @@ export const esVaultMessages: Messages = { 'logs.action.delete': 'Eliminar', // Log view - 'logView.customizeAppearance': 'Personalizar la apariencia', 'logView.appearance': 'Apariencia', 'logView.readOnly': 'Solo lectura', 'logView.export': 'Exportar', diff --git a/application/i18n/locales/externalMcpApprovalAlertLocales.test.ts b/application/i18n/locales/externalMcpApprovalAlertLocales.test.ts deleted file mode 100644 index ed46a225f..000000000 --- a/application/i18n/locales/externalMcpApprovalAlertLocales.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en.ts'; -import ru from './ru.ts'; -import es from './es.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const KEYS = [ - 'ai.externalMcp.approvalAlert', - 'ai.externalMcp.approvalAlert.description', - 'ai.externalMcp.approvalAlert.off', - 'ai.externalMcp.approvalAlert.unfocused', - 'ai.externalMcp.approvalAlert.always', - 'ai.externalMcp.approvalAlert.notificationTitle', - 'ai.externalMcp.approvalAlert.notificationBody', - 'ai.externalMcp.approvalAlert.notificationBodyOnHost', -] as const; - -test('External MCP approval alerts are localized in every supported locale', () => { - for (const [name, messages] of Object.entries({ en, es, 'zh-CN': zhCN, 'zh-TW': zhTW, ru })) { - const missing = KEYS.filter((key) => !messages[key]); - assert.deepEqual(missing, [], `${name} is missing approval alert labels`); - assert.match(messages['ai.externalMcp.approvalAlert.notificationBody'], /\{tool\}/); - assert.match(messages['ai.externalMcp.approvalAlert.notificationBodyOnHost'], /\{tool\}/); - assert.match(messages['ai.externalMcp.approvalAlert.notificationBodyOnHost'], /\{host\}/); - } -}); diff --git a/application/i18n/locales/externalMcpHttpLocales.test.ts b/application/i18n/locales/externalMcpHttpLocales.test.ts deleted file mode 100644 index 41713930a..000000000 --- a/application/i18n/locales/externalMcpHttpLocales.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import en from "./en.ts"; -import ru from "./ru.ts"; -import es from "./es.ts"; -import zhCN from "./zh-CN.ts"; -import zhTW from "./zh-TW.ts"; - -const KEYS = [ - "ai.externalMcp.http.title", - "ai.externalMcp.http.description", - "ai.externalMcp.http.enable", - "ai.externalMcp.http.port", - "ai.externalMcp.http.portHint", - "ai.externalMcp.http.allowCustomBind", - "ai.externalMcp.http.allowCustomBind.description", - "ai.externalMcp.http.listenAddress", - "ai.externalMcp.http.listenAddress.placeholder", - "ai.externalMcp.http.clientHost", - "ai.externalMcp.http.clientHost.description", - "ai.externalMcp.http.clientHost.placeholder", - "ai.externalMcp.http.clientHostRequired", - "ai.externalMcp.http.invalidClientHost", - "ai.externalMcp.http.warning", - "ai.externalMcp.http.url", - "ai.externalMcp.http.token", - "ai.externalMcp.http.regenerate", - "ai.externalMcp.http.regenerateHint", - "ai.externalMcp.http.wslHint", - "ai.externalMcp.http.codexSnippet", - "ai.externalMcp.http.claudeCommand", - "ai.externalMcp.http.genericSnippet", - "ai.externalMcp.http.envLine", - "ai.externalMcp.http.notListening", - "ai.externalMcp.http.listening", - "ai.externalMcp.http.portInUse", - "ai.externalMcp.http.requiresExternalMcp", - "ai.externalMcp.http.invalidPort", - "ai.externalMcp.http.invalidAddress", - "ai.externalMcp.http.listenFailed", - "ai.externalMcp.http.legacySseNote", -] as const; - -test("External MCP HTTP strings exist in every locale", () => { - for (const [name, messages] of Object.entries({ en, es, "zh-CN": zhCN, "zh-TW": zhTW, ru })) { - const missing = KEYS.filter((key) => !messages[key]); - assert.deepEqual(missing, [], `${name} is missing HTTP MCP labels`); - assert.match(messages["ai.externalMcp.http.portInUse"], /\{port\}/); - } - assert.match(zhTW["ai.externalMcp.http.port"], /連接埠/); - assert.match(zhTW["ai.externalMcp.http.listenAddress"], /位址/); - assert.match(zhTW["ai.externalMcp.http.clientHost"], /位址/); - assert.doesNotMatch(zhTW["ai.externalMcp.http.clientHost"], /地址/); - assert.doesNotMatch(zhTW["ai.externalMcp.http.port"], /端口/); - assert.doesNotMatch(zhTW["ai.externalMcp.http.listenAddress"], /地址/); - assert.match(zhTW["ai.externalMcp.http.wslHint"], /鏡像網路/); -}); diff --git a/application/i18n/locales/externalMcpRedactionLocales.test.ts b/application/i18n/locales/externalMcpRedactionLocales.test.ts deleted file mode 100644 index 25d60bfdb..000000000 --- a/application/i18n/locales/externalMcpRedactionLocales.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import en from './en.ts'; -import es from './es.ts'; -import ru from './ru.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const KEYS = [ - 'title', 'description', 'boundary', 'enable', 'privateIps', 'privateIps.description', - 'cidrs', 'cidrs.description', 'patterns', 'patterns.description', - 'connectionScope', 'reconnect', 'apply', 'applying', 'applied', 'failed', -]; - -test('Shared AI privacy settings are localized in every supported locale', () => { - for (const [name, messages] of Object.entries({ en, es, ru, 'zh-CN': zhCN, 'zh-TW': zhTW })) { - assert.deepEqual( - KEYS.filter((key) => !messages[`ai.privacy.${key}`]), - [], - `${name} is missing privacy settings labels`, - ); - } -}); diff --git a/application/i18n/locales/localeCopyRules.test.ts b/application/i18n/locales/localeCopyRules.test.ts new file mode 100644 index 000000000..aa9ae6255 --- /dev/null +++ b/application/i18n/locales/localeCopyRules.test.ts @@ -0,0 +1,212 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +import { describePluginGitHubInstallError } from "../../../domain/pluginGitHubInstallError.ts"; +import { SUPPORTED_UI_LOCALES } from "../../../infrastructure/config/i18n.ts"; +import { getLoadedLocaleMessages, loadLocaleMessages } from "../messages.ts"; +import en from "./en.ts"; +import { enMonitorMessages } from "./en/monitor.ts"; +import { enSystemManagerMessages } from "./en/systemManager.ts"; +import { enTerminalMessages } from "./en/terminal.ts"; +import es from "./es.ts"; +import { esMonitorMessages } from "./es/monitor.ts"; +import { esSystemManagerMessages } from "./es/systemManager.ts"; +import { esTerminalMessages } from "./es/terminal.ts"; +import ru from "./ru.ts"; +import { ruMonitorMessages } from "./ru/monitor.ts"; +import { ruSystemManagerMessages } from "./ru/systemManager.ts"; +import { ruTerminalMessages } from "./ru/terminal.ts"; +import zhCN from "./zh-CN.ts"; +import { zhCNMonitorMessages } from "./zh-CN/monitor.ts"; +import { zhCnSystemManagerMessages } from "./zh-CN/systemManager.ts"; +import { zhCNVaultMessages } from "./zh-CN/vault.ts"; +import zhTW from "./zh-TW.ts"; +import { zhTWMonitorMessages } from "./zh-TW/monitor.ts"; +import { zhTwSystemManagerMessages } from "./zh-TW/systemManager.ts"; +import { zhTWVaultMessages } from "./zh-TW/vault.ts"; + +const ALL_LOCALES = { + en, + es, + ru, + "zh-CN": zhCN, + "zh-TW": zhTW, +} as const; + +test("disconnect confirm copy states that saved provider credentials are removed and local data stays", () => { + const expected = [ + [en, "will be removed"], + [es, "eliminarán"], + [ru, "будут удалены"], + [zhCN, "删除"], + [zhTW, "刪除"], + ] as const; + for (const [messages, fragment] of expected) { + assert.ok( + messages["cloudSync.provider.disconnect.confirmMessage"]?.includes(fragment), + `confirmMessage should mention credential removal: ${fragment}`, + ); + } + assert.match( + en["cloudSync.provider.disconnect.confirmMessage"], + /backup history and sync encryption password stay here/, + ); + assert.doesNotMatch(en["cloudSync.provider.disconnect.cloudRemains"], /change.*password/); +}); + +test("Taiwan Traditional Chinese copy uses Taiwan terminology for HTTP MCP and OpenCode 2", () => { + assert.match(zhTW["ai.externalMcp.http.port"], /連接埠/); + assert.match(zhTW["ai.externalMcp.http.listenAddress"], /位址/); + assert.match(zhTW["ai.externalMcp.http.clientHost"], /位址/); + assert.doesNotMatch(zhTW["ai.externalMcp.http.clientHost"], /地址/); + assert.doesNotMatch(zhTW["ai.externalMcp.http.port"], /端口/); + assert.doesNotMatch(zhTW["ai.externalMcp.http.listenAddress"], /地址/); + assert.match(zhTW["ai.externalMcp.http.wslHint"], /鏡像網路/); + + const opencodeKeys = [ + "ai.opencode.v2.startupTimeout", + "ai.opencode.v2.exited", + "ai.opencode.v2.unauthorized", + "ai.opencode.v2.unavailable", + "ai.opencode.v2.sessionFailed", + "ai.opencode.v2.empty", + "ai.opencode.v2.contextSkipped", + "ai.opencode.v2.mcpSkipped", + ]; + for (const key of opencodeKeys) { + assert.notEqual(en[key], zhCN[key]); + assert.notEqual(en[key], zhTW[key]); + assert.notEqual(zhCN[key], zhTW[key]); + } + const text = opencodeKeys.map((key) => zhTW[key]).join("\n"); + assert.match(text, /終端機/); + assert.match(text, /連線/); + assert.match(text, /設定/); + assert.match(text, /傳回/); + assert.equal(text.includes("终端"), false); + assert.equal(text.includes("连接"), false); + assert.equal(text.includes("设置"), false); + assert.equal(text.includes("返回"), false); +}); + +test("monitoring UI literal message keys exist and all monitor locales stay at parity", () => { + for (const name of ["MonitorPanels", "MonitorNavButton", "MonitorDiskUsage"]) { + const source = readFileSync(new URL(`../../../components/vault/${name}.tsx`, import.meta.url), "utf8"); + const keys = [...source.matchAll(/\bt\("(monitor\.[^"]+)"/g)].map((match) => match[1]); + for (const key of keys) { + assert.ok(Object.hasOwn(enMonitorMessages, key), `${name}: ${key}`); + } + } + for (const [locale, messages] of Object.entries({ + es: esMonitorMessages, + ru: ruMonitorMessages, + "zh-CN": zhCNMonitorMessages, + "zh-TW": zhTWMonitorMessages, + })) { + assert.deepEqual(Object.keys(messages).sort(), Object.keys(enMonitorMessages).sort(), locale); + } +}); + +test("GitHub plugin install copy is complete in every supported locale and error presentation maps statuses", async () => { + const keys = Object.keys(en).filter((key) => key.startsWith("settings.plugins.github.")); + assert.ok(keys.length > 30); + for (const { id } of SUPPORTED_UI_LOCALES) { + await loadLocaleMessages(id); + const messages = getLoadedLocaleMessages(id)!; + for (const key of keys) { + assert.ok(messages[key]?.trim(), `${id}: ${key}`); + } + } + + const expired = describePluginGitHubInstallError( + "Error invoking remote method 'plugins:github:install': Error: GitHub package preview expired. Download and review it again", + ); + assert.equal(expired.key, "settings.plugins.github.error.expired"); + assert.equal(expired.details, null); + assert.deepEqual(describePluginGitHubInstallError("GitHub download failed (HTTP 503)").values, { status: "503" }); + const validator = "manifest version must be a semantic version"; + assert.equal(describePluginGitHubInstallError(validator).details, validator); + assert.equal(describePluginGitHubInstallError(validator).key, "settings.plugins.github.error.failed"); + assert.equal( + describePluginGitHubInstallError("Plugin is incompatible: engine version").key, + "settings.plugins.github.error.incompatible", + ); +}); + +test("SSH network latency wording stays aligned between terminal and system manager surfaces", () => { + const surfaces = [ + [enTerminalMessages, enSystemManagerMessages], + [ruTerminalMessages, ruSystemManagerMessages], + [esTerminalMessages, esSystemManagerMessages], + [zhCNVaultMessages, zhCnSystemManagerMessages], + [zhTWVaultMessages, zhTwSystemManagerMessages], + ] as const; + + for (const [terminalMessages, systemManagerMessages] of surfaces) { + assert.ok(terminalMessages["terminal.serverStats.latency"]); + assert.equal( + terminalMessages["terminal.serverStats.latency"], + systemManagerMessages["systemManager.overview.latency"], + ); + } +}); + +test("English snippet bulk-delete copy stays entity-neutral and grammatical for one item", () => { + assert.equal( + en["snippets.selection.deleteConfirmTitle"].replace("{count}", "1"), + "Delete selected items (1)?", + ); + assert.equal( + en["snippets.selection.deleteSuccess"].replace("{count}", "1"), + "Deleted selected items: 1.", + ); +}); + +test("inline image settings copy is translated rather than left in English", () => { + const translatedKeys = [ + "settings.terminal.section.inlineImages", + "settings.terminal.inlineImages.enabled", + "settings.terminal.inlineImages.enabled.desc", + "settings.terminal.inlineImages.kitty", + "settings.terminal.inlineImages.kitty.desc", + "settings.terminal.inlineImages.sixel.desc", + "settings.terminal.inlineImages.iip", + "settings.terminal.inlineImages.iip.desc", + "settings.terminal.inlineImages.storageLimit", + "settings.terminal.inlineImages.storageLimit.desc", + "settings.terminal.inlineImages.maxMegapixels", + "settings.terminal.inlineImages.maxMegapixels.desc", + "settings.terminal.inlineImages.sequenceLimit", + "settings.terminal.inlineImages.sequenceLimit.desc", + "settings.terminal.inlineImages.hibernateNote", + ]; + + for (const [locale, messages] of Object.entries(ALL_LOCALES)) { + if (locale === "en") continue; + const untranslated = translatedKeys.filter((key) => messages[key] === en[key]); + assert.deepEqual(untranslated, [], `${locale} still uses the English string`); + } +}); + +test("removed session log rememberApplication key stays absent across locales", () => { + for (const [locale, messages] of Object.entries(ALL_LOCALES)) { + assert.equal( + messages["terminal.toolbar.sessionLog.rememberApplication"], + undefined, + `${locale} should not reintroduce removed rememberApplication key`, + ); + } +}); + +test("managed group delete warning mentions SSH config backup in every locale", () => { + const backupMarkers = ["备份", "備份", "copia de seguridad", "резервную копию", "Back up"]; + for (const [locale, messages] of Object.entries(ALL_LOCALES)) { + const text = messages["vault.groups.deleteDialog.managedWarning"] ?? ""; + assert.match(text, /SSH/, `${locale} warning should reference the SSH config file`); + assert.ok( + backupMarkers.some((marker) => text.includes(marker)), + `${locale} warning should tell the user to back up the file`, + ); + } +}); diff --git a/application/i18n/locales/monitorLocales.test.ts b/application/i18n/locales/monitorLocales.test.ts deleted file mode 100644 index e1c204fe7..000000000 --- a/application/i18n/locales/monitorLocales.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { enMonitorMessages } from "./en/monitor"; -import { esMonitorMessages } from "./es/monitor"; -import { ruMonitorMessages } from "./ru/monitor"; -import { zhCNMonitorMessages } from "./zh-CN/monitor"; -import { zhTWMonitorMessages } from "./zh-TW/monitor"; - -test("monitoring UI literal message keys exist, including editor-only controls", () => { - for (const name of ["MonitorPanels", "MonitorNavButton", "MonitorDiskUsage"]) { - const source = readFileSync(new URL(`../../../components/vault/${name}.tsx`, import.meta.url), "utf8"); - const keys = [...source.matchAll(/\bt\("(monitor\.[^"]+)"/g)].map((match) => match[1]); - for (const key of keys) - assert.ok(Object.hasOwn(enMonitorMessages, key), `${name}: ${key}`); - } -}); -for (const [locale, messages] of Object.entries({ - es: esMonitorMessages, - ru: ruMonitorMessages, - "zh-CN": zhCNMonitorMessages, - "zh-TW": zhTWMonitorMessages, -})) { - test(`monitoring has translated actions, states and matching placeholders in ${locale}`, () => { - assert.deepEqual( - Object.keys(messages).sort(), - Object.keys(enMonitorMessages).sort(), - ); - for (const key of Object.keys(enMonitorMessages)) { - const english = enMonitorMessages[key as keyof typeof enMonitorMessages]; - const translated = messages[key as keyof typeof messages]; - assert.ok(translated.trim(), key); - assert.deepEqual( - (translated.match(/\{\w+\}/g) ?? []).sort(), - (english.match(/\{\w+\}/g) ?? []).sort(), - key, - ); - } - }); -} diff --git a/application/i18n/locales/opencodeV2Locales.test.ts b/application/i18n/locales/opencodeV2Locales.test.ts deleted file mode 100644 index e37d4d4c7..000000000 --- a/application/i18n/locales/opencodeV2Locales.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import en from './en'; -import zhCN from './zh-CN'; -import zhTW from './zh-TW'; - -const KEYS = [ - 'ai.opencode.v2.startupTimeout', - 'ai.opencode.v2.exited', - 'ai.opencode.v2.unauthorized', - 'ai.opencode.v2.unavailable', - 'ai.opencode.v2.sessionFailed', - 'ai.opencode.v2.empty', - 'ai.opencode.v2.contextSkipped', - 'ai.opencode.v2.mcpSkipped', -]; - -test('OpenCode 2 strings exist in English, Simplified Chinese, and Taiwan Chinese', () => { - for (const key of KEYS) { - assert.equal(typeof en[key], 'string', `en missing ${key}`); - assert.equal(typeof zhCN[key], 'string', `zh-CN missing ${key}`); - assert.equal(typeof zhTW[key], 'string', `zh-TW missing ${key}`); - assert.notEqual(en[key], zhCN[key]); - assert.notEqual(en[key], zhTW[key]); - assert.notEqual(zhCN[key], zhTW[key]); - } -}); - -test('Taiwan OpenCode 2 wording uses Taiwan terms', () => { - const text = KEYS.map((key) => zhTW[key]).join('\n'); - assert.match(text, /終端機/); - assert.match(text, /連線/); - assert.match(text, /設定/); - assert.match(text, /傳回/); - assert.equal(text.includes('终端'), false); - assert.equal(text.includes('连接'), false); - assert.equal(text.includes('设置'), false); - assert.equal(text.includes('返回'), false); -}); diff --git a/application/i18n/locales/pluginGitHubInstallLocales.test.ts b/application/i18n/locales/pluginGitHubInstallLocales.test.ts deleted file mode 100644 index bf0d385d8..000000000 --- a/application/i18n/locales/pluginGitHubInstallLocales.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { SUPPORTED_UI_LOCALES } from '../../../infrastructure/config/i18n'; -import { getLoadedLocaleMessages, loadLocaleMessages } from '../messages'; -import en from './en'; -import { describePluginGitHubInstallError } from '../../../domain/pluginGitHubInstallError'; - -test('GitHub install copy and error interpolation are complete in every supported UI locale', async () => { - const keys = Object.keys(en).filter(key => key.startsWith('settings.plugins.github.')); - assert.ok(keys.length > 30); - for (const { id } of SUPPORTED_UI_LOCALES) { - await loadLocaleMessages(id); - const messages = getLoadedLocaleMessages(id)!; - for (const key of keys) { - assert.ok(messages[key]?.trim(), `${id}: ${key}`); - assert.deepEqual(messages[key].match(/\{\w+\}/g) ?? [], en[key].match(/\{\w+\}/g) ?? [], `${id}: ${key}`); - } - } -}); - -test('GitHub error presentation handles Electron wrappers, HTTP status and diagnostic fallback', () => { - const expired = describePluginGitHubInstallError("Error invoking remote method 'plugins:github:install': Error: GitHub package preview expired. Download and review it again"); - assert.equal(expired.key, 'settings.plugins.github.error.expired'); - assert.equal(expired.details, null); - assert.deepEqual(describePluginGitHubInstallError('GitHub download failed (HTTP 503)').values, { status: '503' }); - const validator = 'manifest version must be a semantic version'; - assert.equal(describePluginGitHubInstallError(validator).details, validator); - assert.equal(describePluginGitHubInstallError(validator).key, 'settings.plugins.github.error.failed'); - assert.equal(describePluginGitHubInstallError('Plugin is incompatible: engine version').key, 'settings.plugins.github.error.incompatible'); -}); diff --git a/application/i18n/locales/ru/ai.ts b/application/i18n/locales/ru/ai.ts index 6b05a9725..8af7872aa 100644 --- a/application/i18n/locales/ru/ai.ts +++ b/application/i18n/locales/ru/ai.ts @@ -687,9 +687,6 @@ export const ruAiMessages: Messages = { 'terminal.layer.theme': 'Тема', 'terminal.layer.notes': 'Заметки', 'terminal.layer.aiChat': 'AI-чат', - 'terminal.layer.movePanelLeft': 'Переместить панель влево', - 'terminal.layer.movePanelRight': 'Переместить панель вправо', - 'terminal.layer.movePanelBottom': 'Переместить панель вниз', 'terminal.layer.choosePanelPosition': 'Изменить положение', 'terminal.layer.dockLeft': 'Слева', 'terminal.layer.dockRight': 'Справа', @@ -717,15 +714,12 @@ export const ruAiMessages: Messages = { 'topTabs.openQuickSwitcher': 'Открыть быстрый переключатель', 'topTabs.moreTabs': 'Больше вкладок', 'topTabs.aiAssistant': 'AI-помощник', - 'topTabs.newLocalTerminal': 'Новый локальный терминал', 'topTabs.controlPanel': 'Быстрые настройки', 'topTabs.controlPanel.externalMcp': 'Внешний MCP', 'topTabs.controlPanel.theme': 'Тема', 'topTabs.controlPanel.theme.light': 'Светлая', 'topTabs.controlPanel.theme.dark': 'Тёмная', 'topTabs.controlPanel.theme.system': 'Системная', - 'topTabs.externalMcp.enable': 'Включить внешний MCP', - 'topTabs.externalMcp.disable': 'Отключить внешний MCP', 'topTabs.windowOpacity': 'Прозрачность окна', 'topTabs.openSettings': 'Открыть настройки', 'ai.chat.sessionHistory': 'История сессий', diff --git a/application/i18n/locales/ru/core.ts b/application/i18n/locales/ru/core.ts index 058753293..2a0dffaa5 100644 --- a/application/i18n/locales/ru/core.ts +++ b/application/i18n/locales/ru/core.ts @@ -58,7 +58,6 @@ export const ruCoreMessages: Messages = { 'common.edit': 'Редактировать', 'common.clear': 'Очистить', 'common.optional': 'Необязательно', - 'common.selectPlaceholder': 'Выбрать...', 'common.add': 'Добавить', 'common.rename': 'Переименовать', 'common.refresh': 'Обновить', @@ -97,11 +96,9 @@ export const ruCoreMessages: Messages = { 'field.label': 'Метка', 'field.type': 'Тип', 'auth.keyType': 'Тип {type}', - 'auth.showAllKeys': 'Показать все ключи', // Dialogs / prompts 'confirm.deleteHost': 'Удалить хост "{name}"?', - 'confirm.deleteIdentity': 'Удалить идентификатор "{name}"?', 'confirm.removeProvider': 'Удалить провайдера "{name}"?', 'confirm.closeBusyTerminal.title': 'Подтвердите закрытие', 'confirm.closeBusyTerminal.message': 'Процесс "{command}" всё ещё выполняется и будет завершён.', @@ -359,7 +356,6 @@ export const ruCoreMessages: Messages = { 'tray.status.inactive': 'Неактивно', 'tray.status.error': 'Ошибка', 'tray.status.unknown': 'Неизвестно', - 'tray.recentHosts': 'Недавние хосты', 'tray.empty.title': 'Пока здесь ничего нет', 'tray.empty.subtitle': 'Подключитесь к серверу, они по вам скучают 🚀', 'tray.quit': 'Выйти из Netcatty', @@ -418,9 +414,6 @@ export const ruCoreMessages: Messages = { 'update.downloadFailed.message': 'Не удалось скачать обновление. Вы можете скачать его вручную.', 'update.needsSave.title': 'Несохранённые изменения', 'update.needsSave.message': 'Сначала сохраните открытые редакторы, затем снова нажмите «Перезапустить сейчас», чтобы установить обновление.', - 'update.openReleases': 'Открыть релизы', - 'update.remindLater': 'Напомнить позже', - 'update.skipVersion': 'Пропустить эту версию', // Settings > Appearance 'settings.appearance.uiTheme': 'Тема интерфейса', @@ -997,8 +990,6 @@ export const ruCoreMessages: Messages = { 'settings.shortcuts.binding.sftp-navigate-to': 'Перейти в выбранную директорию', // Context menus / common actions - 'action.newHost': 'Новый хост', - 'action.newSubfolder': 'Новая подпапка', 'action.copyPublicKey': 'Копировать публичный ключ', 'action.keyExport': 'Экспорт ключа', 'action.edit': 'Редактировать', @@ -1188,12 +1179,9 @@ export const ruCoreMessages: Messages = { "settings.plugins.manager.remove": "Удалить", "settings.plugins.manager.removeNote": "Удаление очищает код пакета и локальные данные KV. Настройки пользователя, секреты и данные синхронизации сохраняются.", "settings.plugins.permissions.statusUnknown": "Состояние неизвестно", - "plugins.sidebar.extensions": "Страницы расширений", "plugins.sidebar.selectTerminal": "Сначала выберите открытый терминал.", "plugins.sidebar.loading": "Загрузка страницы расширения…", "plugins.vault.loading": "Загрузка страницы плагина…", - "plugins.vault.extensions": "Расширения", - "plugins.vault.back": "К хостам", "plugins.interaction.title": "Запрос плагина", "plugins.interaction.sharing": "Переданный текст доступен плагину и его разрешённым возможностям, включая сеть. Чтение не разрешает новый сетевой адрес.", "plugins.interaction.input": "Ввести текст", diff --git a/application/i18n/locales/ru/scripts.ts b/application/i18n/locales/ru/scripts.ts index cfd2e3935..d462ecc99 100644 --- a/application/i18n/locales/ru/scripts.ts +++ b/application/i18n/locales/ru/scripts.ts @@ -1,6 +1,5 @@ export const ruScriptsMessages = { 'scripts.meta.name': 'Название', - 'scripts.meta.language': 'Язык', 'scripts.meta.description': 'Описание', 'scripts.meta.descriptionPlaceholder': 'Необязательные заметки об этом скрипте', 'scripts.meta.trigger': 'Триггер', @@ -15,7 +14,6 @@ export const ruScriptsMessages = { 'scripts.actions.openEditor': 'Открыть редактор', 'scripts.actions.openEditorHint': 'Редактировать скрипт в большом окне', 'scripts.editor.modalTitle': 'Редактор скриптов', - 'scripts.editor.modalSubtitle': 'Редактируйте метаданные и код скрипта в большом рабочем пространстве.', 'scripts.editor.lineCount': '{count} строк', 'scripts.editor.resize': 'Изменить размер редактора', 'scripts.targets.hint': 'Выбранные группы разрешаются динамически, поэтому новые хосты включаются автоматически.', @@ -86,17 +84,13 @@ export const ruScriptsMessages = { 'scripts.dialog.retry': 'Повторить', 'scripts.dialog.skip': 'Пропустить', 'scripts.dialog.abort': 'Прервать', - 'scripts.running.stepProgress': 'Шаг {current} / {total}', 'scripts.running.determinateProgress': '{label} {current}/{total}', 'scripts.running.progressFallback': 'Выполнение', 'scripts.running.operationsCount': 'Операций: {count}', 'scripts.running.opsPrefix': '', 'scripts.running.opsSuffix': ' операций', - 'scripts.running.elapsedLabel': 'Прошло времени', 'scripts.running.lastSentLabel': 'Отправлено:', 'scripts.running.elapsed': '{elapsed}', - 'scripts.running.completedSummary': 'Завершено · операций: {count} · {elapsed}', - 'scripts.running.dismissHint': 'Нажмите закрытие, чтобы скрыть', 'scripts.running.dismiss': 'Закрыть', 'scripts.running.viewLogs': 'Просмотреть журнал', 'scripts.running.logTitle': '{name} · Журнал запуска', @@ -111,26 +105,12 @@ export const ruScriptsMessages = { 'vault.nav.scripts': 'Скрипты', 'snippets.action.newScript': 'Новый сценарий автоматизации', 'hostDetails.section.automation': 'Автоматизация', - 'hostDetails.automation.loginScript': 'Скрипт входа', - 'hostDetails.automation.loginScriptPlaceholder': 'Выберите скрипт', - 'hostDetails.automation.none': 'Нет', - 'hostDetails.automation.outputTriggers': 'Триггеры вывода', - 'hostDetails.automation.addTrigger': 'Добавить триггер', - 'hostDetails.automation.triggerPatternPlaceholder': 'Регулярное выражение', - 'hostDetails.automation.linkedScripts': 'Связанные скрипты', - 'hostDetails.automation.linkedScriptsEmpty': 'С этим хостом пока не связано ни одного скрипта.', - 'hostDetails.automation.linkScriptPlaceholder': 'Связать существующий скрипт…', - 'hostDetails.automation.unlink': 'Отвязать', - 'hostDetails.automation.equivalenceHint': 'Связь добавляет этот хост в список целей скрипта в разделе «Скрипты». Оба представления синхронизированы.', 'hostDetails.automation.queueHint': 'Скрипты запускаются по порядку при подключении этого хоста. Сначала выполняются глобальные скрипты, затем эта очередь.', 'hostDetails.automation.globalScripts': 'Глобальные скрипты подключения', 'hostDetails.automation.globalScriptsHint': 'Выполняются первыми при каждом подключении. Порядок можно изменить в библиотеке скриптов.', 'hostDetails.automation.connectQueue': 'Очередь запуска этого хоста', 'hostDetails.automation.connectQueueEmpty': 'В очереди этого хоста пока нет скриптов подключения.', 'hostDetails.automation.addToQueuePlaceholder': 'Добавить скрипт в очередь…', - 'hostDetails.automation.moveUp': 'Переместить вверх', - 'hostDetails.automation.moveDown': 'Переместить вниз', 'hostDetails.automation.removeFromQueue': 'Удалить из очереди', 'hostDetails.automation.dragHandle': 'Перетащите для изменения порядка', - 'hostDetails.automation.queueDragHint': 'Перетаскивайте элементы, чтобы изменить порядок очереди подключения.', }; diff --git a/application/i18n/locales/ru/systemManager.ts b/application/i18n/locales/ru/systemManager.ts index 1efd9292a..502c5cb1c 100644 --- a/application/i18n/locales/ru/systemManager.ts +++ b/application/i18n/locales/ru/systemManager.ts @@ -14,13 +14,11 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.tabs.docker': 'Docker', 'systemManager.tabs.gpu': 'GPU', 'systemManager.tabs.ariaLabel': 'Разделы системного менеджера', - 'systemManager.popup.loading': 'Открытие терминала…', 'systemManager.popup.startupFailed': 'Команда запуска не была выполнена успешно. Проверьте, что цель доступна, и повторите попытку.', 'systemManager.errors.loadProcesses': 'Не удалось загрузить процессы', 'systemManager.errors.loadTmux': 'Не удалось загрузить сессии tmux', 'systemManager.errors.loadTmuxWindows': 'Не удалось загрузить окна tmux', - 'systemManager.errors.loadTmuxPanes': 'Не удалось загрузить панели tmux', 'systemManager.errors.loadTmuxClients': 'Не удалось загрузить клиентов tmux', 'systemManager.errors.actionFailed': 'Не удалось выполнить действие', 'systemManager.errors.loadDocker': 'Не удалось загрузить контейнеры', @@ -28,7 +26,6 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.errors.loadDockerImages': 'Не удалось загрузить образы', 'systemManager.errors.loadKubernetes': 'Не удалось загрузить ресурсы Kubernetes', 'systemManager.errors.loadPods': 'Не удалось загрузить поды', - 'systemManager.errors.loadOverview': 'Не удалось загрузить обзор системы', 'systemManager.errors.loadGpu': 'Не удалось загрузить статистику GPU / NPU', 'systemManager.errors.loadPorts': 'Не удалось загрузить слушающие порты', 'systemManager.errors.loadServices': 'Не удалось загрузить службы systemd', @@ -62,13 +59,10 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.overview.noTopProcesses': 'Нет данных процессов', 'systemManager.processes.search': 'Поиск процессов…', - 'systemManager.processes.command': 'Команда', - 'systemManager.processes.user': 'Пользователь', 'systemManager.processes.term': 'Завершить', 'systemManager.processes.kill': 'Убить', 'systemManager.processes.stop': 'Остановить (SIGSTOP)', 'systemManager.processes.cont': 'Продолжить (SIGCONT)', - 'systemManager.processes.hup': 'Сигнал SIGHUP', 'systemManager.processes.renice': 'Изменить приоритет', 'systemManager.processes.renicePrompt': 'Значение nice (-20 до 19)', 'systemManager.processes.reniceInvalid': 'Nice должно быть от -20 до 19', @@ -83,7 +77,6 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.processes.stat': 'Состояние', 'systemManager.processes.meta': '{{count}} проц.', 'systemManager.processes.loading': 'Загрузка процессов…', - 'systemManager.processes.loadingMore': 'Загрузка следующих процессов…', 'systemManager.processes.state.running': 'Активен', 'systemManager.processes.state.sleeping': 'Спящий', 'systemManager.processes.state.stopped': 'Остановлен', @@ -121,12 +114,9 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.tmux.attached': 'Подключена', 'systemManager.tmux.detached': 'Отключена', 'systemManager.tmux.windows': '{{count}} окон', - 'systemManager.tmux.created': 'Создана', - 'systemManager.tmux.activity': 'Активность', 'systemManager.tmux.rename': 'Переименовать', 'systemManager.tmux.detach': 'Отключить всех', 'systemManager.tmux.killSession': 'Завершить сессию', - 'systemManager.tmux.killServer': 'Остановить сервер', 'systemManager.tmux.loadingDetails': 'Загрузка деталей…', 'systemManager.tmux.clients': 'Подключённые клиенты', 'systemManager.tmux.windowList': 'Окна', @@ -137,31 +127,17 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.docker.unavailable': 'На этом хосте не обнаружена среда контейнеров (Docker, Podman, nerdctl или kubectl)', 'systemManager.tmux.windowsMismatch': 'В сессии указано {{count}} окон, но list-windows ничего не вернул', 'systemManager.tmux.lastCommand': 'последняя команда: {{command}}', - 'systemManager.tmux.noPanes': 'Нет панелей', - 'systemManager.tmux.panes': '{{count}} пан.', - 'systemManager.tmux.active': 'активно', 'systemManager.tmux.unnamedWindow': 'Безымянное окно', - 'systemManager.tmux.unnamedPane': 'Безымянная панель', 'systemManager.tmux.attachWindow': 'Подключить к окну', - 'systemManager.tmux.selectWindow': 'Выбрать окно', 'systemManager.tmux.killWindow': 'Закрыть окно', - 'systemManager.tmux.killPane': 'Закрыть панель', - 'systemManager.tmux.splitHorizontal': 'Разделить горизонтально', - 'systemManager.tmux.splitVertical': 'Разделить вертикально', - 'systemManager.tmux.sendKeys': 'Отправить клавиши', - 'systemManager.tmux.sendKeysTo': 'Отправить клавиши в окно {{window}} панель {{pane}}', - 'systemManager.tmux.sendKeysPlaceholder': 'Команда или текст…', 'systemManager.tmux.renameSessionPrompt': 'Переименовать сессию', 'systemManager.tmux.renameWindowPrompt': 'Переименовать окно', 'systemManager.tmux.windowName': 'Имя окна', 'systemManager.tmux.confirmKillSession': 'Завершить сессию tmux «{{name}}»?', 'systemManager.tmux.confirmDetachSession': 'Отключить всех клиентов от «{{name}}»?', 'systemManager.tmux.confirmKillWindow': 'Закрыть окно «{{name}}»?', - 'systemManager.tmux.confirmKillPane': 'Закрыть панель #{{index}}?', - 'systemManager.tmux.confirmKillServer': 'Остановить сервер tmux? Все сессии будут завершены.', 'systemManager.tmux.meta': '{{count}} сессий', - 'systemManager.docker.title': 'Контейнеры', 'systemManager.docker.subTabs.containers': 'Контейнеры', 'systemManager.docker.subTabs.images': 'Образы', 'systemManager.docker.empty': 'Контейнеры не найдены', @@ -174,7 +150,6 @@ export const ruSystemManagerMessages: Messages = { 'systemManager.docker.filter.paused': 'На паузе', 'systemManager.docker.shell': 'Оболочка', 'systemManager.docker.logs': 'Логи', - 'systemManager.docker.details': 'Детали', 'systemManager.docker.inspect': 'Проверить', 'systemManager.docker.imageInspect': 'Проверить образ', 'systemManager.docker.confirmRemove': 'Удалить этот контейнер?', diff --git a/application/i18n/locales/ru/terminal.ts b/application/i18n/locales/ru/terminal.ts index 4e0465709..c05124922 100644 --- a/application/i18n/locales/ru/terminal.ts +++ b/application/i18n/locales/ru/terminal.ts @@ -61,7 +61,6 @@ export const ruTerminalMessages: Messages = { 'logs.action.delete': 'Удалить', // Log view - 'logView.customizeAppearance': 'Настроить внешний вид', 'logView.appearance': 'Внешний вид', 'logView.readOnly': 'Только чтение', 'logView.export': 'Экспорт', @@ -74,7 +73,6 @@ export const ruTerminalMessages: Messages = { 'terminal.toolbar.availableAfterConnect': 'Доступно после подключения', 'terminal.toolbar.sendYmodem': 'Отправить через YMODEM', 'terminal.toolbar.receiveYmodem': 'Получить через YMODEM', - 'terminal.toolbar.sftp': 'SFTP', 'terminal.toolbar.more': 'Другие действия', 'terminal.toolbar.scripts': 'Скрипты', 'terminal.toolbar.history': 'История команд', @@ -122,7 +120,6 @@ export const ruTerminalMessages: Messages = { 'terminal.composeBar.resize': 'Изменить высоту строки ввода', 'terminal.composeBar.manageSnippets': 'Управление быстрыми сниппетами', 'terminal.composeBar.searchSnippets': 'Поиск сниппетов...', - 'terminal.composeBar.noPinnedSnippets': 'Закрепите сниппеты через + для быстрого доступа', 'terminal.composeBar.noMatchingSnippets': 'Сниппеты не найдены', 'terminal.composeBar.pinnedCount': 'Закреплено: {count}', 'terminal.composeBar.unpinSnippet': 'Убрать {label} из панели', @@ -214,7 +211,6 @@ export const ruTerminalMessages: Messages = { 'terminal.osc7Setup.title': 'Настроить отслеживание каталога', 'terminal.osc7Setup.desc': 'Netcatty добавит хуки OSC 7 для текущего удалённого пользователя. Это помогает SFTP следовать за каталогом терминала после sudo или su.', 'terminal.osc7Setup.targets': 'Возможные файлы для обновления', - 'terminal.osc7Setup.command': 'Команда для запуска', 'terminal.osc7Setup.run': 'Запустить настройку', 'terminal.osc7Setup.running': 'Настройка...', 'terminal.osc7Setup.configured': 'Отслеживание каталога настроено', @@ -297,9 +293,6 @@ export const ruTerminalMessages: Messages = { 'terminal.themeModal.themeType': 'Тема {type}', 'terminal.hiddenTheme.title': 'Текущая скрытая тема', 'terminal.hiddenTheme.desc': 'Эта тема скрыта из ручного выбора и будет заменена, когда вы выберете другую тему.', - 'topTabs.toggleTheme.systemExitTitle': 'Активна системная тема', - 'topTabs.toggleTheme.systemExitMessage': 'Откройте настройки, чтобы выбрать фиксированную светлую или тёмную тему.', - 'topTabs.toggleTheme.openSettings': 'Открыть настройки', // Custom Themes 'terminal.customTheme.section': 'Пользовательские темы', @@ -312,7 +305,6 @@ export const ruTerminalMessages: Messages = { 'terminal.customTheme.importDesc': 'Импорт из файла цветовой схемы iTerm2', 'terminal.customTheme.importError': 'Не удалось разобрать выбранный файл. Убедитесь, что это корректный XML-файл .itermcolors.', 'terminal.customTheme.delete': 'Удалить тему', - 'terminal.customTheme.confirmDelete': 'Подтвердить удаление', 'terminal.customTheme.name': 'Название', 'terminal.customTheme.namePlaceholder': 'Моя пользовательская тема', 'terminal.customTheme.type': 'Тип', @@ -372,10 +364,7 @@ export const ruTerminalMessages: Messages = { 'cloudSync.provider.disconnect.cloudRemains': 'Зашифрованные копии синхронизации могут остаться в хранилище {name}. Чтобы удалить их, удалите там файлы синхронизации. Отключение не очищает устройство для передачи другому человеку.', 'cloudSync.provider.disconnect.failed': 'Не удалось завершить отключение от {name}. Сохранённые данные подключения могут остаться. Повторите попытку.', 'cloudSync.provider.webdav': 'WebDAV', - 'cloudSync.provider.webdav.desc': 'Подключение к самостоятельно размещённому WebDAV endpoint', 'cloudSync.provider.s3': 'Совместимое с S3', - 'cloudSync.provider.s3.desc': 'Подключение к объектному хранилищу, совместимому с S3', - 'cloudSync.provider.comingSoon': 'Скоро', 'cloudSync.webdav.title': 'Настройки WebDAV', 'cloudSync.webdav.desc': 'Настройка WebDAV endpoint для зашифрованной синхронизации.', 'cloudSync.webdav.endpoint': 'Конечная точка URL', @@ -404,20 +393,6 @@ export const ruTerminalMessages: Messages = { 'cloudSync.s3.allowInsecure': 'Разрешить небезопасное соединение (игнорировать ошибки сертификата)', 'cloudSync.s3.showSecret': 'Показать секреты', 'cloudSync.s3.validation.required': 'Endpoint, регион, бакет, access key и secret обязательны.', - 'cloudSync.smb.title': 'Настройки SMB', - 'cloudSync.smb.desc': 'Подключение к файловой SMB/CIFS-шаре для зашифрованной синхронизации.', - 'cloudSync.smb.share': 'Путь к шаре', - 'cloudSync.smb.username': 'Имя пользователя', - 'cloudSync.smb.password': 'Пароль', - 'cloudSync.smb.domain': 'Домен (необязательно)', - 'cloudSync.smb.domainPlaceholder': 'например, WORKGROUP', - 'cloudSync.smb.port': 'Порт (необязательно)', - 'cloudSync.smb.showSecret': 'Показать пароль', - 'cloudSync.smb.validation.share': 'Путь к шаре обязателен.', - 'cloudSync.smb.validation.port': 'Порт должен быть числом от 1 до 65535.', - 'cloudSync.connect.smb.success': 'SMB успешно подключён', - 'cloudSync.connect.smb.failedTitle': 'Ошибка подключения SMB', - 'cloudSync.provider.smb': 'SMB-шара', 'cloudSync.connect.webdav.success': 'WebDAV успешно подключён', 'cloudSync.connect.webdav.failedTitle': 'Ошибка подключения WebDAV', 'cloudSync.connect.s3.success': 'S3 успешно подключён', @@ -434,7 +409,6 @@ export const ruTerminalMessages: Messages = { 'cloudSync.lastSync.minutesAgo': '{minutes} мин назад', 'cloudSync.changeKey': 'Изменить ключ', 'cloudSync.providers.title': 'Облачные провайдеры', - 'cloudSync.syncAll': 'Синхронизировать всех подключённых провайдеров', 'cloudSync.autoSync.title': 'Автосинхронизация', 'cloudSync.autoSync.desc': 'Автоматически синхронизировать при внесении изменений', 'cloudSync.strategy.title': 'Стратегия синхронизации', @@ -499,7 +473,6 @@ export const ruTerminalMessages: Messages = { 'cloudSync.localBackups.folderWarning': 'Эта папка сама по себе не является полной переносимой резервной копией. Удаление или очистка профиля приложения (userData) может сделать эти точки восстановления нечитаемыми.', 'cloudSync.localBackups.retentionTitle': 'Хранение резервных копий', 'cloudSync.localBackups.retentionDesc': 'Выберите, сколько локальных резервных копий должен хранить Netcatty.', - 'cloudSync.localBackups.maxCount': 'Макс. число копий', 'cloudSync.localBackups.maxSaved': 'Хранение резервных копий: {count}', 'cloudSync.localBackups.maxInvalid': 'Введите число от 1 до 100.', 'cloudSync.localBackups.empty': 'Локальных резервных копий пока нет.', @@ -622,10 +595,7 @@ export const ruTerminalMessages: Messages = { 'cloudSync.clearLocal.toast.desc': 'Локальная версия сброшена до 0. Выполните синхронизацию для загрузки из облака.', // Keychain - 'keychain.filter.key': 'Ключ', - 'keychain.filter.certificate': 'Сертификат', 'keychain.action.generateKey': 'Создать ключ', - 'keychain.action.importKey': 'Импорт. ключ', 'keychain.action.newIdentity': 'Новый ид-катор', 'keychain.action.importCertificate': 'Импорт. сертификат', 'keychain.view.grid': 'Сетка', @@ -666,20 +636,8 @@ export const ruTerminalMessages: Messages = { 'keychain.export.exporting': 'Экспорт...', 'keychain.export.exportAndAttach': 'Экспортировать и привязать', 'keychain.export.title': 'Экспорт ключа', - 'keychain.export.exportToRequired': 'Экспортировать в *', - 'keychain.export.selectHostPlaceholder': 'Выберите хост...', - 'keychain.export.locationLabel': 'Расположение ~ $1 *', - 'keychain.export.filenameLabel': 'Имя файла ~ $2 *', - 'keychain.export.advanced': 'Дополнительно', - 'keychain.export.note.supportsOnly': 'Экспорт ключей сейчас поддерживается только в', - 'keychain.export.note.systems': 'системах.', - 'keychain.export.note.use': 'Используйте', - 'keychain.export.note.customize': 'раздел для настройки скрипта экспорта.', - 'keychain.export.scriptRequired': 'Скрипт *', 'keychain.export.exportToHost': 'Экспортировать на хост', - 'keychain.export.failedGeneric': 'Ошибка экспорта: {message}', 'keychain.field.label': 'Метка', - 'keychain.field.labelRequired': 'Метка *', 'keychain.field.labelPlaceholder': 'Метка ключа', 'keychain.field.privateKeyRequired': 'Приватный ключ *', 'keychain.field.publicKey': 'Публичный ключ', @@ -715,13 +673,9 @@ export const ruTerminalMessages: Messages = { "fido.recovery.usePassword": "Использовать сохранённый пароль", "fido.recovery.passwordFallback": "Вход с паролем, настроенным для этого хоста", "fido.prompt.cancelled": "Проверка ключа безопасности отменена.", - 'fido.prompt.touchDone': 'Я коснулся', 'fido.prompt.timeout': 'Время ожидания FIDO истекло. Попробуйте снова.', - 'fido.error.opensshMissing': 'Нужен OpenSSH с FIDO/libfido2. macOS: brew install openssh libfido2.', - 'fido.error.agentUnavailable': 'Не удалось запустить SSH agent с FIDO.', 'keychain.generate.resident': 'Хранить учётные данные на ключе', 'keychain.generate.verifyRequired': 'Проверять PIN каждый раз', - 'keychain.action.loadResident': 'Загрузить resident-ключи с устройства', 'keychain.generate.keySize': 'Размер ключа', 'keychain.generate.labelPlaceholder': 'Метка ключа', 'keychain.generate.passphrasePlaceholder': 'Парольная фраза (необязательно)', @@ -731,7 +685,6 @@ export const ruTerminalMessages: Messages = { 'keychain.import.dropHint': 'Перетащите сюда файл ключа', 'keychain.import.importFromFile': 'Импортировать из файла', 'keychain.import.saveKey': 'Сохранить ключ', - 'keychain.import.importedKeyLabel': 'Импортированный ключ', 'keychain.identity.usernameRequired': 'Имя пользователя *', 'keychain.identity.method.passwordOnly': 'Пароль', 'keychain.identity.summary.password': 'Пароль аутентификации', @@ -740,14 +693,8 @@ export const ruTerminalMessages: Messages = { 'keychain.identity.summary.passwordAndKey': 'Пароль и ключ аутентификации', 'keychain.identity.summary.passwordAndCertificate': 'Пароль и сертификат аутентификации', 'keychain.identity.summary.none': 'Нет учётных данных', - 'keychain.identity.selectCredential': 'Выберите {kind}', 'keychain.identity.save': 'Сохранить', 'keychain.identity.update': 'Обновить', - 'keychain.keyDialog.newTitle': 'Новый ключ', - 'keychain.keyDialog.newDesc': 'Добавить новый SSH-ключ', - 'keychain.keyDialog.editTitle': 'Редактировать ключ', - 'keychain.keyDialog.editDesc': 'Обновить этот SSH-ключ', - 'keychain.keyDialog.updateKey': 'Обновить ключ', // Tabs 'tabs.closeSessionAria': 'Закрыть сессию', @@ -859,9 +806,6 @@ export const ruTerminalMessages: Messages = { 'snippets.import.modal.multipleFiles': 'Выбрано файлов: {count}', 'snippets.import.modal.parsedSummary': '{files} файл(ов), {total} сниппет(ов), {packages} пакет(ов), повторяющихся команд: {conflicts}. Привязки к хостам игнорируются.', 'snippets.import.modal.confirm': 'Подтвердить импорт', - 'snippets.import.conflict.title': 'Импортировать сниппеты?', - 'snippets.import.conflict.desc': 'Файл «{file}» содержит {total} сниппет(ов), из них повторяющихся команд: {conflicts}.', - 'snippets.import.conflict.hostBindingsNote': 'Привязки сниппетов к хостам не импортируются и не экспортируются.', 'snippets.import.conflict.skip': 'Пропустить повторы', 'snippets.import.conflict.overwrite': 'Перезаписать повторы', 'snippets.packageDialog.title': 'Новый пакет', @@ -908,9 +852,6 @@ export const ruTerminalMessages: Messages = { 'serial.field.customPort': 'Путь к пользовательскому порту', 'serial.field.namedPipeHint': 'Консоль ВМ Windows: введите \\\\.\\pipe\\name. ВМ должна создать канал как сервер. Скорость и параметры кадра игнорируются.', 'serial.field.customPortPlaceholder': 'например, /dev/ttys001 или COM1', - 'serial.type.hardware': 'Аппаратный', - 'serial.type.pseudo': 'Псевдотерминал', - 'serial.type.custom': 'Пользовательский', 'serial.parity.none': 'Нет', 'serial.parity.even': 'Чётная', 'serial.parity.odd': 'Нечётная', @@ -931,7 +872,6 @@ export const ruTerminalMessages: Messages = { 'serial.backspace.default': 'По умолчанию (DEL, 0x7F)', 'serial.backspace.ctrlH': 'Ctrl+H (BS, 0x08)', 'serial.field.charset': 'Кодировка', - 'serial.connectionError': 'Не удалось подключиться к последовательному порту', 'serial.field.baudRatePlaceholder': 'Выберите или введите скорость...', 'serial.field.baudRateEmpty': 'Введите пользовательскую скорость передачи', 'serial.field.customBaudRate': 'Используется пользовательская скорость передачи', @@ -950,10 +890,7 @@ export const ruTerminalMessages: Messages = { 'keyboard.interactive.title': 'Требуется аутентификация', 'keyboard.interactive.desc': 'Сервер требует дополнительную аутентификацию.', 'keyboard.interactive.descWithHost': 'Сервер {hostname} требует дополнительную аутентификацию.', - 'keyboard.interactive.response': 'Ответ', 'keyboard.interactive.verificationCode': 'Код подтверждения', - 'keyboard.interactive.enterCode': 'Введите код подтверждения', - 'keyboard.interactive.enterResponse': 'Введите ответ', 'keyboard.interactive.submit': 'Отправить', 'keyboard.interactive.verifying': 'Проверка...', 'keyboard.interactive.savePassword': 'Сохранить пароль', diff --git a/application/i18n/locales/ru/vault.ts b/application/i18n/locales/ru/vault.ts index 3570d17ed..0d7c50f4e 100644 --- a/application/i18n/locales/ru/vault.ts +++ b/application/i18n/locales/ru/vault.ts @@ -19,14 +19,6 @@ export const ruVaultMessages: Messages = { 'notes.export.toast.failed': 'Не удалось экспортировать заметки.', 'notes.codeBlock.copied': 'Скопировано', 'notes.codeBlock.copyFailed': 'Не удалось скопировать блок кода.', - 'notes.group.prompt': 'Путь папки', - 'notes.group.all': 'Блокнот', - 'notes.group.ungrouped': 'Без группы', - 'notes.section.notebooks': 'Блокнот', - 'notes.section.notes': 'Заметки', - 'notes.mode.edit': 'Правка', - 'notes.mode.split': 'Разделить', - 'notes.mode.preview': 'Просмотр', 'notes.title.placeholder': 'Заголовок заметки', 'notes.editor.placeholder': 'Пишите Markdown-заметки здесь...', 'notes.editor.unrenderableMarkdown': 'Эта заметка содержит Markdown, который не может отобразить визуальный редактор (например, незакрытые теги вида ). Показан исходный Markdown — содержимое не потеряно.', @@ -72,25 +64,18 @@ export const ruVaultMessages: Messages = { 'notes.toolbar.divider': 'Разделитель', 'notes.toolbar.link': 'Вставить ссылку', 'notes.toolbar.image': 'Вставить изображение', - 'notes.action.pin': 'Закрепить заметку', - 'notes.action.unpin': 'Открепить заметку', 'notes.tag.remove': 'Удалить тег', 'notes.tag.placeholder': 'Имя тега...', 'notes.tag.add': 'Добавить тег', 'notes.outline.title': 'Оглавление', - 'notes.outline.titleWithCount': 'Оглавление ({count})', 'notes.outline.empty': 'Нет заголовков', 'notes.outline.emptyHint': 'Используйте # и ## в Markdown для создания заголовков', 'notes.export.share': 'Экспорт и общий доступ', 'notes.export.currentNote': 'Текущая заметка', 'notes.export.exportMarkdown': 'Экспорт в Markdown (.md)', - 'notes.export.exportHtml': 'Экспорт в HTML (.html)', 'notes.export.copyMarkdown': 'Копировать исходный Markdown', 'notes.export.allNotes': 'Все заметки', 'notes.export.exportAllZip': 'Экспортировать все в ZIP-архив', - 'notes.export.toast.markdownSuccess': 'Markdown-файл экспортирован', - 'notes.export.toast.htmlSuccess': 'HTML-файл экспортирован', - 'notes.export.toast.zipSuccess': 'Все заметки экспортированы в архив ZIP', // Vault hosts header/actions 'vault.hosts.search.placeholder': 'Найти хост или ssh user@hostname / ssh -p 2222 user@hostname...', @@ -305,7 +290,6 @@ export const ruVaultMessages: Messages = { 'pf.tooltip.localDesc': 'Локальный проброс портов: доступ к удалённым сервисам через SSH-туннель', 'pf.tooltip.remoteDesc': 'Удалённый проброс портов: публикация локальных сервисов на удалённом хосте', 'pf.tooltip.dynamicDesc': 'Динамический SOCKS-прокси: маршрутизация трафика через SSH-туннель', - 'pf.deleteActive.title': 'Удалить активное правило проброса портов?', 'pf.deleteActive.desc': 'Правило проброса портов "{label}" сейчас активно. При удалении туннель будет сначала остановлен.', 'pf.deleteActive.confirm': 'Остановить и удалить', 'pf.form.autoStart': 'Автозапуск', @@ -339,13 +323,9 @@ export const ruVaultMessages: Messages = { 'sftp.columns.actions': 'Действия', 'sftp.sort.directoriesFirst': 'Папки сверху', 'sftp.emptyDirectory': 'Пустой каталог', - 'sftp.nav.up': 'Наверх', - 'sftp.nav.home': 'Перейти в домашний каталог', - 'sftp.nav.refresh': 'Обновить', 'sftp.upload': 'Загрузить', 'sftp.uploadFiles': 'Загрузить файлы', 'sftp.uploadFolder': 'Загрузить папку', - 'sftp.dragDropToUpload': 'Перетащите сюда файлы для загрузки', 'sftp.retry': 'Повторить', 'sftp.context.open': 'Открыть', 'sftp.context.navigateTo': 'Перейти к', @@ -384,28 +364,21 @@ export const ruVaultMessages: Messages = { 'sftp.copyCurrentPath': 'Копировать текущий путь', 'sftp.copyCurrentPath.success': 'Текущий путь скопирован', 'sftp.copyCurrentPath.error': 'Не удалось скопировать текущий путь', - 'sftp.viewMode.label': 'Режим просмотра', 'sftp.viewMode.list': 'Список', 'sftp.viewMode.tree': 'Дерево', 'sftp.viewMode.switchToList': 'Переключиться на список', 'sftp.viewMode.switchToTree': 'Переключиться на дерево', - 'sftp.listDensity.compact': 'Компактный список', - 'sftp.listDensity.comfortable': 'Обычный список', 'sftp.listDensity.switchToCompact': 'Переключиться на компактный список', 'sftp.listDensity.switchToComfortable': 'Переключиться на обычный список', 'sftp.tree.loadError': 'Не удалось загрузить каталог', 'sftp.tree.loading': 'Загрузка...', 'sftp.kind.folder': 'Папка', - 'sftp.context.rename': 'Переименовать', 'sftp.context.permissions': 'Права доступа', - 'sftp.context.delete': 'Удалить', 'sftp.context.refresh': 'Обновить', 'sftp.context.uploadFiles': 'Загрузить файл(ы)...', 'sftp.context.uploadFilesHere': 'Загрузить файлы сюда...', 'sftp.context.uploadFolder': 'Загрузить папку...', 'sftp.context.uploadFolderHere': 'Загрузить папку сюда...', - 'sftp.context.downloadSelected': 'Скачать выбранное ({count})', - 'sftp.context.deleteSelected': 'Удалить выбранное ({count})', 'sftp.dropFilesHere': 'Перетащите сюда файлы', 'sftp.itemsCount': '{count} записей', 'sftp.selectedCount': '{count} выбрано', @@ -414,8 +387,6 @@ export const ruVaultMessages: Messages = { 'sftp.task.waiting': 'Ожидание...', 'sftp.transfer.preparing': 'подготовка...', 'sftp.status.loading': 'Загрузка...', - 'sftp.status.uploading': 'Загрузка...', - 'sftp.status.ready': 'Готово', 'sftp.transfers': 'Передачи', 'sftp.transfers.active': '{count} активн(ый/ых)', 'sftp.transfers.clearCompleted': 'Очистить завершённые', @@ -478,7 +449,6 @@ export const ruVaultMessages: Messages = { 'sftp.transferCenter.applyAll': 'Применить ко всем', 'sftp.transfers.resizeNameColumn': 'Изменить ширину столбца имени файла', 'sftp.transfers.dragToResize': 'Перетащите для изменения размера', - 'sftp.goUp': 'Наверх', 'sftp.goToTerminalCwd': 'Перейти в каталог терминала', 'sftp.locatePathInTerminal': 'Открыть путь в терминале', 'sftp.followTerminalCwd': 'Следовать за каталогом терминала', @@ -494,29 +464,22 @@ export const ruVaultMessages: Messages = { 'sftp.folderName.placeholder': 'Введите имя папки', 'sftp.fileName': 'Имя файла', 'sftp.fileName.placeholder': 'Введите имя файла', - 'sftp.prompt.newFolderName': 'Имя новой папки?', 'sftp.rename.title': 'Переименовать', 'sftp.rename.newName': 'Новое имя', 'sftp.rename.placeholder': 'Введите новое имя', - 'sftp.confirm.deleteOne': 'Удалить "{name}"?', - 'sftp.deleteConfirm.single': 'Удалить "{name}"?', 'sftp.deleteConfirm.title': 'Удалить {count} элемент(ов)?', 'sftp.deleteConfirm.desc': 'Это действие нельзя отменить. Будет удалено следующее:', 'sftp.deleteConfirm.descSingle': 'Это действие нельзя отменить.', 'sftp.deleteConfirm.host': 'Хост', 'sftp.deleteConfirm.path': 'Путь', - 'sftp.error.loadFailed': 'Не удалось загрузить каталог', 'sftp.error.downloadFailed': 'Ошибка скачивания', 'sftp.error.uploadFailed': 'Ошибка загрузки', 'sftp.error.deleteFailed': 'Ошибка удаления', - 'sftp.error.createFolderFailed': 'Не удалось создать папку', - 'sftp.error.createFileFailed': 'Не удалось создать файл', 'sftp.error.invalidFileName': 'Имя файла содержит недопустимые символы: {chars}', 'sftp.error.reservedName': 'Это имя файла зарезервировано системой', 'sftp.overwrite.title': 'Файл уже существует', 'sftp.overwrite.desc': 'Файл с именем "{name}" уже существует. Хотите заменить его?', 'sftp.overwrite.confirm': 'Заменить', - 'sftp.error.renameFailed': 'Не удалось переименовать', 'sftp.picker.title': 'Выберите хост', 'sftp.picker.desc': 'Выберите хост для панели {side}', 'sftp.picker.searchPlaceholder': 'Поиск хостов...', @@ -524,8 +487,6 @@ export const ruVaultMessages: Messages = { 'sftp.picker.local.desc': 'Просмотр локальных файлов', 'sftp.picker.local.badge': 'Локально', 'sftp.picker.connected.section': 'Подключённые', - 'sftp.picker.connected.badge': 'Онлайн', - 'sftp.picker.connected.connecting': 'Подключение', 'sftp.picker.noMatch': 'Подходящие хосты не найдены', 'sftp.permissions.title': 'Изменить права доступа', 'sftp.permissions.owner': 'Владелец', @@ -533,16 +494,12 @@ export const ruVaultMessages: Messages = { 'sftp.permissions.others': 'Остальные', 'sftp.permissions.octal': 'Восьмеричный', 'sftp.permissions.symbolic': 'Символьный', - 'sftp.permissions.success': 'Права доступа успешно обновлены', - 'sftp.permissions.failed': 'Не удалось обновить права доступа', 'sftp.pane.local': 'Локально', 'sftp.pane.remote': 'Удалённо', 'sftp.pane.selectHost': 'Выберите хост', 'sftp.pane.selectHostToStart': 'Выберите хост для начала', 'sftp.pane.chooseFilesystem': 'Выберите локальную или удалённую файловую систему для просмотра', 'sftp.tabs.addTab': 'Добавить новую вкладку', - 'sftp.tabs.closeTab': 'Закрыть вкладку', - 'sftp.tabs.newTab': 'Новая вкладка', 'sftp.tabs.copyDefaultPath': 'Копировать вкладку (путь по умолчанию)', 'sftp.tabs.copyCurrentPath': 'Копировать и перейти к текущему пути', 'sftp.conflict.title': 'Конфликт файлов', @@ -568,47 +525,24 @@ export const ruVaultMessages: Messages = { 'sftp.conflict.action.replace': 'Заменить', // SFTP Upload Phases - 'sftp.upload.phase.compressing': 'Сжатие', - 'sftp.upload.phase.uploading': 'Загрузка', - 'sftp.upload.phase.extracting': 'Распаковка', - 'sftp.upload.phase.compressed': 'Сжато', // SFTP File Opener 'sftp.context.copyPath': 'Копировать путь к файлу', 'sftp.context.openWithDefault': 'Открыть в системном приложении', 'sftp.context.openWith': 'Открыть с помощью...', 'sftp.context.edit': 'Редактировать', - 'sftp.context.preview': 'Предпросмотр', 'sftp.opener.title': 'Открыть с помощью', - 'sftp.opener.desc': 'Выберите приложение для открытия этого файла', 'sftp.opener.builtInEditor': 'Встроенный редактор', 'sftp.opener.editDescription': 'Редактировать текстовые файлы', - 'sftp.opener.builtInImageViewer': 'Встроенный просмотрщик изображений', - 'sftp.opener.previewDescription': 'Просмотр изображений', 'sftp.opener.systemApp': 'Выбрать приложение...', 'sftp.opener.systemAppDescription': 'Выберите приложение на вашем компьютере', - 'sftp.opener.onlySystemApp': 'Этот файл можно открыть только во внешнем приложении', - 'sftp.opener.noAppsAvailable': 'Нет доступных приложений', 'sftp.opener.noExtension': 'файлы без расширения', 'sftp.opener.setDefault': 'Всегда использовать это для файлов {ext}', - 'sftp.opener.confirmTitle': 'Установить по умолчанию?', - 'sftp.opener.confirmDescription': 'Хотите всегда использовать {app} для файлов {ext}?', - 'sftp.opener.yesRemember': 'Да, запомнить выбор', - 'sftp.opener.justOnce': 'Только один раз', - 'sftp.opener.confirm.title': 'Установить приложение по умолчанию', - 'sftp.opener.confirm.desc': 'Хотите всегда открывать файлы .{ext} этим приложением?', - 'sftp.editor.title': 'Текстовый редактор', 'sftp.editor.save': 'Сохранить на удалённый сервер', 'sftp.editor.saving': 'Сохранение...', 'sftp.editor.saved': 'Успешно сохранено', 'sftp.editor.saveFailed': 'Не удалось сохранить файл', - 'sftp.editor.unsavedChanges': 'У вас есть несохранённые изменения. Всё равно закрыть?', 'sftp.editor.syntaxHighlight': 'Подсветка синтаксиса', - 'sftp.preview.title': 'Просмотр изображения', - 'sftp.preview.zoomIn': 'Увеличить', - 'sftp.preview.zoomOut': 'Уменьшить', - 'sftp.preview.resetZoom': 'Сбросить масштаб', - 'sftp.preview.fitToWindow': 'Подогнать по окну', // Settings > SFTP File Associations 'settings.tab.sftpFileAssociations': 'SFTP', @@ -687,28 +621,16 @@ export const ruVaultMessages: Messages = { 'sftp.autoSync.error': 'Не удалось синхронизировать файл: {error}', // SFTP Folder Upload Progress - 'sftp.upload.progress': 'Загрузка файлов {current} из {total}...', - 'sftp.upload.uploading': 'Загрузка...', - 'sftp.upload.compressing': 'Сжатие...', - 'sftp.upload.extracting': 'Распаковка...', - 'sftp.upload.scanning': 'Сканирование файлов...', - 'sftp.upload.completed': 'Завершено', - 'sftp.upload.compressed': 'Сжатая передача', - 'sftp.upload.currentFile': 'Текущий: {fileName}', 'sftp.upload.cancelled': 'Загрузка отменена', 'sftp.upload.noFiles': 'Нет файлов для загрузки', 'sftp.upload.partialSuccess': 'Загружено: {success}; ошибок: {failed}', 'sftp.upload.cancel': 'Отмена', - 'sftp.upload.completedToPath': 'Загружено в {path}', // SFTP Download - 'sftp.download.completed': 'Скачано', - 'sftp.download.cancelled': 'Скачивание отменено', // SFTP Reconnecting 'sftp.reconnecting.title': 'Переподключение...', 'sftp.reconnecting.desc': 'Соединение потеряно, выполняется попытка переподключения', - 'sftp.reconnected': 'Соединение восстановлено', 'sftp.error.reconnectFailed': 'Не удалось переподключиться. Попробуйте ещё раз.', 'sftp.error.connectionLostManual': 'Соединение потеряно. Пожалуйста, переподключитесь вручную.', 'sftp.error.connectionLostReconnecting': 'Соединение потеряно. Переподключение...', @@ -783,12 +705,6 @@ export const ruVaultMessages: Messages = { 'vault.panel.resizeWidth': 'Изменить ширину панели', 'hostDetails.saveAria': 'Сохранить', 'hostConnectionTest.title': 'Проверка подключения', - 'hostConnectionTest.test': 'Проверить', - 'hostConnectionTest.chainOf': 'Цепочка {current} из {total}', - 'hostConnectionTest.success': 'Подключение успешно', - 'hostConnectionTest.successHint': 'Хост принял ваши учётные данные. Можно закрыть окно.', - 'hostConnectionTest.connecting': 'Подключение… таймаут через {seconds} с', - 'hostConnectionTest.failed': 'Не удалось подключиться.', 'hostConnectionTest.retry': 'Повторить', 'hostConnectionTest.credentialsUnavailable': 'Сохранённые учётные данные не удаётся расшифровать на этом устройстве. Введите их заново ниже.', 'hostDetails.section.address': 'Адрес', @@ -825,11 +741,8 @@ export const ruVaultMessages: Messages = { 'hostDetails.notes.toggle.show': 'Показать редактор заметок', 'hostDetails.notes.toggle.hide': 'Скрыть редактор заметок', 'hostDetails.group.placeholder': 'Родительская группа', - 'hostDetails.section.credentials': 'Учётные данные', 'hostDetails.section.portCredentials': 'Порт и учётные данные', 'hostDetails.section.appearance': 'Внешний вид', - 'hostDetails.distro.title': 'Дистрибутив Linux', - 'hostDetails.distro.desc': 'Автоопределение при подключении или ручная замена значка дистрибутива.', 'hostDetails.icon.title': 'Значок хоста', 'hostDetails.icon.sectionTitle': 'Цвет и значок', 'hostDetails.icon.desc': 'Выберите источник значка и цвет для этого хоста.', @@ -841,7 +754,6 @@ export const ruVaultMessages: Messages = { 'hostDetails.icon.mode.custom': 'Свой', 'hostDetails.icon.reset': 'Сбросить значок', 'hostDetails.icon.colorLabel': 'Цвет значка', - 'hostDetails.icon.colorDefault': 'По умолчанию', 'hostDetails.icon.colorAuto': 'Авто', 'hostDetails.icon.colorManual': 'Вручную', 'hostDetails.icon.colorChoice': 'Цвет', @@ -892,7 +804,6 @@ export const ruVaultMessages: Messages = { 'hostDetails.distro.mode.auto': 'Автоопределение', 'hostDetails.distro.mode.manual': 'Ручное переопределение', 'hostDetails.distro.detectedLabel': 'Текущий', - 'hostDetails.distro.manualLabel': 'Переопределить', 'hostDetails.distro.pending': 'Определится после первого подключения', 'hostDetails.distro.unknown': 'Неизвестно', 'hostDetails.distro.option.linux': 'Обычный Linux', @@ -940,7 +851,6 @@ export const ruVaultMessages: Messages = { 'hostDetails.auth.mfaFirst': 'Сначала интерактивная аутентификация', 'hostDetails.auth.mfaFirst.desc': 'Для серверов, которым нужны пароль и MFA через keyboard-interactive.', 'hostDetails.totp.title': 'Аутентификатор (TOTP)', - 'hostDetails.totp.enable': 'Сохранить секрет TOTP для этого хоста', 'hostDetails.totp.setup': 'Настроить…', 'hostDetails.totp.edit': 'Изменить', 'hostDetails.totp.modalTitle': 'Настройка аутентификатора', @@ -1043,10 +953,8 @@ export const ruVaultMessages: Messages = { 'hostDetails.jumpHosts.direct': 'Напрямую', 'hostDetails.jumpHosts.configure': 'Настроить прокси-хосты', 'hostDetails.proxy': 'Прокси через HTTP/SOCKS5/Command', - 'hostDetails.proxy.none': 'Нет', 'hostDetails.proxy.direct': 'Напрямую (без прокси)', 'hostDetails.proxy.directHint': 'Не использует прокси группы или глобальный прокси по умолчанию', - 'hostDetails.proxy.edit': 'Редактировать прокси', 'hostDetails.proxy.configure': 'Настроить прокси', 'hostDetails.proxyPanel.title': 'Прокси через HTTP/SOCKS5/Command', 'hostDetails.proxyPanel.hostPlaceholder': 'Прокси-хост', @@ -1056,7 +964,6 @@ export const ruVaultMessages: Messages = { 'hostDetails.proxyPanel.credentials': 'Учётные данные', 'hostDetails.proxyPanel.usernamePlaceholder': 'Имя пользователя', 'hostDetails.proxyPanel.passwordPlaceholder': 'Пароль', - 'hostDetails.proxyPanel.identities': 'Идентификаторы', 'hostDetails.proxyPanel.keychainIdentity': 'Идентификатор из связки ключей', 'hostDetails.proxyPanel.manualCredentials': 'Ввести вручную', 'hostDetails.proxyPanel.remove': 'Удалить прокси', @@ -1079,8 +986,6 @@ export const ruVaultMessages: Messages = { 'hostDetails.envVars.newVariable': 'Новая переменная', 'hostDetails.envVars.variableName': 'Имя переменной', 'hostDetails.chain.title': 'Редактировать цепочку', - 'hostDetails.chain.desc': 'Добавление ещё одного хоста создаст подключение к {host}.', - 'hostDetails.chain.addHost': 'Добавить хост', 'hostDetails.chain.target': 'Цель', 'hostDetails.chain.availableHosts': 'Доступные хосты', 'hostDetails.chain.clear': 'Очистить', @@ -1146,28 +1051,14 @@ export const ruVaultMessages: Messages = { 'hostDetails.plugin.useSsh': 'Использовать SSH', // Host form (legacy modal) - 'hostForm.title.edit': 'Редактировать хост', - 'hostForm.title.new': 'Новый хост', - 'hostForm.desc.edit': 'Обновите параметры подключения для этого хоста', - 'hostForm.desc.new': 'Создайте новую запись SSH-хоста', 'hostForm.field.label': 'Метка', - 'hostForm.placeholder.label': 'Мой production-сервер', 'hostForm.field.hostname': 'Имя хоста / IP', - 'hostForm.placeholder.hostname': '192.168.1.1', 'hostForm.field.port': 'Порт', 'hostForm.field.username': 'Имя пользователя', 'hostForm.field.osType': 'Тип ОС', - 'hostForm.placeholder.selectOs': 'Выберите ОС', 'hostForm.field.group': 'Группа', - 'hostForm.placeholder.group': 'например, AWS, DigitalOcean', 'hostForm.field.tags': 'Теги', - 'hostForm.placeholder.addTag': 'Добавить тег...', - 'hostForm.auth.method': 'Метод аутентификации', - 'hostForm.auth.password': 'Пароль', - 'hostForm.auth.sshKey': 'SSH-ключ', 'hostForm.auth.selectKey': 'Выберите SSH-ключ', - 'hostForm.auth.noKeys': 'Нет доступных ключей', - 'hostForm.auth.noKeysHint': 'В связке ключей не найдено SSH-ключей. Сначала создайте один.', 'hostForm.saveHost': 'Сохранить хост', 'vault.import.plugins.title': 'Импортёры плагинов', 'vault.import.plugins.loading': 'Создание безопасного предварительного просмотра…', diff --git a/application/i18n/locales/serverStatsGpu.test.ts b/application/i18n/locales/serverStatsGpu.test.ts deleted file mode 100644 index 0c93275f5..000000000 --- a/application/i18n/locales/serverStatsGpu.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import { enTerminalMessages } from "./en/terminal"; -import { esTerminalMessages } from "./es/terminal"; -import { ruTerminalMessages } from "./ru/terminal"; -import { zhCNVaultMessages } from "./zh-CN/vault"; -import { zhTWVaultMessages } from "./zh-TW/vault"; - -test("per-GPU stats strings exist in every locale", () => { - const labels = [ - [enTerminalMessages, "GPU Device Usage", "GPU {{index}}"], - [esTerminalMessages, "Uso de cada GPU", "GPU {{index}}"], - [ruTerminalMessages, "Использование видеокарт", "GPU {{index}}"], - [zhCNVaultMessages, "GPU 设备使用率", "GPU {{index}}"], - [zhTWVaultMessages, "GPU 裝置使用率", "GPU {{index}}"], - ] as const; - - for (const [messages, devices, indexLabel] of labels) { - assert.equal(messages["terminal.serverStats.gpuDevices"], devices); - assert.equal(messages["terminal.serverStats.gpuIndex"], indexLabel); - } -}); diff --git a/application/i18n/locales/serverStatsLatency.test.ts b/application/i18n/locales/serverStatsLatency.test.ts deleted file mode 100644 index 266ce89fa..000000000 --- a/application/i18n/locales/serverStatsLatency.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import { enSystemManagerMessages } from "./en/systemManager"; -import { enTerminalMessages } from "./en/terminal"; -import { ruSystemManagerMessages } from "./ru/systemManager"; -import { ruTerminalMessages } from "./ru/terminal"; -import { esSystemManagerMessages } from "./es/systemManager"; -import { esTerminalMessages } from "./es/terminal"; -import { zhCnSystemManagerMessages } from "./zh-CN/systemManager"; -import { zhCNVaultMessages } from "./zh-CN/vault"; -import { zhTwSystemManagerMessages } from "./zh-TW/systemManager"; -import { zhTWVaultMessages } from "./zh-TW/vault"; - -test("SSH network latency is explicit in every locale and UI surface", () => { - const labels = [ - [enTerminalMessages, enSystemManagerMessages, "SSH network latency"], - [ruTerminalMessages, ruSystemManagerMessages, "Сетевая задержка SSH"], - [esTerminalMessages, esSystemManagerMessages, "Latencia de red SSH"], - [zhCNVaultMessages, zhCnSystemManagerMessages, "SSH 网络延迟"], - [zhTWVaultMessages, zhTwSystemManagerMessages, "SSH 網路延遲"], - ] as const; - - for (const [terminalMessages, systemManagerMessages, expected] of labels) { - assert.equal(terminalMessages["terminal.serverStats.latency"], expected); - assert.equal(systemManagerMessages["systemManager.overview.latency"], expected); - } -}); diff --git a/application/i18n/locales/sftpCleanupWarningLocales.test.ts b/application/i18n/locales/sftpCleanupWarningLocales.test.ts deleted file mode 100644 index 3d56d8a8e..000000000 --- a/application/i18n/locales/sftpCleanupWarningLocales.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import en from "./en"; -import es from "./es"; -import ru from "./ru"; -import zhCN from "./zh-CN"; -import zhTW from "./zh-TW"; - -test("folder cleanup-warning counts are localized in every supported locale", () => { - for (const [locale, messages] of Object.entries({ en, es, ru, zhCN, zhTW })) { - assert.match(messages["sftp.transfers.cleanupWarnings"] ?? "", /\{count\}/, locale); - } -}); diff --git a/application/i18n/locales/sftpConflictLocales.test.ts b/application/i18n/locales/sftpConflictLocales.test.ts deleted file mode 100644 index 68c1f2edb..000000000 --- a/application/i18n/locales/sftpConflictLocales.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; - -import { enVaultMessages } from './en/vault.ts'; -import { esVaultMessages } from './es/vault.ts'; -import { ruVaultMessages } from './ru/vault.ts'; -import { zhCNVaultMessages } from './zh-CN/vault.ts'; -import { zhTWVaultMessages } from './zh-TW/vault.ts'; - -const FOLDER_CONFLICT_KEYS = [ - 'sftp.conflict.folderTitle', - 'sftp.conflict.folderDesc', - 'sftp.conflict.folderFileDesc', - 'sftp.conflict.folderSymlinkDesc', - 'sftp.conflict.folderUnknownDesc', - 'sftp.conflict.folderMergeHint', - 'sftp.conflict.folderReplaceWarning', -] as const; - -test('folder conflict safety copy exists in every supported locale', () => { - const locales = { - en: enVaultMessages, - es: esVaultMessages, - ru: ruVaultMessages, - 'zh-CN': zhCNVaultMessages, - 'zh-TW': zhTWVaultMessages, - }; - - for (const [locale, messages] of Object.entries(locales)) { - for (const key of FOLDER_CONFLICT_KEYS) { - assert.equal(typeof messages[key], 'string', `${locale} is missing ${key}`); - assert.notEqual(messages[key]?.trim(), '', `${locale} has an empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/snippetBulkDeleteLocales.test.ts b/application/i18n/locales/snippetBulkDeleteLocales.test.ts deleted file mode 100644 index 3accaad96..000000000 --- a/application/i18n/locales/snippetBulkDeleteLocales.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en.ts'; -import ru from './ru.ts'; -import es from './es.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const KEYS = [ - 'snippets.selection.deleteSelected', - 'snippets.selection.deleteConfirmTitle', - 'snippets.selection.deleteConfirmDesc', - 'snippets.selection.deleteSuccess', -] as const; - -test('snippet bulk-delete copy exists in every locale', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - const missing = KEYS.filter((key) => !messages[key]); - assert.deepEqual(missing, [], `${locale} is missing snippet bulk-delete copy`); - } -}); - -test('snippet shortkey system-conflict copy names the conflicting action', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - const text = messages['snippets.shortkey.error.systemConflict']; - assert.match( - text ?? '', - /\{name\}/, - `${locale} system-conflict copy should include {name}`, - ); - } -}); - -test('English bulk-delete copy is entity-neutral and grammatical for one item', () => { - assert.equal( - en['snippets.selection.deleteConfirmTitle'].replace('{count}', '1'), - 'Delete selected items (1)?', - ); - assert.equal( - en['snippets.selection.deleteSuccess'].replace('{count}', '1'), - 'Deleted selected items: 1.', - ); -}); diff --git a/application/i18n/locales/terminalHostManagementLocales.test.ts b/application/i18n/locales/terminalHostManagementLocales.test.ts deleted file mode 100644 index 494a39e22..000000000 --- a/application/i18n/locales/terminalHostManagementLocales.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en'; -import ru from './ru'; -import es from './es'; -import zhCN from './zh-CN'; -import zhTW from './zh-TW'; - -const keys = [ - 'terminal.layer.hostTree.newHost', - 'terminal.layer.hostTree.newHostInGroup', - 'terminal.layer.hostTree.editHost', - 'terminal.layer.hostTree.hostSavedNextConnection', -] as const; - -test('terminal host management strings exist in every shipped locale', () => { - for (const [locale, messages] of Object.entries({ en, es, 'zh-CN': zhCN, 'zh-TW': zhTW, ru })) { - for (const key of keys) { - assert.equal(typeof messages[key], 'string', `${locale} is missing ${key}`); - assert.notEqual(messages[key], '', `${locale} has an empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/terminalInlineImageLocales.test.ts b/application/i18n/locales/terminalInlineImageLocales.test.ts deleted file mode 100644 index 06b57b59b..000000000 --- a/application/i18n/locales/terminalInlineImageLocales.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import en from "./en.ts"; -import ru from "./ru.ts"; -import es from "./es.ts"; -import zhCN from "./zh-CN.ts"; -import zhTW from "./zh-TW.ts"; - -const INLINE_IMAGE_KEYS = [ - "settings.terminal.section.inlineImages", - "settings.terminal.inlineImages.enabled", - "settings.terminal.inlineImages.enabled.desc", - "settings.terminal.inlineImages.kitty", - "settings.terminal.inlineImages.kitty.desc", - "settings.terminal.inlineImages.sixel", - "settings.terminal.inlineImages.sixel.desc", - "settings.terminal.inlineImages.iip", - "settings.terminal.inlineImages.iip.desc", - "settings.terminal.inlineImages.storageLimit", - "settings.terminal.inlineImages.storageLimit.desc", - "settings.terminal.inlineImages.maxMegapixels", - "settings.terminal.inlineImages.maxMegapixels.desc", - "settings.terminal.inlineImages.sequenceLimit", - "settings.terminal.inlineImages.sequenceLimit.desc", - "settings.terminal.inlineImages.unit.mb", - "settings.terminal.inlineImages.unit.megapixels", - "settings.terminal.inlineImages.hibernateNote", -]; - -const LOCALES = [ - { name: "en", messages: en }, - { name: "es", messages: es }, - { name: "zh-CN", messages: zhCN }, - { name: "zh-TW", messages: zhTW }, - { name: "ru", messages: ru }, -]; - -test("every locale ships the inline image settings strings", () => { - for (const locale of LOCALES) { - const missing = INLINE_IMAGE_KEYS.filter((key) => !locale.messages[key]); - assert.deepEqual(missing, [], `${locale.name} is missing inline image settings labels`); - } -}); - -test("inline image strings are actually translated, not copied from English", () => { - const translatedKeys = INLINE_IMAGE_KEYS.filter( - (key) => !key.startsWith("settings.terminal.inlineImages.unit.") - && key !== "settings.terminal.inlineImages.sixel", - ); - - for (const locale of LOCALES) { - if (locale.name === "en") continue; - const untranslated = translatedKeys.filter((key) => locale.messages[key] === en[key]); - assert.deepEqual(untranslated, [], `${locale.name} still uses the English string`); - } -}); diff --git a/application/i18n/locales/terminalOsc7Locales.test.ts b/application/i18n/locales/terminalOsc7Locales.test.ts deleted file mode 100644 index 07ddc5ab5..000000000 --- a/application/i18n/locales/terminalOsc7Locales.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import en from "./en.ts"; -import ru from "./ru.ts"; -import es from "./es.ts"; -import zhCN from "./zh-CN.ts"; - -const osc7Keys = [ - "terminal.toolbar.configureOsc7", - "terminal.osc7Setup.title", - "terminal.osc7Setup.desc", - "terminal.osc7Setup.targets", - "terminal.osc7Setup.command", - "terminal.osc7Setup.run", - "terminal.osc7Setup.running", - "terminal.osc7Setup.configured", - "terminal.osc7Setup.failed", - "terminal.osc7Setup.sent", -] as const; - -test("OSC 7 setup copy exists in every bundled locale", () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN })) { - for (const key of osc7Keys) { - assert.equal(typeof messages[key], "string", `${locale} is missing ${key}`); - assert.notEqual(messages[key], "", `${locale} has empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/terminalReconnectLocales.test.ts b/application/i18n/locales/terminalReconnectLocales.test.ts deleted file mode 100644 index 855a4574a..000000000 --- a/application/i18n/locales/terminalReconnectLocales.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import { enTerminalMessages } from "./en/terminal"; -import { esTerminalMessages } from "./es/terminal"; -import { ruTerminalMessages } from "./ru/terminal"; -import { zhCNTerminalMessages } from "./zh-CN/terminal"; -import { zhTWTerminalMessages } from "./zh-TW/terminal"; - -test("terminal reconnect notices are localized in every bundled language", () => { - const messages = [ - enTerminalMessages, - esTerminalMessages, - ruTerminalMessages, - zhCNTerminalMessages, - zhTWTerminalMessages, - ]; - const keys = [ - "terminal.progress.enterReconnectHint", - "terminal.progress.reconnecting", - "terminal.progress.autoReconnectScheduled", - "terminal.progress.autoReconnectAttempt", - ]; - - for (const locale of messages) { - for (const key of keys) { - assert.equal(typeof locale[key], "string", `missing ${key}`); - assert.notEqual(locale[key]?.trim(), "", `empty ${key}`); - } - } -}); diff --git a/application/i18n/locales/terminalSessionLogLocales.test.ts b/application/i18n/locales/terminalSessionLogLocales.test.ts deleted file mode 100644 index 5d09e3587..000000000 --- a/application/i18n/locales/terminalSessionLogLocales.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import en from './en'; -import es from './es'; -import ru from './ru'; -import zhCN from './zh-CN'; -import zhTW from './zh-TW'; - -const keys = [ - 'terminal.toolbar.openSessionLog', - 'terminal.toolbar.sessionLogActions', - 'terminal.toolbar.sessionLog.menu', - 'terminal.toolbar.sessionLog.open', - 'terminal.toolbar.sessionLog.reveal', - 'terminal.toolbar.sessionLog.chooseApplication', - 'terminal.toolbar.sessionLog.systemDefault', - 'terminal.toolbar.openSessionLogFailed', -] as const; - -test('saved session log actions are translated in every shipped locale', () => { - for (const [locale, messages] of Object.entries({ en, es, ru, 'zh-CN': zhCN, 'zh-TW': zhTW })) { - for (const key of keys) assert.ok(messages[key], `${locale} is missing ${key}`); - assert.equal(messages['terminal.toolbar.sessionLog.rememberApplication'], undefined); - } - assert.equal(en['terminal.toolbar.sessionLog.menu'], 'Session log'); - assert.equal(en['terminal.toolbar.sessionLog.open'], 'Open'); - assert.equal(en['terminal.toolbar.sessionLog.reveal'], 'Show in folder'); - assert.equal(en['terminal.toolbar.sessionLog.chooseApplication'], 'Open with…'); - assert.equal(en['terminal.toolbar.sessionLog.systemDefault'], 'Open with system default'); - assert.equal(zhCN['terminal.toolbar.sessionLog.menu'], '会话日志'); - assert.equal(zhTW['terminal.toolbar.sessionLog.menu'], '工作階段日誌'); -}); diff --git a/application/i18n/locales/undoLastTurnLocales.test.ts b/application/i18n/locales/undoLastTurnLocales.test.ts deleted file mode 100644 index 32ace3e62..000000000 --- a/application/i18n/locales/undoLastTurnLocales.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en.ts'; -import ru from './ru.ts'; -import es from './es.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const UNDO_KEYS = [ - 'ai.chat.undoLastTurn', - 'ai.chat.undoLastTurnNotice', -] as const; - -test('Undo-last-turn UI is localized in every supported locale', () => { - for (const [name, messages] of Object.entries({ en, es, 'zh-CN': zhCN, 'zh-TW': zhTW, ru })) { - const missing = UNDO_KEYS.filter(key => !messages[key]); - assert.deepEqual(missing, [], `${name} is missing undo-last-turn labels`); - } -}); diff --git a/application/i18n/locales/vaultBulkImportLocales.test.ts b/application/i18n/locales/vaultBulkImportLocales.test.ts deleted file mode 100644 index fe7e9b7c5..000000000 --- a/application/i18n/locales/vaultBulkImportLocales.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import en from "./en.ts"; -import ru from "./ru.ts"; -import es from "./es.ts"; -import zhCN from "./zh-CN.ts"; -import zhTW from "./zh-TW.ts"; - -const KEYS = [ - "vault.hosts.selectedSummary", - "vault.groups.selectedCount", - "vault.groups.deleteMultiple.success", - "vault.groups.deleteDialog.bulkTitle", - "vault.groups.deleteDialog.bulkDesc", - "vault.groups.deleteDialog.bulkDeleteHosts", - "vault.import.destination.title", - "vault.import.destination.settings", - "vault.import.destination.done", - "vault.import.securecrt.folder", - "vault.import.securecrt.promptTitle", - "vault.import.securecrt.promptDesc", - "vault.import.progress.fileCount", - "vault.import.progress.persistFailed", - "vault.import.progress.rollbackFailed", - "vault.import.sshConfig.managedDestinationHint", - "vault.import.mobaxterm.masterPassword", - "vault.import.mobaxterm.masterPasswordPlaceholder", - "vault.import.mobaxterm.masterPasswordHint", -] as const; - -test("bulk vault import and group-selection copy exists in every locale", () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - const missing = KEYS.filter((key) => !messages[key]); - assert.deepEqual(missing, [], `${locale} is missing bulk vault labels`); - } -}); diff --git a/application/i18n/locales/vaultGroupDeleteLocales.test.ts b/application/i18n/locales/vaultGroupDeleteLocales.test.ts deleted file mode 100644 index 594685c91..000000000 --- a/application/i18n/locales/vaultGroupDeleteLocales.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; - -import en from './en.ts'; -import ru from './ru.ts'; -import es from './es.ts'; -import zhCN from './zh-CN.ts'; -import zhTW from './zh-TW.ts'; - -const KEYS = [ - 'vault.groups.deleteDialog.managedDesc', - 'vault.groups.deleteDialog.mixedDesc', - 'vault.groups.deleteDialog.managedWarning', - 'vault.groups.deleteDialog.managedFile', -] as const; - -test('managed group delete warning copy exists in every locale', () => { - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - const missing = KEYS.filter((key) => !messages[key]); - assert.deepEqual(missing, [], `${locale} is missing managed group delete copy`); - } -}); - -test('managed group delete warning mentions data loss in every locale', () => { - const MARKERS = ['备份', '備份', 'copia de seguridad', 'резервную копию', 'Back up']; - for (const [locale, messages] of Object.entries({ en, ru, es, zhCN, zhTW })) { - const text = messages['vault.groups.deleteDialog.managedWarning']; - assert.match( - text ?? '', - /SSH/, - `${locale} warning should reference the SSH config file`, - ); - assert.ok( - MARKERS.some((marker) => text?.includes(marker)), - `${locale} warning should tell the user to back up the file`, - ); - } -}); - -test('linked file line interpolates the file path', () => { - for (const messages of [en, ru, es, zhCN, zhTW]) { - assert.match( - messages['vault.groups.deleteDialog.managedFile'] ?? '', - /\{file\}/, - 'managedFile copy should include the {file} placeholder', - ); - } -}); diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index a252c534e..3ca33b9ab 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -748,9 +748,6 @@ export const zhCNAiMessages: Messages = { 'terminal.layer.theme': '主题', 'terminal.layer.notes': '笔记', 'terminal.layer.aiChat': 'AI 助手', - 'terminal.layer.movePanelLeft': '面板移至左侧', - 'terminal.layer.movePanelRight': '面板移至右侧', - 'terminal.layer.movePanelBottom': '面板移至底部', 'terminal.layer.choosePanelPosition': '改变位置', 'terminal.layer.dockLeft': '左侧', 'terminal.layer.dockRight': '右侧', @@ -784,19 +781,15 @@ export const zhCNAiMessages: Messages = { 'terminal.layer.hostTree.details.protocol': '协议', 'terminal.layer.hostTree.details.group': '分组', 'terminal.layer.hostTree.details.tags': '标签', - 'terminal.layer.hostTree.details.lastConnected': '最近连接', 'topTabs.openQuickSwitcher': '打开快速切换', 'topTabs.moreTabs': '更多标签页', 'topTabs.aiAssistant': 'AI 助手', - 'topTabs.newLocalTerminal': '新建本地终端', 'topTabs.controlPanel': '快捷控制', 'topTabs.controlPanel.externalMcp': '对外 MCP', 'topTabs.controlPanel.theme': '主题', 'topTabs.controlPanel.theme.light': '浅色', 'topTabs.controlPanel.theme.dark': '深色', 'topTabs.controlPanel.theme.system': '系统', - 'topTabs.externalMcp.enable': '启用对外 MCP', - 'topTabs.externalMcp.disable': '停用对外 MCP', 'topTabs.windowOpacity': '窗口透明度', 'topTabs.openSettings': '打开设置', 'ai.chat.sessionHistory': '会话历史', diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index 68ce5b1a9..b026a65fc 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -110,11 +110,9 @@ export const zhCNCoreMessages: Messages = { 'field.label': 'Label', 'field.type': '类型', 'auth.keyType': '类型 {type}', - 'auth.showAllKeys': '显示全部 keys', // Dialogs / prompts 'confirm.deleteHost': '删除主机 "{name}"?', - 'confirm.deleteIdentity': '删除身份 "{name}"?', 'confirm.removeProvider': '移除提供商 "{name}"?', 'confirm.closeBusyTerminal.title': '确认关闭', 'confirm.closeBusyTerminal.message': '进程 "{command}" 仍在运行,关闭后会被终止。', @@ -407,7 +405,6 @@ export const zhCNCoreMessages: Messages = { 'tray.status.inactive': '未启用', 'tray.status.error': '错误', 'tray.status.unknown': '未知', - 'tray.recentHosts': '最近连接的主机', 'tray.empty.title': '一切都很安静', 'tray.empty.subtitle': '去连接个服务器吧,它们想念你了 🚀', 'tray.quit': '退出 Netcatty', @@ -466,9 +463,6 @@ export const zhCNCoreMessages: Messages = { 'update.downloadFailed.message': '下载更新失败,可前往 GitHub 手动下载。', 'update.needsSave.title': '有未保存内容', 'update.needsSave.message': '请先保存已打开的编辑器,然后再次点击「立即重启」以安装更新。', - 'update.openReleases': '打开 Releases', - 'update.remindLater': '稍后提醒', - 'update.skipVersion': '跳过此版本', // Settings > Appearance 'settings.appearance.uiTheme': '界面主题', @@ -651,8 +645,6 @@ Vaults 标签保持扁平,不使用这块背景。 'settings.appearance.appIcon.whiteViolet': '白底 · 紫罗兰猫', 'settings.appearance.appIcon.rainbow': '彩虹猫', // Context menus / common actions - 'action.newHost': '新建主机', - 'action.newSubfolder': '新建文件夹', 'action.copyPublicKey': '复制公钥', 'action.keyExport': '导出密钥', 'action.edit': '编辑', @@ -1034,13 +1026,9 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.columns.actions': '操作', 'sftp.sort.directoriesFirst': '目录置顶', 'sftp.emptyDirectory': '空目录', - 'sftp.nav.up': '返回上层', - 'sftp.nav.home': '返回主目录', - 'sftp.nav.refresh': '刷新', 'sftp.upload': '上传', 'sftp.uploadFiles': '上传文件', 'sftp.uploadFolder': '上传文件夹', - 'sftp.dragDropToUpload': '拖拽文件到这里上传', 'sftp.retry': '重试', 'sftp.context.open': '打开', 'sftp.context.navigateTo': '跳转到这里', @@ -1079,28 +1067,21 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.copyCurrentPath': '复制当前路径', 'sftp.copyCurrentPath.success': '已复制当前路径', 'sftp.copyCurrentPath.error': '无法复制当前路径', - 'sftp.viewMode.label': '视图模式', 'sftp.viewMode.list': '列表视图', 'sftp.viewMode.tree': '树形视图', 'sftp.viewMode.switchToList': '切换到列表视图', 'sftp.viewMode.switchToTree': '切换到树形视图', - 'sftp.listDensity.compact': '紧凑列表', - 'sftp.listDensity.comfortable': '宽松列表', 'sftp.listDensity.switchToCompact': '切换到紧凑列表', 'sftp.listDensity.switchToComfortable': '切换到宽松列表', 'sftp.tree.loadError': '加载目录失败', 'sftp.tree.loading': '加载中...', 'sftp.kind.folder': '文件夹', - 'sftp.context.rename': '重命名', 'sftp.context.permissions': '权限', - 'sftp.context.delete': '删除', 'sftp.context.refresh': '刷新', 'sftp.context.uploadFiles': '上传文件...', 'sftp.context.uploadFilesHere': '上传文件到这里...', 'sftp.context.uploadFolder': '上传文件夹...', 'sftp.context.uploadFolderHere': '上传文件夹到这里...', - 'sftp.context.downloadSelected': '下载选中项({count})', - 'sftp.context.deleteSelected': '删除选中项({count})', 'sftp.dropFilesHere': '拖拽文件到这里', 'sftp.itemsCount': '{count} 个项目', 'sftp.selectedCount': '已选 {count} 个', @@ -1109,8 +1090,6 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.task.waiting': '等待中...', 'sftp.transfer.preparing': '准备中...', 'sftp.status.loading': '加载中...', - 'sftp.status.uploading': '上传中...', - 'sftp.status.ready': '就绪', 'sftp.transfers': '传输', 'sftp.transfers.active': '{count} 个进行中', 'sftp.transfers.clearCompleted': '清除已完成', @@ -1173,7 +1152,6 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.transferCenter.applyAll': '应用到全部', 'sftp.transfers.resizeNameColumn': '调整文件名列宽', 'sftp.transfers.dragToResize': '拖拽调整高度', - 'sftp.goUp': '上一级', 'sftp.goToTerminalCwd': '定位到终端当前目录', 'sftp.locatePathInTerminal': '定位路径到终端', 'sftp.followTerminalCwd': '追随终端目录', @@ -1189,29 +1167,22 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.folderName.placeholder': '输入文件夹名称', 'sftp.fileName': '文件名称', 'sftp.fileName.placeholder': '输入文件名称', - 'sftp.prompt.newFolderName': '新建文件夹名称?', 'sftp.rename.title': '重命名', 'sftp.rename.newName': '新名称', 'sftp.rename.placeholder': '输入新名称', - 'sftp.confirm.deleteOne': '删除 "{name}"?', - 'sftp.deleteConfirm.single': '删除 "{name}"?', 'sftp.deleteConfirm.title': '删除 {count} 个项目?', 'sftp.deleteConfirm.desc': '此操作不可撤销,将删除以下内容:', 'sftp.deleteConfirm.descSingle': '此操作不可撤销。', 'sftp.deleteConfirm.host': '主机', 'sftp.deleteConfirm.path': '路径', - 'sftp.error.loadFailed': '加载目录失败', 'sftp.error.downloadFailed': '下载失败', 'sftp.error.uploadFailed': '上传失败', 'sftp.error.deleteFailed': '删除失败', - 'sftp.error.createFolderFailed': '创建文件夹失败', - 'sftp.error.createFileFailed': '创建文件失败', 'sftp.error.invalidFileName': '文件名包含非法字符:{chars}', 'sftp.error.reservedName': '此文件名是系统保留名称', 'sftp.overwrite.title': '文件已存在', 'sftp.overwrite.desc': '名为"{name}"的文件已存在。是否要替换它?', 'sftp.overwrite.confirm': '替换', - 'sftp.error.renameFailed': '重命名失败', 'sftp.picker.title': '选择主机', 'sftp.picker.desc': '为{side}窗格选择主机', 'sftp.picker.searchPlaceholder': '搜索主机...', @@ -1219,8 +1190,6 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.picker.local.desc': '浏览本地文件', 'sftp.picker.local.badge': '本地', 'sftp.picker.connected.section': '已连接', - 'sftp.picker.connected.badge': '已连接', - 'sftp.picker.connected.connecting': '连接中', 'sftp.picker.noMatch': '没有匹配的主机', 'sftp.permissions.title': '编辑权限', 'sftp.permissions.owner': '所有者', @@ -1228,8 +1197,6 @@ Vaults 标签保持扁平,不使用这块背景。 'sftp.permissions.others': '其他', 'sftp.permissions.octal': '八进制', 'sftp.permissions.symbolic': '符号', - 'sftp.permissions.success': '权限已更新', - 'sftp.permissions.failed': '权限更新失败', // Quick Switcher 'qs.search.placeholder': '搜索主机或标签页', @@ -1255,12 +1222,9 @@ Vaults 标签保持扁平,不使用这块背景。 "settings.plugins.manager.remove": "卸载", "settings.plugins.manager.removeNote": "卸载会移除插件代码和本地 KV 数据,保留用户设置、秘密存储和同步 sidecar。", "settings.plugins.permissions.statusUnknown": "状态未知", - "plugins.sidebar.extensions": "扩展页面", "plugins.sidebar.selectTerminal": "请先选择已打开的终端。", "plugins.sidebar.loading": "正在加载扩展页面…", "plugins.vault.loading": "正在加载插件页面…", - "plugins.vault.extensions": "扩展", - "plugins.vault.back": "返回主机", "plugins.interaction.title": "插件请求", "plugins.interaction.sharing": "分享的文本将交给此插件及其已授权的能力(包括网络访问)。读取文本不代表批准新的网络目标。", "plugins.interaction.input": "输入文本", diff --git a/application/i18n/locales/zh-CN/scripts.ts b/application/i18n/locales/zh-CN/scripts.ts index 615c52073..d057833d7 100644 --- a/application/i18n/locales/zh-CN/scripts.ts +++ b/application/i18n/locales/zh-CN/scripts.ts @@ -1,6 +1,5 @@ export const zhCNScriptsMessages = { 'scripts.meta.name': '名称', - 'scripts.meta.language': '语言', 'scripts.meta.description': '描述', 'scripts.meta.descriptionPlaceholder': '可选,脚本的简要说明', 'scripts.meta.trigger': '触发方式', @@ -15,7 +14,6 @@ export const zhCNScriptsMessages = { 'scripts.actions.openEditor': '弹窗编辑', 'scripts.actions.openEditorHint': '在更大的窗口中编辑脚本', 'scripts.editor.modalTitle': '脚本编辑器', - 'scripts.editor.modalSubtitle': '在更大的工作区中编辑脚本元数据和代码。', 'scripts.editor.lineCount': '{count} 行', 'scripts.editor.resize': '调整编辑器高度', 'scripts.targets.hint': '所选分组会动态匹配,之后加入分组的主机也会自动生效。', @@ -86,17 +84,13 @@ export const zhCNScriptsMessages = { 'scripts.dialog.retry': '重试', 'scripts.dialog.skip': '跳过', 'scripts.dialog.abort': '终止', - 'scripts.running.stepProgress': '步骤 {current} / {total}', 'scripts.running.determinateProgress': '{label} {current}/{total}', 'scripts.running.progressFallback': '进度', 'scripts.running.operationsCount': '已执行 {count} 个操作', 'scripts.running.opsPrefix': '已执行 ', 'scripts.running.opsSuffix': ' 个操作', - 'scripts.running.elapsedLabel': '耗时', 'scripts.running.lastSentLabel': '已发送:', 'scripts.running.elapsed': '耗时 {elapsed}', - 'scripts.running.completedSummary': '已完成 · 共 {count} 个操作 · {elapsed}', - 'scripts.running.dismissHint': '点击关闭', 'scripts.running.dismiss': '关闭', 'scripts.running.viewLogs': '查看日志', 'scripts.running.logTitle': '{name} · 运行日志', @@ -111,26 +105,12 @@ export const zhCNScriptsMessages = { 'vault.nav.scripts': '脚本', 'snippets.action.newScript': '新建自动化脚本', 'hostDetails.section.automation': '自动化', - 'hostDetails.automation.loginScript': '登录脚本', - 'hostDetails.automation.loginScriptPlaceholder': '选择脚本', - 'hostDetails.automation.none': '无', - 'hostDetails.automation.outputTriggers': '输出触发器', - 'hostDetails.automation.addTrigger': '添加触发器', - 'hostDetails.automation.triggerPatternPlaceholder': '正则表达式', - 'hostDetails.automation.linkedScripts': '已关联脚本', - 'hostDetails.automation.linkedScriptsEmpty': '尚未关联任何脚本。', - 'hostDetails.automation.linkScriptPlaceholder': '关联已有脚本…', - 'hostDetails.automation.unlink': '取消关联', - 'hostDetails.automation.equivalenceHint': '此处关联会将本主机加入 Scripts 中该脚本的目标列表,两侧视图同步。', 'hostDetails.automation.queueHint': '连接本主机时按顺序运行脚本。全局脚本最先执行,再执行下方队列。', 'hostDetails.automation.globalScripts': '全局连接脚本', 'hostDetails.automation.globalScriptsHint': '每次连接时最先运行。顺序在脚本库排序中调整。', 'hostDetails.automation.connectQueue': '本主机运行队列', 'hostDetails.automation.connectQueueEmpty': '尚未为本主机配置连接脚本队列。', 'hostDetails.automation.addToQueuePlaceholder': '添加脚本到队列…', - 'hostDetails.automation.moveUp': '上移', - 'hostDetails.automation.moveDown': '下移', 'hostDetails.automation.removeFromQueue': '从队列移除', 'hostDetails.automation.dragHandle': '拖拽排序', - 'hostDetails.automation.queueDragHint': '拖动条目即可调整连接时的运行顺序。', }; diff --git a/application/i18n/locales/zh-CN/systemManager.ts b/application/i18n/locales/zh-CN/systemManager.ts index 8831998d0..6c2eb39ef 100644 --- a/application/i18n/locales/zh-CN/systemManager.ts +++ b/application/i18n/locales/zh-CN/systemManager.ts @@ -14,13 +14,11 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.tabs.docker': 'Docker', 'systemManager.tabs.gpu': 'GPU', 'systemManager.tabs.ariaLabel': '系统管理分区', - 'systemManager.popup.loading': '正在打开终端…', 'systemManager.popup.startupFailed': '启动命令未成功。请确认目标仍然可用后重试。', 'systemManager.errors.loadProcesses': '加载进程列表失败', 'systemManager.errors.loadTmux': '加载 tmux 会话失败', 'systemManager.errors.loadTmuxWindows': '加载 tmux 窗口失败', - 'systemManager.errors.loadTmuxPanes': '加载 tmux 面板失败', 'systemManager.errors.loadTmuxClients': '加载 tmux 客户端失败', 'systemManager.errors.actionFailed': '操作失败', 'systemManager.errors.loadDocker': '加载容器列表失败', @@ -31,7 +29,6 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.errors.nerdctlUnreachable': 'nerdctl 无法连接 containerd', 'systemManager.errors.clusterUnreachable': '无法连接到上下文 {{context}} 的集群', 'systemManager.errors.clusterUnreachableGeneric': '无法连接到集群', - 'systemManager.errors.loadOverview': '加载系统概览失败', 'systemManager.errors.loadGpu': '加载 GPU / NPU 状态失败', 'systemManager.errors.loadPorts': '加载监听端口失败', 'systemManager.errors.loadServices': '加载 systemd 服务失败', @@ -65,13 +62,10 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.overview.noTopProcesses': '暂无进程数据', 'systemManager.processes.search': '搜索进程…', - 'systemManager.processes.command': '命令', - 'systemManager.processes.user': '用户', 'systemManager.processes.term': '终止', 'systemManager.processes.kill': '强杀', 'systemManager.processes.stop': '暂停 (SIGSTOP)', 'systemManager.processes.cont': '继续 (SIGCONT)', - 'systemManager.processes.hup': '挂断 (SIGHUP)', 'systemManager.processes.renice': '调整优先级', 'systemManager.processes.renicePrompt': 'Nice 值 (-20 到 19)', 'systemManager.processes.reniceInvalid': 'Nice 值必须在 -20 到 19 之间', @@ -86,7 +80,6 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.processes.stat': '状态', 'systemManager.processes.meta': '{{count}} 个进程', 'systemManager.processes.loading': '正在加载进程…', - 'systemManager.processes.loadingMore': '正在显示更多进程…', 'systemManager.processes.state.running': '运行中', 'systemManager.processes.state.sleeping': '睡眠', 'systemManager.processes.state.stopped': '已暂停', @@ -124,12 +117,9 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.tmux.attached': '已附加', 'systemManager.tmux.detached': '未附加', 'systemManager.tmux.windows': '{{count}} 个窗口', - 'systemManager.tmux.created': '创建时间', - 'systemManager.tmux.activity': '活动时间', 'systemManager.tmux.rename': '重命名', 'systemManager.tmux.detach': '全部分离', 'systemManager.tmux.killSession': '结束会话', - 'systemManager.tmux.killServer': '结束 tmux 服务', 'systemManager.tmux.loadingDetails': '正在加载详情…', 'systemManager.tmux.clients': '已附加客户端', 'systemManager.tmux.windowList': '窗口', @@ -140,31 +130,17 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.docker.unavailable': '此主机未检测到容器运行时(Docker、Podman、nerdctl 或 kubectl)', 'systemManager.tmux.windowsMismatch': '会话显示有 {{count}} 个窗口,但 list-windows 未返回任何窗口', 'systemManager.tmux.lastCommand': '最后执行的命令:{{command}}', - 'systemManager.tmux.noPanes': '没有面板', - 'systemManager.tmux.panes': '{{count}} 个面板', - 'systemManager.tmux.active': '当前', 'systemManager.tmux.unnamedWindow': '未命名窗口', - 'systemManager.tmux.unnamedPane': '未命名面板', 'systemManager.tmux.attachWindow': '附加到窗口', - 'systemManager.tmux.selectWindow': '选中窗口', 'systemManager.tmux.killWindow': '关闭窗口', - 'systemManager.tmux.killPane': '关闭面板', - 'systemManager.tmux.splitHorizontal': '水平分屏', - 'systemManager.tmux.splitVertical': '垂直分屏', - 'systemManager.tmux.sendKeys': '发送按键', - 'systemManager.tmux.sendKeysTo': '向窗口 {{window}} 面板 {{pane}} 发送按键', - 'systemManager.tmux.sendKeysPlaceholder': '命令或文本…', 'systemManager.tmux.renameSessionPrompt': '重命名会话', 'systemManager.tmux.renameWindowPrompt': '重命名窗口', 'systemManager.tmux.windowName': '窗口名称', 'systemManager.tmux.confirmKillSession': '确定结束 tmux 会话「{{name}}」?', 'systemManager.tmux.confirmDetachSession': '确定将所有客户端从「{{name}}」分离?', 'systemManager.tmux.confirmKillWindow': '确定关闭窗口「{{name}}」?', - 'systemManager.tmux.confirmKillPane': '确定关闭面板 #{{index}}?', - 'systemManager.tmux.confirmKillServer': '确定结束 tmux 服务?所有会话将被终止。', 'systemManager.tmux.meta': '{{count}} 个会话', - 'systemManager.docker.title': '容器', 'systemManager.docker.subTabs.containers': '容器', 'systemManager.docker.subTabs.images': '镜像', 'systemManager.docker.empty': '未找到容器', @@ -177,7 +153,6 @@ export const zhCnSystemManagerMessages: Messages = { 'systemManager.docker.filter.paused': '已暂停', 'systemManager.docker.shell': 'Shell', 'systemManager.docker.logs': '日志', - 'systemManager.docker.details': '详情', 'systemManager.docker.inspect': 'Inspect', 'systemManager.docker.imageInspect': '镜像 Inspect', 'systemManager.docker.confirmRemove': '确定删除此容器?', diff --git a/application/i18n/locales/zh-CN/terminal.ts b/application/i18n/locales/zh-CN/terminal.ts index 330943911..5b7a12e03 100644 --- a/application/i18n/locales/zh-CN/terminal.ts +++ b/application/i18n/locales/zh-CN/terminal.ts @@ -57,7 +57,6 @@ export const zhCNTerminalMessages: Messages = { 'terminal.osc7Setup.title': '配置目录追踪', 'terminal.osc7Setup.desc': 'Netcatty 会为当前远端用户添加 OSC 7 提示符配置。这样在 sudo 或 su 之后,SFTP 也能继续跟随终端目录。', 'terminal.osc7Setup.targets': '可能写入的文件', - 'terminal.osc7Setup.command': '将执行的命令', 'terminal.osc7Setup.run': '执行配置', 'terminal.osc7Setup.running': '正在配置...', 'terminal.osc7Setup.configured': '目录追踪已配置', @@ -98,37 +97,18 @@ export const zhCNTerminalMessages: Messages = { 'sftp.context.copyPath': '复制文件路径', 'sftp.context.openWith': '打开方式...', 'sftp.context.edit': '编辑', - 'sftp.context.preview': '预览', 'sftp.opener.title': '打开方式', - 'sftp.opener.desc': '选择一个应用程序来打开此文件', 'sftp.opener.builtInEditor': '内置编辑器', 'sftp.opener.editDescription': '编辑文本文件', - 'sftp.opener.builtInImageViewer': '内置图片预览', - 'sftp.opener.previewDescription': '预览图片', 'sftp.opener.systemApp': '选择应用程序...', 'sftp.opener.systemAppDescription': '从本地选择一个应用程序', - 'sftp.opener.onlySystemApp': '此文件只能用外部应用程序打开', - 'sftp.opener.noAppsAvailable': '无可用应用程序', 'sftp.opener.noExtension': '无扩展名文件', 'sftp.opener.setDefault': '始终使用此方式打开 {ext} 文件', - 'sftp.opener.confirmTitle': '设为默认?', - 'sftp.opener.confirmDescription': '是否始终使用 {app} 打开 {ext} 文件?', - 'sftp.opener.yesRemember': '是,记住此选择', - 'sftp.opener.justOnce': '仅此一次', - 'sftp.opener.confirm.title': '设置默认应用程序', - 'sftp.opener.confirm.desc': '是否始终使用此应用程序打开 .{ext} 文件?', - 'sftp.editor.title': '文本编辑器', 'sftp.editor.save': '保存到远程', 'sftp.editor.saving': '保存中...', 'sftp.editor.saved': '保存成功', 'sftp.editor.saveFailed': '保存文件失败', - 'sftp.editor.unsavedChanges': '您有未保存的更改。确定要关闭吗?', 'sftp.editor.syntaxHighlight': '语法高亮', - 'sftp.preview.title': '图片预览', - 'sftp.preview.zoomIn': '放大', - 'sftp.preview.zoomOut': '缩小', - 'sftp.preview.resetZoom': '重置缩放', - 'sftp.preview.fitToWindow': '适应窗口', // Settings > SFTP File Associations 'settings.tab.sftpFileAssociations': 'SFTP', @@ -208,28 +188,16 @@ export const zhCNTerminalMessages: Messages = { 'sftp.autoSync.error': '同步文件失败:{error}', // SFTP Folder Upload Progress - 'sftp.upload.progress': '正在上传 {current}/{total} 个文件...', - 'sftp.upload.uploading': '正在上传...', - 'sftp.upload.compressing': '正在压缩...', - 'sftp.upload.extracting': '正在解压...', - 'sftp.upload.scanning': '正在扫描文件...', - 'sftp.upload.completed': '已完成', - 'sftp.upload.compressed': '压缩传输', - 'sftp.upload.currentFile': '当前: {fileName}', 'sftp.upload.cancelled': '上传已取消', 'sftp.upload.noFiles': '没有可上传的文件', 'sftp.upload.partialSuccess': '已上传 {success} 个文件,{failed} 个失败', 'sftp.upload.cancel': '取消', - 'sftp.upload.completedToPath': '已上传至 {path}', // SFTP Download - 'sftp.download.completed': '已下载', - 'sftp.download.cancelled': '下载已取消', // SFTP Reconnecting 'sftp.reconnecting.title': '正在重连...', 'sftp.reconnecting.desc': '连接已断开,正在尝试重新连接', - 'sftp.reconnected': '连接已恢复', 'sftp.error.reconnectFailed': '重连失败,请重试。', 'sftp.error.connectionLostManual': '连接已断开,请手动重新连接。', 'sftp.error.connectionLostReconnecting': '连接已断开,正在重连...', @@ -661,7 +629,6 @@ export const zhCNTerminalMessages: Messages = { 'hostDetails.proxyPanel.credentials': '凭据', 'hostDetails.proxyPanel.usernamePlaceholder': '用户名', 'hostDetails.proxyPanel.passwordPlaceholder': '密码', - 'hostDetails.proxyPanel.identities': '身份', 'hostDetails.proxyPanel.keychainIdentity': '钥匙串身份', 'hostDetails.proxyPanel.manualCredentials': '手动凭据', 'hostDetails.proxyPanel.remove': '移除代理', @@ -682,8 +649,6 @@ export const zhCNTerminalMessages: Messages = { 'hostDetails.envVars.newVariable': '新变量', 'hostDetails.envVars.variableName': '变量名', 'hostDetails.chain.title': '编辑链路', - 'hostDetails.chain.desc': '添加另一台主机将创建到 {host} 的连接。', - 'hostDetails.chain.addHost': '添加主机', 'hostDetails.chain.target': '目标', 'hostDetails.chain.availableHosts': '可用主机', 'hostDetails.chain.clear': '清空', @@ -695,10 +660,7 @@ export const zhCNTerminalMessages: Messages = { 'hostDetails.group.addProtocol': '添加协议', // Keychain - 'keychain.filter.key': '密钥', - 'keychain.filter.certificate': '证书', 'keychain.action.generateKey': '生成密钥', - 'keychain.action.importKey': '导入密钥', 'keychain.action.newIdentity': '新建身份', 'keychain.action.importCertificate': '导入证书', 'keychain.view.grid': '网格', @@ -739,20 +701,8 @@ export const zhCNTerminalMessages: Messages = { 'keychain.export.exporting': '导出中...', 'keychain.export.exportAndAttach': '导出并绑定', 'keychain.export.title': '密钥导出', - 'keychain.export.exportToRequired': '导出到 *', - 'keychain.export.selectHostPlaceholder': '选择主机...', - 'keychain.export.locationLabel': '位置 ~ $1 *', - 'keychain.export.filenameLabel': '文件名 ~ $2 *', - 'keychain.export.advanced': '高级', - 'keychain.export.note.supportsOnly': '密钥导出目前仅支持', - 'keychain.export.note.systems': '系统。', - 'keychain.export.note.use': '请使用', - 'keychain.export.note.customize': '部分自定义导出脚本。', - 'keychain.export.scriptRequired': '脚本 *', 'keychain.export.exportToHost': '导出到主机', - 'keychain.export.failedGeneric': '导出失败:{message}', 'keychain.field.label': '名称', - 'keychain.field.labelRequired': '名称 *', 'keychain.field.labelPlaceholder': '密钥 Label', 'keychain.field.privateKeyRequired': '私钥 *', 'keychain.field.publicKey': '公钥', @@ -788,13 +738,9 @@ export const zhCNTerminalMessages: Messages = { "fido.recovery.usePassword": "改用已配置的密码", "fido.recovery.passwordFallback": "正在使用此主机已配置的密码登录", "fido.prompt.cancelled": "已取消安全密钥验证。", - 'fido.prompt.touchDone': '已触摸', 'fido.prompt.timeout': 'FIDO 提示已超时,请重新连接。', - 'fido.error.opensshMissing': '需要带 FIDO/libfido2 的 OpenSSH。macOS:brew install openssh libfido2。', - 'fido.error.agentUnavailable': '无法启动支持 FIDO 的 SSH agent。', 'keychain.generate.resident': '在设备上保存凭据', 'keychain.generate.verifyRequired': '每次验证 PIN', - 'keychain.action.loadResident': '从安全密钥加载驻留密钥', 'keychain.generate.keySize': '密钥长度', 'keychain.generate.labelPlaceholder': '密钥 Label', 'keychain.generate.passphrasePlaceholder': 'Passphrase(可选)', @@ -804,7 +750,6 @@ export const zhCNTerminalMessages: Messages = { 'keychain.import.dropHint': '将密钥文件拖到这里', 'keychain.import.importFromFile': '从文件导入', 'keychain.import.saveKey': '保存密钥', - 'keychain.import.importedKeyLabel': '已导入密钥', 'keychain.identity.usernameRequired': '用户名 *', 'keychain.identity.method.passwordOnly': '密码', 'keychain.identity.summary.password': '认证密码', @@ -813,14 +758,8 @@ export const zhCNTerminalMessages: Messages = { 'keychain.identity.summary.passwordAndKey': '认证密码与密钥', 'keychain.identity.summary.passwordAndCertificate': '认证密码与证书', 'keychain.identity.summary.none': '无凭据', - 'keychain.identity.selectCredential': '选择{kind}', 'keychain.identity.save': '保存', 'keychain.identity.update': '更新', - 'keychain.keyDialog.newTitle': '新建密钥', - 'keychain.keyDialog.newDesc': '添加新的 SSH 密钥', - 'keychain.keyDialog.editTitle': '编辑密钥', - 'keychain.keyDialog.editDesc': '更新此 SSH 密钥', - 'keychain.keyDialog.updateKey': '更新密钥', // Tabs 'tabs.closeSessionAria': '关闭会话', @@ -895,8 +834,6 @@ export const zhCNTerminalMessages: Messages = { 'snippets.search.noResults.desc': '没有脚本或脚本包与"{query}"匹配。换一个关键字,或清除搜索进行浏览。', 'snippets.section.packages': '脚本包', 'snippets.section.snippets': '脚本', - 'snippets.kind.codeSnippet': '代码片段', - 'snippets.kind.automationScript': '自动化脚本', 'snippets.package.count': '{count} 个脚本', 'snippets.commandFallback': '命令', 'snippets.view.grid': '网格', @@ -928,9 +865,6 @@ export const zhCNTerminalMessages: Messages = { 'snippets.import.modal.multipleFiles': '已选择 {count} 个文件', 'snippets.import.modal.parsedSummary': '{files} 个文件,{total} 个脚本,{packages} 个脚本包,{conflicts} 个重复命令。主机绑定会被忽略。', 'snippets.import.modal.confirm': '确认导入', - 'snippets.import.conflict.title': '导入代码片段?', - 'snippets.import.conflict.desc': '“{file}”包含 {total} 个代码片段,其中 {conflicts} 个命令已存在。', - 'snippets.import.conflict.hostBindingsNote': '代码片段的主机绑定不会被导入或导出。', 'snippets.import.conflict.skip': '跳过重复项', 'snippets.import.conflict.overwrite': '覆盖重复项', 'snippets.packageDialog.title': '新建脚本包', @@ -989,9 +923,6 @@ export const zhCNTerminalMessages: Messages = { 'serial.field.customPort': '自定义串口路径', 'serial.field.namedPipeHint': 'Windows 虚拟机控制台:输入 \\\\.\\pipe\\name。虚拟机需作为服务端创建管道,波特率和串口帧设置不生效。', 'serial.field.customPortPlaceholder': '例如 /dev/ttys001 或 COM1', - 'serial.type.hardware': '硬件', - 'serial.type.pseudo': '虚拟终端', - 'serial.type.custom': '自定义', 'serial.parity.none': '无', 'serial.parity.even': '偶校验', 'serial.parity.odd': '奇校验', @@ -1012,7 +943,6 @@ export const zhCNTerminalMessages: Messages = { 'serial.backspace.default': '默认(DEL,0x7F)', 'serial.backspace.ctrlH': 'Ctrl+H(BS,0x08)', 'serial.field.charset': '字符编码', - 'serial.connectionError': '连接串口失败', 'serial.field.baudRatePlaceholder': '选择或输入波特率...', 'serial.field.baudRateEmpty': '输入自定义波特率', 'serial.field.customBaudRate': '使用自定义波特率', @@ -1031,10 +961,7 @@ export const zhCNTerminalMessages: Messages = { 'keyboard.interactive.title': '需要验证', 'keyboard.interactive.desc': '服务器需要额外的身份验证。', 'keyboard.interactive.descWithHost': '服务器 {hostname} 需要额外的身份验证。', - 'keyboard.interactive.response': '响应', 'keyboard.interactive.verificationCode': '验证码', - 'keyboard.interactive.enterCode': '输入验证码', - 'keyboard.interactive.enterResponse': '输入响应', 'keyboard.interactive.submit': '提交', 'keyboard.interactive.verifying': '验证中...', 'keyboard.interactive.savePassword': '保存密码', diff --git a/application/i18n/locales/zh-CN/vault.ts b/application/i18n/locales/zh-CN/vault.ts index 1b127ea72..8e89fe3fb 100644 --- a/application/i18n/locales/zh-CN/vault.ts +++ b/application/i18n/locales/zh-CN/vault.ts @@ -19,14 +19,6 @@ export const zhCNVaultMessages: Messages = { 'notes.export.toast.failed': '导出笔记失败。', 'notes.codeBlock.copied': '已复制', 'notes.codeBlock.copyFailed': '复制代码块失败。', - 'notes.group.prompt': '文件夹路径', - 'notes.group.all': '笔记本', - 'notes.group.ungrouped': '未分组', - 'notes.section.notebooks': '笔记本', - 'notes.section.notes': '笔记', - 'notes.mode.edit': '编辑', - 'notes.mode.split': '分屏', - 'notes.mode.preview': '预览', 'notes.title.placeholder': '笔记标题', 'notes.editor.placeholder': '在这里写 Markdown 笔记...', 'notes.editor.unrenderableMarkdown': '这篇笔记包含富文本编辑器无法显示的 Markdown(例如未闭合的 文本),已改为显示原始 Markdown 源码,内容并没有丢失。', @@ -72,25 +64,18 @@ export const zhCNVaultMessages: Messages = { 'notes.toolbar.divider': '分割线', 'notes.toolbar.link': '插入超链接', 'notes.toolbar.image': '插入图片', - 'notes.action.pin': '置顶笔记', - 'notes.action.unpin': '取消置顶', 'notes.tag.remove': '移除标签', 'notes.tag.placeholder': '标签名...', 'notes.tag.add': '添加标签', 'notes.outline.title': '大纲目录', - 'notes.outline.titleWithCount': '大纲目录 ({count})', 'notes.outline.empty': '暂无标题大纲', 'notes.outline.emptyHint': '在 Markdown 中使用 #、## 编写各级标题', 'notes.export.share': '导出与分享', 'notes.export.currentNote': '当前笔记', 'notes.export.exportMarkdown': '导出为 Markdown (.md)', - 'notes.export.exportHtml': '导出为 HTML (.html)', 'notes.export.copyMarkdown': '复制 Markdown 源码', 'notes.export.allNotes': '全部笔记', 'notes.export.exportAllZip': '导出全部为 ZIP 压缩包', - 'notes.export.toast.markdownSuccess': '已导出 Markdown 文件', - 'notes.export.toast.htmlSuccess': '已导出 HTML 文件', - 'notes.export.toast.zipSuccess': '已导出全部笔记备份 ZIP', // Select Host panel 'selectHost.title': '选择主机', @@ -131,12 +116,6 @@ export const zhCNVaultMessages: Messages = { 'vault.panel.resizeWidth': '调整面板宽度', 'hostDetails.saveAria': '保存', 'hostConnectionTest.title': '测试连接', - 'hostConnectionTest.test': '测试', - 'hostConnectionTest.chainOf': '第 {current}/{total} 跳', - 'hostConnectionTest.success': '连接成功', - 'hostConnectionTest.successHint': '主机已接受您的凭据。您可以关闭此窗口。', - 'hostConnectionTest.connecting': '正在连接… {seconds} 秒后超时', - 'hostConnectionTest.failed': '连接失败。', 'hostConnectionTest.retry': '重试', 'hostConnectionTest.credentialsUnavailable': '保存的凭据无法在此设备上解密。请在下方重新输入。', 'hostDetails.section.address': '地址', @@ -173,11 +152,8 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.notes.toggle.show': '显示备注编辑框', 'hostDetails.notes.toggle.hide': '隐藏备注编辑框', 'hostDetails.group.placeholder': '父级 Group', - 'hostDetails.section.credentials': '凭据', 'hostDetails.section.portCredentials': '端口与凭据', 'hostDetails.section.appearance': '外观', - 'hostDetails.distro.title': 'Linux 发行版', - 'hostDetails.distro.desc': '可在连接后自动探测,也可以手动覆盖图标所用的发行版。', 'hostDetails.icon.title': '主机图标', 'hostDetails.icon.sectionTitle': '颜色与图标', 'hostDetails.icon.desc': '选择此主机使用的图标来源和颜色。', @@ -189,7 +165,6 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.icon.mode.custom': '自定义', 'hostDetails.icon.reset': '重置主机图标', 'hostDetails.icon.colorLabel': '图标颜色', - 'hostDetails.icon.colorDefault': '默认', 'hostDetails.icon.colorAuto': '自动', 'hostDetails.icon.colorManual': '手动', 'hostDetails.icon.colorChoice': '颜色', @@ -240,7 +215,6 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.distro.mode.auto': '自动探测', 'hostDetails.distro.mode.manual': '手动覆盖', 'hostDetails.distro.detectedLabel': '当前值', - 'hostDetails.distro.manualLabel': '手动指定', 'hostDetails.distro.pending': '首次连接后自动探测', 'hostDetails.distro.unknown': '未知', 'hostDetails.distro.option.linux': '通用 Linux', @@ -291,7 +265,6 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.auth.mfaFirst': '优先交互式认证', 'hostDetails.auth.mfaFirst.desc': '适用于必须通过 keyboard-interactive 输入密码和 MFA 的服务器。', 'hostDetails.totp.title': '验证器 (TOTP)', - 'hostDetails.totp.enable': '为这台主机保存 TOTP 密钥', 'hostDetails.totp.setup': '设置…', 'hostDetails.totp.edit': '编辑', 'hostDetails.totp.modalTitle': '设置验证器', @@ -394,10 +367,8 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.jumpHosts.direct': '直连', 'hostDetails.jumpHosts.configure': '配置代理主机', 'hostDetails.proxy': '通过 HTTP/SOCKS5/命令代理', - 'hostDetails.proxy.none': '无', 'hostDetails.proxy.direct': '直连(不使用代理)', 'hostDetails.proxy.directHint': '不使用分组或全局默认代理', - 'hostDetails.proxy.edit': '编辑代理', 'hostDetails.proxy.configure': '配置代理', 'hostDetails.envVars': '环境变量', 'hostDetails.envVars.add': '添加环境变量', @@ -456,28 +427,14 @@ export const zhCNVaultMessages: Messages = { 'hostDetails.plugin.useSsh': '改用 SSH', // Host form (legacy modal) - 'hostForm.title.edit': '编辑主机', - 'hostForm.title.new': '新建主机', - 'hostForm.desc.edit': '更新该主机的连接信息', - 'hostForm.desc.new': '创建一个新的 SSH 主机条目', 'hostForm.field.label': '名称', - 'hostForm.placeholder.label': 'My Production Server', 'hostForm.field.hostname': 'Hostname / IP', - 'hostForm.placeholder.hostname': '192.168.1.1', 'hostForm.field.port': '端口', 'hostForm.field.username': '用户名', 'hostForm.field.osType': '操作系统类型', - 'hostForm.placeholder.selectOs': '选择操作系统', 'hostForm.field.group': '分组', - 'hostForm.placeholder.group': '例如:AWS、DigitalOcean', 'hostForm.field.tags': '标签', - 'hostForm.placeholder.addTag': '添加标签…', - 'hostForm.auth.method': '认证方式', - 'hostForm.auth.password': '密码', - 'hostForm.auth.sshKey': 'SSH密钥', 'hostForm.auth.selectKey': '选择 SSH密钥', - 'hostForm.auth.noKeys': '暂无密钥', - 'hostForm.auth.noKeysHint': '钥匙串中未找到 SSH密钥,请先创建一个。', 'hostForm.saveHost': '保存主机', // Connection logs @@ -495,7 +452,6 @@ export const zhCNVaultMessages: Messages = { 'logs.action.delete': '删除', // Log view - 'logView.customizeAppearance': '自定义外观', 'logView.appearance': '外观', 'logView.readOnly': '只读', 'logView.export': '导出', @@ -508,7 +464,6 @@ export const zhCNVaultMessages: Messages = { 'terminal.toolbar.availableAfterConnect': '连接后可用', 'terminal.toolbar.sendYmodem': 'YMODEM 发送', 'terminal.toolbar.receiveYmodem': 'YMODEM 接收', - 'terminal.toolbar.sftp': 'SFTP', 'terminal.toolbar.more': '更多操作', 'terminal.toolbar.scripts': '脚本', 'terminal.toolbar.history': '命令历史', @@ -533,7 +488,6 @@ export const zhCNVaultMessages: Messages = { 'terminal.composeBar.resize': '拖拽调整撰写栏高度', 'terminal.composeBar.manageSnippets': '管理快捷代码片段', 'terminal.composeBar.searchSnippets': '搜索代码片段...', - 'terminal.composeBar.noPinnedSnippets': '点击 + 固定常用代码片段', 'terminal.composeBar.noMatchingSnippets': '没有匹配的代码片段', 'terminal.composeBar.pinnedCount': '已固定 {count} 个', 'terminal.composeBar.unpinSnippet': '从快捷栏移除 {label}', @@ -690,9 +644,6 @@ export const zhCNVaultMessages: Messages = { 'terminal.themeModal.themeType': '{type} 主题', 'terminal.hiddenTheme.title': '当前隐藏主题', 'terminal.hiddenTheme.desc': '这个主题已从手动选择列表中隐藏;当你选择其他可见主题后,它会被替换。', - 'topTabs.toggleTheme.systemExitTitle': '当前正在跟随系统主题', - 'topTabs.toggleTheme.systemExitMessage': '请到设置里选择固定的浅色或深色主题。', - 'topTabs.toggleTheme.openSettings': '打开设置', // Custom Themes 'terminal.customTheme.section': '自定义主题', @@ -705,7 +656,6 @@ export const zhCNVaultMessages: Messages = { 'terminal.customTheme.importDesc': '从 iTerm2 配色方案文件导入', 'terminal.customTheme.importError': '无法解析所选文件,请确保它是有效的 .itermcolors XML 文件。', 'terminal.customTheme.delete': '删除主题', - 'terminal.customTheme.confirmDelete': '确认删除', 'terminal.customTheme.name': '名称', 'terminal.customTheme.namePlaceholder': '我的自定义主题', 'terminal.customTheme.type': '类型', @@ -764,10 +714,7 @@ export const zhCNVaultMessages: Messages = { 'cloudSync.provider.disconnect.cloudRemains': '云端的加密同步副本可能仍保存在 {name} 存储中。如需清除,请到该服务商删除同步文件。断开连接不代表设备已完成交接清理。', 'cloudSync.provider.disconnect.failed': '未能完成与 {name} 的断开连接,保存的连接资料可能仍在,请重试。', 'cloudSync.provider.webdav': 'WebDAV', - 'cloudSync.provider.webdav.desc': '连接到自建 WebDAV 端点', 'cloudSync.provider.s3': 'S3 兼容存储', - 'cloudSync.provider.s3.desc': '连接到 S3 兼容对象存储', - 'cloudSync.provider.comingSoon': '即将支持', 'cloudSync.webdav.title': 'WebDAV 设置', 'cloudSync.webdav.desc': '配置 WebDAV 端点用于加密同步。', 'cloudSync.webdav.endpoint': '端点地址', @@ -796,20 +743,6 @@ export const zhCNVaultMessages: Messages = { 'cloudSync.s3.allowInsecure': '允许不安全的连接(忽略证书错误)', 'cloudSync.s3.showSecret': '显示密钥', 'cloudSync.s3.validation.required': '端点、Region、Bucket、Access Key 与 Secret 必填。', - 'cloudSync.smb.title': 'SMB 设置', - 'cloudSync.smb.desc': '连接到 SMB/CIFS 文件共享以进行加密同步。', - 'cloudSync.smb.share': '共享路径', - 'cloudSync.smb.username': '用户名', - 'cloudSync.smb.password': '密码', - 'cloudSync.smb.domain': '域(可选)', - 'cloudSync.smb.domainPlaceholder': '例如:WORKGROUP', - 'cloudSync.smb.port': '端口(可选)', - 'cloudSync.smb.showSecret': '显示密码', - 'cloudSync.smb.validation.share': '共享路径必填。', - 'cloudSync.smb.validation.port': '端口必须是 1 到 65535 之间的数字。', - 'cloudSync.connect.smb.success': 'SMB 已连接', - 'cloudSync.connect.smb.failedTitle': 'SMB 连接失败', - 'cloudSync.provider.smb': 'SMB 共享', 'cloudSync.connect.webdav.success': 'WebDAV 已连接', 'cloudSync.connect.webdav.failedTitle': 'WebDAV 连接失败', 'cloudSync.connect.s3.success': 'S3 已连接', @@ -826,7 +759,6 @@ export const zhCNVaultMessages: Messages = { 'cloudSync.lastSync.minutesAgo': '{minutes} 分钟前', 'cloudSync.changeKey': '更改 Key', 'cloudSync.providers.title': '云服务', - 'cloudSync.syncAll': '同步所有已连接的服务', 'cloudSync.autoSync.title': '自动同步', 'cloudSync.autoSync.desc': '发生变更时自动同步', 'cloudSync.strategy.title': '同步策略', @@ -891,7 +823,6 @@ export const zhCNVaultMessages: Messages = { 'cloudSync.localBackups.folderWarning': '仅复制此文件夹并不构成完整、可迁移的备份。删除或清空应用配置目录(userData)可能导致这些恢复点无法读取。', 'cloudSync.localBackups.retentionTitle': '备份保留数量', 'cloudSync.localBackups.retentionDesc': '设置 Netcatty 最多保留多少份本地备份。', - 'cloudSync.localBackups.maxCount': '最多保留', 'cloudSync.localBackups.maxSaved': '已保存保留数量:{count}', 'cloudSync.localBackups.maxInvalid': '请输入 1 到 100 之间的数字。', 'cloudSync.localBackups.empty': '还没有本地备份。', @@ -1021,7 +952,6 @@ export const zhCNVaultMessages: Messages = { 'sftp.context.openWithDefault': '系统默认程序打开', 'common.clear': '清除', 'common.optional': '可选', - 'common.selectPlaceholder': '请选择...', 'common.error': '错误', 'common.validation': '验证', 'common.saveChanges': '保存修改', @@ -1063,7 +993,6 @@ export const zhCNVaultMessages: Messages = { 'pf.tooltip.localDesc': '本地端口转发:通过 SSH 隧道访问远程服务', 'pf.tooltip.remoteDesc': '远程端口转发:将本地服务暴露给远程主机', 'pf.tooltip.dynamicDesc': '动态 SOCKS 代理:通过 SSH 隧道转发流量', - 'pf.deleteActive.title': '删除正在运行的端口转发?', 'pf.deleteActive.desc': '端口转发规则 "{label}" 当前正在运行。删除前将先关闭转发连接。', 'pf.deleteActive.confirm': '关闭并删除', 'pf.form.autoStart': '自动启动', @@ -1078,8 +1007,6 @@ export const zhCNVaultMessages: Messages = { 'sftp.pane.selectHostToStart': '先选择一个主机', 'sftp.pane.chooseFilesystem': '选择要浏览的本地或远端文件系统', 'sftp.tabs.addTab': '新建标签页', - 'sftp.tabs.closeTab': '关闭标签页', - 'sftp.tabs.newTab': '新标签页', 'sftp.tabs.copyDefaultPath': '复制标签页(默认路径)', 'sftp.tabs.copyCurrentPath': '复制并跳转到当前路径', 'sftp.conflict.title': '文件冲突', @@ -1105,10 +1032,6 @@ export const zhCNVaultMessages: Messages = { 'sftp.conflict.action.replace': '替换', // SFTP Upload Phases - 'sftp.upload.phase.compressing': '正在压缩', - 'sftp.upload.phase.uploading': '正在上传', - 'sftp.upload.phase.extracting': '正在解压', - 'sftp.upload.phase.compressed': '压缩传输', 'vault.import.plugins.title': '插件导入器', 'vault.import.plugins.loading': '正在生成安全导入预览…', 'vault.import.plugins.progress': '已处理 {completed}/{total} {message}', diff --git a/application/i18n/locales/zh-TW/ai.ts b/application/i18n/locales/zh-TW/ai.ts index c334528f3..a4cf21a3b 100644 --- a/application/i18n/locales/zh-TW/ai.ts +++ b/application/i18n/locales/zh-TW/ai.ts @@ -747,9 +747,6 @@ export const zhTWAiMessages: Messages = { 'terminal.layer.theme': '主題', 'terminal.layer.notes': '筆記', 'terminal.layer.aiChat': 'AI 助手', - 'terminal.layer.movePanelLeft': '面板移至左側', - 'terminal.layer.movePanelRight': '面板移至右側', - 'terminal.layer.movePanelBottom': '面板移至底部', 'terminal.layer.choosePanelPosition': '變更位置', 'terminal.layer.dockLeft': '左側', 'terminal.layer.dockRight': '右側', @@ -783,19 +780,15 @@ export const zhTWAiMessages: Messages = { 'terminal.layer.hostTree.details.protocol': '協定', 'terminal.layer.hostTree.details.group': '群組', 'terminal.layer.hostTree.details.tags': '標籤', - 'terminal.layer.hostTree.details.lastConnected': '最近連線', 'topTabs.openQuickSwitcher': '開啟快速切換', 'topTabs.moreTabs': '更多分頁', 'topTabs.aiAssistant': 'AI 助手', - 'topTabs.newLocalTerminal': '新增本機終端', 'topTabs.controlPanel': '快捷控制', 'topTabs.controlPanel.externalMcp': '對外 MCP', 'topTabs.controlPanel.theme': '主題', 'topTabs.controlPanel.theme.light': '淺色', 'topTabs.controlPanel.theme.dark': '深色', 'topTabs.controlPanel.theme.system': '系統', - 'topTabs.externalMcp.enable': '啟用對外 MCP', - 'topTabs.externalMcp.disable': '停用對外 MCP', 'topTabs.windowOpacity': '視窗透明度', 'topTabs.openSettings': '開啟設定', 'ai.chat.sessionHistory': '工作階段歷史', diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index 4b34a1cd4..f6a9be632 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -110,11 +110,9 @@ export const zhTWCoreMessages: Messages = { 'field.label': 'Label', 'field.type': '型別', 'auth.keyType': '型別 {type}', - 'auth.showAllKeys': '顯示全部 keys', // Dialogs / prompts 'confirm.deleteHost': '刪除主機 "{name}"?', - 'confirm.deleteIdentity': '刪除身分 "{name}"?', 'confirm.removeProvider': '移除供應商 "{name}"?', 'confirm.closeBusyTerminal.title': '確認關閉', 'confirm.closeBusyTerminal.message': '行程 "{command}" 仍在執行,關閉後會被終止。', @@ -407,7 +405,6 @@ export const zhTWCoreMessages: Messages = { 'tray.status.inactive': '未啟用', 'tray.status.error': '錯誤', 'tray.status.unknown': '未知', - 'tray.recentHosts': '最近連線的主機', 'tray.empty.title': '一切都很安靜', 'tray.empty.subtitle': '去連線個伺服器吧,它們想念你了 🚀', 'tray.quit': '結束 Netcatty', @@ -466,9 +463,6 @@ export const zhTWCoreMessages: Messages = { 'update.downloadFailed.message': '下載更新失敗,可前往 GitHub 手動下載。', 'update.needsSave.title': '有未儲存內容', 'update.needsSave.message': '請先儲存已開啟的編輯器,然後再次點選「立即重新啟動」以安裝更新。', - 'update.openReleases': '開啟 Releases', - 'update.remindLater': '稍後提醒', - 'update.skipVersion': '跳過此版本', // Settings > Appearance 'settings.appearance.uiTheme': '介面主題', @@ -651,8 +645,6 @@ Vaults 分頁維持扁平,不使用這塊背景。 'settings.appearance.appIcon.whiteViolet': '白底 · 紫羅蘭貓', 'settings.appearance.appIcon.rainbow': '彩虹貓', // Context menus / common actions - 'action.newHost': '新增主機', - 'action.newSubfolder': '新增資料夾', 'action.copyPublicKey': '複製公鑰', 'action.keyExport': '匯出金鑰', 'action.edit': '編輯', @@ -1034,13 +1026,9 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.columns.actions': '操作', 'sftp.sort.directoriesFirst': '資料夾置頂', 'sftp.emptyDirectory': '空目錄', - 'sftp.nav.up': '返回上層', - 'sftp.nav.home': '返回主目錄', - 'sftp.nav.refresh': '重新整理', 'sftp.upload': '上傳', 'sftp.uploadFiles': '上傳檔案', 'sftp.uploadFolder': '上傳資料夾', - 'sftp.dragDropToUpload': '拖曳檔案到這裡上傳', 'sftp.retry': '重試', 'sftp.context.open': '開啟', 'sftp.context.navigateTo': '跳轉到這裡', @@ -1079,28 +1067,21 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.copyCurrentPath': '複製目前路徑', 'sftp.copyCurrentPath.success': '已複製目前路徑', 'sftp.copyCurrentPath.error': '無法複製目前路徑', - 'sftp.viewMode.label': '檢視模式', 'sftp.viewMode.list': '列表檢視', 'sftp.viewMode.tree': '樹形檢視', 'sftp.viewMode.switchToList': '切換到列表檢視', 'sftp.viewMode.switchToTree': '切換到樹形檢視', - 'sftp.listDensity.compact': '緊湊列表', - 'sftp.listDensity.comfortable': '寬鬆列表', 'sftp.listDensity.switchToCompact': '切換到緊湊列表', 'sftp.listDensity.switchToComfortable': '切換到寬鬆列表', 'sftp.tree.loadError': '載入目錄失敗', 'sftp.tree.loading': '載入中...', 'sftp.kind.folder': '資料夾', - 'sftp.context.rename': '重新命名', 'sftp.context.permissions': '權限', - 'sftp.context.delete': '刪除', 'sftp.context.refresh': '重新整理', 'sftp.context.uploadFiles': '上傳檔案...', 'sftp.context.uploadFilesHere': '上傳檔案到這裡...', 'sftp.context.uploadFolder': '上傳資料夾...', 'sftp.context.uploadFolderHere': '上傳資料夾到這裡...', - 'sftp.context.downloadSelected': '下載選取項({count})', - 'sftp.context.deleteSelected': '刪除選取項({count})', 'sftp.dropFilesHere': '拖曳檔案到這裡', 'sftp.itemsCount': '{count} 個專案', 'sftp.selectedCount': '已選 {count} 個', @@ -1109,8 +1090,6 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.task.waiting': '等待中...', 'sftp.transfer.preparing': '準備中...', 'sftp.status.loading': '載入中...', - 'sftp.status.uploading': '上傳中...', - 'sftp.status.ready': '就緒', 'sftp.transfers': '傳輸', 'sftp.transfers.active': '{count} 個進行中', 'sftp.transfers.clearCompleted': '清除已完成', @@ -1173,7 +1152,6 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.transferCenter.applyAll': '套用到全部', 'sftp.transfers.resizeNameColumn': '調整檔名列寬', 'sftp.transfers.dragToResize': '拖曳調整高度', - 'sftp.goUp': '上一級', 'sftp.goToTerminalCwd': '定位到終端目前目錄', 'sftp.locatePathInTerminal': '定位路徑到終端', 'sftp.followTerminalCwd': '追隨終端目錄', @@ -1189,29 +1167,22 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.folderName.placeholder': '輸入資料夾名稱', 'sftp.fileName': '檔案名稱', 'sftp.fileName.placeholder': '輸入檔案名稱', - 'sftp.prompt.newFolderName': '新增資料夾名稱?', 'sftp.rename.title': '重新命名', 'sftp.rename.newName': '新名稱', 'sftp.rename.placeholder': '輸入新名稱', - 'sftp.confirm.deleteOne': '刪除 "{name}"?', - 'sftp.deleteConfirm.single': '刪除 "{name}"?', 'sftp.deleteConfirm.title': '刪除 {count} 個專案?', 'sftp.deleteConfirm.desc': '此操作不可復原,將刪除以下內容:', 'sftp.deleteConfirm.descSingle': '此操作不可復原。', 'sftp.deleteConfirm.host': '主機', 'sftp.deleteConfirm.path': '路徑', - 'sftp.error.loadFailed': '載入目錄失敗', 'sftp.error.downloadFailed': '下載失敗', 'sftp.error.uploadFailed': '上傳失敗', 'sftp.error.deleteFailed': '刪除失敗', - 'sftp.error.createFolderFailed': '建立資料夾失敗', - 'sftp.error.createFileFailed': '建立檔案失敗', 'sftp.error.invalidFileName': '檔名包含非法字元:{chars}', 'sftp.error.reservedName': '此檔名是系統保留名稱', 'sftp.overwrite.title': '檔案已存在', 'sftp.overwrite.desc': '名為"{name}"的檔案已存在。是否要替換它?', 'sftp.overwrite.confirm': '替換', - 'sftp.error.renameFailed': '重新命名失敗', 'sftp.picker.title': '選擇主機', 'sftp.picker.desc': '為{side}窗格選擇主機', 'sftp.picker.searchPlaceholder': '搜尋主機...', @@ -1219,8 +1190,6 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.picker.local.desc': '瀏覽本機檔案', 'sftp.picker.local.badge': '本機', 'sftp.picker.connected.section': '已連線', - 'sftp.picker.connected.badge': '已連線', - 'sftp.picker.connected.connecting': '連線中', 'sftp.picker.noMatch': '沒有相符的主機', 'sftp.permissions.title': '編輯權限', 'sftp.permissions.owner': '擁有者', @@ -1228,8 +1197,6 @@ Vaults 分頁維持扁平,不使用這塊背景。 'sftp.permissions.others': '其他', 'sftp.permissions.octal': '八進位制', 'sftp.permissions.symbolic': '符號', - 'sftp.permissions.success': '權限已更新', - 'sftp.permissions.failed': '權限更新失敗', // Quick Switcher 'qs.search.placeholder': '搜尋主機或分頁', @@ -1256,12 +1223,9 @@ Vaults 分頁維持扁平,不使用這塊背景。 "settings.plugins.manager.remove": "解除安裝", "settings.plugins.manager.removeNote": "解除安裝會移除外掛代碼和本地 KV 資料,保留使用者設定、秘密儲存和同步 sidecar。", "settings.plugins.permissions.statusUnknown": "狀態不明", - "plugins.sidebar.extensions": "擴充功能頁面", "plugins.sidebar.selectTerminal": "請先選擇已開啟的終端。", "plugins.sidebar.loading": "正在載入擴充功能頁面…", "plugins.vault.loading": "正在載入擴充功能頁面…", - "plugins.vault.extensions": "擴充功能", - "plugins.vault.back": "返回主機", "plugins.interaction.title": "外掛請求", "plugins.interaction.sharing": "分享的文字會交給此外掛及其已授權能力(包括網路存取)。讀取文字不代表核准新的網路目的地。", "plugins.interaction.input": "輸入文字", diff --git a/application/i18n/locales/zh-TW/scripts.ts b/application/i18n/locales/zh-TW/scripts.ts index 1fde32bb8..3b19b94f7 100644 --- a/application/i18n/locales/zh-TW/scripts.ts +++ b/application/i18n/locales/zh-TW/scripts.ts @@ -1,6 +1,5 @@ export const zhTWScriptsMessages = { 'scripts.meta.name': '名稱', - 'scripts.meta.language': '語言', 'scripts.meta.description': '描述', 'scripts.meta.descriptionPlaceholder': '可選,指令碼的簡要說明', 'scripts.meta.trigger': '觸發方式', @@ -15,7 +14,6 @@ export const zhTWScriptsMessages = { 'scripts.actions.openEditor': '彈出視窗編輯', 'scripts.actions.openEditorHint': '在更大的視窗中編輯指令碼', 'scripts.editor.modalTitle': '指令碼編輯器', - 'scripts.editor.modalSubtitle': '在更大的工作區中編輯指令碼的中繼資料與程式碼。', 'scripts.editor.lineCount': '{count} 行', 'scripts.editor.resize': '調整編輯器高度', 'scripts.targets.hint': '所選群組會動態比對,之後加入群組的主機也會自動生效。', @@ -86,17 +84,13 @@ export const zhTWScriptsMessages = { 'scripts.dialog.retry': '重試', 'scripts.dialog.skip': '跳過', 'scripts.dialog.abort': '終止', - 'scripts.running.stepProgress': '步驟 {current} / {total}', 'scripts.running.determinateProgress': '{label} {current}/{total}', 'scripts.running.progressFallback': '進度', 'scripts.running.operationsCount': '已執行 {count} 個操作', 'scripts.running.opsPrefix': '已執行 ', 'scripts.running.opsSuffix': ' 個操作', - 'scripts.running.elapsedLabel': '耗時', 'scripts.running.lastSentLabel': '已傳送:', 'scripts.running.elapsed': '耗時 {elapsed}', - 'scripts.running.completedSummary': '已完成 · 共 {count} 個操作 · {elapsed}', - 'scripts.running.dismissHint': '點選關閉', 'scripts.running.dismiss': '關閉', 'scripts.running.viewLogs': '檢視日誌', 'scripts.running.logTitle': '{name} · 執行日誌', @@ -111,26 +105,12 @@ export const zhTWScriptsMessages = { 'vault.nav.scripts': '指令碼', 'snippets.action.newScript': '新增自動化指令碼', 'hostDetails.section.automation': '自動化', - 'hostDetails.automation.loginScript': '登入指令碼', - 'hostDetails.automation.loginScriptPlaceholder': '選擇指令碼', - 'hostDetails.automation.none': '無', - 'hostDetails.automation.outputTriggers': '輸出觸發器', - 'hostDetails.automation.addTrigger': '新增觸發器', - 'hostDetails.automation.triggerPatternPlaceholder': '正規表示式', - 'hostDetails.automation.linkedScripts': '已關聯指令碼', - 'hostDetails.automation.linkedScriptsEmpty': '尚未關聯任何指令碼。', - 'hostDetails.automation.linkScriptPlaceholder': '關聯既有指令碼…', - 'hostDetails.automation.unlink': '取消關聯', - 'hostDetails.automation.equivalenceHint': '此處關聯會將本主機加入 Scripts 中該指令碼的目標列表,兩側檢視同步。', 'hostDetails.automation.queueHint': '連線本主機時依序執行指令碼。全域指令碼最先執行,再執行下方佇列。', 'hostDetails.automation.globalScripts': '全域連線指令碼', 'hostDetails.automation.globalScriptsHint': '每次連線時最先執行。順序在指令碼庫排序中調整。', 'hostDetails.automation.connectQueue': '本主機執行佇列', 'hostDetails.automation.connectQueueEmpty': '尚未為本主機設定連線指令碼佇列。', 'hostDetails.automation.addToQueuePlaceholder': '新增指令碼到佇列…', - 'hostDetails.automation.moveUp': '上移', - 'hostDetails.automation.moveDown': '下移', 'hostDetails.automation.removeFromQueue': '從佇列移除', 'hostDetails.automation.dragHandle': '拖曳排序', - 'hostDetails.automation.queueDragHint': '拖動項目即可調整連線時的執行順序。', }; diff --git a/application/i18n/locales/zh-TW/systemManager.ts b/application/i18n/locales/zh-TW/systemManager.ts index 1d248bb9c..690922300 100644 --- a/application/i18n/locales/zh-TW/systemManager.ts +++ b/application/i18n/locales/zh-TW/systemManager.ts @@ -14,13 +14,11 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.tabs.docker': 'Docker', 'systemManager.tabs.gpu': 'GPU', 'systemManager.tabs.ariaLabel': '系統管理分區', - 'systemManager.popup.loading': '正在開啟終端…', 'systemManager.popup.startupFailed': '啟動指令未順利完成。請確認目標仍可使用後再試一次。', 'systemManager.errors.loadProcesses': '載入行程列表失敗', 'systemManager.errors.loadTmux': '載入 tmux 工作階段失敗', 'systemManager.errors.loadTmuxWindows': '載入 tmux 視窗失敗', - 'systemManager.errors.loadTmuxPanes': '載入 tmux 窗格失敗', 'systemManager.errors.loadTmuxClients': '載入 tmux 用戶端失敗', 'systemManager.errors.actionFailed': '操作失敗', 'systemManager.errors.loadDocker': '載入容器列表失敗', @@ -31,7 +29,6 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.errors.nerdctlUnreachable': 'nerdctl 無法連線到 containerd', 'systemManager.errors.clusterUnreachable': '無法連到內容 {{context}} 的叢集', 'systemManager.errors.clusterUnreachableGeneric': '無法連到叢集', - 'systemManager.errors.loadOverview': '載入系統概覽失敗', 'systemManager.errors.loadGpu': '載入 GPU / NPU 狀態失敗', 'systemManager.errors.loadPorts': '載入監聽連接埠失敗', 'systemManager.errors.loadServices': '載入 systemd 服務失敗', @@ -65,13 +62,10 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.overview.noTopProcesses': '暫無行程資料', 'systemManager.processes.search': '搜尋行程…', - 'systemManager.processes.command': '指令', - 'systemManager.processes.user': '使用者', 'systemManager.processes.term': '終止', 'systemManager.processes.kill': '強制終止', 'systemManager.processes.stop': '暫停 (SIGSTOP)', 'systemManager.processes.cont': '繼續 (SIGCONT)', - 'systemManager.processes.hup': '掛斷 (SIGHUP)', 'systemManager.processes.renice': '調整優先順序', 'systemManager.processes.renicePrompt': 'Nice 值 (-20 到 19)', 'systemManager.processes.reniceInvalid': 'Nice 值必須在 -20 到 19 之間', @@ -86,7 +80,6 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.processes.stat': '狀態', 'systemManager.processes.meta': '{{count}} 個行程', 'systemManager.processes.loading': '正在載入行程…', - 'systemManager.processes.loadingMore': '正在載入更多行程…', 'systemManager.processes.state.running': '執行中', 'systemManager.processes.state.sleeping': '睡眠', 'systemManager.processes.state.stopped': '已暫停', @@ -124,12 +117,9 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.tmux.attached': '已附加', 'systemManager.tmux.detached': '未附加', 'systemManager.tmux.windows': '{{count}} 個視窗', - 'systemManager.tmux.created': '建立時間', - 'systemManager.tmux.activity': '活動時間', 'systemManager.tmux.rename': '重新命名', 'systemManager.tmux.detach': '全部分離', 'systemManager.tmux.killSession': '結束工作階段', - 'systemManager.tmux.killServer': '結束 tmux 伺服器', 'systemManager.tmux.loadingDetails': '正在載入詳情…', 'systemManager.tmux.clients': '已附加用戶端', 'systemManager.tmux.windowList': '視窗', @@ -140,31 +130,17 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.docker.unavailable': '此主機未偵測到容器執行環境(Docker、Podman、nerdctl 或 kubectl)', 'systemManager.tmux.windowsMismatch': '工作階段顯示有 {{count}} 個視窗,但 list-windows 未傳回任何視窗', 'systemManager.tmux.lastCommand': '最後執行的指令:{{command}}', - 'systemManager.tmux.noPanes': '沒有窗格', - 'systemManager.tmux.panes': '{{count}} 個窗格', - 'systemManager.tmux.active': '使用中', 'systemManager.tmux.unnamedWindow': '未命名視窗', - 'systemManager.tmux.unnamedPane': '未命名窗格', 'systemManager.tmux.attachWindow': '附加到視窗', - 'systemManager.tmux.selectWindow': '選擇視窗', 'systemManager.tmux.killWindow': '關閉視窗', - 'systemManager.tmux.killPane': '關閉窗格', - 'systemManager.tmux.splitHorizontal': '水平分割', - 'systemManager.tmux.splitVertical': '垂直分割', - 'systemManager.tmux.sendKeys': '傳送按鍵', - 'systemManager.tmux.sendKeysTo': '向視窗 {{window}} 窗格 {{pane}} 傳送按鍵', - 'systemManager.tmux.sendKeysPlaceholder': '指令或文字…', 'systemManager.tmux.renameSessionPrompt': '重新命名工作階段', 'systemManager.tmux.renameWindowPrompt': '重新命名視窗', 'systemManager.tmux.windowName': '視窗名稱', 'systemManager.tmux.confirmKillSession': '確定結束 tmux 工作階段「{{name}}」?', 'systemManager.tmux.confirmDetachSession': '確定將所有用戶端從「{{name}}」分離?', 'systemManager.tmux.confirmKillWindow': '確定關閉視窗「{{name}}」?', - 'systemManager.tmux.confirmKillPane': '確定關閉窗格 #{{index}}?', - 'systemManager.tmux.confirmKillServer': '確定結束 tmux 伺服器?所有工作階段將被終止。', 'systemManager.tmux.meta': '{{count}} 個工作階段', - 'systemManager.docker.title': '容器', 'systemManager.docker.subTabs.containers': '容器', 'systemManager.docker.subTabs.images': '映像', 'systemManager.docker.empty': '未找到容器', @@ -177,7 +153,6 @@ export const zhTwSystemManagerMessages: Messages = { 'systemManager.docker.filter.paused': '已暫停', 'systemManager.docker.shell': 'Shell', 'systemManager.docker.logs': '日誌', - 'systemManager.docker.details': '詳情', 'systemManager.docker.inspect': 'Inspect', 'systemManager.docker.imageInspect': '映像 Inspect', 'systemManager.docker.confirmRemove': '確定刪除此容器?', diff --git a/application/i18n/locales/zh-TW/terminal.ts b/application/i18n/locales/zh-TW/terminal.ts index c70dc4ed6..389b6be6e 100644 --- a/application/i18n/locales/zh-TW/terminal.ts +++ b/application/i18n/locales/zh-TW/terminal.ts @@ -57,7 +57,6 @@ export const zhTWTerminalMessages: Messages = { 'terminal.osc7Setup.title': '設定目錄追蹤', 'terminal.osc7Setup.desc': 'Netcatty 會為目前遠端使用者新增 OSC 7 提示字元設定。這樣在 sudo 或 su 之後,SFTP 也能繼續跟隨終端目錄。', 'terminal.osc7Setup.targets': '可能寫入的檔案', - 'terminal.osc7Setup.command': '將執行的指令', 'terminal.osc7Setup.run': '執行設定', 'terminal.osc7Setup.running': '正在設定...', 'terminal.osc7Setup.configured': '目錄追蹤已設定', @@ -98,37 +97,18 @@ export const zhTWTerminalMessages: Messages = { 'sftp.context.copyPath': '複製檔案路徑', 'sftp.context.openWith': '開啟方式...', 'sftp.context.edit': '編輯', - 'sftp.context.preview': '預覽', 'sftp.opener.title': '開啟方式', - 'sftp.opener.desc': '選擇一個應用程式來開啟此檔案', 'sftp.opener.builtInEditor': '內建編輯器', 'sftp.opener.editDescription': '編輯文字檔案', - 'sftp.opener.builtInImageViewer': '內建圖片預覽', - 'sftp.opener.previewDescription': '預覽圖片', 'sftp.opener.systemApp': '選擇應用程式...', 'sftp.opener.systemAppDescription': '從本機選擇一個應用程式', - 'sftp.opener.onlySystemApp': '此檔案只能用外部應用程式開啟', - 'sftp.opener.noAppsAvailable': '無可用應用程式', 'sftp.opener.noExtension': '無副檔名檔案', 'sftp.opener.setDefault': '始終使用此方式開啟 {ext} 檔案', - 'sftp.opener.confirmTitle': '設為預設?', - 'sftp.opener.confirmDescription': '是否始終使用 {app} 開啟 {ext} 檔案?', - 'sftp.opener.yesRemember': '是,記住此選擇', - 'sftp.opener.justOnce': '僅此一次', - 'sftp.opener.confirm.title': '設定預設應用程式', - 'sftp.opener.confirm.desc': '是否始終使用此應用程式開啟 .{ext} 檔案?', - 'sftp.editor.title': '文字編輯器', 'sftp.editor.save': '儲存到遠端', 'sftp.editor.saving': '儲存中...', 'sftp.editor.saved': '儲存成功', 'sftp.editor.saveFailed': '儲存檔案失敗', - 'sftp.editor.unsavedChanges': '你有未儲存的更改。確定要關閉嗎?', 'sftp.editor.syntaxHighlight': '語法標示', - 'sftp.preview.title': '圖片預覽', - 'sftp.preview.zoomIn': '放大', - 'sftp.preview.zoomOut': '縮小', - 'sftp.preview.resetZoom': '重設縮放', - 'sftp.preview.fitToWindow': '適應視窗', // Settings > SFTP File Associations 'settings.tab.sftpFileAssociations': 'SFTP', @@ -208,28 +188,16 @@ export const zhTWTerminalMessages: Messages = { 'sftp.autoSync.error': '同步檔案失敗:{error}', // SFTP Folder Upload Progress - 'sftp.upload.progress': '正在上傳 {current}/{total} 個檔案...', - 'sftp.upload.uploading': '正在上傳...', - 'sftp.upload.compressing': '正在壓縮...', - 'sftp.upload.extracting': '正在解壓...', - 'sftp.upload.scanning': '正在掃描檔案...', - 'sftp.upload.completed': '已完成', - 'sftp.upload.compressed': '壓縮傳輸', - 'sftp.upload.currentFile': '目前: {fileName}', 'sftp.upload.cancelled': '上傳已取消', 'sftp.upload.noFiles': '沒有可上傳的檔案', 'sftp.upload.partialSuccess': '已上傳 {success} 個檔案,{failed} 個失敗', 'sftp.upload.cancel': '取消', - 'sftp.upload.completedToPath': '已上傳至 {path}', // SFTP Download - 'sftp.download.completed': '已下載', - 'sftp.download.cancelled': '下載已取消', // SFTP Reconnecting 'sftp.reconnecting.title': '正在重連...', 'sftp.reconnecting.desc': '連線已斷開,正在嘗試重新連線', - 'sftp.reconnected': '連線已恢復', 'sftp.error.reconnectFailed': '重連失敗,請重試。', 'sftp.error.connectionLostManual': '連線已斷開,請手動重新連線。', 'sftp.error.connectionLostReconnecting': '連線已斷開,正在重連...', @@ -661,7 +629,6 @@ export const zhTWTerminalMessages: Messages = { 'hostDetails.proxyPanel.credentials': '憑證', 'hostDetails.proxyPanel.usernamePlaceholder': '使用者名稱', 'hostDetails.proxyPanel.passwordPlaceholder': '密碼', - 'hostDetails.proxyPanel.identities': '身分', 'hostDetails.proxyPanel.keychainIdentity': '鑰匙串身分', 'hostDetails.proxyPanel.manualCredentials': '手動憑證', 'hostDetails.proxyPanel.remove': '移除代理', @@ -682,8 +649,6 @@ export const zhTWTerminalMessages: Messages = { 'hostDetails.envVars.newVariable': '新變數', 'hostDetails.envVars.variableName': '變數名', 'hostDetails.chain.title': '編輯鏈路', - 'hostDetails.chain.desc': '新增另一台主機將建立到 {host} 的連線。', - 'hostDetails.chain.addHost': '新增主機', 'hostDetails.chain.target': '目標', 'hostDetails.chain.availableHosts': '可用主機', 'hostDetails.chain.clear': '清空', @@ -695,10 +660,7 @@ export const zhTWTerminalMessages: Messages = { 'hostDetails.group.addProtocol': '新增協定', // Keychain - 'keychain.filter.key': '金鑰', - 'keychain.filter.certificate': '憑證', 'keychain.action.generateKey': '產生金鑰', - 'keychain.action.importKey': '匯入金鑰', 'keychain.action.newIdentity': '新增身分', 'keychain.action.importCertificate': '匯入憑證', 'keychain.view.grid': '網格', @@ -739,20 +701,8 @@ export const zhTWTerminalMessages: Messages = { 'keychain.export.exporting': '匯出中...', 'keychain.export.exportAndAttach': '匯出並繫結', 'keychain.export.title': '金鑰匯出', - 'keychain.export.exportToRequired': '匯出到 *', - 'keychain.export.selectHostPlaceholder': '選擇主機...', - 'keychain.export.locationLabel': '位置 ~ $1 *', - 'keychain.export.filenameLabel': '檔名 ~ $2 *', - 'keychain.export.advanced': '高階', - 'keychain.export.note.supportsOnly': '金鑰匯出目前僅支援', - 'keychain.export.note.systems': '系統。', - 'keychain.export.note.use': '請使用', - 'keychain.export.note.customize': '部分自訂匯出指令碼。', - 'keychain.export.scriptRequired': '指令碼 *', 'keychain.export.exportToHost': '匯出到主機', - 'keychain.export.failedGeneric': '匯出失敗:{message}', 'keychain.field.label': '名稱', - 'keychain.field.labelRequired': '名稱 *', 'keychain.field.labelPlaceholder': '金鑰 Label', 'keychain.field.privateKeyRequired': '私鑰 *', 'keychain.field.publicKey': '公鑰', @@ -788,13 +738,9 @@ export const zhTWTerminalMessages: Messages = { "fido.recovery.usePassword": "改用已設定的密碼", "fido.recovery.passwordFallback": "正在使用此主機已設定的密碼登入", "fido.prompt.cancelled": "已取消安全金鑰驗證。", - 'fido.prompt.touchDone': '已觸摸', 'fido.prompt.timeout': 'FIDO 提示已逾時,請重新連線。', - 'fido.error.opensshMissing': '需要支援 FIDO/libfido2 的 OpenSSH。macOS:brew install openssh libfido2。', - 'fido.error.agentUnavailable': '無法啟動支援 FIDO 的 SSH agent。', 'keychain.generate.resident': '在裝置上儲存憑證', 'keychain.generate.verifyRequired': '每次驗證 PIN', - 'keychain.action.loadResident': '從安全金鑰載入駐留金鑰', 'keychain.generate.keySize': '金鑰長度', 'keychain.generate.labelPlaceholder': '金鑰 Label', 'keychain.generate.passphrasePlaceholder': 'Passphrase(可選)', @@ -804,7 +750,6 @@ export const zhTWTerminalMessages: Messages = { 'keychain.import.dropHint': '將金鑰檔案拖到這裡', 'keychain.import.importFromFile': '從檔案匯入', 'keychain.import.saveKey': '儲存金鑰', - 'keychain.import.importedKeyLabel': '已匯入金鑰', 'keychain.identity.usernameRequired': '使用者名稱 *', 'keychain.identity.method.passwordOnly': '密碼', 'keychain.identity.summary.password': '認證密碼', @@ -813,14 +758,8 @@ export const zhTWTerminalMessages: Messages = { 'keychain.identity.summary.passwordAndKey': '認證密碼與金鑰', 'keychain.identity.summary.passwordAndCertificate': '認證密碼與憑證', 'keychain.identity.summary.none': '無憑證', - 'keychain.identity.selectCredential': '選擇{kind}', 'keychain.identity.save': '儲存', 'keychain.identity.update': '更新', - 'keychain.keyDialog.newTitle': '新增金鑰', - 'keychain.keyDialog.newDesc': '新增新的 SSH 金鑰', - 'keychain.keyDialog.editTitle': '編輯金鑰', - 'keychain.keyDialog.editDesc': '更新此 SSH 金鑰', - 'keychain.keyDialog.updateKey': '更新金鑰', // Tabs 'tabs.closeSessionAria': '關閉工作階段', @@ -891,8 +830,6 @@ export const zhTWTerminalMessages: Messages = { 'snippets.targets.allHosts': '對所有主機生效', 'snippets.targets.allHostsShort': '所有主機', 'snippets.targets.allHostsActive': '將作用於所有可連線的主機。', - 'snippets.kind.codeSnippet': '程式碼片段', - 'snippets.kind.automationScript': '自動化指令碼', 'snippets.search.noResults.title': '無相符結果', 'snippets.search.noResults.desc': '沒有程式碼片段或程式碼包與"{query}"相符。換一個關鍵字,或清除搜尋進行瀏覽。', 'snippets.section.packages': '程式碼包', @@ -928,9 +865,6 @@ export const zhTWTerminalMessages: Messages = { 'snippets.import.modal.multipleFiles': '已選擇 {count} 個檔案', 'snippets.import.modal.parsedSummary': '{files} 個檔案,{total} 個程式碼片段,{packages} 個程式碼包,{conflicts} 個重複指令。主機繫結會被忽略。', 'snippets.import.modal.confirm': '確認匯入', - 'snippets.import.conflict.title': '匯入程式碼片段?', - 'snippets.import.conflict.desc': '“{file}”包含 {total} 個程式碼片段,其中 {conflicts} 個指令已存在。', - 'snippets.import.conflict.hostBindingsNote': '程式碼片段的主機繫結不會被匯入或匯出。', 'snippets.import.conflict.skip': '跳過重複項', 'snippets.import.conflict.overwrite': '覆蓋重複項', 'snippets.packageDialog.title': '新增程式碼包', @@ -989,9 +923,6 @@ export const zhTWTerminalMessages: Messages = { 'serial.field.customPort': '自訂序列埠路徑', 'serial.field.namedPipeHint': 'Windows 虛擬機主控台:輸入 \\\\.\\pipe\\name。虛擬機需作為伺服器端建立管道,鮑率與串口框架設定不生效。', 'serial.field.customPortPlaceholder': '例如 /dev/ttys001 或 COM1', - 'serial.type.hardware': '硬體', - 'serial.type.pseudo': '虛擬終端', - 'serial.type.custom': '自訂', 'serial.parity.none': '無', 'serial.parity.even': '偶同位', 'serial.parity.odd': '奇同位', @@ -1012,7 +943,6 @@ export const zhTWTerminalMessages: Messages = { 'serial.backspace.default': '預設(DEL,0x7F)', 'serial.backspace.ctrlH': 'Ctrl+H(BS,0x08)', 'serial.field.charset': '字元編碼', - 'serial.connectionError': '連線序列埠失敗', 'serial.field.baudRatePlaceholder': '選擇或輸入鮑率...', 'serial.field.baudRateEmpty': '輸入自訂鮑率', 'serial.field.customBaudRate': '使用自訂鮑率', @@ -1031,10 +961,7 @@ export const zhTWTerminalMessages: Messages = { 'keyboard.interactive.title': '需要驗證', 'keyboard.interactive.desc': '伺服器需要額外的身分驗證。', 'keyboard.interactive.descWithHost': '伺服器 {hostname} 需要額外的身分驗證。', - 'keyboard.interactive.response': '回應', 'keyboard.interactive.verificationCode': '驗證碼', - 'keyboard.interactive.enterCode': '輸入驗證碼', - 'keyboard.interactive.enterResponse': '輸入回應', 'keyboard.interactive.submit': '送出', 'keyboard.interactive.verifying': '驗證中...', 'keyboard.interactive.savePassword': '儲存密碼', diff --git a/application/i18n/locales/zh-TW/vault.ts b/application/i18n/locales/zh-TW/vault.ts index b881f49d7..7073d7dcb 100644 --- a/application/i18n/locales/zh-TW/vault.ts +++ b/application/i18n/locales/zh-TW/vault.ts @@ -19,14 +19,6 @@ export const zhTWVaultMessages: Messages = { 'notes.export.toast.failed': '匯出筆記失敗。', 'notes.codeBlock.copied': '已複製', 'notes.codeBlock.copyFailed': '複製程式碼塊失敗。', - 'notes.group.prompt': '資料夾路徑', - 'notes.group.all': '筆記本', - 'notes.group.ungrouped': '未群組', - 'notes.section.notebooks': '筆記本', - 'notes.section.notes': '筆記', - 'notes.mode.edit': '編輯', - 'notes.mode.split': '分割', - 'notes.mode.preview': '預覽', 'notes.title.placeholder': '筆記標題', 'notes.editor.placeholder': '在這裡寫 Markdown 筆記...', 'notes.editor.unrenderableMarkdown': '這篇筆記包含富文本編輯器無法顯示的 Markdown(例如未閉合的 文字),已改為顯示原始 Markdown 原始碼,內容並沒有遺失。', @@ -72,25 +64,18 @@ export const zhTWVaultMessages: Messages = { 'notes.toolbar.divider': '分隔線', 'notes.toolbar.link': '插入超連結', 'notes.toolbar.image': '插入圖片', - 'notes.action.pin': '置頂筆記', - 'notes.action.unpin': '取消置頂', 'notes.tag.remove': '移除標籤', 'notes.tag.placeholder': '標籤名...', 'notes.tag.add': '新增標籤', 'notes.outline.title': '大綱目錄', - 'notes.outline.titleWithCount': '大綱目錄 ({count})', 'notes.outline.empty': '暫無標題大綱', 'notes.outline.emptyHint': '在 Markdown 中使用 #、## 編寫各級標題', 'notes.export.share': '匯出與分享', 'notes.export.currentNote': '目前筆記', 'notes.export.exportMarkdown': '匯出為 Markdown (.md)', - 'notes.export.exportHtml': '匯出為 HTML (.html)', 'notes.export.copyMarkdown': '複製 Markdown 源碼', 'notes.export.allNotes': '全部筆記', 'notes.export.exportAllZip': '匯出全部為 ZIP 壓縮包', - 'notes.export.toast.markdownSuccess': '已匯出 Markdown 檔案', - 'notes.export.toast.htmlSuccess': '已匯出 HTML 檔案', - 'notes.export.toast.zipSuccess': '已匯出全部筆記備份 ZIP', // Select Host panel 'selectHost.title': '選擇主機', @@ -130,12 +115,6 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.title.new': '新增主機', 'hostDetails.saveAria': '儲存', 'hostConnectionTest.title': '測試連線', - 'hostConnectionTest.test': '測試', - 'hostConnectionTest.chainOf': '第 {current}/{total} 跳', - 'hostConnectionTest.success': '連線成功', - 'hostConnectionTest.successHint': '主機已接受您的憑證。您可以關閉此視窗。', - 'hostConnectionTest.connecting': '正在連線… {seconds} 秒後逾時', - 'hostConnectionTest.failed': '連線失敗。', 'hostConnectionTest.retry': '重試', 'hostConnectionTest.credentialsUnavailable': '儲存的憑證無法在此裝置上解密。請在下方重新輸入。', 'hostDetails.section.address': '位址', @@ -172,11 +151,8 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.notes.toggle.show': '顯示備註編輯框', 'hostDetails.notes.toggle.hide': '隱藏備註編輯框', 'hostDetails.group.placeholder': '父級 Group', - 'hostDetails.section.credentials': '憑證', 'hostDetails.section.portCredentials': '埠與憑證', 'hostDetails.section.appearance': '外觀', - 'hostDetails.distro.title': 'Linux 發行版', - 'hostDetails.distro.desc': '可在連線後自動探測,也可以手動覆蓋圖示所用的發行版。', 'hostDetails.icon.title': '主機圖示', 'hostDetails.icon.preview': '圖示預覽', 'vault.panel.resizeWidth': '調整面板寬度', @@ -190,7 +166,6 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.icon.mode.custom': '自訂', 'hostDetails.icon.reset': '重設主機圖示', 'hostDetails.icon.colorLabel': '圖示顏色', - 'hostDetails.icon.colorDefault': '預設', 'hostDetails.icon.colorAuto': '自動', 'hostDetails.icon.colorManual': '手動', 'hostDetails.icon.colorChoice': '顏色', @@ -240,7 +215,6 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.distro.mode.auto': '自動探測', 'hostDetails.distro.mode.manual': '手動覆蓋', 'hostDetails.distro.detectedLabel': '目前值', - 'hostDetails.distro.manualLabel': '手動指定', 'hostDetails.distro.pending': '首次連線後自動探測', 'hostDetails.distro.unknown': '未知', 'hostDetails.distro.option.linux': '通用 Linux', @@ -291,7 +265,6 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.auth.mfaFirst': '優先互動式驗證', 'hostDetails.auth.mfaFirst.desc': '適用於必須透過 keyboard-interactive 輸入密碼和 MFA 的伺服器。', 'hostDetails.totp.title': '驗證器 (TOTP)', - 'hostDetails.totp.enable': '為這台主機儲存 TOTP 金鑰', 'hostDetails.totp.setup': '設定…', 'hostDetails.totp.edit': '編輯', 'hostDetails.totp.modalTitle': '設定驗證器', @@ -394,10 +367,8 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.jumpHosts.direct': '直連', 'hostDetails.jumpHosts.configure': '設定代理主機', 'hostDetails.proxy': '透過 HTTP/SOCKS5/指令代理', - 'hostDetails.proxy.none': '無', 'hostDetails.proxy.direct': '直連(不使用代理)', 'hostDetails.proxy.directHint': '不使用群組或全域預設代理', - 'hostDetails.proxy.edit': '編輯代理', 'hostDetails.proxy.configure': '設定代理', 'hostDetails.envVars': '環境變數', 'hostDetails.envVars.add': '新增環境變數', @@ -456,28 +427,14 @@ export const zhTWVaultMessages: Messages = { 'hostDetails.plugin.useSsh': '改用 SSH', // Host form (legacy modal) - 'hostForm.title.edit': '編輯主機', - 'hostForm.title.new': '新增主機', - 'hostForm.desc.edit': '更新該主機的連線資訊', - 'hostForm.desc.new': '建立一個新的 SSH 主機條目', 'hostForm.field.label': '名稱', - 'hostForm.placeholder.label': 'My Production Server', 'hostForm.field.hostname': 'Hostname / IP', - 'hostForm.placeholder.hostname': '192.168.1.1', 'hostForm.field.port': '埠', 'hostForm.field.username': '使用者名稱', 'hostForm.field.osType': '作業系統型別', - 'hostForm.placeholder.selectOs': '選擇作業系統', 'hostForm.field.group': '群組', - 'hostForm.placeholder.group': '例如:AWS、DigitalOcean', 'hostForm.field.tags': '標籤', - 'hostForm.placeholder.addTag': '新增標籤…', - 'hostForm.auth.method': '認證方式', - 'hostForm.auth.password': '密碼', - 'hostForm.auth.sshKey': 'SSH金鑰', 'hostForm.auth.selectKey': '選擇 SSH金鑰', - 'hostForm.auth.noKeys': '暫無金鑰', - 'hostForm.auth.noKeysHint': '鑰匙串中未找到 SSH金鑰,請先建立一個。', 'hostForm.saveHost': '儲存主機', // Connection logs @@ -495,7 +452,6 @@ export const zhTWVaultMessages: Messages = { 'logs.action.delete': '刪除', // Log view - 'logView.customizeAppearance': '自訂外觀', 'logView.appearance': '外觀', 'logView.readOnly': '只讀', 'logView.export': '匯出', @@ -508,7 +464,6 @@ export const zhTWVaultMessages: Messages = { 'terminal.toolbar.availableAfterConnect': '連線後可用', 'terminal.toolbar.sendYmodem': 'YMODEM 傳送', 'terminal.toolbar.receiveYmodem': 'YMODEM 接收', - 'terminal.toolbar.sftp': 'SFTP', 'terminal.toolbar.more': '更多操作', 'terminal.toolbar.scripts': '指令碼', 'terminal.toolbar.history': '指令歷史', @@ -533,7 +488,6 @@ export const zhTWVaultMessages: Messages = { 'terminal.composeBar.resize': '拖曳調整撰寫欄高度', 'terminal.composeBar.manageSnippets': '管理快捷程式碼片段', 'terminal.composeBar.searchSnippets': '搜尋程式碼片段...', - 'terminal.composeBar.noPinnedSnippets': '點選 + 固定常用程式碼片段', 'terminal.composeBar.noMatchingSnippets': '沒有相符的程式碼片段', 'terminal.composeBar.pinnedCount': '已固定 {count} 個', 'terminal.composeBar.unpinSnippet': '從快捷欄移除 {label}', @@ -690,9 +644,6 @@ export const zhTWVaultMessages: Messages = { 'terminal.themeModal.themeType': '{type} 主題', 'terminal.hiddenTheme.title': '目前隱藏主題', 'terminal.hiddenTheme.desc': '這個主題已從手動選擇列表中隱藏;當你選擇其他可見主題後,它會被替換。', - 'topTabs.toggleTheme.systemExitTitle': '目前正在跟隨系統主題', - 'topTabs.toggleTheme.systemExitMessage': '請到設定裡選擇固定的淺色或深色主題。', - 'topTabs.toggleTheme.openSettings': '開啟設定', // Custom Themes 'terminal.customTheme.section': '自訂主題', @@ -705,7 +656,6 @@ export const zhTWVaultMessages: Messages = { 'terminal.customTheme.importDesc': '從 iTerm2 配色方案檔案匯入', 'terminal.customTheme.importError': '無法解析所選檔案,請確保它是有效的 .itermcolors XML 檔案。', 'terminal.customTheme.delete': '刪除主題', - 'terminal.customTheme.confirmDelete': '確認刪除', 'terminal.customTheme.name': '名稱', 'terminal.customTheme.namePlaceholder': '我的自訂主題', 'terminal.customTheme.type': '型別', @@ -764,10 +714,7 @@ export const zhTWVaultMessages: Messages = { 'cloudSync.provider.disconnect.cloudRemains': '雲端的加密同步副本可能仍保存在 {name} 儲存空間中。如需清除,請到該服務商刪除同步檔案。中斷連線不代表裝置已完成交接清理。', 'cloudSync.provider.disconnect.failed': '未能完成與 {name} 的中斷連線,保存的連線資料可能仍在,請重試。', 'cloudSync.provider.webdav': 'WebDAV', - 'cloudSync.provider.webdav.desc': '連線到自建 WebDAV 端點', 'cloudSync.provider.s3': 'S3 相容儲存', - 'cloudSync.provider.s3.desc': '連線到 S3 相容物件儲存', - 'cloudSync.provider.comingSoon': '即將支援', 'cloudSync.webdav.title': 'WebDAV 設定', 'cloudSync.webdav.desc': '設定 WebDAV 端點用於加密同步。', 'cloudSync.webdav.endpoint': '端點位址', @@ -796,20 +743,6 @@ export const zhTWVaultMessages: Messages = { 'cloudSync.s3.allowInsecure': '允許不安全的連線(忽略憑證錯誤)', 'cloudSync.s3.showSecret': '顯示金鑰', 'cloudSync.s3.validation.required': '端點、Region、Bucket、Access Key 與 Secret 必填。', - 'cloudSync.smb.title': 'SMB 設定', - 'cloudSync.smb.desc': '連線到 SMB/CIFS 檔案共享以進行加密同步。', - 'cloudSync.smb.share': '共享路徑', - 'cloudSync.smb.username': '使用者名稱', - 'cloudSync.smb.password': '密碼', - 'cloudSync.smb.domain': '域(可選)', - 'cloudSync.smb.domainPlaceholder': '例如:WORKGROUP', - 'cloudSync.smb.port': '埠(可選)', - 'cloudSync.smb.showSecret': '顯示密碼', - 'cloudSync.smb.validation.share': '共享路徑必填。', - 'cloudSync.smb.validation.port': '埠必須是 1 到 65535 之間的數字。', - 'cloudSync.connect.smb.success': 'SMB 已連線', - 'cloudSync.connect.smb.failedTitle': 'SMB 連線失敗', - 'cloudSync.provider.smb': 'SMB 共享', 'cloudSync.connect.webdav.success': 'WebDAV 已連線', 'cloudSync.connect.webdav.failedTitle': 'WebDAV 連線失敗', 'cloudSync.connect.s3.success': 'S3 已連線', @@ -826,7 +759,6 @@ export const zhTWVaultMessages: Messages = { 'cloudSync.lastSync.minutesAgo': '{minutes} 分鐘前', 'cloudSync.changeKey': '更改 Key', 'cloudSync.providers.title': '雲服務', - 'cloudSync.syncAll': '同步所有已連線的服務', 'cloudSync.autoSync.title': '自動同步', 'cloudSync.autoSync.desc': '發生變更時自動同步', 'cloudSync.strategy.title': '同步策略', @@ -891,7 +823,6 @@ export const zhTWVaultMessages: Messages = { 'cloudSync.localBackups.folderWarning': '僅複製此資料夾並不構成完整、可攜的備份。刪除或清空應用程式設定目錄(userData)可能導致這些還原點無法讀取。', 'cloudSync.localBackups.retentionTitle': '備份保留數量', 'cloudSync.localBackups.retentionDesc': '設定 Netcatty 最多保留多少份本機備份。', - 'cloudSync.localBackups.maxCount': '最多保留', 'cloudSync.localBackups.maxSaved': '已儲存保留數量:{count}', 'cloudSync.localBackups.maxInvalid': '請輸入 1 到 100 之間的數字。', 'cloudSync.localBackups.empty': '還沒有本機備份。', @@ -1021,7 +952,6 @@ export const zhTWVaultMessages: Messages = { 'sftp.context.openWithDefault': '系統預設程式開啟', 'common.clear': '清除', 'common.optional': '可選', - 'common.selectPlaceholder': '請選擇...', 'common.error': '錯誤', 'common.validation': '驗證', 'common.saveChanges': '儲存修改', @@ -1063,7 +993,6 @@ export const zhTWVaultMessages: Messages = { 'pf.tooltip.localDesc': '本機埠轉發:透過 SSH 隧道存取遠端服務', 'pf.tooltip.remoteDesc': '遠端埠轉發:將本機服務公開給遠端主機', 'pf.tooltip.dynamicDesc': '動態 SOCKS 代理:透過 SSH 隧道轉發流量', - 'pf.deleteActive.title': '刪除正在執行的埠轉發?', 'pf.deleteActive.desc': '埠轉發規則 "{label}" 目前正在執行。刪除前將先關閉轉發連線。', 'pf.deleteActive.confirm': '關閉並刪除', 'pf.form.autoStart': '自動啟動', @@ -1078,8 +1007,6 @@ export const zhTWVaultMessages: Messages = { 'sftp.pane.selectHostToStart': '先選擇一個主機', 'sftp.pane.chooseFilesystem': '選擇要瀏覽的本機或遠端檔案系統', 'sftp.tabs.addTab': '新增分頁', - 'sftp.tabs.closeTab': '關閉分頁', - 'sftp.tabs.newTab': '新分頁', 'sftp.tabs.copyDefaultPath': '複製分頁(預設路徑)', 'sftp.tabs.copyCurrentPath': '複製並跳轉到目前路徑', 'sftp.conflict.title': '檔案衝突', @@ -1105,10 +1032,6 @@ export const zhTWVaultMessages: Messages = { 'sftp.conflict.action.replace': '替換', // SFTP Upload Phases - 'sftp.upload.phase.compressing': '正在壓縮', - 'sftp.upload.phase.uploading': '正在上傳', - 'sftp.upload.phase.extracting': '正在解壓', - 'sftp.upload.phase.compressed': '壓縮傳輸', 'vault.import.plugins.title': '外掛程式匯入器', 'vault.import.plugins.loading': '正在建立安全匯入預覽…', 'vault.import.plugins.progress': '已處理 {completed}/{total} {message}', diff --git a/application/state/activeChromeThemeSync.test.ts b/application/state/activeChromeThemeSync.test.ts deleted file mode 100644 index c3dfdc09c..000000000 --- a/application/state/activeChromeThemeSync.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -const source = readFileSync(new URL("./activeChromeThemeSync.ts", import.meta.url), "utf8"); -const chromeThemeSource = readFileSync(new URL("./useActiveChromeTheme.ts", import.meta.url), "utf8"); -const storeSource = readFileSync(new URL("./activeTabStore.ts", import.meta.url), "utf8"); - -test("active tab changes notify chrome theme before react subscribers", () => { - const setActiveTabIdBody = storeSource.match(/setActiveTabId = \(id: string(?:, options\?: \w+)?\) => \{[\s\S]*?\n {2}\};/)?.[0] ?? ""; - assert.match(setActiveTabIdBody, /this\.syncListeners\.forEach\(\(listener\) => listener\(id\)\)/); - assert.match(setActiveTabIdBody, /this\.scheduleNotify\(\)/); - assert.ok( - setActiveTabIdBody.indexOf("syncListeners.forEach") < setActiveTabIdBody.indexOf("scheduleNotify"), - "sync chrome theme listeners must run before deferred react notify", - ); - assert.match(source, /activeTabStore\.subscribeSync\(notifyActiveChromeThemeForTab\)/); - assert.match(source, /isActiveChromeThemeResolvable/); - assert.match(source, /clearTopTabsChromeThemeVars/); -}); - -test("tab chrome notify defers apply via rAF and short-circuits on fingerprint", () => { - assert.match(source, /requestAnimationFrame/); - assert.match(source, /themeFingerprint/); - assert.match(source, /export function applyChromeThemeForTab/); - assert.match(source, /export function notifyActiveChromeThemeForTab/); - // Tab path must not use view transitions. - assert.doesNotMatch(source, /mode:\s*['"]view['"]/); -}); - -test("syncActiveChromeTheme applies terminal chrome with instant mode", () => { - assert.match(chromeThemeSource, /mode:\s*['"]instant['"]/); - assert.match(chromeThemeSource, /nextFingerprint === appliedFingerprint/); -}); diff --git a/application/state/appearanceChromeStore.ts b/application/state/appearanceChromeStore.ts index 789395e87..42e9155d8 100644 --- a/application/state/appearanceChromeStore.ts +++ b/application/state/appearanceChromeStore.ts @@ -1,6 +1,4 @@ -import { useSyncExternalStore } from 'react'; - -type Listener = () => void; +import { createExternalStore, type StoreListener } from './createExternalStore'; export type AppearanceChromeSnapshot = { accentMode: 'theme' | 'custom'; @@ -16,53 +14,31 @@ const DEFAULT_SNAPSHOT: AppearanceChromeSnapshot = Object.freeze({ * External store for app accent chrome so Terminal leaves can apply custom * accent without TerminalLayer rebuilding on every color-picker drag tick. */ -class AppearanceChromeStore { - private snapshot: AppearanceChromeSnapshot = DEFAULT_SNAPSHOT; - private listeners = new Set(); +const store = createExternalStore(DEFAULT_SNAPSHOT, { + isEqual: (prev, next) => + prev.accentMode === next.accentMode && prev.customAccent === next.customAccent, +}); - getSnapshot = (): AppearanceChromeSnapshot => this.snapshot; - - subscribe = (listener: Listener): (() => void) => { - this.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - }; - - setSnapshot(next: AppearanceChromeSnapshot): void { - if ( - this.snapshot.accentMode === next.accentMode - && this.snapshot.customAccent === next.customAccent - ) { - return; - } - this.snapshot = next; - for (const listener of this.listeners) { - listener(); - } - } -} - -export const appearanceChromeStore = new AppearanceChromeStore(); +export const appearanceChromeStore = { + getSnapshot: store.getSnapshot, + subscribe: store.subscribe, + setSnapshot: store.setSnapshot, +}; export function publishAppearanceChromeSnapshot( snapshot: AppearanceChromeSnapshot, ): void { - appearanceChromeStore.setSnapshot(snapshot); + store.setSnapshot(snapshot); } export function getAppearanceChromeSnapshot(): AppearanceChromeSnapshot { - return appearanceChromeStore.getSnapshot(); + return store.getSnapshot(); } -export function subscribeAppearanceChrome(listener: Listener): () => void { - return appearanceChromeStore.subscribe(listener); +export function subscribeAppearanceChrome(listener: StoreListener): () => void { + return store.subscribe(listener); } export function useAppearanceChromeStore(): AppearanceChromeSnapshot { - return useSyncExternalStore( - subscribeAppearanceChrome, - getAppearanceChromeSnapshot, - getAppearanceChromeSnapshot, - ); + return store.useStore(); } diff --git a/application/state/createExternalStore.ts b/application/state/createExternalStore.ts new file mode 100644 index 000000000..109c5c628 --- /dev/null +++ b/application/state/createExternalStore.ts @@ -0,0 +1,98 @@ +import { useSyncExternalStore } from 'react'; + +export type StoreListener = () => void; + +export interface ListenerRegistry { + subscribe: (listener: StoreListener) => () => void; + notify: () => void; + scheduleNotify: () => void; + readonly size: number; +} + +const scheduleFrame = (cb: () => void): number => + typeof requestAnimationFrame === 'function' + ? requestAnimationFrame(cb) + : (setTimeout(cb, 0) as unknown as number); + +/** + * Lightweight listener registry supporting both immediate and rAF-coalesced + * notifications for `useSyncExternalStore` external stores. + */ +export function createListenerRegistry(): ListenerRegistry { + const listeners = new Set(); + let notifyRafId: number | null = null; + + const notify = (): void => { + for (const listener of listeners) { + listener(); + } + }; + + return { + subscribe(listener: StoreListener): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + notify, + scheduleNotify(): void { + if (notifyRafId !== null) return; + notifyRafId = scheduleFrame(() => { + notifyRafId = null; + notify(); + }); + }, + get size(): number { + return listeners.size; + }, + }; +} + +export interface ExternalStore { + getSnapshot: () => T; + setSnapshot: (next: T) => void; + update: (updater: (prev: T) => T) => void; + subscribe: (listener: StoreListener) => () => void; + useStore: () => T; +} + +export interface CreateExternalStoreOptions { + isEqual?: (prev: T, next: T) => boolean; +} + +/** + * Factory for simple React `useSyncExternalStore` single-value stores. + * Defaults to `Object.is` equality to avoid redundant notifications. + */ +export function createExternalStore( + initial: T, + options?: CreateExternalStoreOptions, +): ExternalStore { + const isEqual = options?.isEqual ?? Object.is; + const registry = createListenerRegistry(); + let snapshot = initial; + + const getSnapshot = (): T => snapshot; + + const setSnapshot = (next: T): void => { + if (isEqual(snapshot, next)) return; + snapshot = next; + registry.notify(); + }; + + const update = (updater: (prev: T) => T): void => { + setSnapshot(updater(snapshot)); + }; + + const useStore = (): T => + useSyncExternalStore(registry.subscribe, getSnapshot, getSnapshot); + + return { + getSnapshot, + setSnapshot, + update, + subscribe: registry.subscribe, + useStore, + }; +} diff --git a/application/state/editorSftpBridge.ts b/application/state/editorSftpBridge.ts index 09bfb187c..255f97b65 100644 --- a/application/state/editorSftpBridge.ts +++ b/application/state/editorSftpBridge.ts @@ -25,19 +25,6 @@ const writers = new Set(); const NOT_MY_CONNECTION_RE = /SFTP connection is no longer available/i; -export const registerEditorSftpWriter = (fn: EditorSftpWrite | null) => { - // Pass `null` on cleanup — but cleanup also needs to know WHICH writer to - // remove. Callers who register once per mount should instead use - // `registerEditorSftpWriterScoped` below, which returns an unregister fn. - // This legacy signature is preserved for callers that prefer the - // register/unregister-with-null pattern: we clear ALL writers on null. - if (fn === null) { - writers.clear(); - return; - } - writers.add(fn); -}; - export const registerEditorSftpWriterScoped = (fn: EditorSftpWrite): (() => void) => { writers.add(fn); return () => { diff --git a/application/state/fontStore.test.ts b/application/state/fontStore.test.ts deleted file mode 100644 index c96f329ce..000000000 --- a/application/state/fontStore.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { readFileSync } from 'node:fs'; -import assert from 'node:assert/strict'; -import test from 'node:test'; - -const source = readFileSync(new URL('./fontStore.ts', import.meta.url), 'utf8'); - -test('refresh clears local font and availability detection caches', () => { - assert.match(source, /clearLocalFontsCache\(\);\s*clearFontAvailabilityCache\(\);/); -}); diff --git a/application/state/hostTreeInlineGroupDeleteStore.ts b/application/state/hostTreeInlineGroupDeleteStore.ts index 6a1207cc0..add146491 100644 --- a/application/state/hostTreeInlineGroupDeleteStore.ts +++ b/application/state/hostTreeInlineGroupDeleteStore.ts @@ -1,36 +1,17 @@ -import { useSyncExternalStore } from 'react'; +import { createExternalStore } from './createExternalStore'; -type Listener = () => void; +const store = createExternalStore(null, { + isEqual: () => false, +}); -class HostTreeInlineGroupDeleteStore { - private targetPath: string | null = null; - private listeners = new Set(); - - getTargetPath = () => this.targetPath; - - open = (groupPath: string) => { - this.targetPath = groupPath; - this.listeners.forEach((listener) => listener()); - }; - - close = () => { - if (!this.targetPath) return; - this.targetPath = null; - this.listeners.forEach((listener) => listener()); - }; - - subscribe = (listener: Listener) => { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - }; -} - -export const hostTreeInlineGroupDeleteStore = new HostTreeInlineGroupDeleteStore(); - -export const useHostTreeInlineGroupDeleteTarget = () => { - return useSyncExternalStore( - hostTreeInlineGroupDeleteStore.subscribe, - hostTreeInlineGroupDeleteStore.getTargetPath, - hostTreeInlineGroupDeleteStore.getTargetPath, - ); +export const hostTreeInlineGroupDeleteStore = { + getTargetPath: store.getSnapshot, + open: (groupPath: string) => store.setSnapshot(groupPath), + close: () => { + if (!store.getSnapshot()) return; + store.setSnapshot(null); + }, + subscribe: store.subscribe, }; + +export const useHostTreeInlineGroupDeleteTarget = () => store.useStore(); diff --git a/application/state/hostTreeInlineGroupEditStore.ts b/application/state/hostTreeInlineGroupEditStore.ts index a5d6e9995..0dee08cf0 100644 --- a/application/state/hostTreeInlineGroupEditStore.ts +++ b/application/state/hostTreeInlineGroupEditStore.ts @@ -1,4 +1,4 @@ -import { useSyncExternalStore } from 'react'; +import { createExternalStore } from './createExternalStore'; export type HostTreeInlineGroupEdit = { groupPath: string; @@ -7,46 +7,28 @@ export type HostTreeInlineGroupEdit = { shouldScrollIntoView?: boolean; }; -type Listener = () => void; +const store = createExternalStore(null, { + isEqual: () => false, +}); -class HostTreeInlineGroupEditStore { - private edit: HostTreeInlineGroupEdit | null = null; - private listeners = new Set(); - - getEdit = () => this.edit; - - startEdit = (edit: HostTreeInlineGroupEdit) => { - this.edit = { +export const hostTreeInlineGroupEditStore = { + getEdit: store.getSnapshot, + startEdit: (edit: HostTreeInlineGroupEdit) => { + store.setSnapshot({ ...edit, shouldScrollIntoView: edit.isNew ? true : edit.shouldScrollIntoView, - }; - this.listeners.forEach((listener) => listener()); - }; - - markScrollHandled = () => { - if (!this.edit?.shouldScrollIntoView) return; - this.edit = { ...this.edit, shouldScrollIntoView: false }; - this.listeners.forEach((listener) => listener()); - }; - - clear = () => { - if (!this.edit) return; - this.edit = null; - this.listeners.forEach((listener) => listener()); - }; - - subscribe = (listener: Listener) => { - this.listeners.add(listener); - return () => this.listeners.delete(listener); - }; -} - -export const hostTreeInlineGroupEditStore = new HostTreeInlineGroupEditStore(); - -export const useHostTreeInlineGroupEdit = () => { - return useSyncExternalStore( - hostTreeInlineGroupEditStore.subscribe, - hostTreeInlineGroupEditStore.getEdit, - hostTreeInlineGroupEditStore.getEdit, - ); + }); + }, + markScrollHandled: () => { + const current = store.getSnapshot(); + if (!current?.shouldScrollIntoView) return; + store.setSnapshot({ ...current, shouldScrollIntoView: false }); + }, + clear: () => { + if (!store.getSnapshot()) return; + store.setSnapshot(null); + }, + subscribe: store.subscribe, }; + +export const useHostTreeInlineGroupEdit = () => store.useStore(); diff --git a/application/state/pluginViewOcclusion.ts b/application/state/pluginViewOcclusion.ts deleted file mode 100644 index cb26013df..000000000 --- a/application/state/pluginViewOcclusion.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** Native child views must yield to host dialogs and overlapping portals. */ -export function isPluginViewOccluded(mount: HTMLElement): boolean { - const rect = mount.getBoundingClientRect(); - if (!mount.isConnected || mount.closest('[hidden], [inert], [aria-hidden="true"]')) return true; - const overlays = mount.ownerDocument.querySelectorAll( - '[data-app-lock-overlay], [role="dialog"], [role="alertdialog"], ' - + '[role="menu"][data-state="open"], [data-radix-popper-content-wrapper] > *, [data-native-view-occluder]', - ); - return [...overlays].some((overlay) => { - if (mount.contains(overlay)) return false; - const style = getComputedStyle(overlay); - if (style.display === 'none' || style.visibility === 'hidden' || overlay.closest('[hidden], [inert]')) return false; - if (overlay.matches('[data-app-lock-overlay], [role="dialog"][aria-modal="true"], [role="alertdialog"]')) return true; - const other = overlay.getBoundingClientRect(); - return other.width > 0 && other.height > 0 && other.x < rect.right && other.right > rect.x - && other.y < rect.bottom && other.bottom > rect.y; - }); -} diff --git a/application/state/scriptAutomationCoordinator.ts b/application/state/scriptAutomationCoordinator.ts index 7c957a1cf..18b4229ff 100644 --- a/application/state/scriptAutomationCoordinator.ts +++ b/application/state/scriptAutomationCoordinator.ts @@ -1,5 +1,5 @@ import type { Snippet } from '@/domain/models'; -import { isScriptSnippet, scriptContainsWriteOperations } from '@/domain/snippetScript.ts'; +import { scriptContainsWriteOperations } from '@/domain/snippetScript.ts'; import { localStorageAdapter } from '@/infrastructure/persistence/localStorageAdapter.ts'; import { STORAGE_KEY_AI_PERMISSION_MODE } from '@/infrastructure/config/storageKeys.ts'; import type { AIPermissionMode } from '@/infrastructure/ai/types.ts'; @@ -252,28 +252,6 @@ export async function runConnectScriptsSequential(params: { } } -export async function runSnippetOrScript(params: { - snippet: Snippet; - sessionId: string; - runSnippetText: ( - command: string, - noAutoRun?: boolean, - options?: { multiLineRunMode?: Snippet["multiLineRunMode"] }, - ) => void; - command: string; -}) { - if (isScriptSnippet(params.snippet)) { - await runAutomationScript({ - snippet: params.snippet, - sessionId: params.sessionId, - }); - return; - } - params.runSnippetText(params.command, params.snippet.noAutoRun, { - multiLineRunMode: params.snippet.multiLineRunMode, - }); -} - export async function stopScriptRun(runId: string): Promise<{ ok: boolean }> { const result = await netcattyBridge.get()?.scriptStop?.(runId); return { ok: result?.ok !== false }; diff --git a/application/state/sessionHistorySearch.test.ts b/application/state/sessionHistorySearch.test.ts index 9bd440a5f..06f7577cd 100644 --- a/application/state/sessionHistorySearch.test.ts +++ b/application/state/sessionHistorySearch.test.ts @@ -9,7 +9,7 @@ import { PINYIN_CACHE_MAX_CHARS, getPinyinCacheStatsForTests, resetPinyinCacheForTests, -} from "../../lib/searchMatcher.ts"; +} from "../../domain/searchMatcher.ts"; import { createSessionHistorySearch } from "./sessionHistorySearch.ts"; // One instance for the whole file: it keeps the pre-factory semantics of every diff --git a/application/state/sessionHistorySearch.ts b/application/state/sessionHistorySearch.ts index 01d1a6166..23e5b71fd 100644 --- a/application/state/sessionHistorySearch.ts +++ b/application/state/sessionHistorySearch.ts @@ -5,7 +5,7 @@ import { type SessionHistorySearchTarget, type SessionSearchIndex, } from '../../domain/sessionHistorySearch'; -import { prepareSearchQuery, truncateQueryForMatch } from '../../lib/searchMatcher'; +import { prepareSearchQuery, truncateQueryForMatch } from '../../domain/searchMatcher'; /** * Memory bounds for the per-session search index cache. `filterSessionHistory` diff --git a/application/state/settingsIpcSync.autoLaunch.test.ts b/application/state/settingsIpcSync.autoLaunch.test.ts deleted file mode 100644 index 250233a69..000000000 --- a/application/state/settingsIpcSync.autoLaunch.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import test from 'node:test'; - -/** - * useSettingsIpcSync is a React hook (useEffect-driven); without - * react-test-renderer available in this environment we can't mount it and - * assert on live cross-window broadcast behavior. These structural checks - * instead verify the source wiring end-to-end: every other window's - * useSettingsState instance (mounted via AppLockGate, even though the - * auto-launch toggle only ever renders in the Settings window) must consume - * the STORAGE_KEY_AUTO_LAUNCH_ENABLED broadcast, matching the established - * pattern used by every other synchronized boolean setting in this file. - */ - -test('settingsIpcSync handles the auto-launch broadcast key like other synced booleans', () => { - const source = fs.readFileSync(new URL('./settingsIpcSync.ts', import.meta.url), 'utf8'); - - assert.match( - source, - /STORAGE_KEY_AUTO_LAUNCH_ENABLED/, - 'must import the storage key', - ); - assert.match( - source, - /if \(key === STORAGE_KEY_AUTO_LAUNCH_ENABLED && typeof value === 'boolean'\) \{\s*[\s\S]*?setAutoLaunchEnabled\(/, - 'must apply the broadcast value to local state, same as e.g. STORAGE_KEY_GLOBAL_HOTKEY_ENABLED', - ); - assert.match( - source, - /setAutoLaunchEnabled: Dispatch>/, - 'the setter prop must be declared on the params interface', - ); - - // The dependency array of the effect must list the setter, or the - // listener could close over a stale setter reference after a re-render. - const effectStart = source.indexOf('useEffect(() => {'); - const depsStart = source.indexOf('}, [', effectStart); - assert.ok(effectStart > -1 && depsStart > effectStart, 'expected to find the sync effect and its deps array'); - const depsSlice = source.slice(depsStart, source.indexOf(']);', depsStart)); - assert.match(depsSlice, /setAutoLaunchEnabled/, 'setAutoLaunchEnabled must be listed in the effect deps array'); -}); - -test('useSettingsState wires the real autoLaunchEnabled setter into useSettingsIpcSync (not a no-op)', () => { - const source = fs.readFileSync(new URL('./useSettingsState.ts', import.meta.url), 'utf8'); - - const hookCallStart = source.indexOf('useSettingsIpcSync({'); - assert.notEqual(hookCallStart, -1, 'expected to find the useSettingsIpcSync(...) call'); - const hookCallEnd = source.indexOf('});', hookCallStart); - const callSlice = source.slice(hookCallStart, hookCallEnd); - - assert.match( - callSlice, - /setAutoLaunchEnabled,/, - 'useSettingsIpcSync must receive the real setAutoLaunchEnabled state setter, ' + - 'or a broadcast from another window silently does nothing in this one', - ); -}); diff --git a/application/state/sftp/compressedUploadControl.test.ts b/application/state/sftp/compressedUploadControl.test.ts deleted file mode 100644 index 0563d8bb5..000000000 --- a/application/state/sftp/compressedUploadControl.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { resumeCompressedUploadSafely } from "./compressedUploadControl.ts"; - -test("live compressed resume failure stays paused instead of starting a second transfer", async () => { - const outcome = await resumeCompressedUploadSafely({ - transferId: "compressed-live", - reconnectRequired: false, - resume: async () => ({ success: false, reason: "Upload resume is unavailable" }), - }); - assert.deepEqual(outcome, { kind: "failed", reason: "Upload resume is unavailable" }); -}); - -test("restored compressed task may restart when its old worker no longer exists", async () => { - const outcome = await resumeCompressedUploadSafely({ - transferId: "compressed-restored", - reconnectRequired: true, - resume: async () => ({ success: false, reason: "Compression is not active" }), - }); - assert.deepEqual(outcome, { kind: "restart", reason: "Compression is not active" }); -}); - -test("successful compressed resume rejoins the existing job", async () => { - const outcome = await resumeCompressedUploadSafely({ - transferId: "compressed-live", - reconnectRequired: false, - resume: async () => ({ success: true }), - }); - assert.deepEqual(outcome, { kind: "resumed" }); -}); diff --git a/application/state/sftp/compressedUploadControl.ts b/application/state/sftp/compressedUploadControl.ts deleted file mode 100644 index 54d3c7664..000000000 --- a/application/state/sftp/compressedUploadControl.ts +++ /dev/null @@ -1,16 +0,0 @@ -export type CompressedUploadResumeOutcome = - | { kind: "resumed" } - | { kind: "restart"; reason?: string } - | { kind: "failed"; reason: string }; - -export async function resumeCompressedUploadSafely(params: { - transferId: string; - reconnectRequired: boolean; - resume?: (transferId: string) => Promise<{ success: boolean; reason?: string }>; -}): Promise { - const result = await (params.resume?.(params.transferId) - ?? { success: false, reason: "Resume unavailable" }); - if (result.success) return { kind: "resumed" }; - if (params.reconnectRequired) return { kind: "restart", reason: result.reason }; - return { kind: "failed", reason: result.reason ?? "Could not resume the compressed upload." }; -} diff --git a/application/state/sftp/sftpDialogActionStore.ts b/application/state/sftp/sftpDialogActionStore.ts index 9fdd63641..05e3a851c 100644 --- a/application/state/sftp/sftpDialogActionStore.ts +++ b/application/state/sftp/sftpDialogActionStore.ts @@ -1,11 +1,12 @@ /** * SFTP Dialog Action Store - * + * * Manages dialog action triggers for SFTP operations. * This store allows keyboard shortcuts to trigger dialogs in the appropriate pane. */ -import { useSyncExternalStore, useEffect } from "react"; +import { useEffect } from "react"; +import { createExternalStore } from "../createExternalStore"; import { sftpFocusStore, SftpFocusedSide } from "./sftpFocusStore"; type SftpDialogActionType = "rename" | "delete" | "newFolder" | "newFile" | null; @@ -18,65 +19,48 @@ interface SftpDialogAction { timestamp: number; // To distinguish different triggers of the same action } -type ActionListener = () => void; - -let dialogAction: SftpDialogAction | null = null; -const actionListeners = new Set(); - -const notifyListeners = () => { - actionListeners.forEach((listener) => listener()); -}; +const store = createExternalStore(null, { + isEqual: () => false, +}); export const sftpDialogActionStore = { - getSnapshot: (): SftpDialogAction | null => dialogAction, - - subscribe: (listener: ActionListener) => { - actionListeners.add(listener); - return () => actionListeners.delete(listener); - }, + getSnapshot: store.getSnapshot, + subscribe: store.subscribe, /** * Trigger a dialog action */ trigger: (type: SftpDialogActionType, targetScopeId: string, targetFiles?: string[]) => { if (!type) { - dialogAction = null; + store.setSnapshot(null); } else { - dialogAction = { + store.setSnapshot({ type, targetSide: sftpFocusStore.getFocusedSide(), targetScopeId, targetFiles, timestamp: Date.now(), - }; + }); } - notifyListeners(); }, /** * Clear the current action (called after a pane handles it) */ clear: () => { - dialogAction = null; - notifyListeners(); + store.setSnapshot(null); }, /** * Get the current action */ - get: (): SftpDialogAction | null => dialogAction, + get: store.getSnapshot, }; /** * React hook to subscribe to dialog action changes */ -export const useSftpDialogAction = (): SftpDialogAction | null => { - return useSyncExternalStore( - sftpDialogActionStore.subscribe, - sftpDialogActionStore.getSnapshot, - sftpDialogActionStore.getSnapshot - ); -}; +export const useSftpDialogAction = (): SftpDialogAction | null => store.useStore(); /** * React hook for a pane to respond to dialog actions diff --git a/application/state/sftp/sftpFocusStore.ts b/application/state/sftp/sftpFocusStore.ts index 69f9bc50c..a11d606d6 100644 --- a/application/state/sftp/sftpFocusStore.ts +++ b/application/state/sftp/sftpFocusStore.ts @@ -1,54 +1,24 @@ /** * SFTP Focused Pane Store - * + * * Tracks which SFTP pane (left or right) is currently focused. * This is used to determine which pane should receive keyboard shortcut actions. */ -import { useSyncExternalStore } from "react"; +import { createExternalStore } from "../createExternalStore"; export type SftpFocusedSide = "left" | "right"; -type FocusListener = () => void; - -let focusedSide: SftpFocusedSide = "left"; -const focusListeners = new Set(); - -const notifyListeners = () => { - focusListeners.forEach((listener) => listener()); -}; +const store = createExternalStore("left"); export const sftpFocusStore = { - getSnapshot: (): SftpFocusedSide => focusedSide, - - subscribe: (listener: FocusListener) => { - focusListeners.add(listener); - return () => focusListeners.delete(listener); - }, - - /** - * Set the focused side - */ - setFocusedSide: (side: SftpFocusedSide) => { - if (focusedSide !== side) { - focusedSide = side; - notifyListeners(); - } - }, - - /** - * Get the current focused side - */ - getFocusedSide: (): SftpFocusedSide => focusedSide, + getSnapshot: store.getSnapshot, + subscribe: store.subscribe, + setFocusedSide: store.setSnapshot, + getFocusedSide: store.getSnapshot, }; /** * React hook to subscribe to focused side changes */ -export const useSftpFocusedSide = (): SftpFocusedSide => { - return useSyncExternalStore( - sftpFocusStore.subscribe, - sftpFocusStore.getSnapshot, - sftpFocusStore.getSnapshot - ); -}; +export const useSftpFocusedSide = (): SftpFocusedSide => store.useStore(); diff --git a/application/state/sftp/sftpHostViewModeStore.ts b/application/state/sftp/sftpHostViewModeStore.ts index 2d1e8cbcd..ad30c8374 100644 --- a/application/state/sftp/sftpHostViewModeStore.ts +++ b/application/state/sftp/sftpHostViewModeStore.ts @@ -1,70 +1,58 @@ -import { useCallback, useSyncExternalStore } from "react"; +import { useCallback } from "react"; import { localStorageAdapter } from "../../../infrastructure/persistence/localStorageAdapter"; import { STORAGE_KEY_SFTP_HOST_VIEW_MODES } from "../../../infrastructure/config/storageKeys"; +import { createExternalStore } from "../createExternalStore"; -// ── Shared external store for per-host SFTP view mode preferences ── +// Shared external store for per-host SFTP view mode preferences type ViewMode = 'list' | 'tree'; -type Listener = () => void; -const listeners = new Set(); - -let snapshot: Record = - localStorageAdapter.read>(STORAGE_KEY_SFTP_HOST_VIEW_MODES) ?? {}; - -function subscribe(listener: Listener) { - listeners.add(listener); - return () => { listeners.delete(listener); }; -} - -function getSnapshot() { - return snapshot; -} +const store = createExternalStore>( + localStorageAdapter.read>(STORAGE_KEY_SFTP_HOST_VIEW_MODES) ?? {}, + { isEqual: () => false }, +); function persist(next: Record) { - snapshot = next; - localStorageAdapter.write(STORAGE_KEY_SFTP_HOST_VIEW_MODES, snapshot); - for (const l of listeners) l(); + localStorageAdapter.write(STORAGE_KEY_SFTP_HOST_VIEW_MODES, next); + store.setSnapshot(next); } // Sync across windows/tabs via storage events if (typeof window !== 'undefined') { - window.addEventListener('storage', (e) => { - if (e.key !== STORAGE_KEY_SFTP_HOST_VIEW_MODES) return; - try { - snapshot = e.newValue - ? (JSON.parse(e.newValue) as Record) - : {}; - } catch { - snapshot = {}; - } - for (const l of listeners) l(); - }); + window.addEventListener('storage', (e) => { + if (e.key !== STORAGE_KEY_SFTP_HOST_VIEW_MODES) return; + try { + store.setSnapshot( + e.newValue ? (JSON.parse(e.newValue) as Record) : {}, + ); + } catch { + store.setSnapshot({}); + } + }); } /** Get the saved view mode for a specific host, or null if none saved. */ export function getHostViewMode(hostId: string): ViewMode | null { - return snapshot[hostId] ?? null; + return store.getSnapshot()[hostId] ?? null; } /** Save the view mode preference for a specific host. */ export function setHostViewMode(hostId: string, mode: ViewMode): void { - if (snapshot[hostId] === mode) return; - persist({ ...snapshot, [hostId]: mode }); + const current = store.getSnapshot(); + if (current[hostId] === mode) return; + persist({ ...current, [hostId]: mode }); } -// ── Hook ── - export function useSftpHostViewMode(hostId: string | undefined) { - const store = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); + const snapshot = store.useStore(); - const mode: ViewMode | null = hostId ? (store[hostId] ?? null) : null; + const mode: ViewMode | null = hostId ? (snapshot[hostId] ?? null) : null; - const setMode = useCallback((newMode: ViewMode) => { - if (hostId) { - setHostViewMode(hostId, newMode); - } - }, [hostId]); + const setMode = useCallback((newMode: ViewMode) => { + if (hostId) { + setHostViewMode(hostId, newMode); + } + }, [hostId]); - return { hostViewMode: mode, setHostViewMode: setMode }; + return { hostViewMode: mode, setHostViewMode: setMode }; } diff --git a/application/state/sftp/transferDirectoryOps.latchFreeze.test.ts b/application/state/sftp/transferDirectoryOps.latchFreeze.test.ts deleted file mode 100644 index 096f979b5..000000000 --- a/application/state/sftp/transferDirectoryOps.latchFreeze.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -test("directory parent progress freezes while pausing without re-pausing child streams", () => { - const source = readFileSync(new URL("./transferDirectoryOps.ts", import.meta.url), "utf8"); - assert.match(source, /const parentFrozen = !!parentRow/); - assert.match(source, /parentRow\.status === "paused"/); - assert.match(source, /parentRow\.status === "pausing"/); - assert.match(source, /\|\| isPauseLatched\(rootTaskId\)/); - assert.match(source, /if \(parentFrozen\) \{\s*return \{ \.\.\.t, speed: 0 \};/); - assert.doesNotMatch(source, /const pauseRequested = .*status === "paused"/); -}); - -test("directory pauseWatch undoes pause when control epoch is superseded", () => { - const source = readFileSync(new URL("./transferDirectoryOps.ts", import.meta.url), "utf8"); - assert.match(source, /epochAtAttempt/); - assert.match(source, /isTransferControlEpochCurrent\(rootTaskId, epochAtAttempt\)/); - assert.match(source, /resumeTransfer\?\.\(task\.id\)/); -}); - -test("store soft-fail demotes and held rejoin uses bridge lifecycleEpoch (source contract)", () => { - const source = readFileSync(new URL("../sftpTransferCenterStore.ts", import.meta.url), "utf8"); - // Soft-fail must demote before silent return - assert.match(source, /softFailedNeedsHard|Transfer session is no longer active/); - assert.match(source, /controller = undefined/); - // Held soft-rejoin must not stamp control-plane epoch onto task.lifecycleEpoch - assert.doesNotMatch(source, /lifecycleEpoch: heldResumeEpoch/); - assert.match(source, /Prefer bridge lifecycleEpoch|bridgeEpoch/); -}); - -test("directory childTask clears inherited lifecycleEpoch before stream arm", () => { - const source = readFileSync(new URL("./transferDirectoryOps.ts", import.meta.url), "utf8"); - assert.match(source, /lifecycleEpoch: undefined/); - assert.match(source, /Never\s+inherit the parent's soft-resume epoch|New\/restarted child streams arm at bridge lifecycleEpoch 0/i); -}); - -test("softResume does not stamp parent resume epoch onto non-resumed siblings", () => { - const source = readFileSync(new URL("./globalSftpTransferControl.ts", import.meta.url), "utf8"); - assert.match(source, /Non-resumed siblings under the folder/); - assert.match(source, /lifecycleEpoch: undefined/); - assert.match(source, /bridgeEpochById/); -}); diff --git a/application/state/sftp/useSftpDirectoryListing.ts b/application/state/sftp/useSftpDirectoryListing.ts index 87f46f9e7..65ed1f639 100644 --- a/application/state/sftp/useSftpDirectoryListing.ts +++ b/application/state/sftp/useSftpDirectoryListing.ts @@ -1,19 +1,15 @@ import { useCallback } from "react"; import { netcattyBridge } from "../../../infrastructure/services/netcattyBridge"; import type { SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models"; -import { buildMockLocalFiles } from "./mockLocalFiles"; import { formatFileSize, formatDate } from "./utils"; export const useSftpDirectoryListing = () => { - const getMockLocalFiles = useCallback((path: string): SftpFileEntry[] => { - return buildMockLocalFiles(path); - }, []); - const listLocalFiles = useCallback( async (path: string): Promise => { const rawFiles = await netcattyBridge.get()?.listLocalDir?.(path); if (!rawFiles) { - return getMockLocalFiles(path); + const { buildMockLocalFiles } = await import("./mockLocalFiles"); + return buildMockLocalFiles(path); } return rawFiles.map((f) => { @@ -32,7 +28,7 @@ export const useSftpDirectoryListing = () => { }; }); }, - [getMockLocalFiles], + [], ); const listRemoteFiles = useCallback( diff --git a/application/state/sftpTransferCenterStore.ts b/application/state/sftpTransferCenterStore.ts index 8e4d69674..632872730 100644 --- a/application/state/sftpTransferCenterStore.ts +++ b/application/state/sftpTransferCenterStore.ts @@ -2688,14 +2688,6 @@ const browserPersistence: StorePersistence | undefined = typeof globalThis.local export const sftpTransferCenterStore = createSftpTransferCenterStore(browserPersistence); -export function useSftpTransferCenter(): SftpTransferCenterSnapshot { - return useSyncExternalStore( - sftpTransferCenterStore.subscribe, - sftpTransferCenterStore.getSnapshot, - sftpTransferCenterStore.getSnapshot, - ); -} - /** Badge only — stable when counts are unchanged so TopTabs does not re-render every progress byte. */ export function useSftpTransferCenterBadge(): { count: number; hasAttention: boolean } { return useSyncExternalStore( diff --git a/application/state/shellHistoryPersistence.test.ts b/application/state/shellHistoryPersistence.test.ts index e554b1563..a1d3d15d7 100644 --- a/application/state/shellHistoryPersistence.test.ts +++ b/application/state/shellHistoryPersistence.test.ts @@ -1,7 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { buildDockerLogsCommand } from '../../domain/systemManager/dockerShell.ts'; +import { buildContainerLogsCommand } from '../../domain/systemManager/containerRuntime.ts'; import { loadSanitizedShellHistory } from './shellHistoryPersistence.ts'; import type { ShellHistoryEntry } from '../../domain/models.ts'; @@ -16,7 +16,7 @@ const entry = (id: string, command: string): ShellHistoryEntry => ({ test('loadSanitizedShellHistory removes persisted managed startup commands and writes back cleaned history', () => { const stored = [ - entry('managed', buildDockerLogsCommand('587abcdef123')), + entry('managed', buildContainerLogsCommand('docker', '587abcdef123')), entry('user', 'docker ps -a'), ]; let written: ShellHistoryEntry[] | null = null; diff --git a/application/state/startupLandingSettings.test.ts b/application/state/startupLandingSettings.test.ts deleted file mode 100644 index 69a4bd091..000000000 --- a/application/state/startupLandingSettings.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("startup landing setting participates in cross-window settings sync", () => { - const storageSyncSource = readFileSync(new URL("./settingsStorageSync.ts", import.meta.url), "utf8"); - const ipcSyncSource = readFileSync(new URL("./settingsIpcSync.ts", import.meta.url), "utf8"); - - assert.match(storageSyncSource, /STORAGE_KEY_STARTUP_LANDING/); - assert.match(storageSyncSource, /setStartupLandingState/); - assert.match(storageSyncSource, /e\.key === STORAGE_KEY_STARTUP_LANDING/); - - assert.match(ipcSyncSource, /STORAGE_KEY_STARTUP_LANDING/); - assert.match(ipcSyncSource, /setStartupLandingState/); - assert.match(ipcSyncSource, /key === STORAGE_KEY_STARTUP_LANDING/); -}); - -test("startup landing does not bump the cloud sync settings version", () => { - const settingsSource = readFileSync(new URL("./useSettingsState.ts", import.meta.url), "utf8"); - const settingsVersionIndex = settingsSource.indexOf("settingsVersion: useMemo"); - const settingsVersionSource = settingsSource.slice(settingsVersionIndex); - - assert.notEqual(settingsVersionIndex, -1); - assert.doesNotMatch(settingsVersionSource, /startupLanding/); -}); - -test("main window opens local terminal on cold start when preferred", () => { - const sideEffectsSource = readFileSync(new URL("../app/AppSideEffects.tsx", import.meta.url), "utf8"); - - assert.match(sideEffectsSource, /startupLocalTerminalAttemptedRef/); - assert.match(sideEffectsSource, /shouldOpenLocalTerminalOnStartup/); - assert.match(sideEffectsSource, /STORAGE_KEY_STARTUP_LANDING/); - assert.match(sideEffectsSource, /handleCreateLocalTerminal\(/); - assert.match(sideEffectsSource, /onColdStartIntentsSettled/); - assert.match(sideEffectsSource, /ensureDiscoveredShells/); - assert.match(sideEffectsSource, /hasQueuedStartupIntent:\s*startupLaunchIntentReceivedRef\.current/); - - const latchAt = sideEffectsSource.indexOf("if (startupLocalTerminalAttemptedRef.current) return;"); - const setLatchAt = sideEffectsSource.indexOf( - "startupLocalTerminalAttemptedRef.current = true;", - latchAt, - ); - const createAt = sideEffectsSource.indexOf("handleCreateLocalTerminal(", setLatchAt); - assert.notEqual(latchAt, -1); - assert.notEqual(setLatchAt, -1); - assert.notEqual(createAt, -1); - assert.ok(setLatchAt < createAt, "StrictMode latch must be set before creating the terminal"); -}); - -test("settings system tab exposes startup landing control", () => { - const tabSource = readFileSync( - new URL("../../components/settings/tabs/SettingsSystemTab.tsx", import.meta.url), - "utf8", - ); - assert.match(tabSource, /system-startup-landing/); - assert.match(tabSource, /settings\.sessionRestore\.startupLanding/); - assert.match(tabSource, /local-terminal/); -}); diff --git a/application/state/terminalLayoutSuppressStore.ts b/application/state/terminalLayoutSuppressStore.ts index f26dc4924..5a01a3d2b 100644 --- a/application/state/terminalLayoutSuppressStore.ts +++ b/application/state/terminalLayoutSuppressStore.ts @@ -1,42 +1,24 @@ import { useSyncExternalStore } from 'react'; - -type Listener = () => void; +import { createListenerRegistry } from './createExternalStore'; let suppressDepth = 0; -const listeners = new Set(); -let notifyRafId: number | null = null; - -const scheduleFrame = - typeof requestAnimationFrame === 'function' - ? requestAnimationFrame - : (cb: () => void) => setTimeout(cb, 0) as unknown as number; - -function scheduleEmit() { - if (notifyRafId !== null) return; - notifyRafId = scheduleFrame(() => { - notifyRafId = null; - listeners.forEach((listener) => listener()); - }); -} +const registry = createListenerRegistry(); export const terminalLayoutSuppressStore = { getActive: () => suppressDepth > 0, - subscribe: (listener: Listener) => { - listeners.add(listener); - return () => listeners.delete(listener); - }, + subscribe: registry.subscribe, begin: () => { suppressDepth += 1; - scheduleEmit(); + registry.scheduleNotify(); }, end: () => { const wasActive = suppressDepth > 0; suppressDepth = Math.max(0, suppressDepth - 1); if (wasActive) { - scheduleEmit(); + registry.scheduleNotify(); } }, }; diff --git a/application/state/useAutoSync.test.ts b/application/state/useAutoSync.test.ts deleted file mode 100644 index 401befb67..000000000 --- a/application/state/useAutoSync.test.ts +++ /dev/null @@ -1,296 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("auto-sync establishes the initial data baseline before debouncing edits", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const baselineCommentIndex = source.indexOf("Establish the initial baseline immediately"); - const baselineHelperIndex = source.indexOf("const establishInitialBaseline = () =>", baselineCommentIndex); - const initializedAssignmentIndex = source.indexOf("isInitializedRef.current = true;", baselineHelperIndex); - const hashReadIndex = source.indexOf("const currentHash = await getDataHash();", baselineHelperIndex); - const initializationGuardIndex = source.indexOf("if (!isInitializedRef.current)", baselineCommentIndex); - const baselineCallIndex = source.indexOf("establishInitialBaseline();", initializationGuardIndex); - const debounceCommentIndex = source.indexOf("Debounce first, then build the expensive full-data hash", initializationGuardIndex); - const debounceTimerIndex = source.indexOf("syncTimeoutRef.current = setTimeout", debounceCommentIndex); - - assert.notEqual(baselineCommentIndex, -1); - assert.notEqual(baselineHelperIndex, -1); - assert.notEqual(initializationGuardIndex, -1); - assert.notEqual(initializedAssignmentIndex, -1); - assert.notEqual(hashReadIndex, -1); - assert.notEqual(baselineCallIndex, -1); - assert.notEqual(debounceCommentIndex, -1); - assert.notEqual(debounceTimerIndex, -1); - assert.ok( - initializedAssignmentIndex < hashReadIndex, - "initialization must be marked synchronously before reading the baseline hash", - ); - assert.ok( - baselineCallIndex < debounceTimerIndex, - "the first baseline hash must be captured before scheduling the debounced auto-sync timer", - ); -}); - -test("paused convergent sync captures a baseline before returning", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const effectIndex = source.indexOf("// Debounced auto-sync when data changes"); - const pausedGuardIndex = source.indexOf("if (convergentSyncPaused)", effectIndex); - const initializationGuardIndex = source.indexOf("if (!isInitializedRef.current)", pausedGuardIndex); - const baselineCallIndex = source.indexOf("establishInitialBaseline();", initializationGuardIndex); - const pausedReturnIndex = source.indexOf("return () =>", baselineCallIndex); - - assert.notEqual(pausedGuardIndex, -1); - assert.notEqual(initializationGuardIndex, -1); - assert.notEqual(baselineCallIndex, -1); - assert.notEqual(pausedReturnIndex, -1); - assert.ok( - pausedGuardIndex < initializationGuardIndex - && initializationGuardIndex < baselineCallIndex - && baselineCallIndex < pausedReturnIndex, - "paused mode must preserve the pre-edit baseline before suppressing network sync", - ); -}); - -test("an unchanged remote check cannot absorb an existing paused-edit baseline", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const baselineSnapshotIndex = source.indexOf("const hadInitialBaseline = isInitializedRef.current"); - const remoteChangeIndex = source.indexOf("inspectedRemoteChange = true", baselineSnapshotIndex); - const guardedUpdateIndex = source.indexOf( - "if (markCurrentDataSynced && (!hadInitialBaseline || inspectedRemoteChange))", - remoteChangeIndex, - ); - - assert.notEqual(baselineSnapshotIndex, -1); - assert.notEqual(remoteChangeIndex, -1); - assert.notEqual(guardedUpdateIndex, -1); - assert.ok( - baselineSnapshotIndex < remoteChangeIndex && remoteChangeIndex < guardedUpdateIndex, - "remote inspection must preserve an existing baseline unless it reconciled changed cloud data", - ); -}); - -test("enabled convergent remote checks use the CRDT runtime before legacy inspection", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const checkIndex = source.indexOf("const checkRemoteVersion = useCallback"); - const convergentGuardIndex = source.indexOf( - "if (currentConvergentConfig.initialized && currentConvergentConfig.enabled)", - checkIndex, - ); - const convergentSyncIndex = source.indexOf( - "syncNowRef.current({ notifyOnFailure, allowEmptyConvergentSync })", - convergentGuardIndex, - ); - const legacyInspectionIndex = source.indexOf( - "manager.inspectProviderRemote(connectedProvider)", - convergentSyncIndex, - ); - - assert.notEqual(checkIndex, -1); - assert.notEqual(convergentGuardIndex, -1); - assert.notEqual(convergentSyncIndex, -1); - assert.notEqual(legacyInspectionIndex, -1); - assert.ok( - convergentGuardIndex < convergentSyncIndex && convergentSyncIndex < legacyInspectionIndex, - "v2 checks must return through the CRDT runtime before the legacy snapshot inspector", - ); -}); - -test("enabled convergent startup checks preview empty-vault recovery before syncing", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const convergentGuardIndex = source.indexOf( - "if (currentConvergentConfig.initialized && currentConvergentConfig.enabled)", - ); - const previewIndex = source.indexOf("manager.previewConvergentRecovery()", convergentGuardIndex); - const recoveryPromptIndex = source.indexOf( - "requestEmptyVaultRecovery(recoveryPayload)", - previewIndex, - ); - const cloudWinsIndex = source.indexOf( - "conflictActionOverride: 'download-remote'", - recoveryPromptIndex, - ); - const manualTriggerIndex = source.indexOf("trigger: 'manual'", recoveryPromptIndex); - const normalSyncIndex = source.indexOf( - "syncNowRef.current({ notifyOnFailure, allowEmptyConvergentSync })", - cloudWinsIndex, - ); - - assert.notEqual(convergentGuardIndex, -1); - assert.notEqual(previewIndex, -1); - assert.notEqual(recoveryPromptIndex, -1); - assert.notEqual(cloudWinsIndex, -1); - assert.notEqual(manualTriggerIndex, -1); - assert.notEqual(normalSyncIndex, -1); - assert.ok( - convergentGuardIndex < previewIndex - && previewIndex < recoveryPromptIndex - && recoveryPromptIndex < manualTriggerIndex - && manualTriggerIndex < cloudWinsIndex - && cloudWinsIndex < normalSyncIndex, - "v2 startup must offer recovery and use cloud-wins before the normal CRDT sync path", - ); -}); - -test("empty-vault recovery restore bypasses the auto-sync preference gate", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const recoveryPromptIndex = source.indexOf("requestEmptyVaultRecovery(recoveryPayload)"); - const restoreCallIndex = source.indexOf("syncNowRef.current({", recoveryPromptIndex); - const triggerIndex = source.indexOf("trigger: 'manual'", restoreCallIndex); - const conflictIndex = source.indexOf( - "conflictActionOverride: 'download-remote'", - restoreCallIndex, - ); - const callEndIndex = source.indexOf("});", conflictIndex); - - assert.notEqual(recoveryPromptIndex, -1); - assert.notEqual(restoreCallIndex, -1); - assert.notEqual(triggerIndex, -1); - assert.notEqual(conflictIndex, -1); - assert.ok( - restoreCallIndex < triggerIndex - && triggerIndex < conflictIndex - && conflictIndex < callEndIndex, - "recovery Restore must pass trigger:manual so disabled auto-sync cannot block it", - ); -}); - -test("empty v2 startup checks allow a validated empty sync to open the gate", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const convergentGuardIndex = source.indexOf( - "if (currentConvergentConfig.initialized && currentConvergentConfig.enabled)", - ); - const replicaIndex = source.indexOf("manager.loadConvergentReplica()", convergentGuardIndex); - const emptyDecisionIndex = source.indexOf("allowEmptyConvergentSync = (", replicaIndex); - const syncIndex = source.indexOf( - "syncNowRef.current({ notifyOnFailure, allowEmptyConvergentSync })", - emptyDecisionIndex, - ); - const guardIndex = source.indexOf( - "options?.allowEmptyConvergentSync !== true", - source.indexOf("const syncNow = useCallback"), - ); - - assert.notEqual(replicaIndex, -1); - assert.notEqual(emptyDecisionIndex, -1); - assert.notEqual(syncIndex, -1); - assert.notEqual(guardIndex, -1); - assert.ok(replicaIndex < emptyDecisionIndex && emptyDecisionIndex < syncIndex); -}); - -test("auto-sync skips only the exact remote-applied data hash", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const helperIndex = source.indexOf("const getSyncPayloadDataHash = (payload: SyncPayload): string"); - const skipRefIndex = source.indexOf("const skipNextSyncHashRef = useRef(null)"); - const assignmentIndex = source.indexOf("skipNextSyncHashRef.current = getSyncPayloadDataHash(remotePayload)"); - const debounceTimerIndex = source.indexOf("syncTimeoutRef.current = setTimeout", assignmentIndex); - const skipHashIndex = source.indexOf("const skipHash = skipNextSyncHashRef.current", debounceTimerIndex); - const decisionIndex = source.indexOf("resolveAutoSyncHashDecision({", skipHashIndex); - const appliedSkipIndex = source.indexOf("appliedSkipHash: skipHash", decisionIndex); - const syncingGuardIndex = source.indexOf("if (sync.isSyncing || isSyncRunningRef.current)", decisionIndex); - const restoreGuardIndex = source.indexOf("if (isRestoreInProgress())", decisionIndex); - const interruptedGuardIndex = source.indexOf("if (readInterruptedVaultApply())", decisionIndex); - const syncNowIndex = source.indexOf("const didSync = await syncNow();", interruptedGuardIndex); - const didSyncGuardIndex = source.indexOf("if (didSync && skipHash !== null", syncNowIndex); - const clearAfterSyncIndex = source.indexOf("skipNextSyncHashRef.current = null;", didSyncGuardIndex); - const booleanSkipIndex = source.indexOf("skipNextSyncRef"); - - assert.notEqual(helperIndex, -1); - assert.notEqual(skipRefIndex, -1); - assert.notEqual(assignmentIndex, -1); - assert.notEqual(debounceTimerIndex, -1); - assert.notEqual(skipHashIndex, -1); - assert.notEqual(decisionIndex, -1); - assert.notEqual(appliedSkipIndex, -1); - assert.notEqual(syncingGuardIndex, -1); - assert.notEqual(restoreGuardIndex, -1); - assert.notEqual(interruptedGuardIndex, -1); - assert.notEqual(syncNowIndex, -1); - assert.notEqual(didSyncGuardIndex, -1); - assert.notEqual(clearAfterSyncIndex, -1); - assert.equal(booleanSkipIndex, -1); - assert.ok( - skipHashIndex < decisionIndex, - "remote-apply skip must pass through the hash decision helper before suppressing a sync", - ); - assert.ok( - interruptedGuardIndex < syncNowIndex && syncNowIndex < clearAfterSyncIndex, - "remote-apply skip hash must survive temporary sync blockers and clear only after a successful sync", - ); -}); - -test("auto syncNow and debounce re-check manager autoSyncEnabled before pushing", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const helperIndex = source.indexOf("function isPersistedAutoSyncEnabled"); - const syncNowIndex = source.indexOf("const syncNow = useCallback"); - const autoGateIndex = source.indexOf( - "if (trigger === 'auto' && !isPersistedAutoSyncEnabled(manager.getState().autoSyncEnabled))", - syncNowIndex, - ); - const debounceIndex = source.indexOf("// Debounced auto-sync when data changes"); - const fireTimeGateIndex = source.indexOf( - "if (!isPersistedAutoSyncEnabled(manager.getState().autoSyncEnabled))", - debounceIndex, - ); - const clearTimerIndex = source.indexOf( - "if (syncTimeoutRef.current) {\n clearTimeout(syncTimeoutRef.current);\n syncTimeoutRef.current = null;\n }\n return;", - debounceIndex, - ); - - assert.notEqual(helperIndex, -1); - assert.notEqual(syncNowIndex, -1); - assert.notEqual(autoGateIndex, -1); - assert.notEqual(fireTimeGateIndex, -1); - assert.notEqual(clearTimerIndex, -1); - assert.ok( - helperIndex < syncNowIndex - && syncNowIndex < autoGateIndex - && debounceIndex < fireTimeGateIndex - && debounceIndex < clearTimerIndex, - "auto-sync off must gate both syncNow(auto) and the debounced timer path", - ); -}); - -test("startup local-wins and merge round-trips refuse device-bound credential placeholders", () => { - const source = readFileSync(new URL("./useAutoSync.ts", import.meta.url), "utf8"); - const uploadLocalIndex = source.indexOf("if (conflictAction === 'upload-local')"); - const uploadGuardIndex = source.indexOf( - "findSyncPayloadEncryptedCredentialPaths(localPayload)", - uploadLocalIndex, - ); - const uploadPushIndex = source.indexOf("manager.syncAllProviders(localPayload)", uploadGuardIndex); - const mergeRoundTripBlockIndex = source.indexOf( - "stripSyncPayloadEncryptedCredentials(mergeResult.payload)", - ); - const mergeLocalHealIndex = source.indexOf( - "healPoisonedSecretsForMerge(localPayload, remoteRaw, base)", - ); - const mergeRemoteHealIndex = source.indexOf( - "healPoisonedSecretsForMerge(remoteRaw, localPayload, base)", - ); - const mergePushIndex = source.indexOf( - "manager.syncAllProviders(portableMerge)", - mergeRoundTripBlockIndex, - ); - const stripRemoteIndex = source.indexOf( - "stripSyncPayloadEncryptedCredentials(remoteRaw)", - ); - - assert.notEqual(uploadLocalIndex, -1); - assert.notEqual(uploadGuardIndex, -1); - assert.notEqual(uploadPushIndex, -1); - assert.notEqual(mergeLocalHealIndex, -1); - assert.notEqual(mergeRemoteHealIndex, -1); - assert.notEqual(mergeRoundTripBlockIndex, -1); - assert.notEqual(mergePushIndex, -1); - assert.notEqual(stripRemoteIndex, -1); - assert.ok( - uploadGuardIndex < uploadPushIndex, - "startup local-wins must guard placeholders before syncAllProviders", - ); - assert.ok( - mergeLocalHealIndex < mergeRoundTripBlockIndex - && mergeRemoteHealIndex < mergeRoundTripBlockIndex - && mergeRoundTripBlockIndex < mergePushIndex, - "startup merge must heal local+remote secrets, then strip, then upload", - ); -}); diff --git a/application/state/useManualTerminalChromeSurfaceInjection.test.ts b/application/state/useManualTerminalChromeSurfaceInjection.test.ts deleted file mode 100644 index 6e201e965..000000000 --- a/application/state/useManualTerminalChromeSurfaceInjection.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const appSource = [ - readFileSync(new URL('../app/AppSideEffects.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('../app/hosts/TerminalHost.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('../app/hosts/ChromeHost.tsx', import.meta.url), 'utf8'), -].join('\n'); -const hookSource = readFileSync(new URL('./useManualTerminalChromeSurfaceInjection.ts', import.meta.url), 'utf8'); -const bridgeSource = readFileSync(new URL('../../components/terminalLayer/TerminalLayerTabBridge.tsx', import.meta.url), 'utf8'); -const varsSource = readFileSync(new URL('../../infrastructure/theme/terminalAppearanceVars.ts', import.meta.url), 'utf8'); - -test('manual mode injects chrome surfaces from focused session theme', () => { - assert.match(appSource, /includeChromeSurfaces: followAppTerminalTheme/); - assert.match(bridgeSource, /useManualTerminalChromeSurfaceInjection/); - assert.match(bridgeSource, /!s\.followAppTerminalTheme && isTerminalLayerVisible/); - assert.match(readFileSync(new URL('../app/AppHostTreeLayer.tsx', import.meta.url), 'utf8'), /useManualTerminalChromeSurfaceInjection/); - // App feeds the focused-session resolver to AppActiveTabChrome through the - // memoized shell chrome bag (AppShell spreads it onto the chrome component). - assert.match(appSource, /resolveSessionAppearance: resolveFocusedAppearance/); - assert.match(hookSource, /applyTopTabsChromeThemeVars\(theme\)/); - assert.match(hookSource, /injectTerminalLayerChromeSurfaceVars\(theme\)/); - assert.match(hookSource, /if \(wasEnabled\) \{[\s\S]*clearTerminalLayerChromeSurfaceVars\(\)/); - assert.doesNotMatch(hookSource, /clearTopTabsChromeThemeVars\(\)/); - assert.match(varsSource, /injectTerminalLayerChromeSurfaceVars/); - assert.match(varsSource, /clearTerminalLayerChromeSurfaceVars/); -}); diff --git a/application/state/usePluginTerminalSelection.ts b/application/state/usePluginTerminalSelection.ts index fcdd8a66f..7faa19534 100644 --- a/application/state/usePluginTerminalSelection.ts +++ b/application/state/usePluginTerminalSelection.ts @@ -1,6 +1,6 @@ import { useEffect, useRef } from 'react'; import type { Terminal } from '@xterm/xterm'; -import { getTerminalSelectionForClipboard } from '../../components/terminal/normalizeTerminalSelection'; +import { getTerminalSelectionForClipboard } from '../../domain/terminalSelection'; import { publishTerminalSelectionTarget, registerTerminalSelectionSource } from '../../infrastructure/plugins/terminalSelectionRegistry'; type SelectionState = { diff --git a/application/state/useSettingsStateSshDeepLink.test.ts b/application/state/useSettingsStateSshDeepLink.test.ts deleted file mode 100644 index 633e08095..000000000 --- a/application/state/useSettingsStateSshDeepLink.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("ssh deep link native startup sync cannot overwrite a later setting change", () => { - const source = readFileSync(new URL("./useSettingsState.ts", import.meta.url), "utf8"); - const getEnabledIndex = source.indexOf("bridge.getSshDeepLinkEnabled()"); - const requestIdCaptureIndex = source.lastIndexOf( - "const requestIdAtStart = sshDeepLinkSetRequestIdRef.current", - getEnabledIndex, - ); - const staleGuardIndex = source.indexOf( - "if (sshDeepLinkSetRequestIdRef.current !== requestIdAtStart) return;", - getEnabledIndex, - ); - - assert.notEqual(getEnabledIndex, -1); - assert.notEqual(requestIdCaptureIndex, -1); - assert.notEqual(staleGuardIndex, -1); - assert.ok(requestIdCaptureIndex < getEnabledIndex); - assert.ok(staleGuardIndex > getEnabledIndex); -}); - -test("incoming ssh deep link setting changes invalidate pending local responses", () => { - const source = readFileSync(new URL("./useSettingsState.ts", import.meta.url), "utf8"); - const setterIndex = source.indexOf("const applyIncomingSshDeepLinkEnabled = useCallback"); - const incrementIndex = source.indexOf("sshDeepLinkSetRequestIdRef.current += 1;", setterIndex); - const stateUpdateIndex = source.indexOf("setSshDeepLinkEnabledState((prev)", setterIndex); - - assert.notEqual(setterIndex, -1); - assert.notEqual(incrementIndex, -1); - assert.notEqual(stateUpdateIndex, -1); - assert.ok(incrementIndex < stateUpdateIndex); -}); diff --git a/application/state/useSftpBackend.legacyExternalEdit.test.ts b/application/state/useSftpBackend.legacyExternalEdit.test.ts deleted file mode 100644 index 96483e7fa..000000000 --- a/application/state/useSftpBackend.legacyExternalEdit.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("useSftpBackend no longer exposes the retired external-edit orchestration", () => { - const source = readFileSync(new URL("./useSftpBackend.ts", import.meta.url), "utf8"); - - assert.doesNotMatch(source, /downloadSftpToTempAndOpen/); - assert.doesNotMatch(source, /registerTempFile|startFileWatch|openWithApplication|downloadSftpToTemp/); -}); - -test("the active external-edit path remains owned by useSftpExternalOperations", () => { - const source = readFileSync( - new URL("./sftp/useSftpExternalOperations.ts", import.meta.url), - "utf8", - ); - - assert.match(source, /downloadToTempAndOpen/); - assert.match(source, /registerTempFile/); - assert.match(source, /startFileWatch/); -}); diff --git a/application/state/useThemeRuntime.accentStability.test.ts b/application/state/useThemeRuntime.accentStability.test.ts deleted file mode 100644 index fae0f8b4d..000000000 --- a/application/state/useThemeRuntime.accentStability.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const runtimeSource = readFileSync(new URL('./useThemeRuntime.ts', import.meta.url), 'utf8'); -const terminalHostSource = readFileSync( - new URL('../app/hosts/TerminalHost.tsx', import.meta.url), - 'utf8', -); - -test('published currentTerminalTheme resolves without live custom accent', () => { - // Base global appearance must use accentMode: 'theme' so HSL drag does not - // mint a new theme object into TerminalHost / AppShell domain bags. - assert.match( - runtimeSource, - /accentMode: 'theme',\s*\n\s*customAccent: '',/, - 'globalAppearance must ignore live custom accent', - ); - assert.match(runtimeSource, /accentedGlobalAppearance/); - assert.match( - runtimeSource, - /currentTerminalTheme: globalAppearance\.theme/, - 'published theme must come from the stable base appearance', - ); -}); - -test('TerminalHost injects accented appearance without bridging it', () => { - assert.match( - terminalHostSource, - /useTerminalAppearanceInjection\(accentedGlobalAppearance/, - 'CSS vars still track live accent during drag', - ); - const bridgeStart = terminalHostSource.indexOf('const themeBridgeActions = useMemo'); - assert.notEqual(bridgeStart, -1); - const bridge = terminalHostSource.slice(bridgeStart, bridgeStart + 900); - assert.match(bridge, /globalAppearance,/); - assert.doesNotMatch( - bridge, - /accentedGlobalAppearance/, - 'theme bridge must not republish on accented appearance identity churn', - ); -}); diff --git a/application/state/useVaultState.connectionLogTerminalData.test.ts b/application/state/useVaultState.connectionLogTerminalData.test.ts deleted file mode 100644 index 49411e763..000000000 --- a/application/state/useVaultState.connectionLogTerminalData.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -const source = readFileSync(new URL("./useVaultState.ts", import.meta.url), "utf8"); -const terminalLayerSource = readFileSync( - new URL("../../components/TerminalLayer.tsx", import.meta.url), - "utf8", -); - -test("connection log replay blobs persist through IndexedDB instead of the legacy localStorage blob", () => { - assert.match(source, /await migrateLegacyConnectionLogTerminalData\(/); - assert.match(source, /await writeTerminalDataMapDiff\(/); - assert.match(source, /STORAGE_KEY_CONNECTION_LOG_TERMINAL_DATA_REV/); - assert.match(source, /syncConnectionLogTerminalData !== false|syncConnectionLogTerminalData\)/); - assert.doesNotMatch(source, /writeTerminalDataMapWithQuotaRetry/); - assert.doesNotMatch( - source, - /localStorageAdapter\.write\(\s*STORAGE_KEY_CONNECTION_LOG_TERMINAL_DATA\s*,/, - ); -}); - -test("close-path connection log updates await the indexedDB persist task", () => { - assert.match( - source, - /const updateConnectionLog = useCallback\([\s\S]*?return commitConnectionLogs\(/, - ); - assert.match(source, /rebaseQueuedConnectionLogs\(\s*memory,\s*removedIds,\s*changedIds,/); - assert.match( - source, - /if \(!options\?\.pruneMainBlob\) \{[\s\S]*?rebaseQueuedConnectionLogs\(/, - ); - assert.match(source, /retainNewestUnsavedReplays\(fallbackLogs, keep\)/); - assert.match(source, /if \(!map\) return;/); - assert.match( - source, - /if \(key === STORAGE_KEY_CONNECTION_LOGS\) \{\s*\/\/ This window already updated connectionLogsRef before setItem\.[\s\S]*?return;\s*\}/, - ); - assert.match( - terminalLayerSource, - /const handleTerminalDataCapture = useCallback\(\(sessionId: string, data: string\) => \{\s*return onTerminalDataCapture\?\.\(sessionId, data\);/, - ); -}); - -test("boot re-reads connection logs after indexedDB load and falls back to the main blob", () => { - const revAt = source.indexOf("let revSeen = readTerminalDataRev()"); - const bootAt = source.indexOf("const loaded = await migrateLegacyConnectionLogTerminalData"); - assert.notEqual(revAt, -1); - assert.ok(revAt < bootAt); - const bootSlice = source.slice(bootAt, bootAt + 2800); - assert.match(bootSlice, /revNow !== revSeen[\s\S]*?await loadConnectionLogTerminalData\(\)/); - assert.match( - bootSlice, - /localStorageAdapter\.read\(\s*STORAGE_KEY_CONNECTION_LOGS,\s*\)[\s\S]*?pruneTerminalDataMapForStorage\(connectionLogsForBoot/, - ); - assert.match( - source, - /!sidePersisted && unsavedTerminalDataPending && mainPersisted\) \{\s*\/\/[\s\S]*?localStorageAdapter\.read\(\s*STORAGE_KEY_CONNECTION_LOGS\s*\)[\s\S]*?mergeTerminalDataIntoLogs\(freshLogs, buildTerminalDataMapFromLogs\(logs\)\)/, - ); -}); diff --git a/application/state/useVaultState.snippetsDelete.test.ts b/application/state/useVaultState.snippetsDelete.test.ts deleted file mode 100644 index b2824d149..000000000 --- a/application/state/useVaultState.snippetsDelete.test.ts +++ /dev/null @@ -1,265 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -const source = readFileSync(new URL("./useVaultState.ts", import.meta.url), "utf8"); - -test("deleteSelectedSnippets merges into persisted vault under the shared lock", () => { - assert.match(source, /const deleteSelectedSnippets = useCallback\(async/); - assert.match( - source, - /deleteSelectedSnippets[\s\S]*withVaultImportLock\("vault"/, - ); - assert.match( - source, - /deleteSelectedSnippetsFromVault\(\s*latestSnippets\s*,\s*latestHosts\s*,\s*selectedSnippetIds,?\s*\)/, - ); - assert.match( - source, - /deleteSelectedSnippets[\s\S]*commitPluginImporterTransaction\(localStorageAdapter, \[[\s\S]*STORAGE_KEY_HOSTS[\s\S]*STORAGE_KEY_SNIPPETS/, - ); - // Persistence rejection must be caught: callers void the promise after the - // confirm dialog closes, so an uncaught throw would leave no retry feedback. - assert.match( - source, - /deleteSelectedSnippets[\s\S]*try \{\s*commitPluginImporterTransaction[\s\S]*catch \{[\s\S]*notify\.error\([\s\S]*Snippets could not be deleted/, - ); - // Must not rebuild hosts from a per-window in-memory snapshot (popup race). - assert.doesNotMatch( - source, - /deleteSelectedSnippetsFromVault\(\s*snippetsRef\.current\s*,\s*hostsRef\.current/, - ); - // Paired writes must not publish in-memory state if only one key lands. - assert.doesNotMatch( - source, - /deleteSelectedSnippets[\s\S]*localStorageAdapter\.write\(STORAGE_KEY_HOSTS, encryptedHosts\)[\s\S]*localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS/, - ); -}); - -test("updateHosts prunes stale snippet bindings under the vault lock", () => { - // Cross-window bulk-delete can land while a host writer is queued with a - // pre-delete encrypted blob. Re-check the live snippet catalog under the lock - // before persisting so login/connect bindings are not restored. - assert.match( - source, - /commitEncryptedHostsUnderVaultLock[\s\S]*pruneHostsStaleSnippetBindings\(hostsToPersist, latestSnippets\)/, - ); - assert.match( - source, - /const writePromise = encryptPromise\.then\(async \(enc\) => \{[\s\S]*return commitEncryptedHostsUnderVaultLock\(ver, cleaned, enc\)/, - ); -}); - -test("importData replaces snippets instead of additive-rebasing", () => { - // Sync restore / backup import must match the selected snapshot. Additive - // rebase would keep concurrent disk-only ids and report a successful restore - // that still contains snippets absent from the imported payload. - assert.match( - source, - /updateSnippets\(payload\.snippets,\s*\{\s*replace:\s*true\s*\}\)/, - ); -}); - -test("updateSnippets disk writes take the shared vault lock", () => { - // Unlocked snippet saves can interleave with bulk-delete's journaled commit - // and discard concurrent edits. Ordinary writers must queue on the same lock - // and be visible to waitForPendingVaultWrites. - assert.match( - source, - /const updateSnippets = useCallback\(\([\s\S]*withVaultImportLock\("vault", async \(\) => \{[\s\S]*localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS, rebased\)/, - ); - assert.match( - source, - /snippetsWritePendingRef\.current = writePromise/, - ); - assert.match( - source, - /waitForPendingVaultWrites[\s\S]*snippetsWritePendingRef\.current/, - ); - assert.doesNotMatch( - source, - /const updateSnippets = useCallback\(\([\s\S]*?\) => \{[\s\S]*setSnippets\(cleaned\);\s*localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS, cleaned\);\s*\}, \[\]\);/, - ); -}); - -test("updateSnippets rebases onto the latest persisted snapshot under the lock", () => { - // Web Locks serialize writers but do not merge snapshots. A popup bulk-delete - // that lands while a main-window save is queued must not be resurrected. - assert.match( - source, - /rebaseSnippetVaultWrite\(\{\s*base,\s*ours: cleaned,\s*theirs:/, - ); - assert.match( - source, - /snippetsWriteOwnerRef\.current !== ver/, - ); -}); - -test("updateSnippets functional updates derive from the latest in-memory snapshot", () => { - // Group deletion can wait for managed-source cleanup. A script created while - // it waits must still be present when the deletion callback removes the old - // group path, so updater callbacks must not derive from the initiating render. - assert.match( - source, - /data: Snippet\[\] \| \(\(current: Snippet\[\]\) => Snippet\[\]\)/, - ); - assert.match( - source, - /const updater = typeof data === "function" \? data : null;[\s\S]*const current = snippetsRef\.current;[\s\S]*typeof data === "function" \? data\(current\) : data/, - ); - assert.match( - source, - /updater\(rebaseSnippetVaultWrite\(\{\s*base,\s*ours: current,\s*theirs: latestPersisted,\s*\}\)\)/, - ); -}); - -test("clearVaultData replaces snippets without additive rebase", () => { - // Clear All Local Data must not preserve concurrent disk-only snippet adds - // that rebaseSnippetVaultWrite would otherwise keep. - assert.match( - source, - /updateSnippets\(\[\],\s*\{\s*replace:\s*true\s*\}\)/, - ); - assert.match( - source, - /const replace =\s*options\?\.replace === true \|\| snippetsWriteReplaceRef\.current/, - ); - assert.match( - source, - /replace\s*\?\s*cleaned\s*:\s*updater\s*\?\s*updater\(rebaseSnippetVaultWrite/, - ); - assert.match( - source, - /if \(replace\) \{\s*\/\/ Restore\/import\/clear[\s\S]*snippetsWriteBaseRef\.current = null/, - ); -}); - -test("updateSnippets preserves replace mode across superseded local saves", () => { - // A clear/restore queued behind the vault lock must not lose replacement - // intent when a later create/edit becomes the write owner — otherwise that - // save additively rebases against the stale disk catalog and resurrects - // every pre-replacement snippet. - assert.match( - source, - /const snippetsWriteReplaceRef = useRef\(false\)/, - ); - assert.match( - source, - /if \(options\?\.replace === true\) \{\s*snippetsWriteReplaceRef\.current = true;\s*\}/, - ); - assert.match( - source, - /snippetsWriteBaseRef\.current = null;\s*snippetsWriteReplaceRef\.current = false;/, - ); -}); - -test("updateSnippets keeps the persisted rebase ancestor across superseded saves", () => { - // Two queued local saves must not let the second treat the first save's - // optimistic in-memory array as base — that array never hit disk, so an add - // would look like a concurrent delete and be dropped. - assert.match( - source, - /const snippetsWriteBaseRef = useRef\(null\)/, - ); - assert.match( - source, - /const current = snippetsRef\.current;\s*const base = snippetsWriteBaseRef\.current \?\? current/, - ); - assert.match( - source, - /if \(snippetsWriteBaseRef\.current === null\) \{\s*snippetsWriteBaseRef\.current = base;\s*\}/, - ); - assert.match( - source, - /const persisted = localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS, rebased\)/, - ); - // Quota failure must keep the ancestor; clearing it would drop a local add on - // the next save after space is freed. - assert.match( - source, - /if \(!persisted\) \{[\s\S]*return "failed" as const;[\s\S]*\}\s*\/\/ Disk caught up[\s\S]*snippetsWriteBaseRef\.current = null/, - ); - assert.match( - source, - /if \(!persisted\) \{[\s\S]*Snippets could not be saved/, - ); -}); - -test("snippet storage events keep queued local edits and their rebase ancestor", () => { - // A cross-window write must not clear snippetsWriteBaseRef / replace optimistic - // state while a local owner is still queued — the next edit would supersede - // that owner from a remote-only snapshot and drop the first local mutation. - assert.match( - source, - /if \(key === STORAGE_KEY_SNIPPETS\) \{[\s\S]*const pendingBase = snippetsWriteBaseRef\.current;\s*if \(pendingBase !== null\) \{[\s\S]*rebaseSnippetVaultWrite\(\{\s*base: pendingBase,\s*ours: snippetsRef\.current,\s*theirs: next,\s*\}\)/, - ); - assert.doesNotMatch( - source, - /if \(key === STORAGE_KEY_SNIPPETS\) \{[\s\S]*snippetsWriteBaseRef\.current = null;\s*snippetsRef\.current = next/, - ); -}); - -test("snippet storage events retain outstanding replace snapshots", () => { - // clear/restore sets replace with base null. Adopting a remote old catalog - // before the lock is acquired would pollute memory; a later local edit would - // still replace disk with that polluted snapshot. - assert.match( - source, - /if \(key === STORAGE_KEY_SNIPPETS\) \{[\s\S]*if \(snippetsWriteReplaceRef\.current\) \{[\s\S]*return;\s*\}[\s\S]*snippetsRef\.current = next/, - ); -}); - -test("snippet storage events reject payloads older than current disk", () => { - // After a queued replace commits, snippetsWriteReplaceRef is false again. A - // delayed peer StorageEvent still carries the pre-replacement newValue; if - // adopted, the next edit would persist that resurrected catalog. - assert.match( - source, - /if \(key === STORAGE_KEY_SNIPPETS\) \{[\s\S]*event\.newValue !== localStorageAdapter\.readString\(STORAGE_KEY_SNIPPETS\)[\s\S]*return;/, - ); -}); - -test("startup host re-encryption uses the locked prune writer", () => { - // A second renderer migrating saved hosts must not write the pre-delete - // encryption blob unlocked after bulk-delete cleared login/connect bindings. - assert.match( - source, - /migrateHostsFromLegacyLineTimestamps[\s\S]*commitEncryptedHostsUnderVaultLock\(ver, sanitized, enc\)/, - ); - assert.match( - source, - /migrateHostsFromLegacyLineTimestamps[\s\S]*hostsWritePendingRef\.current = writePromise/, - ); - assert.doesNotMatch( - source, - /migrateHostsFromLegacyLineTimestamps[\s\S]*localStorageAdapter\.write\(STORAGE_KEY_HOSTS, enc\)/, - ); -}); - -test("startup snippet order backfill uses the locked vault writer", () => { - // An initializing renderer must not rewrite a pre-delete snippet snapshot - // unlocked after peer bulk-delete cleared host bindings — that resurrects - // every selected snippet while binding cleanup remains committed. - assert.match( - source, - /needsOrderPersist[\s\S]*withVaultImportLock\("vault", async \(\) => \{[\s\S]*readStoredArray\([\s\S]*STORAGE_KEY_SNIPPETS[\s\S]*localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS, latest\)/, - ); - assert.match( - source, - /needsOrderPersist[\s\S]*snippetsWritePendingRef\.current = writePromise/, - ); - assert.doesNotMatch( - source, - /const orderedSnippets = normalizeVaultOrder\(savedSnippets\);\s*setSnippets\(orderedSnippets\);\s*localStorageAdapter\.write\(STORAGE_KEY_SNIPPETS, orderedSnippets\);/, - ); -}); - -test("importData preserves device-local lastConnectedAt when a cloud payload omits it", () => { - // Cloud payloads no longer carry lastConnectedAt (#2629), but any remote - // reconciliation replaces the whole local host array. Import must re-attach - // each matching local host's device-local timestamp instead of dropping it. - assert.match( - source, - /retainLocalHostLastConnectedAt\(payload\.hosts,\s*hostsRef\.current\)/, - ); -}); diff --git a/components/AIChatPanelContent.test.ts b/components/AIChatPanelContent.test.ts deleted file mode 100644 index 05ba17ba5..000000000 --- a/components/AIChatPanelContent.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const panelSource = readFileSync(new URL('./AIChatPanelContent.tsx', import.meta.url), 'utf8'); -const selectorSource = readFileSync(new URL('./ai/AgentSelector.tsx', import.meta.url), 'utf8'); -const preparingSource = readFileSync(new URL('./AIChatSidePanel.tsx', import.meta.url), 'utf8'); - -const primaryToolbarSources = [ - panelSource, - readFileSync(new URL('./ScriptsSidePanel.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('./HistorySidePanel.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('./SftpSidePanel.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('./notes/NotesManager.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('./systemManager/SystemManagerSidePanel.tsx', import.meta.url), 'utf8'), - readFileSync(new URL('./terminal/ThemeSidePanel.tsx', import.meta.url), 'utf8'), -]; - -test('AI chat header matches the compact system panel toolbar height', () => { - assert.match(panelSource, /TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS/); - assert.match(selectorSource, /className="group flex h-6/); - assert.match(selectorSource, /truncate text-\[11px\]/); - assert.match(panelSource, /className="h-6 w-6 rounded-md/); -}); - -test('AI chat preparing state keeps the same compact header height', () => { - assert.match(preparingSource, /TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS/); - assert.match(preparingSource, /className="h-6 w-32/); -}); - -test('agent selector menu stays compact with restrained corners', () => { - assert.match(selectorSource, /w-\[256px\].*rounded-md/); - assert.match(selectorSource, /flex h-9 w-full items-center gap-2\.5 px-3/); - assert.doesNotMatch(selectorSource, /rounded-lg/); - assert.doesNotMatch(selectorSource, /rounded-2xl/); -}); - -test('terminal side panel tools share one primary toolbar height', () => { - for (const source of primaryToolbarSources) { - assert.match(source, /TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS/); - } -}); - -test('/rename and /chats panel commands stay out of the agent message path', () => { - const sidePanel = preparingSource; - // Panel implements the commands with updateSessionTitle + a note state — - // never addMessageToSession, so the commands cannot leak into chat history. - assert.match(sidePanel, /handleRenameSession = useCallback/); - assert.match(sidePanel, /handleListChats = useCallback/); - assert.match(sidePanel, /updateSessionTitle\(sessionId, title\)/); - assert.match(sidePanel, /setPanelCommandNote\(formatAiChatsListingNote\(entries, t\)\)/); - const renameHandler = sidePanel.slice( - sidePanel.indexOf('handleRenameSession = useCallback'), - sidePanel.indexOf('const handleRenameSlashCommand'), - ); - assert.doesNotMatch(renameHandler, /addMessageToSession/); - const chatsHandler = sidePanel.slice( - sidePanel.indexOf('handleListChats = useCallback'), - sidePanel.indexOf('const handleSend'), - ); - assert.doesNotMatch(chatsHandler, /addMessageToSession/); - // Wiring reaches AIChatPanelContent. - assert.match(sidePanel, /onRenameActiveChat=\{handleRenameSlashCommand\}/); - assert.match(sidePanel, /onListChats=\{handleListChats\}/); -}); - -test('AIChatPanelContent renders the panel command note and wires rename/list props', () => { - assert.match(panelSource, /panelCommandNote \? \(/); - assert.match(panelSource, /role="status"/); - assert.match(panelSource, /onDismissPanelCommandNote/); - assert.match(panelSource, /onRenameSession=\{onRenameActiveChat\}/); - assert.match(panelSource, /onListChats=\{onListChats\}/); - assert.match(panelSource, /onRename=\{onRenameSession\}/); -}); diff --git a/components/AIChatSessionHistoryDrawer.tsx b/components/AIChatSessionHistoryDrawer.tsx index d8927016c..46886d622 100644 --- a/components/AIChatSessionHistoryDrawer.tsx +++ b/components/AIChatSessionHistoryDrawer.tsx @@ -3,7 +3,7 @@ import { Download, 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'; -import { MAX_SEARCH_QUERY_LENGTH, truncateQueryForMatch } from '../lib/searchMatcher'; +import { MAX_SEARCH_QUERY_LENGTH, truncateQueryForMatch } from '../domain/searchMatcher'; import { Input } from './ui/input'; import { ScrollArea } from './ui/scroll-area'; import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip'; diff --git a/components/CloudSyncSettings.test.ts b/components/CloudSyncSettings.test.ts deleted file mode 100644 index c72da6ee6..000000000 --- a/components/CloudSyncSettings.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("USE_LOCAL conflict resolution forces upload-local without decrypting remote", () => { - const source = readFileSync(new URL("./CloudSyncSettings.tsx", import.meta.url), "utf8"); - const useLocalIndex = source.indexOf("} else if (resolution === 'USE_LOCAL') {"); - const syncNowIndex = source.indexOf("results = await sync.syncNow(localPayload, {", useLocalIndex); - const overrideShrinkIndex = source.indexOf("overrideShrink: true,", syncNowIndex); - const uploadLocalIndex = source.indexOf("conflictActionOverride: 'upload-local',", syncNowIndex); - const nextBranchIndex = source.indexOf("toast.success(t('cloudSync.resolve.uploaded'));", syncNowIndex); - - assert.notEqual(useLocalIndex, -1); - assert.notEqual(syncNowIndex, -1); - assert.notEqual(overrideShrinkIndex, -1); - assert.notEqual(uploadLocalIndex, -1); - assert.notEqual(nextBranchIndex, -1); - assert.ok( - useLocalIndex < syncNowIndex - && syncNowIndex < overrideShrinkIndex - && overrideShrinkIndex < uploadLocalIndex - && uploadLocalIndex < nextBranchIndex, - "keep-local must re-sync with conflictActionOverride upload-local so a new master password can overwrite an undecryptable cloud backup", - ); -}); diff --git a/components/CreateWorkspaceDialog.tsx b/components/CreateWorkspaceDialog.tsx index f88cc713f..7c3d590b4 100644 --- a/components/CreateWorkspaceDialog.tsx +++ b/components/CreateWorkspaceDialog.tsx @@ -1,7 +1,7 @@ import { Search } from 'lucide-react'; import React, { useMemo, useState, useEffect, useCallback } from 'react'; import { useI18n } from '../application/i18n/I18nProvider'; -import { matchesWorkspaceHostPickerQuery } from '../lib/searchMatcher'; +import { matchesWorkspaceHostPickerQuery } from '../domain/searchMatcher'; import { Host } from '../types'; import { DistroAvatar } from './DistroAvatar'; import { Button } from './ui/button'; diff --git a/components/FidoPromptModal.test.ts b/components/FidoPromptModal.test.ts deleted file mode 100644 index 691acd8e6..000000000 --- a/components/FidoPromptModal.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; - -test("FidoPromptModal ships PIN and touch UI wiring", () => { - const source = readFileSync(join(import.meta.dirname, "FidoPromptModal.tsx"), "utf8"); - assert.match(source, /kind === "touch"/); - assert.match(source, /fido-pin-input/); - assert.match(source, /fido\.prompt\.pinTitle/); - assert.match(source, /fido\.prompt\.touchTitle/); - assert.match(source, /onSubmit\(request\.requestId/); - assert.match(source, /onCancel\(request\.requestId/); -}); - -test("AppView mounts FidoPromptModal", () => { - const source = readFileSync( - join(import.meta.dirname, "../application/app/AppView.tsx"), - "utf8", - ); - assert.match(source, /FidoPromptModal/); - assert.match(source, /fidoPromptQueue/); - assert.match(source, /handleFidoPromptSubmit/); -}); - -test("GenerateStandardPanel exposes FIDO options", () => { - const source = readFileSync( - join(import.meta.dirname, "keychain/GenerateStandardPanel.tsx"), - "utf8", - ); - assert.match(source, /ED25519-SK/); - assert.match(source, /ECDSA-SK/); - assert.match(source, /resident/); - assert.match(source, /verifyRequired/); - assert.match(source, /fidoHint/); -}); diff --git a/components/HostDetailsAdvancedSections.test.ts b/components/HostDetailsAdvancedSections.test.ts deleted file mode 100644 index 50a948833..000000000 --- a/components/HostDetailsAdvancedSections.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./HostDetailsAdvancedSections.tsx', import.meta.url), 'utf8'); - -test('advanced host settings expose per-host SSH connection timeouts', () => { - assert.match(source, /hostDetails\.section\.sshTimeouts/); - assert.match(source, /value=\{form\.sshTcpConnectTimeoutSeconds \?\?/); - assert.match(source, /update\("sshTcpConnectTimeoutSeconds", value\)/); - assert.match(source, /value=\{form\.sshAuthReadyTimeoutSeconds \?\?/); - assert.match(source, /update\("sshAuthReadyTimeoutSeconds", value\)/); - assert.equal(source.match(/!Number\.isFinite\(value\)/g)?.length, 2); -}); - -test('editing enabled SSH agent controls persists the enabled state', () => { - assert.match(source, /effectiveGroupDefaults,\s*effectiveAuthMethod,/); - assert.doesNotMatch(source, /resolveHostAuthMethodSelection/); - assert.match(source, /const systemSshAgentSupported = effectiveAuthMethod === "auto" \|\| effectiveAuthMethod === "key"/); - assert.match(source, /effectiveAuthMethod === "key" && form\.useSshAgent === true/); - assert.match(source, /enabled=\{systemSshAgentEnabled\}/); - assert.match(source, /disabled=\{!systemSshAgentSupported\}/); - assert.match(source, /resolveSshAgentToggleUpdate\(previous, effectiveAuthMethod, enabling\)/); - assert.match(source, /\{systemSshAgentEnabled && \(/); - assert.match(source, /useSshAgent: true,\s*identityAgent:/); - assert.match(source, /useSshAgent: true,\s*identitiesOnly:/); -}); - -test('enabling SSH agent login clears an imported none sentinel', () => { - assert.match(source, /resolveSshAgentToggleUpdate/); -}); - -test('X11 forwarding display follows the effective host after group defaults', () => { - assert.match(source, /applyGroupDefaults\(form, effectiveGroupDefaults\)/); - assert.match(source, /const showX11Forwarding = \(!effectiveConnectionHost\.protocol \|\| effectiveConnectionHost\.protocol === "ssh"\)/); - assert.match(source, /!effectiveConnectionHost\.moshEnabled/); - assert.match(source, /!effectiveConnectionHost\.etEnabled/); - assert.match(source, /const effectiveX11Forwarding = !!effectiveConnectionHost\.x11Forwarding/); - assert.match(source, /\{showX11Forwarding && \(/); - assert.match(source, /enabled=\{effectiveX11Forwarding\}/); - assert.doesNotMatch(source, /effectiveGroupDefaults\?\.x11Forwarding/); -}); - -test('login and forwarding warnings use independent agent status', () => { - assert.match(source, /systemSshAgentEnabled && sshAgentStatus && !sshAgentStatus\.running/); - assert.match(source, /form\.agentForwarding && sshForwardingAgentStatus && !sshForwardingAgentStatus\.running/); -}); diff --git a/components/HostDetailsPanel.sshAgentStatus.test.ts b/components/HostDetailsPanel.sshAgentStatus.test.ts deleted file mode 100644 index 3d796654a..000000000 --- a/components/HostDetailsPanel.sshAgentStatus.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8'); - -test('login and forwarding agent availability are checked independently', () => { - assert.equal(source.match(/let cancelled = false/g)?.length, 2); - assert.match(source, /if \(!cancelled\) setSshAgentStatus\(status\)/); - assert.match(source, /if \(!cancelled\) setSshForwardingAgentStatus\(status\)/); - assert.match(source, /if \(form\.agentForwarding \|\| form\.useSshAgent === true\) \{\s*void checkSshAgent\(\{\s*identityAgent: form\.useSshAgent === true \? form\.identityAgent : undefined,\s*hostname:/); - assert.match(source, /if \(form\.agentForwarding\) \{\s*void checkSshAgent\(\{\s*identityAgent: form\.identityAgent,\s*agentForwarding: true,/); - assert.equal(source.match(/return \(\) => \{\s*cancelled = true/g)?.length, 2); - assert.match(source, /sshForwardingAgentStatus=\{sshForwardingAgentStatus\}/); -}); - -test('inherited identity actions use the resolved authentication username', () => { - assert.match(source, /const effectiveAuth = useMemo\(\(\) => resolveHostAuth/); - assert.match(source, /detachEffectiveHostIdentity\(prev, effectiveAuth\.username\)/); - assert.match(source, /effectiveUsername=\{effectiveAuth\.username\}/); -}); diff --git a/components/KeyboardInteractiveModal.test.ts b/components/KeyboardInteractiveModal.test.ts index 8020f71a9..96ce42a5b 100644 --- a/components/KeyboardInteractiveModal.test.ts +++ b/components/KeyboardInteractiveModal.test.ts @@ -31,12 +31,10 @@ test("keyboard-interactive dialog shows a field label and an inline TOTP action" assert.match(modalSource, /data-totp-fill=\{fillPlacement\}/); assert.match(modalSource, /variant="secondary"/); assert.doesNotMatch(modalSource, /variant=\{fillPlacement/); - assert.match(modalSource, /totpPrompt\.shared\.mjs/); + assert.match(modalSource, /totpPrompt\.shared\.cjs/); const shared = require("../domain/totpPrompt.shared.cjs") as { NON_TOTP_PROMPT: RegExp }; const runtime = require("../domain/totp.shared.cjs") as { NON_TOTP_PROMPT: RegExp }; - const esm = await import("../domain/totpPrompt.shared.mjs"); assert.equal(shared.NON_TOTP_PROMPT, runtime.NON_TOTP_PROMPT); - assert.equal(esm.NON_TOTP_PROMPT.source, shared.NON_TOTP_PROMPT.source); assert.doesNotMatch(modalSource, /ring-primary/); assert.doesNotMatch(modalSource, /className="w-full"/); assert.doesNotMatch(modalSource, /onTypeTotp/); diff --git a/components/KeyboardInteractiveModal.tsx b/components/KeyboardInteractiveModal.tsx index c5bbd68b3..a535b83c4 100644 --- a/components/KeyboardInteractiveModal.tsx +++ b/components/KeyboardInteractiveModal.tsx @@ -5,7 +5,7 @@ */ import { Eye, EyeOff, KeyRound, Loader2 } from "lucide-react"; import React, { useCallback, useEffect, useMemo, useState } from "react"; -import { NON_TOTP_PROMPT } from "../domain/totpPrompt.shared.mjs"; +import { NON_TOTP_PROMPT } from "../domain/totpPrompt.shared.cjs"; import { useI18n } from "../application/i18n/I18nProvider"; import { Button } from "./ui/button"; import { diff --git a/components/KeychainExportPanel.test.ts b/components/KeychainExportPanel.test.ts deleted file mode 100644 index 1eabafff1..000000000 --- a/components/KeychainExportPanel.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./KeychainExportPanel.tsx', import.meta.url), 'utf8'); - -test('key export forwards the selected host SSH connection timeouts', () => { - assert.match(source, /resolveHostSshConnectionTimeouts\(effectiveExportHost\)/); - assert.match(source, /sshTcpConnectTimeoutMs: connectionTimeouts\.tcpConnectTimeoutSeconds \* 1000/); - assert.match(source, /sshAuthReadyTimeoutMs: connectionTimeouts\.authReadyTimeoutSeconds \* 1000/); -}); - -test('key export omits stale identity files for password-only auth', () => { - assert.match( - source, - /fallbackIdentityFilePaths: exportAuth\.authMethod === "password" \|\| exportAuth\.keyId/, - ); -}); - -test('key export passes the selected vault key to agent filtering', () => { - assert.match(source, /resolveBridgeSshAgentAuth\(\s*effectiveExportHost,\s*exportAuth\.key,\s*exportAuth\.authMethod,\s*\)/); -}); - -test('key export defaults blank usernames the same way as other SSH entry points', () => { - assert.match(source, /username: exportAuth\.username \|\| "root"/); -}); - -test('key export forwards host MFA metadata to one-off exec commands', () => { - assert.match(source, /hostId: effectiveExportHost\.id/); - assert.match(source, /requiresMfa: !!effectiveExportHost\.requiresMfa/); -}); diff --git a/components/LogView.accent.test.ts b/components/LogView.accent.test.ts deleted file mode 100644 index 3db9023e5..000000000 --- a/components/LogView.accent.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./LogView.tsx', import.meta.url), 'utf8'); - -test('LogView applies live custom accent at the leaf from appearanceChromeStore', () => { - assert.match(source, /useAppearanceChromeStore/); - assert.match(source, /applyCustomAccentToTerminalTheme\(baseTheme, accentMode, customAccent\)/); - // Must not rely on an accent-baked defaultTerminalTheme from AppShell bags. - assert.match( - source, - /published defaultTerminalTheme is the stable base catalog/, - ); -}); diff --git a/components/PortForwardingNew.test.ts b/components/PortForwardingNew.test.ts deleted file mode 100644 index efe5a7877..000000000 --- a/components/PortForwardingNew.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const source = readFileSync(new URL("./PortForwardingNew.tsx", import.meta.url), "utf8"); - -test("port forwarding toolbar exposes start-all and stop-all actions", () => { - assert.match(source, /pf\.action\.startAll/); - assert.match(source, /pf\.action\.stopAll/); - assert.match(source, /handleStartAll/); - assert.match(source, /handleStopAll/); - assert.match(source, /startAllTunnels/); - assert.match(source, /stopAllTunnels/); - assert.match(source, /startableRules\.length === 0/); - assert.match(source, /stoppableRules\.length === 0/); - assert.match(source, //); - assert.match(source, //); -}); - -test("port forwarding bulk actions stay on start/stop all without selection checkboxes", () => { - assert.match(source, /startAllTunnels\(/); - assert.match(source, /stopAllTunnels\(/); - assert.doesNotMatch(source, /selectedRuleIds|bulkDelete|type="checkbox"/); -}); diff --git a/components/QuickSwitcher.tsx b/components/QuickSwitcher.tsx index 5c9e9eb0c..82af115ca 100644 --- a/components/QuickSwitcher.tsx +++ b/components/QuickSwitcher.tsx @@ -16,7 +16,7 @@ import { Host, TerminalSession, TerminalSettings, Workspace } from "../types"; import { KeyBinding } from "../domain/models"; import type { PaneMagnificationState } from "../domain/paneMagnification"; import { isSwitcherQuickConnectInput } from "../domain/quickConnect"; -import { matchesSearchQuery } from "../lib/searchMatcher"; +import { matchesSearchQuery } from "../domain/searchMatcher"; import { buildQuickSwitcherShells, useDiscoveredShells, getShellIconPath, isMonochromeShellIcon } from "../lib/useDiscoveredShells"; import { usePluginContributions } from "../application/state/usePluginContributions"; import { requestOpenPluginView } from "./plugins/PluginContributionHost"; diff --git a/components/SelectHostPanelContent.tsx b/components/SelectHostPanelContent.tsx index 0bd52b2e9..46da67842 100644 --- a/components/SelectHostPanelContent.tsx +++ b/components/SelectHostPanelContent.tsx @@ -11,7 +11,7 @@ import { } from 'lucide-react'; import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { cn } from '../lib/utils'; -import { matchesHostSearchQuery, matchesSearchQuery } from '../lib/searchMatcher'; +import { matchesHostSearchQuery, matchesSearchQuery } from '../domain/searchMatcher'; import { useI18n } from '../application/i18n/I18nProvider'; import { collectSelectableHostIdsInGroup, diff --git a/components/SerialAdvancedOptions.tsx b/components/SerialAdvancedOptions.tsx new file mode 100644 index 000000000..4804839fd --- /dev/null +++ b/components/SerialAdvancedOptions.tsx @@ -0,0 +1,321 @@ +/** + * Shared serial port form constants and sections used by both + * SerialConnectModal and SerialHostDetailsPanel. + */ +import { ChevronDown, ChevronUp } from 'lucide-react'; +import React from 'react'; +import { useI18n } from '../application/i18n/I18nProvider'; +import type { SerialConfig, SerialFlowControl, SerialParity } from '../domain/models'; +import { Button } from './ui/button'; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible'; +import { Combobox } from './ui/combobox'; +import { Input } from './ui/input'; +import { Label } from './ui/label'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; + +export interface SerialPortInfo { + path: string; + manufacturer: string; + serialNumber: string; + vendorId: string; + productId: string; + pnpId: string; + type?: 'hardware' | 'pseudo' | 'custom'; +} + +export const SERIAL_BAUD_RATES = [ + 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600, +]; +const DATA_BITS: Array<5 | 6 | 7 | 8> = [5, 6, 7, 8]; +const STOP_BITS: Array<1 | 1.5 | 2> = [1, 1.5, 2]; +const PARITY_OPTIONS: SerialParity[] = ['none', 'even', 'odd', 'mark', 'space']; +const FLOW_CONTROL_OPTIONS: SerialFlowControl[] = ['none', 'xon/xoff', 'rts/cts']; + +export interface SerialBaudRateFieldProps { + baudRate: number; + onChange: (baudRate: number) => void; +} + +export const SerialBaudRateField: React.FC = ({ + baudRate, + onChange, +}) => { + const { t } = useI18n(); + return ( +
+ + ({ + value: String(rate), + label: String(rate), + }))} + value={String(baudRate)} + onValueChange={(val) => { + const parsed = parseInt(val, 10); + if (!isNaN(parsed) && parsed > 0) { + onChange(parsed); + } + }} + placeholder={t('serial.field.baudRatePlaceholder')} + emptyText={t('serial.field.baudRateEmpty')} + allowCreate + createText={t('common.use')} + /> + {baudRate > 0 && !SERIAL_BAUD_RATES.includes(baudRate) && ( +

+ {t('serial.field.customBaudRate')} +

+ )} +
+ ); +}; + +export interface SerialAdvancedOptionsSectionProps { + open: boolean; + onOpenChange: (open: boolean) => void; + isNamedPipe: boolean; + dataBits: 5 | 6 | 7 | 8; + onDataBitsChange: (value: 5 | 6 | 7 | 8) => void; + stopBits: 1 | 1.5 | 2; + onStopBitsChange: (value: 1 | 1.5 | 2) => void; + parity: SerialParity; + onParityChange: (value: SerialParity) => void; + flowControl: SerialFlowControl; + onFlowControlChange: (value: SerialFlowControl) => void; + backspaceBehavior: SerialConfig['backspaceBehavior']; + onBackspaceBehaviorChange: (value: 'default' | 'ctrl-h') => void; + byteOrientedBackspace: boolean; + onByteOrientedBackspaceChange: (value: boolean) => void; + localEcho: boolean; + onLocalEchoChange: (value: boolean) => void; + lineMode: boolean; + onLineModeChange: (value: boolean) => void; + charset: string; + onCharsetChange: (value: string) => void; +} + +export const SerialAdvancedOptionsSection: React.FC = ({ + open, + onOpenChange, + isNamedPipe, + dataBits, + onDataBitsChange, + stopBits, + onStopBitsChange, + parity, + onParityChange, + flowControl, + onFlowControlChange, + backspaceBehavior, + onBackspaceBehaviorChange, + byteOrientedBackspace, + onByteOrientedBackspaceChange, + localEcho, + onLocalEchoChange, + lineMode, + onLineModeChange, + charset, + onCharsetChange, +}) => { + const { t } = useI18n(); + const isStopBits15 = stopBits === 1.5; + + return ( + + + + + + {/* Hardware-only serial framing is not used by named pipes. */} + {!isNamedPipe && ( + <> +
+
+ + +
+ +
+ + + {isStopBits15 && ( +

+ {t('serial.field.stopBits15Warning')} +

+ )} +
+
+ +
+ + +
+ +
+ + +
+ + )} + + {/* Terminal Options */} +
+
+ + +

+ {t('serial.field.backspaceBehaviorDesc')} +

+
+ +
+
+ +

+ {t('serial.field.byteOrientedBackspaceDesc')} +

+
+ onByteOrientedBackspaceChange(e.target.checked)} + className="h-4 w-4 rounded border-input" + /> +
+ +
+
+ +

+ {t('serial.field.localEchoDesc')} +

+
+ onLocalEchoChange(e.target.checked)} + className="h-4 w-4 rounded border-input" + /> +
+ +
+
+ +

+ {t('serial.field.lineModeDesc')} +

+
+ onLineModeChange(e.target.checked)} + className="h-4 w-4 rounded border-input" + /> +
+ + {/* Charset */} +
+ + onCharsetChange(e.target.value)} + className="h-9" + /> +
+
+
+
+ ); +}; diff --git a/components/SerialConnectModal.tsx b/components/SerialConnectModal.tsx index d26068faf..fc4c61109 100644 --- a/components/SerialConnectModal.tsx +++ b/components/SerialConnectModal.tsx @@ -2,7 +2,7 @@ * Serial Port Connect Modal * Allows users to configure and connect to a serial port */ -import { ChevronDown, ChevronUp, Cpu, RefreshCw, Save, Usb } from 'lucide-react'; +import { Cpu, RefreshCw, Save, Usb } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useI18n } from '../application/i18n/I18nProvider'; import { useTerminalBackend } from '../application/state/useTerminalBackend'; @@ -10,6 +10,11 @@ import type { Host, SerialConfig, SerialFlowControl, SerialParity } from '../dom import { prepareSerialConfigForSavedHost } from '../domain/serialBackspace'; import { isSerialEndpointPath, isWindowsNamedPipePath } from '../domain/serialEndpoint'; import { cn } from '../lib/utils'; +import { + SerialAdvancedOptionsSection, + SerialBaudRateField, + type SerialPortInfo, +} from './SerialAdvancedOptions'; import { Button } from './ui/button'; import { Combobox, type ComboboxOption } from './ui/combobox'; import { @@ -22,18 +27,6 @@ import { } from './ui/dialog'; import { Input } from './ui/input'; import { Label } from './ui/label'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible'; - -interface SerialPort { - path: string; - manufacturer: string; - serialNumber: string; - vendorId: string; - productId: string; - pnpId: string; - type?: 'hardware' | 'pseudo' | 'custom'; -} interface SerialConnectModalProps { open: boolean; @@ -42,12 +35,6 @@ interface SerialConnectModalProps { onSaveHost?: (host: Host) => void; } -const BAUD_RATES = [300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600]; -const DATA_BITS: Array<5 | 6 | 7 | 8> = [5, 6, 7, 8]; -const STOP_BITS: Array<1 | 1.5 | 2> = [1, 1.5, 2]; -const PARITY_OPTIONS: SerialParity[] = ['none', 'even', 'odd', 'mark', 'space']; -const FLOW_CONTROL_OPTIONS: SerialFlowControl[] = ['none', 'xon/xoff', 'rts/cts']; - export const SerialConnectModal: React.FC = ({ open, onClose, @@ -55,7 +42,7 @@ export const SerialConnectModal: React.FC = ({ onSaveHost, }) => { const { t } = useI18n(); - const [ports, setPorts] = useState([]); + const [ports, setPorts] = useState([]); const [isLoadingPorts, setIsLoadingPorts] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); @@ -163,9 +150,6 @@ export const SerialConnectModal: React.FC = ({ const isPortValid = isSerialEndpointPath(trimmedPort); // Allow custom baud rates as long as they are positive integers const isBaudRateValid = Number.isInteger(baudRate) && baudRate > 0; - - // Check if using 1.5 stop bits (limited Windows support) - const isStopBits15 = stopBits === 1.5; const isValid = isPortValid && (isNamedPipe || isBaudRateValid); return ( @@ -222,235 +206,33 @@ export const SerialConnectModal: React.FC = ({ {/* Baud Rate (not used by named pipes) */} {!isNamedPipe && ( -
- - ({ - value: String(rate), - label: String(rate), - }))} - value={String(baudRate)} - onValueChange={(val) => { - const parsed = parseInt(val, 10); - if (!isNaN(parsed) && parsed > 0) { - setBaudRate(parsed); - } - }} - placeholder={t('serial.field.baudRatePlaceholder')} - emptyText={t('serial.field.baudRateEmpty')} - allowCreate - createText={t('common.use')} - /> - {baudRate > 0 && !BAUD_RATES.includes(baudRate) && ( -

- {t('serial.field.customBaudRate')} -

- )} -
+ )} {/* Advanced Options */} - - - - - - {/* Hardware-only serial framing is not used by named pipes. */} - {!isNamedPipe && ( - <> - {/* Data Bits */} -
-
- - -
- - {/* Stop Bits */} -
- - - {isStopBits15 && ( -

- {t('serial.field.stopBits15Warning')} -

- )} -
-
- - {/* Parity */} -
- - -
- - {/* Flow Control */} -
- - -
- - - )} - - {/* Terminal Options */} -
-
- - -

- {t('serial.field.backspaceBehaviorDesc')} -

-
- -
-
- -

- {t('serial.field.byteOrientedBackspaceDesc')} -

-
- setByteOrientedBackspace(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- -
-
- -

- {t('serial.field.localEchoDesc')} -

-
- setLocalEcho(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- -
-
- -

- {t('serial.field.lineModeDesc')} -

-
- setLineMode(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- - {/* Charset */} -
- - setCharset(e.target.value)} - className="h-9" - /> -
-
-
-
+ {/* Save Configuration */} {onSaveHost && ( diff --git a/components/SerialHostDetailsPanel.tsx b/components/SerialHostDetailsPanel.tsx index 069cabce0..b8af3508e 100644 --- a/components/SerialHostDetailsPanel.tsx +++ b/components/SerialHostDetailsPanel.tsx @@ -2,7 +2,7 @@ * Serial Host Details Panel * A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel) */ -import { ChevronDown, ChevronUp, Eye, EyeOff, Save, Tag, Usb, X } from 'lucide-react'; +import { Eye, EyeOff, Save, Tag, Usb, X } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useI18n } from '../application/i18n/I18nProvider'; import { useTerminalBackend } from '../application/state/useTerminalBackend'; @@ -14,12 +14,15 @@ import { import { isSerialEndpointPath, isWindowsNamedPipePath } from '../domain/serialEndpoint'; +import { + SerialAdvancedOptionsSection, + SerialBaudRateField, + type SerialPortInfo, +} from './SerialAdvancedOptions'; import { Button } from './ui/button'; import { Combobox, ComboboxOption, MultiCombobox } from './ui/combobox'; import { Input } from './ui/input'; import { Label } from './ui/label'; -import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible'; import { AsidePanel, AsidePanelContent, @@ -30,16 +33,6 @@ import { import { HostNotesEditor } from './host/HostNotesEditor'; import { cn } from '../lib/utils'; -interface SerialPort { - path: string; - manufacturer: string; - serialNumber: string; - vendorId: string; - productId: string; - pnpId: string; - type?: 'hardware' | 'pseudo' | 'custom'; -} - interface SerialHostDetailsPanelProps { initialData: Host; allTags?: string[]; @@ -53,12 +46,6 @@ interface SerialHostDetailsPanelProps { type SerialHostDetailsPanelPropsWithResize = SerialHostDetailsPanelProps & AsidePanelResizeProps; -const BAUD_RATES = [300, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600]; -const DATA_BITS: Array<5 | 6 | 7 | 8> = [5, 6, 7, 8]; -const STOP_BITS: Array<1 | 1.5 | 2> = [1, 1.5, 2]; -const PARITY_OPTIONS: SerialParity[] = ['none', 'even', 'odd', 'mark', 'space']; -const FLOW_CONTROL_OPTIONS: SerialFlowControl[] = ['none', 'xon/xoff', 'rts/cts']; - export const SerialHostDetailsPanel: React.FC = ({ initialData, allTags = [], @@ -74,7 +61,7 @@ export const SerialHostDetailsPanel: React.FC { const { t } = useI18n(); const terminalBackend = useTerminalBackend(); - const [ports, setPorts] = useState([]); + const [ports, setPorts] = useState([]); const [isLoadingPorts, setIsLoadingPorts] = useState(false); const [showAdvanced, setShowAdvanced] = useState(false); const [showPassword, setShowPassword] = useState(false); @@ -213,9 +200,6 @@ export const SerialHostDetailsPanel: React.FC 0; const isValid = isPortValid && (isNamedPipe || isBaudRateValid); - // Check if using 1.5 stop bits (limited Windows support) - const isStopBits15 = stopBits === 1.5; - return ( - - ({ - value: String(rate), - label: String(rate), - }))} - value={String(baudRate)} - onValueChange={(val) => { - const parsed = parseInt(val, 10); - if (!isNaN(parsed) && parsed > 0) { - setBaudRate(parsed); - } - }} - placeholder={t('serial.field.baudRatePlaceholder')} - emptyText={t('serial.field.baudRateEmpty')} - allowCreate - createText={t('common.use')} - /> - {baudRate > 0 && !BAUD_RATES.includes(baudRate) && ( -

- {t('serial.field.customBaudRate')} -

- )} - + )} {/* Login credentials (auto-login) */} @@ -396,210 +356,32 @@ export const SerialHostDetailsPanel: React.FC {/* Advanced Options */} - - - - - - {/* Hardware-only serial framing is not used by named pipes. */} - {!isNamedPipe && ( - <> - {/* Data Bits */} -
-
- - -
- - {/* Stop Bits */} -
- - - {isStopBits15 && ( -

- {t('serial.field.stopBits15Warning')} -

- )} -
-
- - {/* Parity */} -
- - -
- - {/* Flow Control */} -
- - -
- - - )} - - {/* Terminal Options */} -
-
- - -

- {t('serial.field.backspaceBehaviorDesc')} -

-
- -
-
- -

- {t('serial.field.byteOrientedBackspaceDesc')} -

-
- setByteOrientedBackspace(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- -
-
- -

- {t('serial.field.localEchoDesc')} -

-
- setLocalEcho(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- -
-
- -

- {t('serial.field.lineModeDesc')} -

-
- setLineMode(e.target.checked)} - className="h-4 w-4 rounded border-input" - /> -
- - {/* Charset */} -
- - setCharset(e.target.value)} - className="h-9" - /> -
-
-
-
+ { + setBackspaceBehavior(value); + setBackspaceBehaviorChanged(true); + }} + byteOrientedBackspace={byteOrientedBackspace} + onByteOrientedBackspaceChange={setByteOrientedBackspace} + localEcho={localEcho} + onLocalEchoChange={setLocalEcho} + lineMode={lineMode} + onLineModeChange={setLineMode} + charset={charset} + onCharsetChange={setCharset} + /> diff --git a/components/SnippetScriptEditor.test.ts b/components/SnippetScriptEditor.test.ts deleted file mode 100644 index f59df437b..000000000 --- a/components/SnippetScriptEditor.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const snippetEditorSource = readFileSync( - new URL('./snippets/SnippetScriptEditor.tsx', import.meta.url), - 'utf8', -); -const codeEditorSource = readFileSync( - new URL('./scripts/ScriptCodeEditor.tsx', import.meta.url), - 'utf8', -); - -test('snippet editing uses the Monaco editor in both inline and expanded layouts', () => { - assert.doesNotMatch(snippetEditorSource, /CodeTextarea/); - assert.equal(snippetEditorSource.match(/ { - assert.match(snippetEditorSource, /inlineEditorRef\.current\?\.focus\(\)/); - assert.match(snippetEditorSource, /\sref=\{inlineEditorRef\}/); - assert.match(snippetEditorSource, /\stabFocusMode(?:\s|\n)/); - assert.match(codeEditorSource, /tabFocusMode,/); -}); - -test('snippet editor forwards the surrounding form submit shortcut', () => { - assert.equal(snippetEditorSource.match(/onSubmitShortcut=\{onSubmitShortcut\}/g)?.length, 2); - assert.match(codeEditorSource, /if \(onSubmitShortcut\)/); - assert.match(codeEditorSource, /KeyMod\.CtrlCmd \| monacoInstance\.KeyCode\.Enter/); - assert.match(codeEditorSource, /onSubmitShortcutRef\.current\?\.\(\)/); -}); - -test('dialog submit handlers ignore shortcuts already handled by Monaco', () => { - const quickAddSource = readFileSync(new URL('./QuickAddSnippetDialog.tsx', import.meta.url), 'utf8'); - const tmuxSource = readFileSync( - new URL('./systemManager/TmuxNewSessionModal.tsx', import.meta.url), - 'utf8', - ); - assert.match(quickAddSource, /if \(e\.defaultPrevented\) return/); - assert.match(tmuxSource, /if \(e\.defaultPrevented\) return/); -}); - -test('visual placeholder is hidden from assistive technology', () => { - assert.match(codeEditorSource, / { - assert.match(codeEditorSource, /useClipboardBackend/); - assert.match(codeEditorSource, /readClipboardTextWithFallbacks/); - assert.match(codeEditorSource, /buildMonacoPasteEdits/); - assert.match(codeEditorSource, /KeyMod\.CtrlCmd \| monacoInstance\.KeyCode\.KeyV/); - assert.match(codeEditorSource, /contextmenu:\s*false/); - assert.match(codeEditorSource, /editor\.action\.clipboardPasteAction/); -}); - -test('script code editor pastes into Monaco find widget instead of script body', () => { - assert.match(codeEditorSource, /pasteForMonacoEditorCommand/); - assert.match(codeEditorSource, /activeElement:\s*document\.activeElement/); - assert.match(codeEditorSource, /pasteIntoEditor:\s*\(\)\s*=>\s*handlePasteRef\.current\(\)/); -}); diff --git a/components/Terminal.accentBase.test.ts b/components/Terminal.accentBase.test.ts deleted file mode 100644 index 03f2f9063..000000000 --- a/components/Terminal.accentBase.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./Terminal.tsx", import.meta.url), "utf8"); - -test("Terminal re-resolves catalog theme before applying store accent", () => { - // appearanceTheme may still carry a baked custom accent while TerminalLayer - // memo ignores accent churn. Switching accentMode back to `theme` must clear - // cursor/selection by starting from the clean catalog theme id. - assert.match(source, /useAppearanceChromeStore\(\)/); - assert.match( - source, - /getBuiltinTerminalThemeById\(appearanceTheme\.id\)/, - ); - assert.match( - source, - /applyCustomAccentToTerminalTheme\(resolveBase\(\), accentMode, customAccent\)/, - ); - assert.doesNotMatch( - source, - /if \(appearanceTheme\) return appearanceTheme;/, - ); -}); diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 5c1e978c9..f3bbdbc56 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -155,7 +155,7 @@ import { createReplaySafeTerminalLogSanitizer } from "./terminal/replaySafeTermi import { createConnectionLogBuffer } from "./terminal/connectionLogBuffer"; import { createProgrammaticCommandLogRewriter, type ProgrammaticCommandLogRewrite } from "./terminal/programmaticCommandLog"; import { getSessionLogInitialLine } from "./terminal/sessionLogInitialLine"; -import { getTerminalSelectionForClipboard } from "./terminal/normalizeTerminalSelection"; +import { getTerminalSelectionForClipboard } from "../domain/terminalSelection"; import { getHistoryPreviewSelectionFromRoot } from "./terminal/runtime/terminalHistoryScrollOverride"; import { createTerminalOutputHistoryPreview } from "./terminal/runtime/terminalOutputHistory"; import { useZmodemTransfer } from "./terminal/hooks/useZmodemTransfer"; diff --git a/components/TopTabs.test.ts b/components/TopTabs.test.ts index f66fddf46..313309da6 100644 --- a/components/TopTabs.test.ts +++ b/components/TopTabs.test.ts @@ -1,5 +1,4 @@ import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; import test from "node:test"; const storage = new Map(); @@ -36,25 +35,8 @@ const { formatSessionTopTabLabel, formatSessionTopTabTooltip, resolveSessionTabCodingCliIconState, - stopCloseButtonDoubleClickPropagation, } = await import("./top-tabs/TopTabItems.tsx"); const { activeTabStore } = await import("../application/state/activeTabStore.ts"); -const indexCss = readFileSync(new URL("../index.css", import.meta.url), "utf8"); -const topTabsSource = readFileSync(new URL("./TopTabs.tsx", import.meta.url), "utf8"); -const topTabItemsSource = readFileSync(new URL("./top-tabs/TopTabItems.tsx", import.meta.url), "utf8"); -const topTabsQuickControlsSource = readFileSync(new URL("./TopTabsQuickControls.tsx", import.meta.url), "utf8"); -const syncStatusButtonSource = readFileSync(new URL("./SyncStatusButton.tsx", import.meta.url), "utf8"); -const switchSource = readFileSync(new URL("./ui/switch.tsx", import.meta.url), "utf8"); -const appViewSource = readFileSync(new URL("../application/app/AppView.tsx", import.meta.url), "utf8"); -const appSource = [ - readFileSync(new URL("../App.tsx", import.meta.url), "utf8"), - readFileSync(new URL("../application/app/AppSideEffects.tsx", import.meta.url), "utf8"), - readFileSync(new URL("../application/app/hosts/TerminalHost.tsx", import.meta.url), "utf8"), - readFileSync(new URL("../application/app/hosts/ChromeHost.tsx", import.meta.url), "utf8"), -].join("\n"); -const externalMcpToggleSource = readFileSync(new URL("../application/state/useExternalMcpToggleState.ts", import.meta.url), "utf8"); -const zhTwAiSource = readFileSync(new URL("../application/i18n/locales/zh-TW/ai.ts", import.meta.url), "utf8"); -const terminalViewSource = readFileSync(new URL("./terminal/TerminalView.tsx", import.meta.url), "utf8"); test("host tree tab gutter fills the remaining sidebar width", () => { assert.equal(computeHostTreeTabGutter(280, 120), 160); @@ -78,139 +60,6 @@ test("host tree tab surface is hidden without work tabs", () => { }), false); }); -test("host tree tab layout transitions match the sidebar timing", () => { - const hostTreeCss = [ - ".top-tab-root-label", - ".top-tab-host-tree-toggle-slot", - ].map((selector) => { - const start = indexCss.indexOf(selector); - assert.notEqual(start, -1); - const end = indexCss.indexOf("}", start); - return indexCss.slice(start, end); - }).join("\n"); - const gutterStart = indexCss.indexOf(".top-tab-host-tree-gutter"); - assert.notEqual(gutterStart, -1); - const gutterEnd = indexCss.indexOf("}", gutterStart); - const gutterCss = indexCss.slice(gutterStart, gutterEnd); - - assert.match(hostTreeCss, /width 220ms cubic-bezier\(0\.4, 0, 0\.2, 1\)/); - assert.match(hostTreeCss, /max-width 220ms cubic-bezier\(0\.4, 0, 0\.2, 1\)/); - assert.doesNotMatch(hostTreeCss, /transition:\s*none/); - assert.doesNotMatch(hostTreeCss, /280ms/); - assert.doesNotMatch(gutterCss, /transition/); - assert.match(indexCss, /\.top-tab-host-tree-gutter-exit[\s\S]*transition: width 220ms/); -}); - -test("host tree toggle appears with opacity only and no bounce animation", () => { - assert.doesNotMatch(indexCss, /top-tab-host-tree-toggle-pop/); - assert.doesNotMatch(indexCss, /@keyframes\s+pop-in/); - - const start = indexCss.indexOf(".top-tab-host-tree-toggle-slot"); - assert.notEqual(start, -1); - const end = indexCss.indexOf("}", start); - const toggleSlotCss = indexCss.slice(start, end); - - assert.match(toggleSlotCss, /opacity 220ms ease/); - assert.doesNotMatch(toggleSlotCss, /transform/); - assert.doesNotMatch(toggleSlotCss, /scale/); -}); - -test("host tree toggle exposes a custom CSS hook", () => { - assert.match(topTabsSource, /data-section="top-tabs-host-tree-toggle"/); -}); - -test("quick switcher plus button exposes a custom CSS hook", () => { - assert.match(topTabsSource, /data-section="top-tabs-quick-switcher-toggle"/); -}); - -test("top tabs keep cloud sync separate from quick controls", () => { - assert.match(topTabsSource, /SyncStatusButton/); - assert.match(topTabsSource, /TopTabsQuickControls/); - assert.match(topTabsSource, /onOpenSettings=\{onOpenSettings\}/); - assert.match(topTabsSource, /onSyncNow=\{onSyncNow\}/); - assert.match(topTabsSource, /theme=\{theme\}/); - assert.match(topTabsSource, /themePreference=\{themePreference\}/); - assert.match(topTabsSource, /onThemeChange=\{onThemeChange\}/); - assert.match(topTabsSource, /externalMcpEnabled=\{externalMcpEnabled\}/); - assert.match(topTabsSource, /windowOpacity=\{windowOpacity\}/); - assert.match(topTabsSource, /showExternalMcpToggle=\{showExternalMcpToggle\}/); - assert.doesNotMatch(topTabsSource, /WindowOpacityButton/); - assert.doesNotMatch(topTabsSource, /onToggleTheme/); - const syncButtonUsage = topTabsSource.match(//); - assert.ok(syncButtonUsage, 'expected a SyncStatusButton usage'); - assert.doesNotMatch(syncButtonUsage[0], /externalMcpEnabled=/); - assert.doesNotMatch(syncButtonUsage[0], /windowOpacity=/); - assert.doesNotMatch(syncButtonUsage[0], /onThemeChange=/); - const quickControlsUsage = topTabsSource.match(//); - assert.ok(quickControlsUsage, 'expected a TopTabsQuickControls usage'); - assert.match(quickControlsUsage[0], /showExternalMcpToggle=\{showExternalMcpToggle\}/); - assert.match(quickControlsUsage[0], /externalMcpEnabled=\{externalMcpEnabled\}/); -}); - -test("quick controls panel hosts External MCP, opacity, and theme", () => { - assert.match(topTabsQuickControlsSource, /data-section="top-tabs-quick-controls"/); - assert.match(topTabsQuickControlsSource, /className="w-72 p-0 app-no-drag"/); - assert.match(topTabsQuickControlsSource, /topTabs\.controlPanel/); - assert.doesNotMatch(topTabsQuickControlsSource, /topTabs\.controlPanel\.description/); - assert.match(topTabsQuickControlsSource, /externalMcpEnabled/); - assert.match(topTabsQuickControlsSource, /onToggleExternalMcp/); - assert.match(topTabsQuickControlsSource, /windowOpacity/); - assert.match(topTabsQuickControlsSource, /setWindowOpacity/); - assert.match(topTabsQuickControlsSource, /themePreference/); - assert.match(topTabsQuickControlsSource, /onThemeChange/); - assert.match(topTabsQuickControlsSource, /topTabs\.controlPanel\.theme\.system/); - assert.match(topTabsQuickControlsSource, /aria-pressed=\{themePreference === option\.value\}/); - assert.match(topTabsQuickControlsSource, /onClick=\{\(\) => onThemeChange\(option\.value\)\}/); - assert.match(topTabsQuickControlsSource, / { - assert.match(zhTwAiSource, /'topTabs\.externalMcp\.enable':/); - assert.match(zhTwAiSource, /'topTabs\.externalMcp\.disable':/); - assert.match(zhTwAiSource, /'topTabs\.controlPanel':/); - assert.match(zhTwAiSource, /'topTabs\.controlPanel\.externalMcp':/); -}); - -test("AppView hides External MCP toggle in peer session windows", () => { - assert.match(appViewSource, /hash\.startsWith\('#\/session-window'\)/); - assert.match(appViewSource, /showExternalMcpToggle=\{!isPeerSessionWindow\}/); -}); - -test("External MCP top-bar status sync waits for App startup reconcile", () => { - assert.match(appSource, /await syncExternalMcpStartupStateOnce\(netcattyBridge\.get\(\)\)/); - assert.match(appSource, /markExternalMcpStartupReady\(\)/); - assert.ok( - appSource.indexOf("await syncExternalMcpStartupStateOnce(netcattyBridge.get())") - < appSource.indexOf("markExternalMcpStartupReady()"), - "startup ready must be marked only after await syncExternalMcpStartupStateOnce", - ); - assert.match(externalMcpToggleSource, /shouldWaitForExternalMcpStartupReady/); - assert.match(externalMcpToggleSource, /waitForExternalMcpStartupReady\(/); - assert.match(externalMcpToggleSource, /!status\.enabled && !status\.error/); - assert.match(externalMcpToggleSource, /if \(isPeerSessionWindow \|\| !enabled\) return;/); -}); - -test("SessionTabIcon checks custom host icon appearance before distro logos", () => { - assert.match(topTabItemsSource, /resolveHostIconAppearance\(host\)/); - assert.ok( - topTabItemsSource.indexOf("resolveHostIconAppearance(host)") < topTabItemsSource.indexOf("getEffectiveHostDistro(host)"), - "custom host icon should be checked before distro fallback", - ); -}); - test("disabling dynamic titles freezes a stored coding CLI icon and stops title fallback", () => { assert.deepEqual( resolveSessionTabCodingCliIconState({ @@ -248,26 +97,6 @@ test("disabling dynamic titles freezes a stored coding CLI icon and stops title ); }); -test("session top tab double click dispatches the configured behavior", () => { - const copiedSessionIds: string[] = []; - const duplicatedSessionIds: string[] = []; - const handlers = (["duplicate", "copy", "disabled"] as const).map((behavior) => - createTopTabSessionDoubleClickHandler({ - behavior, - onCopySession: (sessionId) => copiedSessionIds.push(sessionId), - onDuplicateSession: (sessionId) => duplicatedSessionIds.push(sessionId), - sessionId: `session-${behavior}`, - }), - ); - - handlers.forEach((handler) => handler({} as Parameters[0])); - - assert.deepEqual(duplicatedSessionIds, ["session-duplicate"]); - assert.deepEqual(copiedSessionIds, ["session-copy"]); - assert.match(topTabItemsSource, /behavior: tabDoubleClickBehavior/); - assert.match(topTabItemsSource, /onDoubleClick=\{handleDoubleClick\}/); -}); - test("duplicate double-click behavior falls back to copying when unavailable", () => { const copiedSessionIds: string[] = []; const handleDoubleClick = createTopTabSessionDoubleClickHandler({ @@ -281,108 +110,6 @@ test("duplicate double-click behavior falls back to copying when unavailable", ( assert.deepEqual(copiedSessionIds, ["session-1"]); }); -test("draggable top-tab close buttons cancel the drag gesture on mousedown", () => { - const closeButtonLabels = [ - "tabs.closePluginViewAria", - "Close editor tab", - "tabs.closeSessionAria", - "tabs.closeLogViewAria", - ]; - - for (const label of closeButtonLabels) { - const labelIndex = topTabItemsSource.indexOf(label); - assert.notEqual(labelIndex, -1, `missing close label ${label}`); - const buttonStart = topTabItemsSource.lastIndexOf("", labelIndex); - const openingTag = topTabItemsSource.slice(buttonStart, buttonEnd); - assert.match( - openingTag, - /onMouseDown=\{handleTabCloseButtonMouseDown\}/, - `${label} close button must guard mousedown`, - ); - } - - assert.equal( - topTabItemsSource.match(/onMouseDown=\{handleTabCloseButtonMouseDown\}/g)?.length, - 4, - ); - - const workspaceSource = topTabItemsSource.slice( - topTabItemsSource.indexOf("export const WorkspaceTopTab"), - topTabItemsSource.indexOf("WorkspaceTopTab.displayName"), - ); - assert.equal(workspaceSource.includes("handleTabCloseButtonMouseDown"), false); - assert.equal(workspaceSource.includes(" { - const tabTypes = ["plugin-view", "editor", "session", "workspace", "logView"]; - - for (const tabType of tabTypes) { - const marker = `data-tab-type="${tabType}"`; - const start = topTabItemsSource.indexOf(marker); - assert.notEqual(start, -1, marker); - const classNameAt = topTabItemsSource.indexOf("className={cn(", start); - assert.notEqual(classNameAt, -1, tabType); - const openingHandlers = topTabItemsSource.slice(start, classNameAt); - assert.match(openingHandlers, /onMouseDown=\{handleTabDragThresholdMouseDown\}/, tabType); - assert.match(openingHandlers, /onMouseUp=\{\(event\) => handleTabDragThresholdRelease\(event,/, tabType); - assert.match( - openingHandlers, - /onDragStart=\{\(event\) => \{\s*handleTabDragThresholdDragStart\(event\);\s*onTabDragStart\(event,/, - tabType, - ); - assert.match( - openingHandlers, - /onDrag=\{\(event\) => \{\s*if \(!handleTabDragThresholdDrag\(event\)\) return;\s*onTabDragStart\(event,/, - tabType, - ); - assert.match( - openingHandlers, - /onDragEnd=\{\(event\) => \{\s*handleTabDragThresholdRelease\(event,[\s\S]*?onTabDragEnd\(\);\s*\}\}/, - tabType, - ); - assert.equal(openingHandlers.includes("handleTabCloseButtonMouseDown"), false, tabType); - assert.equal(openingHandlers.includes("preventDefault"), false, tabType); - } - - assert.equal(topTabItemsSource.match(/onMouseDown=\{handleTabMiddleMouseDown\}/g)?.length ?? 0, 0); - assert.equal(topTabItemsSource.match(/handleTabDragThresholdRelease\(/g)?.length, 10); -}); - -test("session close button double click stays on the close button", () => { - let stopPropagationCount = 0; - - stopCloseButtonDoubleClickPropagation({ - stopPropagation: () => { - stopPropagationCount += 1; - }, - }); - - assert.equal(stopPropagationCount, 1); - assert.match(topTabItemsSource, /onDoubleClick=\{stopCloseButtonDoubleClickPropagation\}/); -}); - -test("main window controls keep mouse presses from taking focus", () => { - const windowControlsSource = topTabItemsSource.slice( - topTabItemsSource.indexOf("export const WindowControls"), - topTabItemsSource.indexOf("WindowControls.displayName"), - ); - - assert.match( - windowControlsSource, - /const preventWindowControlFocus: React\.MouseEventHandler = \(event\) => \{\s*event\.preventDefault\(\);\s*\};/, - ); - assert.equal(windowControlsSource.match(/onMouseDown=\{preventWindowControlFocus\}/g)?.length, 2); - const closeButton = windowControlsSource.match( - / + - - - {/* Destination - for local/remote only */} - {(draft.type === 'local' || draft.type === 'remote') && ( - <> -
- - onDraftChange({ remoteHost: e.target.value })} - /> -
- -
- - onDraftChange({ remotePort: parseInt(e.target.value) || undefined })} - /> -
- - )} - - {/* Auto Start Toggle */} -
-
- -

{t('pf.form.autoStartDesc')}

-
- onDraftChange({ autoStart: checked })} - /> -
- - {/* Auto Reconnect Toggle */} -
-
- -

{t('pf.form.autoReconnectDesc')}

-
- onDraftChange({ autoReconnect: checked })} - /> -
- - - - - -
- ); + {t('common.cancel')} + + + + ); }; export default EditPanel; diff --git a/components/port-forwarding/NewFormPanel.tsx b/components/port-forwarding/NewFormPanel.tsx index f084129a5..3a26b56ec 100644 --- a/components/port-forwarding/NewFormPanel.tsx +++ b/components/port-forwarding/NewFormPanel.tsx @@ -2,232 +2,117 @@ * Port Forwarding New Form Panel * All-in-one form for creating new port forwarding rules (skip wizard mode) */ -import { ChevronDown,Zap } from 'lucide-react'; +import { Zap } from 'lucide-react'; import React from 'react'; -import { isPortForwardingAutoReconnectEnabled } from '../../domain/portForwardingReconnect'; import { useI18n } from '../../application/i18n/I18nProvider'; -import { Host,PortForwardingRule,PortForwardingType } from '../../domain/models'; +import { Host, PortForwardingRule, PortForwardingType } from '../../domain/models'; import { cn } from '../../lib/utils'; -import { DistroAvatar } from '../DistroAvatar'; -import { TrafficDiagram } from '../TrafficDiagram'; import { - AsidePanel, - AsidePanelContent, - AsidePanelFooter, - type AsidePanelLayout, - type AsidePanelResizeProps, + AsidePanel, + AsidePanelContent, + AsidePanelFooter, + type AsidePanelLayout, + type AsidePanelResizeProps, } from '../ui/aside-panel'; import { Button } from '../ui/button'; -import { Input } from '../ui/input'; import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; -import { Label } from '../ui/label'; -import { Switch } from '../ui/switch'; +import { PortForwardRuleFields } from './PortForwardRuleFields'; import { getTypeLabel } from './utils'; export interface NewFormPanelProps extends AsidePanelResizeProps { - draft: Partial; - hosts: Host[]; - onDraftChange: (updates: Partial) => void; - onSave: () => void; - onClose: () => void; - onOpenHostSelector: () => void; - onOpenWizard: () => void; - isValid: boolean; - layout?: AsidePanelLayout; + draft: Partial; + hosts: Host[]; + onDraftChange: (updates: Partial) => void; + onSave: () => void; + onClose: () => void; + onOpenHostSelector: () => void; + onOpenWizard: () => void; + isValid: boolean; + layout?: AsidePanelLayout; } export const NewFormPanel: React.FC = ({ - draft, - hosts, - onDraftChange, - onSave, - onClose, - onOpenHostSelector, - onOpenWizard, - isValid, - layout = 'inline', - resizable = false, - persistWidthStorageKey, - resizeAriaLabel, + draft, + hosts, + onDraftChange, + onSave, + onClose, + onOpenHostSelector, + onOpenWizard, + isValid, + layout = 'inline', + resizable = false, + persistWidthStorageKey, + resizeAriaLabel, }) => { - const { t } = useI18n(); - const selectedHost = hosts.find(h => h.id === draft.hostId); + const { t } = useI18n(); - return ( - - - {/* Type Selector */} -
- {(['local', 'remote', 'dynamic'] as PortForwardingType[]).map((type) => ( - - ))} -
+ return ( + + + {/* Type Selector */} +
+ {(['local', 'remote', 'dynamic'] as PortForwardingType[]).map((type) => ( + + ))} +
- {/* Traffic Diagram */} -
- -
- - {/* Label */} -
- - onDraftChange({ label: e.target.value })} - /> -
- - {/* Local Port */} -
- - onDraftChange({ localPort: parseInt(e.target.value) || undefined })} - /> -
- - {/* Bind Address */} -
- - onDraftChange({ bindAddress: e.target.value })} - /> -
- - {/* Intermediate Host */} -
- - -
- - {/* Destination - for local/remote only */} - {(draft.type === 'local' || draft.type === 'remote') && ( - <> -
- - onDraftChange({ remoteHost: e.target.value })} - /> -
- -
- - onDraftChange({ remotePort: parseInt(e.target.value) || undefined })} - /> -
- - )} - - {/* Auto Start Toggle */} -
-
- -

{t('pf.form.autoStartDesc')}

-
- onDraftChange({ autoStart: checked })} - /> -
- - {/* Auto Reconnect Toggle */} -
-
- -

{t('pf.form.autoReconnectDesc')}

-
- onDraftChange({ autoReconnect: checked })} - /> -
-
- - -
- - - - - - {t('pf.form.openWizardTitle')} - -
-
-
- ); + +
+ + +
+ + + + + + {t('pf.form.openWizardTitle')} + +
+
+
+ ); }; export default NewFormPanel; diff --git a/components/port-forwarding/PortForwardHostKeyDialog.test.ts b/components/port-forwarding/PortForwardHostKeyDialog.test.ts deleted file mode 100644 index e17c858e2..000000000 --- a/components/port-forwarding/PortForwardHostKeyDialog.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const dialogSource = readFileSync( - new URL("./PortForwardHostKeyDialog.tsx", import.meta.url), - "utf8", -); - -const trayPanelSource = readFileSync( - new URL("../TrayPanel.tsx", import.meta.url), - "utf8", -); - -const trayPromptSource = readFileSync( - new URL("./PortForwardHostKeyTrayPrompt.tsx", import.meta.url), - "utf8", -); - -test("port-forward host-key dialog is marked so tray outside-click handling ignores it", () => { - assert.match(dialogSource, /data-port-forward-host-key-dialog="true"/); - assert.match(dialogSource, /overlayClassName="port-forward-host-key-dialog-layer"/); - assert.match(dialogSource, /w-\[calc\(100vw-1\.5rem\)\]/); - assert.match(dialogSource, /rounded-lg/); - assert.match(trayPanelSource, /data-port-forward-host-key-dialog/); - assert.match(trayPanelSource, /port-forward-host-key-dialog-layer/); -}); - -test("tray uses the lightweight host-key prompt instead of the main dialog", () => { - assert.match(trayPromptSource, /data-port-forward-host-key-tray-prompt="true"/); - assert.match(trayPromptSource, /px-3 py-2/); - assert.match(trayPromptSource, /grid-cols-\[auto_auto_1fr\] gap-1/); - assert.match(trayPromptSource, /h-6 px-1\.5 text-\[10px\]/); - assert.doesNotMatch(trayPromptSource, /border-b/); - assert.doesNotMatch(trayPromptSource, /rounded-md border p-2\.5 shadow-sm/); - assert.doesNotMatch(trayPromptSource, /lucide-react/); - assert.match(trayPanelSource, //); - assert.doesNotMatch(trayPanelSource, /; + hosts: Host[]; + onDraftChange: (updates: Partial) => void; + onOpenHostSelector: () => void; +} + +export const PortForwardRuleFields: React.FC = ({ + diagramType, + draft, + hosts, + onDraftChange, + onOpenHostSelector, +}) => { + const { t } = useI18n(); + const selectedHost = hosts.find(h => h.id === draft.hostId); + + return ( + <> + {/* Traffic Diagram */} +
+ +
+ + {/* Label */} +
+ + onDraftChange({ label: e.target.value })} + /> +
+ + {/* Local Port */} +
+ + onDraftChange({ localPort: parseInt(e.target.value) || undefined })} + /> +
+ + {/* Bind Address */} +
+ + onDraftChange({ bindAddress: e.target.value })} + /> +
+ + {/* Intermediate Host */} +
+ + +
+ + {/* Destination - for local/remote only */} + {(draft.type === 'local' || draft.type === 'remote') && ( + <> +
+ + onDraftChange({ remoteHost: e.target.value })} + /> +
+ +
+ + onDraftChange({ remotePort: parseInt(e.target.value) || undefined })} + /> +
+ + )} + + {/* Auto Start Toggle */} +
+
+ +

{t('pf.form.autoStartDesc')}

+
+ onDraftChange({ autoStart: checked })} + /> +
+ + {/* Auto Reconnect Toggle */} +
+
+ +

{t('pf.form.autoReconnectDesc')}

+
+ onDraftChange({ autoReconnect: checked })} + /> +
+ + ); +}; diff --git a/components/port-forwarding/hostKeyVerification.test.ts b/components/port-forwarding/hostKeyVerification.test.ts index dbc079186..07f80d51b 100644 --- a/components/port-forwarding/hostKeyVerification.test.ts +++ b/components/port-forwarding/hostKeyVerification.test.ts @@ -7,7 +7,7 @@ import { isPortForwardHostKeySessionId, removePortForwardHostKeyVerification, toPendingPortForwardHostKeyVerification, -} from "./hostKeyVerification.ts"; +} from "../../domain/portForwardHostKey.ts"; test("isPortForwardHostKeySessionId only accepts port-forward tunnel sessions", () => { assert.equal(isPortForwardHostKeySessionId("pf-rule-1-123456"), true); diff --git a/components/port-forwarding/hostKeyVerification.ts b/components/port-forwarding/hostKeyVerification.ts deleted file mode 100644 index d0e6d6cf1..000000000 --- a/components/port-forwarding/hostKeyVerification.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** @deprecated Import from `@/domain/portForwardHostKey` instead. */ -export { - createKnownHostFromPortForwardHostKeyInfo, - enqueuePortForwardHostKeyVerification, - isPortForwardHostKeySessionId, - removePortForwardHostKeyVerification, - toPendingPortForwardHostKeyVerification, - type PendingPortForwardHostKeyVerification, - type PortForwardHostKeyRequest, -} from "../../domain/portForwardHostKey"; diff --git a/components/settings/DebouncedTextarea.test.tsx b/components/settings/DebouncedTextarea.test.tsx deleted file mode 100644 index 5aac5fd5a..000000000 --- a/components/settings/DebouncedTextarea.test.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import test from 'node:test'; - -const root = new URL('../..', import.meta.url); - -function readProjectFile(path: string): string { - return readFileSync(join(root.pathname, path), 'utf8'); -} - -test('DebouncedTextarea keeps draft locally and commits on debounce/blur', () => { - const source = readProjectFile('components/settings/DebouncedTextarea.tsx'); - - assert.match(source, /useState\(value\)/); - assert.match(source, /onDraftChangeRef\.current\?\.\(next\)/); - assert.match(source, /setTimeout\(\(\) =>/); - assert.match(source, /onBlur/); - assert.match(source, /onCommitRef\.current\(draft\)/); - assert.match(source, /draftRef\.current !== committedRef\.current/); -}); - -test('settings appearance uses debounced custom CSS textarea with live preview', () => { - const source = readProjectFile('components/settings/tabs/SettingsAppearanceTab.tsx'); - - assert.match(source, /DebouncedTextarea/); - assert.match(source, /applyCustomCssToDocument/); - assert.match(source, /onDraftChange=\{applyCustomCssToDocument\}/); -}); diff --git a/components/settings/FontSelect.test.tsx b/components/settings/FontSelect.test.tsx deleted file mode 100644 index c52a2280e..000000000 --- a/components/settings/FontSelect.test.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { readFileSync } from 'node:fs'; -import assert from 'node:assert/strict'; -import test from 'node:test'; - -test('font picker uses the searchable combobox and preserves font previews', () => { - const source = readFileSync(new URL('./FontSelect.tsx', import.meta.url), 'utf8'); - - assert.match(source, / { - const source = readFileSync(new URL('./TerminalFontSelect.tsx', import.meta.url), 'utf8'); - - assert.match(source, / { - assert.match( - source, - /getTerminalCjkFontSelectionStatus\(\s*previewSelection,/, - ); - assert.match( - source, - /previewSelection && isFontInstalled\(previewSelection\)/, - ); -}); diff --git a/components/settings/TerminalFontSelect.test.ts b/components/settings/TerminalFontSelect.test.ts deleted file mode 100644 index b262d0d4d..000000000 --- a/components/settings/TerminalFontSelect.test.ts +++ /dev/null @@ -1,8 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("terminal font dropdown always preserves an explicit default option", () => { - const source = readFileSync(new URL("./TerminalFontSelect.tsx", import.meta.url), "utf8"); - assert.match(source, /font\.id === "" \|\| font\.id === value/); -}); diff --git a/components/settings/tabs/PluginMarketplace.interaction.test.tsx b/components/settings/tabs/PluginMarketplace.interaction.test.tsx index 4ab4639ea..a0d355840 100644 --- a/components/settings/tabs/PluginMarketplace.interaction.test.tsx +++ b/components/settings/tabs/PluginMarketplace.interaction.test.tsx @@ -6,7 +6,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer'; import { renderToStaticMarkup } from 'react-dom/server'; import { readFileSync } from 'node:fs'; import { I18nProvider } from '../../../application/i18n/I18nProvider'; -import { PluginMarketplaceContent } from './PluginMarketplace'; +import { filterPluginCatalog, PluginMarketplaceContent } from './PluginMarketplace'; import type { usePluginCatalog } from '../../../application/state/usePluginCatalog'; const infoDom = new JSDOM(''); @@ -180,3 +180,10 @@ test('a mirror cannot claim another source installation or offer cross-source re assert.match(detail, /https:\/\/plugins.netcatty.app/); assert.match(detail, /disabled=""[^>]*>Install this version/); }); + +test('catalog search matches name, author and description without case sensitivity', () => { + const sample = [{ id: 'a', name: 'Starter', author: 'Netcatty', description: 'Local greeting' }] as NetcattyPluginCatalogEntry[]; + for (const query of ['starter', 'NETCATTY', ' greeting ']) assert.equal(filterPluginCatalog(sample, query).length, 1); + assert.equal(filterPluginCatalog(sample, 'unrelated').length, 0); + assert.equal(filterPluginCatalog(sample, '').length, 1); +}); diff --git a/components/settings/tabs/PluginMarketplace.test.ts b/components/settings/tabs/PluginMarketplace.test.ts deleted file mode 100644 index 73024d858..000000000 --- a/components/settings/tabs/PluginMarketplace.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { filterPluginCatalog } from './PluginMarketplace'; -test('catalog search matches name, author and description without case sensitivity', () => { - const entries = [{ id: 'a', name: 'Starter', author: 'Netcatty', description: 'Local greeting' }] as NetcattyPluginCatalogEntry[]; - for (const query of ['starter', 'NETCATTY', ' greeting ']) assert.equal(filterPluginCatalog(entries, query).length, 1); - assert.equal(filterPluginCatalog(entries, 'unrelated').length, 0); - assert.equal(filterPluginCatalog(entries, '').length, 1); -}); diff --git a/components/settings/tabs/SettingsFileAssociationsTab.test.ts b/components/settings/tabs/SettingsFileAssociationsTab.test.ts deleted file mode 100644 index 3feb8e241..000000000 --- a/components/settings/tabs/SettingsFileAssociationsTab.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./SettingsFileAssociationsTab.tsx", import.meta.url), "utf8"); - -test("SFTP settings imports the shared Toggle used by its option rows", () => { - assert.match(source, / { - assert.match( - source, - / { - assert.match(source, /import \{ ConfirmDialog \} from "\.\.\/\.\.\/ui\/confirm-dialog";/); - assert.doesNotMatch(source, /window\.confirm|globalThis\.confirm|\bconfirm\(/); - assert.match( - source, - /const \[removeConfirmExt, setRemoveConfirmExt\] = useState\(null\);/, - ); - - const handleRemove = functionBody("handleRemove"); - assert.match(handleRemove, /setRemoveConfirmExt\(extension\)/); - assert.doesNotMatch(handleRemove, /removeAssociation\(/); - - const handleConfirm = functionBody("handleConfirmRemove"); - assert.match(handleConfirm, /if \(!removeConfirmExt\) return;/); - assert.match(handleConfirm, /removeAssociation\(removeConfirmExt\);\s*setRemoveConfirmExt\(null\);/); - - const dialogStart = source.indexOf(" ( - readFileSync(new URL("./AppLockSettingsSection.tsx", import.meta.url), "utf8") -); - -test("disabling app lock does not trigger a second renderer-side unlock request", () => { - const source = readAppLockSectionSource(); - - assert.doesNotMatch(source, /unlockApp\?\.\(/); - assert.doesNotMatch(source, /unlockApp\?:/); -}); - -test("app lock setup starts with password setup instead of a misleading enable toggle", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /!hasPassword \? \(/); - assert.match(source, /settings\.appLock\.setupTitle/); - assert.match(source, /settings\.appLock\.setupDescription/); - assert.match(source, /settings\.appLock\.manageTitle/); - assert.doesNotMatch( - source, - /hasAppLockPassword \? t\("settings\.appLock\.enableDesc"\) : t\("settings\.appLock\.enableAfterPassword"\)/, - ); -}); - -test("app lock section exposes settings-search anchors", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /anchorId="system-app-lock"/); -}); - -test("app lock disable handler uses its modal current password field", () => { - const source = readAppLockSectionSource(); - const handlerStart = source.indexOf("const handleDisable = useCallback"); - const handlerEnd = source.indexOf("const handleSavePassword", handlerStart); - const handlerSource = source.slice(handlerStart, handlerEnd); - - assert.match(handlerSource, /requestAppLockDisable\(disablePassword\)/); - assert.match(handlerSource, /disablePassword,/); - assert.doesNotMatch(source, /handleAppLockEnabledChange/); -}); - -test("app lock page uses settings rows and moves password forms into a dialog", () => { - const source = readAppLockSectionSource(); - const dialogStart = source.indexOf('/); - assert.match(source, / dialogStart, "password inputs should only render inside the dialog"); - assert.doesNotMatch(source.slice(0, dialogStart), / { - const source = readAppLockSectionSource(); - - assert.ok(source.includes("newPassword.length === 0")); - assert.ok(source.includes("confirmPassword.length === 0")); - assert.ok(!source.includes("newPassword.trim()")); - assert.ok(!source.includes("confirmPassword.trim()")); -}); - -test("app lock system unlock setting uses bridge-provided platform label", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /showSystemUnlock/); - assert.match(source, /appLockSystemUnlockStatus\.label/); - assert.match(source, /settings\.appLock\.systemUnlock\.label/); - assert.doesNotMatch(source, /navigator\.platform/); -}); - -test("app lock system unlock enablement does not require current password in settings", () => { - const source = readAppLockSectionSource(); - const handlerStart = source.indexOf("const handleSystemUnlockChange = useCallback"); - const handlerEnd = source.indexOf("const handleAutoPromptChange", handlerStart); - const handlerSource = source.slice(handlerStart, handlerEnd); - - assert.match(handlerSource, /setAppLockSystemUnlockEnabled\(\{/); - assert.doesNotMatch(handlerSource, /appLockSystemUnlockPassword/); - assert.doesNotMatch(handlerSource, /currentPassword:/); - - const systemUnlockStart = source.indexOf("{showSystemUnlock"); - const systemUnlockEnd = source.indexOf("settings.appLock.changePasswordTitle", systemUnlockStart); - const systemUnlockSection = source.slice(systemUnlockStart, systemUnlockEnd); - assert.doesNotMatch(systemUnlockSection, /settings\.appLock\.currentPassword/); -}); - -test("app lock system unlock setting hides when unavailable unless already enabled", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /appLockSystemUnlockStatus\.available \|\| appLockSettings\.systemUnlockEnabled/); - // Already-enabled toggle stays clickable when unavailable so the user can disable. - assert.match( - source, - /disabled=\{\s*isSavingSystemUnlock\s*\|\|\s*\(!appLockSystemUnlockStatus\.available && !appLockSettings\.systemUnlockEnabled\)\s*\}/, - ); -}); - -test("app lock system unlock exposes auto prompt as a child option", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /settings\.appLock\.systemUnlock\.autoPrompt\.label/); - assert.match(source, /settings\.appLock\.systemUnlock\.autoPrompt\.desc/); - assert.match(source, /appLockSettings\.systemUnlockAutoPromptEnabled/); - assert.match(source, /appLockSettings\.systemUnlockEnabled/); -}); - -test("app lock system unlock handles native verification failures", () => { - const source = readAppLockSectionSource(); - - assert.match(source, /'cancelled' \| 'failed'/); - assert.match(source, /result\.error === 'cancelled'/); - assert.match(source, /case 'failed':\s*return t\('settings\.appLock\.systemUnlock\.unavailable'\)/); -}); - -test("app lock disable explains that turning it off removes the saved password", () => { - const englishLocale = readFileSync(new URL("../../../application/i18n/locales/en/core.ts", import.meta.url), "utf8"); - - assert.match(englishLocale, /saved password will be removed/); - assert.match(englishLocale, /requires creating a new one/); -}); diff --git a/components/settings/tabs/SettingsTerminalTab.test.ts b/components/settings/tabs/SettingsTerminalTab.test.ts deleted file mode 100644 index 25d996c7c..000000000 --- a/components/settings/tabs/SettingsTerminalTab.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./SettingsTerminalTab.tsx", import.meta.url), "utf8"); - -test("terminal settings expose cursor line highlight toggle", () => { - assert.match(source, /settings\.terminal\.cursor\.highlightLine/); - assert.match(source, /checked=\{terminalSettings\.highlightCursorLine\}/); - assert.match(source, /updateTerminalSetting\("highlightCursorLine", v\)/); -}); - -test("terminal settings expose a bounded bar cursor width control", () => { - assert.match(source, /settings\.terminal\.cursor\.barWidth/); - assert.match(source, /min=\{1\}/); - assert.match(source, /max=\{4\}/); - assert.match(source, /value=\{terminalSettings\.cursorBarWidth\}/); - assert.match(source, /aria-label=\{t\("settings\.terminal\.cursor\.barWidth"\)\}/); - assert.match(source, /updateTerminalSetting\("cursorBarWidth", parseInt\(e\.target\.value\)\)/); -}); - -test("terminal settings hide terminal theme pickers while following app theme", () => { - assert.match(source, /\{!followAppTerminalTheme && \(/); - assert.doesNotMatch(source, /settings\.terminal\.theme\.followingTheme/); -}); - -test("terminal settings only update the legacy global theme for the active mode", () => { - assert.match(source, /if \(themeModalSlot === resolvedTheme\) \{\s*setTerminalThemeId\(id\);/); -}); - -test("terminal settings expose host key verification toggle", () => { - assert.match(source, /settings\.terminal\.connection\.verifyHostKeys/); - assert.match(source, /checked=\{terminalSettings\.verifyHostKeys\}/); - assert.match(source, /updateTerminalSetting\("verifyHostKeys", v\)/); -}); - -test("terminal settings expose SSH auto reconnect toggle", () => { - assert.match(source, /settings\.terminal\.connection\.sshAutoReconnectEnabled/); - assert.match(source, /checked=\{terminalSettings\.sshAutoReconnectEnabled\}/); - assert.match(source, /updateTerminalSetting\("sshAutoReconnectEnabled", v\)/); -}); - -test("terminal settings expose the host information bar toggle", () => { - assert.match(source, /checked=\{terminalSettings\.showHostInfoBar\}/); - assert.match(source, /updateTerminalSetting\("showHostInfoBar", v\)/); -}); - -test("terminal settings expose host information title mode when the bar is shown", () => { - assert.match(source, /terminalSettings\.showHostInfoBar && \(/); - assert.match(source, /updateTerminalSetting\("hostInfoBarTitleMode"/); - assert.match(source, /settings\.terminal\.hostInfoBar\.titleMode/); -}); diff --git a/components/settings/tabs/ai/agentConfigEnv.ts b/components/settings/tabs/ai/agentConfigEnv.ts new file mode 100644 index 000000000..b12ff5701 --- /dev/null +++ b/components/settings/tabs/ai/agentConfigEnv.ts @@ -0,0 +1,49 @@ +/** + * Shared env-line parser/serializer for external AI agent config editors + * (Claude Code, CodeBuddy, etc.). + */ + +export function parseEnvLines(text: string): Record { + const out: Record = {}; + for (const rawLine of String(text || "").split("\n")) { + const line = rawLine.trim(); + if (!line || line.startsWith("#")) continue; + const eq = line.indexOf("="); + if (eq <= 0) continue; + const key = line.slice(0, eq).trim(); + const value = line.slice(eq + 1).trim(); + if (key) out[key] = value; + } + return out; +} + +export function serializeEnvLines(env: Record): string { + return Object.entries(env) + .map(([k, v]) => `${k}=${v}`) + .join("\n"); +} + +export function extractUnmanagedEnvText( + env: Record | undefined, + managedKeys: ReadonlySet, +): string { + if (!env) return ""; + const rest: Record = {}; + for (const [k, v] of Object.entries(env)) { + if (managedKeys.has(k)) continue; + rest[k] = v; + } + return serializeEnvLines(rest); +} + +export function mergeManagedAndUserEnv( + managedEntries: Record, + envText: string, + managedKeys: ReadonlySet, +): Record | undefined { + const next: Record = { ...managedEntries }; + const parsed = parseEnvLines(envText); + for (const key of managedKeys) delete parsed[key]; + Object.assign(next, parsed); + return Object.keys(next).length > 0 ? next : undefined; +} diff --git a/components/settings/tabs/ai/claudeConfigEnv.ts b/components/settings/tabs/ai/claudeConfigEnv.ts index 301640e34..69f59cd23 100644 --- a/components/settings/tabs/ai/claudeConfigEnv.ts +++ b/components/settings/tabs/ai/claudeConfigEnv.ts @@ -6,6 +6,15 @@ * is preserved across edits but never shown in the env editor. */ +import { + extractUnmanagedEnvText, + mergeManagedAndUserEnv, + parseEnvLines, + serializeEnvLines, +} from "./agentConfigEnv"; + +export { parseEnvLines, serializeEnvLines }; + const CONFIG_DIR_KEY = "CLAUDE_CONFIG_DIR"; // netcatty marker carrying the claude SDK `settings` option (a settings.json // path or inline JSON). Extracted in the main process and passed to the SDK as @@ -14,38 +23,15 @@ const CONFIG_DIR_KEY = "CLAUDE_CONFIG_DIR"; const SETTINGS_KEY = "NETCATTY_CLAUDE_SETTINGS"; const MANAGED_KEYS = new Set(["CLAUDE_CODE_EXECUTABLE", CONFIG_DIR_KEY, SETTINGS_KEY]); -export function parseEnvLines(text: string): Record { - const out: Record = {}; - for (const rawLine of String(text || "").split("\n")) { - const line = rawLine.trim(); - if (!line || line.startsWith("#")) continue; - const eq = line.indexOf("="); - if (eq <= 0) continue; - const key = line.slice(0, eq).trim(); - const value = line.slice(eq + 1).trim(); - if (key) out[key] = value; - } - return out; -} - -export function serializeEnvLines(env: Record): string { - return Object.entries(env) - .map(([k, v]) => `${k}=${v}`) - .join("\n"); -} - export function splitClaudeEnv( env: Record | undefined, ): { configDir: string; settingsPath: string; envText: string } { if (!env) return { configDir: "", settingsPath: "", envText: "" }; - const configDir = env[CONFIG_DIR_KEY] ?? ""; - const settingsPath = env[SETTINGS_KEY] ?? ""; - const rest: Record = {}; - for (const [k, v] of Object.entries(env)) { - if (MANAGED_KEYS.has(k)) continue; - rest[k] = v; - } - return { configDir, settingsPath, envText: serializeEnvLines(rest) }; + return { + configDir: env[CONFIG_DIR_KEY] ?? "", + settingsPath: env[SETTINGS_KEY] ?? "", + envText: extractUnmanagedEnvText(env, MANAGED_KEYS), + }; } export function buildClaudeEnv( @@ -54,22 +40,15 @@ export function buildClaudeEnv( settingsPath: string, envText: string, ): Record | undefined { - const next: Record = {}; - // Preserve discovery-owned key if present. + const managed: Record = {}; const exe = prevEnv?.CLAUDE_CODE_EXECUTABLE; - if (exe) next.CLAUDE_CODE_EXECUTABLE = exe; + if (exe) managed.CLAUDE_CODE_EXECUTABLE = exe; const trimmedDir = String(configDir || "").trim(); - if (trimmedDir) next[CONFIG_DIR_KEY] = trimmedDir; + if (trimmedDir) managed[CONFIG_DIR_KEY] = trimmedDir; const trimmedSettings = String(settingsPath || "").trim(); - if (trimmedSettings) next[SETTINGS_KEY] = trimmedSettings; + if (trimmedSettings) managed[SETTINGS_KEY] = trimmedSettings; - // Drop managed keys if a user typed them into the free-text editor — the - // dedicated fields and path discovery own these keys. - const parsed = parseEnvLines(envText); - for (const key of MANAGED_KEYS) delete parsed[key]; - Object.assign(next, parsed); - - return Object.keys(next).length > 0 ? next : undefined; + return mergeManagedAndUserEnv(managed, envText, MANAGED_KEYS); } diff --git a/components/settings/tabs/ai/codebuddyConfigEnv.ts b/components/settings/tabs/ai/codebuddyConfigEnv.ts index 8e29c9d8c..ae63dfb57 100644 --- a/components/settings/tabs/ai/codebuddyConfigEnv.ts +++ b/components/settings/tabs/ai/codebuddyConfigEnv.ts @@ -9,45 +9,29 @@ * * The SDK supports CODEBUDDY_API_KEY (via options.env), but the CLI itself * does not. CODEBUDDY_INTERNET_ENVIRONMENT is managed as a first-class field. - * Users who need CODEBUDDY_API_KEY or CODEBUDDY_AUTH_TOKEN should set them - * in the free-text environment editor or in their shell profile. */ +import { + extractUnmanagedEnvText, + mergeManagedAndUserEnv, + parseEnvLines, + serializeEnvLines, +} from "./agentConfigEnv"; + +export { parseEnvLines, serializeEnvLines }; + const INTERNET_ENV_VAR = "CODEBUDDY_INTERNET_ENVIRONMENT"; const CODE_PATH_KEY = "CODEBUDDY_CODE_PATH"; const MANAGED_KEYS = new Set([INTERNET_ENV_VAR, CODE_PATH_KEY]); -export function parseEnvLines(text: string): Record { - const out: Record = {}; - for (const rawLine of String(text || "").split("\n")) { - const line = rawLine.trim(); - if (!line || line.startsWith("#")) continue; - const eq = line.indexOf("="); - if (eq <= 0) continue; - const key = line.slice(0, eq).trim(); - const value = line.slice(eq + 1).trim(); - if (key) out[key] = value; - } - return out; -} - -export function serializeEnvLines(env: Record): string { - return Object.entries(env) - .map(([k, v]) => `${k}=${v}`) - .join("\n"); -} - export function splitCodebuddyEnv( env: Record | undefined, ): { internetEnv: string; envText: string } { if (!env) return { internetEnv: "", envText: "" }; - const internetEnv = env[INTERNET_ENV_VAR] ?? ""; - const rest: Record = {}; - for (const [k, v] of Object.entries(env)) { - if (MANAGED_KEYS.has(k)) continue; - rest[k] = v; - } - return { internetEnv, envText: serializeEnvLines(rest) }; + return { + internetEnv: env[INTERNET_ENV_VAR] ?? "", + envText: extractUnmanagedEnvText(env, MANAGED_KEYS), + }; } export function buildCodebuddyEnv( @@ -55,19 +39,13 @@ export function buildCodebuddyEnv( internetEnv: string, envText: string, ): Record | undefined { - const next: Record = {}; + const managed: Record = {}; const trimmedInternetEnv = String(internetEnv || "").trim(); - if (trimmedInternetEnv) next[INTERNET_ENV_VAR] = trimmedInternetEnv; + if (trimmedInternetEnv) managed[INTERNET_ENV_VAR] = trimmedInternetEnv; - // Preserve auto-injected CODEBUDDY_CODE_PATH across edits. const codePath = prevEnv?.[CODE_PATH_KEY]; - if (codePath) next[CODE_PATH_KEY] = codePath; + if (codePath) managed[CODE_PATH_KEY] = codePath; - // Drop managed keys if a user typed them into the free-text editor - const parsed = parseEnvLines(envText); - for (const key of MANAGED_KEYS) delete parsed[key]; - Object.assign(next, parsed); - - return Object.keys(next).length > 0 ? next : undefined; + return mergeManagedAndUserEnv(managed, envText, MANAGED_KEYS); } diff --git a/components/sftp/SftpContext.tsx b/components/sftp/SftpContext.tsx index b00ab50b3..d83da40c2 100644 --- a/components/sftp/SftpContext.tsx +++ b/components/sftp/SftpContext.tsx @@ -134,9 +134,6 @@ export interface SftpPaneCallbacksContextValue { rightCallbacks: SftpPaneCallbacks; } -/** @deprecated Prefer useSftpHosts / useSftpPaneCallbacks to avoid cross-churn. */ -export type SftpContextValue = SftpHostsContextValue & SftpPaneCallbacksContextValue; - export interface SftpDragContextValue { draggedFiles: (SftpTransferSource & { side: "left" | "right" })[] | null; dragCallbacks: SftpDragCallbacks; @@ -146,19 +143,6 @@ const SftpHostsContext = createContext(null); const SftpPaneCallbacksContext = createContext(null); const SftpDragContext = createContext(null); -/** @deprecated Prefer selective hooks; this re-renders on hosts OR callbacks churn. */ -export const useSftpContext = (): SftpContextValue => { - const hosts = useContext(SftpHostsContext); - const callbacks = useContext(SftpPaneCallbacksContext); - if (!hosts || !callbacks) { - throw new Error("useSftpContext must be used within SftpContextProvider"); - } - return useMemo( - () => ({ ...hosts, ...callbacks }), - [hosts, callbacks], - ); -}; - // Hook to get callbacks for a specific side export const useSftpPaneCallbacks = (side: "left" | "right"): SftpPaneCallbacks => { const context = useContext(SftpPaneCallbacksContext); diff --git a/components/sftp/SftpHostPicker.test.ts b/components/sftp/SftpHostPicker.test.ts deleted file mode 100644 index 41b7ae658..000000000 --- a/components/sftp/SftpHostPicker.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const source = fs.readFileSync( - path.join(path.dirname(fileURLToPath(import.meta.url)), "SftpHostPicker.tsx"), - "utf8", -); - -test("sftp host picker rows reuse quick switcher selection classes", () => { - assert.match(source, /getQuickSwitcherRowStateClass/); - assert.match(source, /shouldUseQuickSwitcherPointerNavigation/); - assert.match(source, /isKeyboardNavigating/); - assert.match(source, /onMouseMove=\{\(event\) => handlePointerHover\(event\.movementX, event\.movementY\)\}/); - assert.match( - source, - /const handlePointerHover = useCallback\(\(movementX: number, movementY: number\) => \{[\s\S]*if \(!isKeyboardNavigatingRef\.current\) return;[\s\S]*setIsKeyboardNavigating\(false\);[\s\S]*\}, \[\]\);/, - ); - assert.doesNotMatch( - source, - /const handlePointerHover = useCallback\(\(itemIndex: number, movementX: number, movementY: number\) => \{[\s\S]*setSelectedIndex\(itemIndex\);/, - ); -}); - -test("sftp host picker uses single-line quick switcher row layout", () => { - assert.match( - source, - /className=\{`flex items-center justify-between px-4 py-2\.5 cursor-pointer transition-colors \$\{getQuickSwitcherRowStateClass/, - ); - assert.match( - source, - /className="h-6 w-6 rounded flex items-center justify-center text-muted-foreground"/, - ); - assert.match( - source, - /\{t\('sftp\.picker\.local\.title'\)\}<\/span>/, - ); - assert.match( - source, - /\{host\.label\}<\/span>/, - ); - assert.match( - source, - /className="ml-3 shrink-0 text-\[11px\] text-muted-foreground truncate max-w-\[12rem\]"/, - ); - assert.match(source, /formatHostMeta\(host\)/); - assert.doesNotMatch(source, /bg-primary\/10 border border-primary\/30/); - assert.doesNotMatch(source, /text-xs text-muted-foreground truncate/); -}); - -test("sftp host picker passes sourceSessionId for sudo connected hosts", () => { - assert.match(source, /sftpSourceSessionIdForHost/); - assert.match( - source, - /const sourceSessionId = sftpSourceSessionIdForHost\(\s*item\.entry\.host,\s*item\.entry\.sessionId,\s*\);/, - ); - assert.match( - source, - /onSelectHost\(\s*item\.entry\.host,\s*sourceSessionId \? \{ sourceSessionId \} : undefined,\s*\)/, - ); -}); - -test("sftp host picker virtualizes the host list", () => { - assert.match(source, /VariableSizeVirtualList/); - assert.match(source, /data-host-picker-virtual="sftp"/); - assert.match(source, /itemIndexToVisualIndex/); - assert.doesNotMatch(source, /filteredHosts\.map\(\(host\) =>/); - // Connected-only results must not leave a dangling empty Hosts header. - assert.match(source, /if \(filteredHosts\.length > 0\) \{\s*pushHeader\('header:hosts'/); - assert.match( - source, - /else if \(filteredConnectedHosts\.length === 0\) \{\s*pushHeader\('header:hosts'/, - ); - // Short lists shrink; long lists cap at 360px (not a forced blank 360px dialog). - assert.match(source, /Math\.min\(360, Math\.max\(total, 1\)\)/); - assert.match(source, /listViewportHeight/); - assert.doesNotMatch(source, /className="h-\[360px\]"/); -}); diff --git a/components/sftp/hooks/useLocalSftpBookmarks.ts b/components/sftp/hooks/useLocalSftpBookmarks.ts deleted file mode 100644 index 438e3a69d..000000000 --- a/components/sftp/hooks/useLocalSftpBookmarks.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/localSftpBookmarks` instead. */ -export { - useLocalSftpBookmarks, - subscribeLocalSftpBookmarks, - getLocalSftpBookmarksSnapshot, - rehydrateLocalSftpBookmarks, - setLocalSftpBookmarks, -} from "../../../application/state/sftp/localSftpBookmarks"; diff --git a/components/sftp/hooks/useSftpClipboard.ts b/components/sftp/hooks/useSftpClipboard.ts deleted file mode 100644 index f92812805..000000000 --- a/components/sftp/hooks/useSftpClipboard.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/sftpClipboardStore` instead. */ -export { - sftpClipboardStore, - useSftpClipboard, - type SftpClipboardFile, -} from "../../../application/state/sftp/sftpClipboardStore"; diff --git a/components/sftp/hooks/useSftpDialogAction.ts b/components/sftp/hooks/useSftpDialogAction.ts deleted file mode 100644 index 2eb979878..000000000 --- a/components/sftp/hooks/useSftpDialogAction.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/sftpDialogActionStore` instead. */ -export { - sftpDialogActionStore, - useSftpDialogAction, - useSftpDialogActionHandler, -} from "../../../application/state/sftp/sftpDialogActionStore"; diff --git a/components/sftp/hooks/useSftpFocusedPane.ts b/components/sftp/hooks/useSftpFocusedPane.ts deleted file mode 100644 index 1a2128e1b..000000000 --- a/components/sftp/hooks/useSftpFocusedPane.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/sftpFocusStore` instead. */ -export { - sftpFocusStore, - useSftpFocusedSide, - type SftpFocusedSide, -} from "../../../application/state/sftp/sftpFocusStore"; diff --git a/components/sftp/hooks/useSftpHostViewMode.ts b/components/sftp/hooks/useSftpHostViewMode.ts deleted file mode 100644 index 1851fc775..000000000 --- a/components/sftp/hooks/useSftpHostViewMode.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/sftpHostViewModeStore` instead. */ -export { - getHostViewMode, - setHostViewMode, - useSftpHostViewMode, -} from "../../../application/state/sftp/sftpHostViewModeStore"; diff --git a/components/sftp/hooks/useSftpPaneSorting.ts b/components/sftp/hooks/useSftpPaneSorting.ts deleted file mode 100644 index 6ecb2cc0b..000000000 --- a/components/sftp/hooks/useSftpPaneSorting.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/useSftpPaneSorting` instead. */ -export { - useSftpPaneSorting, - type UseSftpPaneSortingResult, -} from "../../../application/state/sftp/useSftpPaneSorting"; diff --git a/components/sftp/hooks/useSftpTreeSelectionStore.ts b/components/sftp/hooks/useSftpTreeSelectionStore.ts deleted file mode 100644 index 5f2627a8e..000000000 --- a/components/sftp/hooks/useSftpTreeSelectionStore.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** @deprecated Import from `@/application/state/sftp/sftpTreeSelectionStore` instead. */ -export { - sftpTreeSelectionStore, - useSftpTreeSelectionState, - type SftpTreeSelectionItem, -} from "../../../application/state/sftp/sftpTreeSelectionStore"; diff --git a/components/sftp/sftpColumnVisibilityIntegration.test.ts b/components/sftp/sftpColumnVisibilityIntegration.test.ts deleted file mode 100644 index 8e0a8d595..000000000 --- a/components/sftp/sftpColumnVisibilityIntegration.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; - -const readSource = (fileName: string): string => - readFileSync(new URL(fileName, import.meta.url), 'utf8'); - -test('list and tree SFTP views share column visibility and keyboard-accessible menus', () => { - const listSource = readSource('./SftpPaneFileList.tsx'); - const treeSource = readSource('./SftpPaneTreeView.tsx'); - const treeNodeSource = readSource('./SftpPaneTreeNode.tsx'); - const columnMenuSource = readSource('./SftpColumnMenuItems.tsx'); - - for (const source of [listSource, treeSource]) { - assert.match(source, /buildSftpColumnTemplate\(columnWidths, visibleColumns\)/); - assert.match(source, /SftpColumnMenuItems/); - assert.match(source, /isSftpColumnMenuKey/); - assert.match(source, /tabIndex=\{0\}/); - } - - assert.match(columnMenuSource, /ContextMenuCheckboxItem/); - assert.match( - listSource, - /import\s*\{[^}]*\bContextMenuSeparator\b[^}]*\}\s*from "\.\.\/ui\/context-menu";/, - ); - - assert.match(treeNodeSource, /visibleColumns\.modified/); - assert.match(treeNodeSource, /visibleColumns\.size/); - assert.match(treeNodeSource, /visibleColumns\.type/); - assert.match(treeNodeSource, /visibleColumns\.owner/); - assert.match(columnMenuSource, /'modified', 'size', 'type', 'owner'/); - - const paneCallbacksSource = readFileSync(new URL('./hooks/useSftpViewPaneCallbacks.ts', import.meta.url), 'utf8'); - assert.match(paneCallbacksSource, /owner: f\.owner/); -}); diff --git a/components/sftp/sftpLocatePathInTerminalSafety.test.ts b/components/sftp/sftpLocatePathInTerminalSafety.test.ts index c2182c220..510e1961d 100644 --- a/components/sftp/sftpLocatePathInTerminalSafety.test.ts +++ b/components/sftp/sftpLocatePathInTerminalSafety.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import test from "node:test"; -import { remoteSoftwareRequiresSingleChannel } from "../../domain/singleChannelSshBanner.shared.mjs"; +import { remoteSoftwareRequiresSingleChannel } from "../../domain/singleChannelSshBanner.shared.cjs"; import { sftpRequiresDedicatedLogin } from "../../domain/sftpDedicatedLogin"; const sidePanelSource = readFileSync(new URL("../SftpSidePanel.tsx", import.meta.url), "utf8"); diff --git a/components/sftp/sftpSidePanelReconnectSafety.test.ts b/components/sftp/sftpSidePanelReconnectSafety.test.ts deleted file mode 100644 index 9e8014028..000000000 --- a/components/sftp/sftpSidePanelReconnectSafety.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const sidePanelSource = readFileSync(new URL("../SftpSidePanel.tsx", import.meta.url), "utf8"); -const tabBridgeSource = readFileSync( - new URL("../terminalLayer/TerminalLayerTabBridge.tsx", import.meta.url), - "utf8", -); - -test("SFTP side panel rebinds after same-tab SSH start-over", () => { - assert.match(sidePanelSource, /shouldRebindSftpSidePanelSourceSession\(/); - assert.match(sidePanelSource, /shouldDeferSftpSidePanelAutoConnectForSession\(/); - assert.match(sidePanelSource, /lastSourceSessionStatusRef/); - assert.match( - sidePanelSource, - /previousStatus:\s*lastSourceSessionStatusRef\.current/, - ); - // Reuse the terminal transport only when SSH is connected, or when a strict - // pending source id is already pinned. A dedicated login (bastion banner, - // network-vendor banner, or network-device mode) never reuses that - // transport. A linked id may arrive while reconnecting. - assert.match( - sidePanelSource, - /const dedicatedSftpLogin = sftpRequiresDedicatedLogin\(\{/, - ); - assert.match( - sidePanelSource, - /const reuseTerminalTransport = !dedicatedSftpLogin && \(\s*Boolean\(pendingStrictSourceSessionId\) \|\| activeSessionStatus === "connected"\s*\);/, - ); - assert.match( - sidePanelSource, - /sourceSessionId: reuseTerminalTransport\s*\?\s*\(pendingStrictSourceSessionId \?\? \(activeSessionId \?\? undefined\)\)\s*: undefined/, - ); - assert.match( - sidePanelSource, - /requireSourceSessionReuse: reuseTerminalTransport && Boolean\(pendingStrictSourceSessionId\)/, - ); - assert.match(sidePanelSource, /resolveSftpSidePanelTrackedSourceStatusUpdate\(/); - assert.match( - sidePanelSource, - /trackedSessionId = lastSourceSessionIdRef\.current/, - ); - assert.match(sidePanelSource, /if \(activeSessionId\) return;/); -}); - -test("terminal layer keeps the linked SFTP session id while SSH reconnects", () => { - assert.match(tabBridgeSource, /isTerminalSessionEligibleForSftpReuse\(session\)/); - assert.doesNotMatch( - tabBridgeSource, - /activeTerminalSessionIdForSftp[\s\S]*canReuseTerminalConnection\(session\)/, - ); -}); diff --git a/components/systemManager/GpuManagerTab.test.ts b/components/systemManager/GpuManagerTab.test.ts deleted file mode 100644 index d393061b2..000000000 --- a/components/systemManager/GpuManagerTab.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -test("gpu tab keeps loading while accelerator query is pending", () => { - const source = readFileSync(new URL("./GpuManagerTab.tsx", import.meta.url), "utf8"); - assert.match(source, /setGpuListPending\(true\)/); - assert.match(source, /if \(result\.pending\)/); - assert.match(source, /isRefreshActive = loading \|\| gpuListPending/); - assert.match(source, /if \(!data\)/); - assert.doesNotMatch( - source, - /if \(result\.pending\) return null;\s*\n\s*if \(!result\.success\)/, - ); -}); - -test("gpu tab still renders compute processes when device list is empty", () => { - const source = readFileSync(new URL("./GpuManagerTab.tsx", import.meta.url), "utf8"); - assert.match(source, /if \(!devices\.length && !processes\.length\)/); - assert.match(source, /processes\.map\(\(process\) =>/); -}); - -test("gpu tab passes null utilization to ResourceBar instead of zero", () => { - const source = readFileSync(new URL("./GpuManagerTab.tsx", import.meta.url), "utf8"); - assert.match(source, /value=\{util\}/); - assert.match(source, /value=\{memPct\}/); - assert.doesNotMatch(source, /value=\{util \?\? 0\}/); - assert.doesNotMatch(source, /value=\{memPct \?\? 0\}/); -}); - -test("gpu tab keeps a compact sparkline history like overview/nvtop charts", () => { - const source = readFileSync(new URL("./GpuManagerTab.tsx", import.meta.url), "utf8"); - assert.match(source, /HISTORY_LIMIT/); - assert.match(source, /GpuSparkline/); - assert.match(source, /historyByDevice/); - assert.match(source, /setHistoryByDevice/); - // Sparklines sit under the resource bars, not in a side column. - assert.doesNotMatch(source, /grid-cols-\[minmax\(0,1fr\)_72px\]/); - assert.match(source, /grid grid-cols-2 gap-x-3/); -}); - -test("gpu device card uses vendor vector badges", () => { - const source = readFileSync(new URL("./GpuManagerTab.tsx", import.meta.url), "utf8"); - const badgeSource = readFileSync(new URL("./GpuVendorBadge.tsx", import.meta.url), "utf8"); - assert.match(source, /GpuVendorBadge/); - assert.match(source, /vendor=\{device\.vendor\}/); - // Process rows share the same display helper (no deleted vendorLabel). - assert.match(source, /vendorDisplayLabel\(process\.vendor/); - assert.doesNotMatch(source, /vendorLabel\(/); - assert.match(badgeSource, /NVIDIA_PATH/); - assert.match(badgeSource, /HUAWEI_PATH/); - assert.match(badgeSource, /vendor === 'nvidia'/); - assert.match(badgeSource, /vendor === 'ascend'/); -}); - -test("resource bar animates width and uses load-aware tones", () => { - const source = readFileSync(new URL("./ResourceBar.tsx", import.meta.url), "utf8"); - assert.match(source, /transition-\[width,background-color\]/); - assert.match(source, /bg-amber-500/); - assert.match(source, /bg-destructive/); -}); diff --git a/components/systemManager/GpuVendorBadge.test.ts b/components/systemManager/GpuVendorBadge.test.ts deleted file mode 100644 index 2312103a0..000000000 --- a/components/systemManager/GpuVendorBadge.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { readFileSync } from 'node:fs'; - -test('gpu vendor badge embeds monochrome vector marks for nvidia and ascend', () => { - const source = readFileSync(new URL('./GpuVendorBadge.tsx', import.meta.url), 'utf8'); - assert.match(source, /viewBox="0 0 24 24"/); - assert.match(source, /fill-current/); - assert.match(source, /NVIDIA_PATH/); - assert.match(source, /HUAWEI_PATH/); - assert.match(source, /GpuVendorBadge/); - assert.match(source, /vendorDisplayLabel/); - // Mark is decorative; text label is the accessible name (no double announce). - assert.match(source, /aria-hidden="true"/); - assert.doesNotMatch(source, /role="img"/); -}); diff --git a/components/systemManager/SystemManagerSidePanel.tsx b/components/systemManager/SystemManagerSidePanel.tsx index 07d1e5098..73d63f0ea 100644 --- a/components/systemManager/SystemManagerSidePanel.tsx +++ b/components/systemManager/SystemManagerSidePanel.tsx @@ -5,7 +5,7 @@ import { useI18n } from '../../application/i18n/I18nProvider'; import { SYSTEM_MANAGER_TAB_LAYOUT_DEFAULTS } from '../../application/state/systemManagerTabLayout'; import { useSystemManagerBackend } from '../../application/state/useSystemManagerBackend'; import { useTerminalBackend } from '../../application/state/useTerminalBackend'; -import { remoteSoftwareRequiresSingleChannel } from '../../domain/singleChannelSshBanner.shared.mjs'; +import { remoteSoftwareRequiresSingleChannel } from '../../domain/singleChannelSshBanner.shared.cjs'; import { useToolbarItemLayout } from '../../application/state/useToolbarItemLayout'; import type { TerminalSettings } from '../../domain/models'; import type { Host } from '../../domain/models/connection'; diff --git a/components/systemManager/SystemOverviewTab.test.ts b/components/systemManager/SystemOverviewTab.test.ts deleted file mode 100644 index 946a4af67..000000000 --- a/components/systemManager/SystemOverviewTab.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("overview CPU cores list renders every reported core and can scroll", () => { - const source = readFileSync(new URL("./SystemOverviewTab.tsx", import.meta.url), "utf8"); - - assert.doesNotMatch(source, /cpuPerCore\.slice\(/); - assert.match( - source, - /className="grid grid-cols-2 gap-x-3 gap-y-1\.5 max-h-\[\d+px\] overflow-y-auto pr-1 overscroll-contain"/, - ); -}); diff --git a/components/systemManager/TmuxNewSessionModal.test.ts b/components/systemManager/TmuxNewSessionModal.test.ts deleted file mode 100644 index 1132f576d..000000000 --- a/components/systemManager/TmuxNewSessionModal.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const modalSource = readFileSync(new URL("./TmuxNewSessionModal.tsx", import.meta.url), "utf8"); -const editorSource = readFileSync(new URL("../snippets/SnippetScriptEditor.tsx", import.meta.url), "utf8"); - -test("tmux new session modal is only modestly wider than the default dialog", () => { - assert.match(modalSource, /w-\[min\(92vw,560px\)\]/); - assert.match(modalSource, /max-w-none/); - assert.doesNotMatch(modalSource, /bg-background\/95/); - assert.doesNotMatch(modalSource, /bg-muted\/10/); - assert.doesNotMatch(modalSource, /border-b border-border\/60/); - assert.doesNotMatch(modalSource, /border-t border-border\/60/); -}); - -test("tmux command editor does not inherit the global snippet editor height", () => { - assert.match(modalSource, /defaultHeight=\{150\}/); - assert.match(modalSource, /maxHeight=\{260\}/); - assert.match(modalSource, /persistHeight=\{false\}/); - assert.match(editorSource, /persistHeight\?: boolean/); -}); diff --git a/components/systemManager/dockerManagerRuntimeSwitch.test.ts b/components/systemManager/dockerManagerRuntimeSwitch.test.ts deleted file mode 100644 index 8d20dcc68..000000000 --- a/components/systemManager/dockerManagerRuntimeSwitch.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import assert from 'node:assert/strict'; -import test from 'node:test'; -import { readFileSync } from 'node:fs'; - -test('kubernetes keeps the shared runtime select and drops the Containers back button', () => { - const tab = readFileSync(new URL('./DockerManagerTab.tsx', import.meta.url), 'utf8'); - const hook = readFileSync( - new URL('../../application/state/systemManager/useContainerRuntimeSelection.ts', import.meta.url), - 'utf8', - ); - - assert.equal(tab.includes('container-runtime-back'), false); - assert.match(tab, /data-section=\{section\}/); - assert.match(tab, /section="container-runtime-switcher"/); - assert.match(tab, /section="k8s-context-select"/); - assert.match(tab, /section="k8s-namespace-select"/); - assert.doesNotMatch(tab, /
/); - assert.match(tab, /section="k8s-context-select"[\s\S]*className="w-full min-w-0 max-w-none flex-1"/); - assert.match(tab, /section="container-runtime-switcher"[\s\S]*className="shrink-0"/); - assert.match(tab, /section="k8s-namespace-select"[\s\S]*className="shrink-0"/); - assert.match(hook, /const showRuntimeSwitcher = detected\.length > 1;/); - assert.doesNotMatch(hook, /source !== 'kubernetes' && detected\.length/); - assert.match(hook, /reconcileContainerSource\(/); - assert.match(hook, /isAutomaticRuntimeFallback\(remembered, source, available\)/); -}); diff --git a/components/systemManager/hooks/useAsyncRecordCache.ts b/components/systemManager/hooks/useAsyncRecordCache.ts deleted file mode 100644 index e326969a4..000000000 --- a/components/systemManager/hooks/useAsyncRecordCache.ts +++ /dev/null @@ -1,5 +0,0 @@ -/** @deprecated Import from `@/application/state/systemManager/useAsyncRecordCache` instead. */ -export { - useAsyncRecordCache, - type AsyncRecordState, -} from "../../../application/state/systemManager/useAsyncRecordCache"; diff --git a/components/systemManager/hooks/useSystemManager.ts b/components/systemManager/hooks/useSystemManager.ts deleted file mode 100644 index 6f5fa47ac..000000000 --- a/components/systemManager/hooks/useSystemManager.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** @deprecated Import from `@/application/state/useSystemManager` instead. */ -export { - useStableTranslate, - useSessionCapabilities, - useSystemCapabilitiesWarmup, - usePolling, -} from "../../../application/state/useSystemManager"; diff --git a/components/systemManager/systemPanelConfirmDialogRegression.test.ts b/components/systemManager/systemPanelConfirmDialogRegression.test.ts deleted file mode 100644 index 70543bb4e..000000000 --- a/components/systemManager/systemPanelConfirmDialogRegression.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; -import { fileURLToPath } from "node:url"; -import test from "node:test"; - -const root = fileURLToPath(new URL("../..", import.meta.url)); - -function readProjectFile(path: string): string { - return readFileSync(join(root, path), "utf8"); -} - -const SYSTEM_MANAGER_PANELS = [ - "components/systemManager/ProcessManagerTab.tsx", - "components/systemManager/TmuxSessionCard.tsx", - "components/systemManager/DockerContainersPanel.tsx", - "components/systemManager/DockerImagesPanel.tsx", - "components/systemManager/PortsManagerTab.tsx", - "components/systemManager/ServicesManagerTab.tsx", -] as const; - -test("system manager destructive actions use in-app confirm dialogs", () => { - for (const path of SYSTEM_MANAGER_PANELS) { - const source = readProjectFile(path); - assert.match( - source, - /import \{ SystemPanelConfirmDialog \} from ['"]\.\/SystemPanelConfirmDialog['"]/, - `${path} should import SystemPanelConfirmDialog`, - ); - assert.match( - source, - / { - const processSource = readProjectFile("components/systemManager/ProcessManagerTab.tsx"); - const containersSource = readProjectFile("components/systemManager/DockerContainersPanel.tsx"); - const imagesSource = readProjectFile("components/systemManager/DockerImagesPanel.tsx"); - - assert.match(processSource, /setPendingSignal\(null\)/); - assert.match(processSource, /}, \[sessionId\]\);/); - - assert.match(containersSource, /setConfirmAction\(null\)/); - assert.match(containersSource, /}, \[runtime, sessionId\]\);/); - - assert.match(imagesSource, /setConfirmTarget\(null\)/); - assert.match(imagesSource, /setActionBusy\(false\)/); - assert.match(imagesSource, /}, \[runtime, sessionId\]\);/); -}); - -test("ports and services confirm dialogs reset when sessionId changes", () => { - const portsSource = readProjectFile("components/systemManager/PortsManagerTab.tsx"); - const servicesSource = readProjectFile("components/systemManager/ServicesManagerTab.tsx"); - - assert.match(portsSource, /setPendingKillPid\(null\)/); - assert.match(portsSource, /setKillBusy\(false\)/); - assert.match(portsSource, /setActionError\(null\)/); - assert.match(portsSource, /}, \[sessionId\]\);/); - - assert.match(servicesSource, /setPending\(null\)/); - assert.match(servicesSource, /setActionBusy\(false\)/); - assert.match(servicesSource, /setActionError\(null\)/); - assert.match(servicesSource, /}, \[sessionId\]\);/); -}); - -test("ports and services surface pending channel results instead of treating them as success", () => { - const portsSource = readProjectFile("components/systemManager/PortsManagerTab.tsx"); - const servicesSource = readProjectFile("components/systemManager/ServicesManagerTab.tsx"); - - assert.match(portsSource, /result\.pending/); - assert.match(portsSource, /systemManager\.errors\.sshChannelUnavailable/); - assert.match(servicesSource, /result\.pending/); - assert.match(servicesSource, /systemManager\.errors\.sshChannelUnavailable/); -}); - -test("ports and services ignore late action results after session switches", () => { - const portsSource = readProjectFile("components/systemManager/PortsManagerTab.tsx"); - const servicesSource = readProjectFile("components/systemManager/ServicesManagerTab.tsx"); - - assert.match(portsSource, /sessionIdRef\.current !== requestedSessionId/); - assert.match(servicesSource, /sessionIdRef\.current !== requestedSessionId/); -}); diff --git a/components/terminal/TerminalSelectionAIOverlay.tsx b/components/terminal/TerminalSelectionAIOverlay.tsx index 563d842e2..1ecd0ac68 100644 --- a/components/terminal/TerminalSelectionAIOverlay.tsx +++ b/components/terminal/TerminalSelectionAIOverlay.tsx @@ -12,7 +12,7 @@ import { subscribeCopyOnSelectUserCommand, subscribeCopyOnSelectUserGesture, } from './copyOnSelect'; -import { getTerminalSelectionForClipboard } from './normalizeTerminalSelection'; +import { getTerminalSelectionForClipboard } from '../../domain/terminalSelection'; import { resolveSelectionOverlayPosition } from './useTerminalEffects'; import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip'; import { shouldShowSelectionAIOverlay } from './TerminalView'; diff --git a/components/terminal/TerminalServerStats.test.ts b/components/terminal/TerminalServerStats.test.ts deleted file mode 100644 index e9cdf5e69..000000000 --- a/components/terminal/TerminalServerStats.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -test("CPU per-core stats list can scroll when many cores are reported", () => { - const source = readFileSync(new URL("./TerminalServerStats.tsx", import.meta.url), "utf8"); - - assert.match( - source, - /className="grid gap-1\.5 max-h-\[\d+px\] overflow-y-auto/, - ); -}); - -test("server stats stay subscribed while the terminal is in the background", () => { - const source = readFileSync(new URL("./TerminalServerStats.tsx", import.meta.url), "utf8"); - - assert.doesNotMatch(source, /usePaneVisible/); - assert.doesNotMatch(source, /isVisible,/); -}); - -test("GPU chip only renders when the remote reports GPU utilization", () => { - const source = readFileSync(new URL("./TerminalServerStats.tsx", import.meta.url), "utf8"); - - // Conditional render — hosts without nvidia-smi must not show an empty GPU chip. - assert.match(source, /\{serverStats\.gpu !== null && \(/); - // Sits directly after the CPU chip, before the memory chip. - assert.match( - source, - /terminal\.serverStats\.gpu[\s\S]{0,2000}terminal\.serverStats\.memory/, - ); - // Same hover card as CPU: compact aggregate trigger, per-device body. - assert.match(source, /HoverCardTrigger asChild[\s\S]*terminal\.serverStats\.gpu[\s\S]* { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - assert.match( - source, - / { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const startReconnect = source.indexOf('const startReconnect = async'); - const updateNotice = source.indexOf('setReconnectNoticeMessage(reconnectAttemptMessage)', startReconnect); - const wakeHibernated = source.indexOf('if (!termRef.current && hibernatedRef.current)', startReconnect); - - assert.ok(startReconnect >= 0); - assert.ok(updateNotice > startReconnect); - assert.ok(wakeHibernated > updateNotice); -}); - -test("hibernated manual reconnect can continue after its runtime wakes", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const startReconnect = source.indexOf("const startReconnect = async"); - const markManualReconnect = source.indexOf( - 'setManualReconnectActive(mode === "manual")', - startReconnect, - ); - const initialGuard = source.slice(startReconnect, markManualReconnect); - const clearWakeInFlight = source.indexOf( - "reconnectWakeInFlightRef.current = false", - markManualReconnect, - ); - const continueReconnect = source.indexOf("startReconnectRef.current?.(mode)", clearWakeInFlight); - - assert.ok(startReconnect >= 0); - assert.ok(markManualReconnect > startReconnect); - assert.match(initialGuard, /reconnectPreparationTokenRef\.current !== null/); - assert.match(initialGuard, /reconnectWakeInFlightRef\.current/); - assert.doesNotMatch(initialGuard, /manualReconnectActive/); - assert.ok(clearWakeInFlight > markManualReconnect); - assert.ok(continueReconnect > clearWakeInFlight); -}); - -test("manual reconnect publishes preparation without starting the connection timeout", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const startReconnect = source.indexOf("const startReconnect = async"); - const publishPreparation = source.indexOf( - "terminalReconnectRegistry.setActive(sessionId, true)", - startReconnect, - ); - const cleanupSession = source.indexOf( - "await cleanupSession({ retainOwnership: true })", - startReconnect, - ); - const restoreDisconnected = source.indexOf( - 'updateStatus("disconnected")', - startReconnect, - ); - - assert.ok(startReconnect >= 0); - assert.ok(publishPreparation > startReconnect); - assert.ok(cleanupSession > publishPreparation); - assert.equal( - source.indexOf('if (mode === "manual") updateStatus("connecting")', startReconnect), - -1, - ); - assert.ok(restoreDisconnected > startReconnect); - assert.ok(restoreDisconnected < cleanupSession); -}); - -test("programmatic input during hibernated reconnect does not clear reconnect presentation", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const scrollStart = source.indexOf("const scrollToBottomAfterProgrammaticInput"); - const scrollEnd = source.indexOf("useEffect(() =>", scrollStart); - const scrollBody = source.slice(scrollStart, scrollEnd); - - assert.notEqual(scrollStart, -1); - assert.notEqual(scrollEnd, -1); - assert.doesNotMatch(scrollBody, /manualReconnectActiveRef|setReconnectNoticeMessage/); -}); - test("line timestamp toggle creates a persistent host update", () => { const host = { id: "host-1", @@ -184,31 +110,6 @@ test("line timestamp toolbar toggle is hidden when timestamps are unavailable", assert.equal(shouldShowLineTimestampToolbarToggle(true, undefined), false); }); -test("line timestamp gutter reserves no space while the alternate screen is active", () => { - assert.deepEqual(resolveLineTimestampGutterLayout({ - showLineTimestampGutter: true, - alternateScreenActive: true, - gutterWidth: 72, - }), { enabled: false, width: 0 }); - assert.deepEqual(resolveLineTimestampGutterLayout({ - showLineTimestampGutter: true, - alternateScreenActive: false, - gutterWidth: 72, - }), { enabled: true, width: 72 }); - assert.deepEqual(resolveLineTimestampGutterLayout({ - showLineTimestampGutter: false, - alternateScreenActive: false, - gutterWidth: 72, - }), { enabled: false, width: 0 }); - - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - assert.match(source, /const activeLineTimestampGutterWidth = lineTimestampGutterLayout\.width/); - assert.match(source, /enabled=\{lineTimestampGutterLayout\.enabled\}/); - assert.doesNotMatch(source, /enabled=\{showLineTimestampGutter\}/); - assert.match(source, /aria-pressed=\{showLineTimestampGutter\}/); - assert.doesNotMatch(source, /aria-pressed=\{[^}]*alternateScreenActive/); -}); - type AlternateScreenWatchTerm = { buffer: { active: { type: string } }; onRender: (callback: () => void) => { dispose: () => void }; @@ -478,58 +379,6 @@ test("host info bar title follows address or label mode", () => { ); }); -test("terminal title row does not render a status dot beside the address", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const titleStart = source.indexOf("data-terminal-detach-drag-handle"); - const titleEnd = source.indexOf("shouldShowLineTimestampToolbarToggle", titleStart); - assert.notEqual(titleStart, -1); - assert.notEqual(titleEnd, -1); - - assert.doesNotMatch(source.slice(titleStart, titleEnd), /statusDotTone/); -}); - -test("terminal title keeps the copy host action beside the address", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const titleStart = source.indexOf("data-terminal-detach-drag-handle"); - const copyAction = source.indexOf('aria-label={t("terminal.statusbar.copyHostname.label")}', titleStart); - const timestampToggle = source.indexOf("shouldShowLineTimestampToolbarToggle", titleStart); - - assert.notEqual(titleStart, -1); - assert.notEqual(copyAction, -1); - assert.notEqual(timestampToggle, -1); - assert.ok(copyAction < timestampToggle); -}); - -test("focus mode and temporary pane magnification use separate toolbar actions", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const focusAction = source.indexOf("onClick={onExpandToFocus}"); - const magnifyAction = source.indexOf("onClick={onTogglePaneMagnification}"); - - assert.notEqual(focusAction, -1); - assert.notEqual(magnifyAction, -1); - assert.ok(focusAction < magnifyAction); - assert.match(source.slice(focusAction, magnifyAction), /terminal\.toolbar\.focusMode/); - assert.match(source.slice(magnifyAction), /terminal\.paneMagnification\.(restore|magnify)/); -}); - -test("popup terminals disable line timestamp controls", () => { - const source = readFileSync(new URL("../TerminalPopupPage.tsx", import.meta.url), "utf8"); - - assert.match(source, /lineTimestampsAvailable=\{false\}/); -}); - -test("terminal body keeps a slight inset from the surrounding chrome", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - - assert.match(source, /const terminalBodyInset = 4/); - assert.match(source, /left: activeLineTimestampGutterWidth \+ terminalBodyInset/); - assert.match(source, /right: terminalRightInset/); - assert.match(source, /const terminalBottomInset = terminalBodyInset \+ \(showDisconnectedTerminalNotice \? 28 : 0\)/); - assert.match(source, /bottom: terminalBottomInset/); - assert.match(source, /left=\{terminalBodyInset\}/); - assert.match(source, /bottom=\{terminalBottomInset\}/); -}); - test("hidden host information bar gives its vertical space back to the terminal", () => { assert.deepEqual( resolveTerminalTopOffsets({ showHostInfoBar: false, isSearchOpen: false }), @@ -576,43 +425,6 @@ test("hidden host information does not reserve a side gutter for its floating ac assert.equal(resolveTerminalRightInset({ showHostInfoBar: false, isSearchOpen: true }), 4); }); -test("hidden host information keeps terminal actions rendered", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const hostInfoStart = source.indexOf("{showHostInfoBar && }", hostInfoStart); - const copyAction = source.indexOf('aria-label={t("terminal.statusbar.copyHostname.label")}'); - const timestampAction = source.indexOf("shouldShowLineTimestampToolbarToggle", copyAction); - const systemAction = source.indexOf('aria-label={t("terminal.layer.system")}', timestampAction); - const disconnectAction = source.indexOf('aria-label={t("terminal.statusbar.disconnect.label")}', systemAction); - const reconnectAction = source.indexOf('aria-label={t("terminal.statusbar.reconnect.label")}', disconnectAction); - const actionsStart = source.indexOf('className="flex items-center gap-0.5 flex-shrink-0"'); - const controls = source.indexOf("{renderControls({ showClose: inWorkspace, restorePaneLayout: isPaneMagnified })}"); - const compactDragHandle = source.indexOf('data-terminal-detach-drag-handle="true"'); - - assert.notEqual(hostInfoStart, -1); - assert.notEqual(hostInfoEnd, -1); - assert.notEqual(copyAction, -1); - assert.notEqual(timestampAction, -1); - assert.notEqual(systemAction, -1); - assert.notEqual(disconnectAction, -1); - assert.notEqual(reconnectAction, -1); - assert.notEqual(actionsStart, -1); - assert.notEqual(controls, -1); - assert.notEqual(compactDragHandle, -1); - // Compact drag handle uses GripVertical, not the old radial-dot “chessboard”. - assert.match(source, /GripVertical/); - assert.ok(!source.includes("backgroundSize: '4px 4px'")); - assert.ok(hostInfoStart < hostInfoEnd); - assert.ok(hostInfoEnd < copyAction); - assert.ok(copyAction < timestampAction); - assert.ok(timestampAction < systemAction); - assert.ok(systemAction < disconnectAction); - assert.ok(disconnectAction < reconnectAction); - assert.ok(reconnectAction < actionsStart); - assert.ok(actionsStart < controls); - assert.ok(compactDragHandle < hostInfoStart); -}); - test("status bar disconnect stays enabled while connected or connecting", () => { assert.equal(shouldEnableStatusBarDisconnect("connected"), true); assert.equal(shouldEnableStatusBarDisconnect("connecting"), true); @@ -653,222 +465,3 @@ test("status bar connection controls require an owned session surface", () => { false, ); }); - -test("manual disconnect keeps the session pane for reconnect", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const disconnectStart = source.indexOf("const handleDisconnect = () => {"); - const disconnectEnd = source.indexOf("const handleDismissDisconnectedDialog", disconnectStart); - assert.notEqual(disconnectStart, -1); - assert.notEqual(disconnectEnd, -1); - const body = source.slice(disconnectStart, disconnectEnd); - assert.match(body, /clearAutoReconnect\(\{ stopLoop: true \}\)/); - assert.match(body, /reconnectWakeTokenRef\.current = null/); - assert.match(body, /reconnectWakeInFlightRef\.current = false/); - assert.match(body, /netcatty:terminal-session-disconnected/); - assert.match(body, /invalidateBootEpochForClose\(\)/); - assert.match(body, /isBootActiveRef\.current = false/); - assert.match(body, /setIsCancelling\(true\)/); - assert.match(body, /updateStatus\("disconnected"\)/); - assert.match(body, /void cleanupSession\(\{ retainOwnership: true \}\)/); - assert.match(source, /trackSessionCleanup/); - assert.doesNotMatch(body, /onCloseSession/); - assert.match(source, /handleDisconnect: \(attachExistingSession \|\| compactToolbar\) \? undefined : handleDisconnect/); - assert.match(source, /showConnectionControls: !attachExistingSession && !compactToolbar/); - assert.match(source, /setTerminalBootEpoch/); - - const startersSource = readFileSync( - new URL("./runtime/createTerminalSessionStarters.ts", import.meta.url), - "utf8", - ); - assert.match(startersSource, /createBootAttemptGuard\(ctx\)/); - assert.match(startersSource, /setTerminalBootEpoch\(ctx\.sessionId, bootEpoch\)/); - - const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); - assert.match( - effectsSource, - /!isBootActiveRef\.current[\s\S]*statusRef\.current === "disconnected"[\s\S]*bootEpochMismatch/, - ); - assert.match( - effectsSource, - /respondHostKeyVerification\?\.\(request\.requestId, false\)/, - ); - assert.match(effectsSource, /request\.bootEpoch/); - assert.match( - startersSource, - /if \(!isCurrentAttempt\(\)\) return;/, - ); - assert.match(startersSource, /bootEpoch,/); -}); - -test("cancel connect invalidates the boot epoch like disconnect", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const cancelStart = source.indexOf("const handleCancelConnect = () => {"); - const cancelEnd = source.indexOf("const handleDisconnect = () => {", cancelStart); - assert.notEqual(cancelStart, -1); - assert.notEqual(cancelEnd, -1); - const body = source.slice(cancelStart, cancelEnd); - - assert.match(body, /invalidateBootEpochForClose\(\)/); - assert.match(body, /isBootActiveRef\.current = false/); - // Both must land before cleanupSession so the close targets the pre-bump epoch. - assert.ok( - body.indexOf("invalidateBootEpochForClose()") < body.indexOf("void cleanupSession()"), - "cancel must invalidate the boot epoch before cleanupSession", - ); - assert.ok( - body.indexOf("isBootActiveRef.current = false") < body.indexOf("void cleanupSession()"), - "cancel must clear boot-active before cleanupSession", - ); -}); - -test("terminal boot is cancelable and closes eagerly on cleanup", () => { - const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); - const startersSource = readFileSync( - new URL("./runtime/createTerminalSessionStarters.ts", import.meta.url), - "utf8", - ); - - assert.match(effectsSource, /const bootAbort = new AbortController\(\)/); - assert.match(effectsSource, /const bootStartOptions = \{ signal: bootAbort\.signal \}/); - assert.match( - effectsSource, - /queueMicrotask\(\(\) => \{\s*\n\s*if \(disposed\) return;\s*\n\s*void boot\(\);/, - "backend boot must defer past StrictMode's synchronous re-invoke", - ); - for (const starter of [ - "startPluginConnection", - "startSerial", - "startLocal", - "startTelnet", - "startMosh", - "startEt", - "startSSH", - ]) { - assert.match( - effectsSource, - new RegExp(`sessionStarters\\.${starter}\\(term, bootStartOptions\\)`), - `${starter} must receive the boot abort signal`, - ); - } - - // Cleanup order: abort, then eager close + sync dispose for never-connected - // boots (StrictMode remount), else the async capture/teardown path. - const cleanupStart = effectsSource.indexOf(" disposed = true;"); - assert.notEqual(cleanupStart, -1); - const cleanup = effectsSource.slice(cleanupStart); - const abortAt = cleanup.indexOf("bootAbort.abort()"); - const neverConnectedAt = cleanup.indexOf("if (!hasConnectedRef.current)"); - assert.ok(abortAt !== -1 && neverConnectedAt !== -1); - assert.ok(abortAt < neverConnectedAt, "cleanup must abort before the never-connected close branch"); - const neverConnectedBranch = cleanup.slice( - neverConnectedAt, - cleanup.indexOf("const persistCloseCapture", neverConnectedAt), - ); - const closeAt = neverConnectedBranch.indexOf("terminalBackend.closeSession("); - const syncDisposeAt = neverConnectedBranch.indexOf("disposeOwnedRuntime();"); - const earlyReturnAt = neverConnectedBranch.indexOf("return;"); - assert.ok(closeAt !== -1 && syncDisposeAt !== -1 && earlyReturnAt !== -1); - assert.ok(closeAt < syncDisposeAt, "eager close must run before sync runtime dispose"); - assert.ok( - syncDisposeAt < earlyReturnAt, - "never-connected boots must sync-dispose before leaving cleanup", - ); - // Owner panes close the pending backend; attach popups only dispose xterm. - assert.match(neverConnectedBranch, /if \(!attachExistingSession\)/); - const emptySessionBranch = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const emptyStart = emptySessionBranch.indexOf("if (!closingSessionId)"); - const emptyEnd = emptySessionBranch.indexOf("Observe/attach popups must not kill", emptyStart); - const emptyBranch = emptySessionBranch.slice(emptyStart, emptyEnd); - const attachGuardAt = emptyBranch.indexOf("if (attachExistingSession)"); - const emptyCloseAt = emptyBranch.indexOf("terminalBackend.closeSession("); - assert.ok( - attachGuardAt !== -1 && emptyCloseAt !== -1 && attachGuardAt < emptyCloseAt, - "a second attach cleanup after sessionRef is cleared must not closeSession", - ); - assert.match(effectsSource, /let ownedRuntime:/); - assert.match( - cleanup, - /void completeClose\(\)/, - "connected boots still use the async capture path", - ); - - // An aborted boot must stop counting as the current attempt so the existing - // orphan-close / attach-refusal guards cover cancellation too. - assert.match( - startersSource, - /options\?\.signal\?\.aborted !== true && isBootEpochCurrent\(\)/, - ); - for (const starter of [ - "startSSH", - "startTelnet", - "startMosh", - "startEt", - "startPluginConnection", - "startLocal", - "startSerial", - ]) { - assert.match( - startersSource, - new RegExp( - `const ${starter} = async \\(term: XTerm, options\\?: TerminalSessionStartOptions\\)`, - ), - `${starter} must accept an abort signal`, - ); - } - // The plugin path holds its own in-flight request controller; the boot abort - // has to reach it or the extension request outlives the pane. - assert.match(startersSource, /options\?\.signal\?\.addEventListener\("abort", onBootAborted/); - assert.match(startersSource, /options\?\.signal\?\.removeEventListener\("abort", onBootAborted\)/); -}); - -test("hidden host information reveals actions without permanently covering terminal content", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - - assert.match(source, /aria-label=\{t\("terminal\.toolbar\.showActions"\)\}/); - assert.match(source, /aria-expanded=\{compactActionsOpen\}/); - assert.match(source, /aria-controls=\{`terminal-actions-\$\{sessionId\}`\}/); - assert.match(source, /id=\{`terminal-actions-\$\{sessionId\}`\}/); - assert.match(source, /onClick=\{\(\) => setCompactActionsOpen/); - assert.match(source, /right: terminalRightInset/); - // Compact mode is a circular speed-dial: tray springs left via 0fr→1fr grid - // (must not use .terminal-topbar — container-type collapses content width). - assert.match(source, /flex flex-row-reverse items-center/); - assert.match(source, /rounded-full/); - assert.match(source, /grid-cols-\[1fr\]/); - assert.match(source, /grid-cols-\[0fr\]/); - assert.match(source, /ChevronsLeft/); - assert.match(source, /h-7/); - assert.match(source, /Do NOT use `\.terminal-topbar`|container-type:inline-size|container-type collapses/); - assert.match(source, /document\.addEventListener\("pointerdown", handlePointerDown\)/); - assert.match(source, /closest\('\[data-radix-popper-content-wrapper\]'\)/); - assert.match(source, /event\.key !== "Escape"/); - assert.match(source, /compactActionsButtonRef\.current\?\.focus\(\)/); -}); - -test("compact action toggle preserves terminal focus like the visible toolbar", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const overlayStart = source.indexOf('ref={compactActionsRef}'); - const toggleStart = source.indexOf('ref={compactActionsButtonRef}', overlayStart); - - assert.notEqual(overlayStart, -1); - assert.notEqual(toggleStart, -1); - assert.ok(overlayStart < toggleStart); - assert.match(source.slice(overlayStart, toggleStart), /onMouseDownCapture=\{handleTopOverlayMouseDownCapture\}/); -}); - -test("terminal theme updates force xterm renderer to repaint immediately", () => { - const source = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); - const schedulerSource = readFileSync(new URL("./terminalThemeScheduler.ts", import.meta.url), "utf8"); - - assert.match(source, /applyTerminalThemeSync\(term, effectiveTheme\)/); - assert.match(schedulerSource, /term\.options\.theme = \{/); - assert.match(schedulerSource, /forceSyncRenderAfterResize\(term\)/); -}); - -test("SFTP context action reuses the pane toolbar handler and its availability", () => { - const source = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8"); - const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - assert.match(source, /onOpenSftp=\{status === "connected" && !isSerialConnection && !host\?\.id\?\.startsWith\("serial-"\) && !isPluginHostProtocol\(host\?\.protocol\) \? ctx\.handleOpenSFTP : undefined\}/); - assert.match(terminalSource, /onOpenSFTP=\{handleOpenSFTP\}/); - assert.match(terminalSource, / { - assert.doesNotMatch(source, /const \[activeTab, setActiveTab\] = useState\(followAppTerminalTheme \? 'font' : 'theme'\)/); - assert.doesNotMatch(source, /!\s*themeEditingLocked\s*&&\s*\(\s* { - assert.match(source, /hiddenSelectedTheme && \(\s* { - assert.match( - source, - /TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS, 'flex items-center px-1\.5 gap-0\.5 border-b'/, - ); -}); diff --git a/components/terminal/appResumeWebglRecovery.test.ts b/components/terminal/appResumeWebglRecovery.test.ts deleted file mode 100644 index a49575b5d..000000000 --- a/components/terminal/appResumeWebglRecovery.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const assertRecoverTerminalOnAppResumeOrder = (source: string): void => { - const handlerIndex = source.indexOf("const recoverTerminalOnAppResume = () => {"); - assert.notEqual(handlerIndex, -1, "recoverTerminalOnAppResume must exist"); - - const bodyStart = source.indexOf("{", handlerIndex); - assert.notEqual(bodyStart, -1, "recoverTerminalOnAppResume must have a body"); - - let depth = 0; - let bodyEnd = -1; - for (let index = bodyStart; index < source.length; index += 1) { - const char = source[index]; - if (char === "{") depth += 1; - if (char === "}") { - depth -= 1; - if (depth === 0) { - bodyEnd = index + 1; - break; - } - } - } - assert.notEqual(bodyEnd, -1, "recoverTerminalOnAppResume body must close"); - - const handlerSource = source.slice(handlerIndex, bodyEnd); - const flushIndex = handlerSource.indexOf("flushPendingTerminalWritesOnResume(term)"); - const scrollIndex = handlerSource.indexOf("flushPendingOutputScroll()"); - const recoveryIndex = handlerSource.indexOf("recoverWebglRendererOnAppResume()"); - const refitIndex = handlerSource.indexOf("scheduleLayoutRecoveryRefit([0, 100, 300])"); - - assert.notEqual(flushIndex, -1, "recoverTerminalOnAppResume must flush pending writes"); - assert.notEqual(scrollIndex, -1, "recoverTerminalOnAppResume must flush pending scroll"); - assert.notEqual(recoveryIndex, -1, "recoverTerminalOnAppResume must recover WebGL"); - assert.notEqual(refitIndex, -1, "recoverTerminalOnAppResume must schedule layout recovery"); - assert.ok(flushIndex < scrollIndex, "flush pending writes before pending scroll"); - assert.ok(scrollIndex < recoveryIndex, "flush pending scroll before WebGL recovery"); - assert.ok(recoveryIndex < refitIndex, "recover WebGL before layout recovery"); -}; - -test("app resume handlers flush backlog and recover the terminal renderer before refit", () => { - const source = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); - const resumeEffectIndex = source.indexOf("const recoverWebglRendererOnAppResume = () => {"); - const resumeEffectEnd = source.indexOf("// Only register the snippet executor", resumeEffectIndex); - const resumeEffectSource = source.slice(resumeEffectIndex, resumeEffectEnd); - - assert.ok(resumeEffectIndex >= 0); - assert.ok(resumeEffectEnd > resumeEffectIndex); - assertRecoverTerminalOnAppResumeOrder(source); - assert.match( - resumeEffectSource, - /const handleVisibilityChange = \(\) => \{\s*if \(document\.visibilityState !== 'visible'\) \{\s*syncOutputPressureVisibility\(\);\s*return;\s*\}\s*recoverTerminalOnAppResume\(\);\s*\};/, - ); - assert.match( - resumeEffectSource, - /const handleWindowFocus = \(\) => \{\s*recoverTerminalOnAppResume\(\);\s*\};/, - ); - assert.match( - resumeEffectSource, - /const unsubscribeWindowShown = terminalBackend\.onWindowShown\?\.\(\(\) => \{\s*recoverTerminalOnAppResume\(\);\s*\}\);/, - ); - assert.doesNotMatch(resumeEffectSource, /\binWorkspace\b/); - assert.doesNotMatch(resumeEffectSource, /\bisFocusMode\b/); - assert.doesNotMatch(resumeEffectSource, /\bisFocused\b/); - assert.doesNotMatch(source, /shouldRecoverOnAppResume/); -}); - -test("useTerminalBackend exposes onWindowShown so the resume hook actually fires", () => { - const source = readFileSync( - new URL("../../application/state/useTerminalBackend.ts", import.meta.url), - "utf8", - ); - assert.match(source, /const onWindowShown = useCallback\(\(cb: \(\) => void\) => \{\s*const bridge = netcattyBridge\.get\(\);\s*return bridge\?\.onWindowShown\?\.\(cb\);/); - const returnIndex = source.indexOf("useMemo("); - assert.notEqual(returnIndex, -1); - assert.match(source.slice(returnIndex), /onWindowShown,/); -}); diff --git a/components/terminal/autocomplete/snippetCompleter.ts b/components/terminal/autocomplete/snippetCompleter.ts index aaf76404a..e76574f9f 100644 --- a/components/terminal/autocomplete/snippetCompleter.ts +++ b/components/terminal/autocomplete/snippetCompleter.ts @@ -8,7 +8,7 @@ */ import type { Snippet } from "../../../domain/models"; import { snippetAppliesToHost } from "../../../domain/snippetTargets"; -import { matchesSearchQuery, matchesWordPrefixQuery } from "../../../lib/searchMatcher"; +import { matchesSearchQuery, matchesWordPrefixQuery } from "../../../domain/searchMatcher"; import type { CompletionSuggestion } from "./completionEngine"; const SNIPPET_BASE_SCORE = 2000; // Above history (1000+freq) per "snippet > history". diff --git a/components/terminal/completionEngineSnippets.test.ts b/components/terminal/completionEngineSnippets.test.ts index 5af1bc054..a9323028f 100644 --- a/components/terminal/completionEngineSnippets.test.ts +++ b/components/terminal/completionEngineSnippets.test.ts @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { getCompletions } from "./autocomplete/completionEngine"; import { DEFAULT_AUTOCOMPLETE_SETTINGS } from "./autocomplete/useTerminalAutocomplete"; -import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../lib/searchMatcher"; +import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../domain/searchMatcher"; import type { Snippet } from "../../domain/models"; const deploySnippet: Snippet = { id: "d", label: "deploy", command: "kubectl apply -f ." }; diff --git a/components/terminal/hooks/useServerStats.ts b/components/terminal/hooks/useServerStats.ts deleted file mode 100644 index dab60c6a6..000000000 --- a/components/terminal/hooks/useServerStats.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** @deprecated Import from `@/application/state/useServerStats` instead. */ -export { - useServerStats, - type DiskInfo, - type NetInterfaceInfo, - type ProcessInfo, - type ServerStats, -} from "../../../application/state/useServerStats"; diff --git a/components/terminal/hooks/useTerminalContextActions.ts b/components/terminal/hooks/useTerminalContextActions.ts index 0ac342608..5598f1b54 100644 --- a/components/terminal/hooks/useTerminalContextActions.ts +++ b/components/terminal/hooks/useTerminalContextActions.ts @@ -13,7 +13,7 @@ import { } from "../clipboardImagePaste"; import { handleTerminalClipboardPaste, pasteTextWithMultilineConfirm } from "../terminalClipboardPaste"; import { pulseCopyOnSelectUserCommand } from "../copyOnSelect"; -import { getTerminalSelectionForClipboard } from "../normalizeTerminalSelection"; +import { getTerminalSelectionForClipboard } from "../../../domain/terminalSelection"; import { getHistoryPreviewSelectionFromRoot, requestHistoryPreviewHide, diff --git a/components/terminal/inlineImageRendering.test.ts b/components/terminal/inlineImageRendering.test.ts deleted file mode 100644 index e6e6a09d0..000000000 --- a/components/terminal/inlineImageRendering.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -const runtimeSource = readFileSync( - new URL("./runtime/createXTermRuntime.ts", import.meta.url), - "utf8", -); -const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - -const readCallbackBody = (source: string, marker: string): string => { - const start = source.indexOf(marker); - assert.notEqual(start, -1, `${marker} must exist`); - - const bodyStart = source.indexOf("{", start); - assert.notEqual(bodyStart, -1, `${marker} must have a body`); - - let depth = 0; - for (let index = bodyStart; index < source.length; index += 1) { - const char = source[index]; - if (char === "{") depth += 1; - else if (char === "}") { - depth -= 1; - if (depth === 0) return source.slice(bodyStart, index + 1); - } - } - - assert.fail(`${marker} body must close`); -}; - -test("the image addon is created from settings and only when inline images are on", () => { - assert.match(runtimeSource, /import \{ ImageAddon \} from "@xterm\/addon-image"/); - assert.match( - runtimeSource, - /const inlineImageOptions = resolveTerminalInlineImageAddonOptions\(settings\);[\s\S]{0,400}?if \(inlineImageOptions\) \{[\s\S]{0,300}?new ImageAddon\(inlineImageOptions\)[\s\S]{0,120}?term\.loadAddon\(imageAddon\)/, - "the addon must be constructed from resolved settings and skipped when they resolve to null", - ); - - const openIndex = runtimeSource.indexOf("term.open(ctx.container)"); - const imageAddonIndex = runtimeSource.indexOf("new ImageAddon(inlineImageOptions)"); - const webglIndex = runtimeSource.indexOf("const webglController = createWebglRendererController("); - - assert.ok(openIndex !== -1 && imageAddonIndex !== -1 && webglIndex !== -1); - assert.ok( - openIndex < imageAddonIndex, - "the addon needs the render service, so it must be loaded after term.open", - ); - assert.ok( - imageAddonIndex < webglIndex, - "the addon must patch setRenderer before the WebGL renderer is created, so image layers survive renderer swaps", - ); -}); - -test("the image addon is disposed before the terminal that owns its layers", () => { - const disposeBody = readCallbackBody(runtimeSource, " dispose: () => {"); - const imageDisposeIndex = disposeBody.indexOf("imageAddon.dispose()"); - const termDisposeIndex = disposeBody.indexOf("term.dispose()"); - - assert.notEqual(imageDisposeIndex, -1, "runtime dispose must release the image addon"); - assert.notEqual(termDisposeIndex, -1); - assert.ok( - imageDisposeIndex < termDisposeIndex, - "image storage and canvas layers must be released before xterm tears down its screen element", - ); -}); - -test("hasInlineImages reports live image storage instead of a sticky flag", () => { - assert.match(runtimeSource, /hasInlineImages: \(\) => boolean;/); - assert.match( - runtimeSource, - /const hasInlineImages = \(\): boolean => \{[\s\S]{0,200}?imageAddon\.storageUsage > 0/, - "a session must stop blocking hibernate once its image cache is emptied", - ); - assert.match(runtimeSource, /\n {4}hasInlineImages,\n/, "the runtime must expose hasInlineImages"); -}); - -test("a session holding inline images degrades to soft-hide instead of full hibernate", () => { - assert.match( - terminalSource, - /const runtimeHasInlineImages = useCallback\(\s*\(\) => xtermRuntimeRef\.current\?\.hasInlineImages\(\) === true,/, - ); - - const hibernateBody = readCallbackBody(terminalSource, "const hibernateRuntime = useCallback(() =>"); - const gateIndex = hibernateBody.indexOf("if (runtimeHasInlineImages()) {"); - const softHideIndex = hibernateBody.indexOf("hideRuntimeOnly();", gateIndex); - const keepCountIndex = hibernateBody.indexOf("resolveHibernateKeepRendererCount(terminalSettings)"); - const evictionIndex = hibernateBody.indexOf("retainLeavingTabAfterEviction("); - const fullHibernateIndex = hibernateBody.indexOf("void fullHibernateRuntime()"); - - assert.notEqual(gateIndex, -1, "hibernate must check for inline images"); - assert.ok(gateIndex < softHideIndex, "the inline image branch must soft-hide the runtime"); - assert.ok( - gateIndex < keepCountIndex && gateIndex < evictionIndex && gateIndex < fullHibernateIndex, - "the inline image branch must run before the keep-count, eviction and full-hibernate paths", - ); -}); - -test("full hibernate and the eviction upgrade both re-check inline images", () => { - const fullHibernateBody = readCallbackBody( - terminalSource, - "const fullHibernateRuntime = useCallback(async (): Promise =>", - ); - const canFinishIndex = fullHibernateBody.indexOf("const canFinishHibernate = () => ("); - const imageCheckIndex = fullHibernateBody.indexOf("&& !runtimeHasInlineImages()", canFinishIndex); - const canFinishEndIndex = fullHibernateBody.indexOf(");", canFinishIndex); - - assert.notEqual(canFinishIndex, -1); - assert.notEqual(imageCheckIndex, -1, "canFinishHibernate must reject sessions holding images"); - assert.ok( - imageCheckIndex < canFinishEndIndex, - "the image check must be part of canFinishHibernate so it is re-evaluated after every async step", - ); - - const evictionIndex = terminalSource.indexOf( - "terminalHiddenRendererStore.consumeEvictionRequest(sessionId)", - ); - const evictionGuardIndex = terminalSource.indexOf( - "if (runtimeHasInlineImages()) return;", - evictionIndex, - ); - const evictionUpgradeIndex = terminalSource.indexOf( - "upgradeSoftHiddenRuntimeToHibernate();", - evictionIndex, - ); - const upgradeBody = readCallbackBody( - terminalSource, - "const upgradeSoftHiddenRuntimeToHibernate = useCallback(() =>", - ); - - assert.notEqual(evictionIndex, -1); - assert.notEqual( - evictionGuardIndex, - -1, - "an evicted soft-hidden session with images must stay soft-hidden", - ); - assert.ok( - evictionGuardIndex < evictionUpgradeIndex, - "the image guard must run before the renderer is woken for the hibernate upgrade", - ); - assert.match( - upgradeBody, - /wakeSoftHiddenRuntimeRef\.current\?\.\(\);[\s\S]*?fullHibernateRuntime\(\)/, - "the shared upgrade path must wake the soft-hidden renderer before hibernating", - ); -}); diff --git a/components/terminal/localTerminalHibernate.test.ts b/components/terminal/localTerminalHibernate.test.ts deleted file mode 100644 index 2b10a250a..000000000 --- a/components/terminal/localTerminalHibernate.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); -const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); -const runtimeSource = readFileSync(new URL("./runtime/createXTermRuntime.ts", import.meta.url), "utf8"); -const layerSupportSource = readFileSync(new URL("../terminalLayer/TerminalLayerSupport.tsx", import.meta.url), "utf8"); -const layerBridgeSource = readFileSync(new URL("../terminalLayer/TerminalLayerTabBridge.tsx", import.meta.url), "utf8"); -const layerViewSource = readFileSync(new URL("../terminalLayer/TerminalLayerView.tsx", import.meta.url), "utf8"); - -test("local terminals stay out of hibernate and hidden-renderer paths", () => { - assert.match( - terminalSource, - /const effectiveTerminalProtocol = resolveEffectiveTerminalProtocol\(host\);[\s\S]*const hibernateEnabled =\s+resolveTerminalHibernateEnabledForProtocol\([\s\S]*effectiveTerminalProtocol/, - ); - assert.match( - terminalSource, - /kittyKeyboardProtocolEnabledForSessionRef = useRef\([\s\S]*const kittyKeyboardProtocolEnabledForSession =[\s\S]*kittyKeyboardProtocolEnabledForSessionRef\.current/, - ); - assert.match(terminalSource, /!kittyKeyboardProtocolEnabledForSession &&\s+!isBroadcastEnabled/); - assert.match(terminalSource, /hibernateEnabledRef\.current = hibernateEnabled/); - assert.match(terminalSource, /hibernateEnabled: hibernateEnabled/); - assert.match( - effectsSource, - /const effectiveTerminalProtocol = resolveEffectiveTerminalProtocol\(host\);[\s\S]*resolveTerminalHibernateEnabledForProtocol\([\s\S]*effectiveTerminalProtocol[\s\S]*&& !kittyKeyboardProtocolEnabledForSession/, - ); - assert.match(layerSupportSource, /resolveTerminalHibernateEnabledForProtocol\(terminalSettings, host\.protocol\)/); - assert.match(layerBridgeSource, /const localWorkspaceIds = useMemo\(\(\) => new Set\(/); - assert.match(layerBridgeSource, /!hibernateHiddenTabs \|\| localWorkspaceIds\.has\(workspace\.id\)/); - assert.match(layerViewSource, /ctx\.hibernateHiddenTabs/); -}); - -test("reconnect clears keyboard pairing before resetting protocol state", () => { - assert.match( - terminalSource, - /startNewSession = \(\) => \{[\s\S]*resetConnectionInputState\(host\);[\s\S]*resetKittyKeyboardModeStateForSession/, - ); - assert.match( - runtimeSource, - /clearKittyKeyboardBroadcastPairingState\([\s\S]*broadcastEncodedKeys,[\s\S]*broadcastLegacySuppressedKeys/, - ); - assert.match( - runtimeSource, - /resetConnectionInputState: \(host\) => \{[\s\S]*clearKittyConnectionInputState\(\)/, - ); - assert.match( - runtimeSource, - /kittyKeyboardLockState\.capsLock = event\.getModifierState\("CapsLock"\);[\s\S]*kittyKeyboardLockState\.numLock = event\.getModifierState\("NumLock"\);/, - ); - assert.match( - runtimeSource, - /flushKittyKeyboardBroadcastReleases\([\s\S]*broadcastForwardedKeys,[\s\S]*broadcastKittyInput,[\s\S]*kittyKeyboardLockState/, - ); - assert.doesNotMatch( - runtimeSource.match(/const clearKittyConnectionInputState = \(\) => \{[\s\S]*?\n {2}\};/)?.[0] ?? "", - /broadcastForwardedKeys\.clear\(\)/, - ); -}); - -test("session cleanup flushes owed Kitty releases before dropping the backend id", () => { - assert.match( - terminalSource, - /const closingSessionId = sessionRef\.current;\s+xtermRuntimeRef\.current\?\.flushKittyKeyboardReleases\(\);\s+sessionRef\.current = null;/, - ); - assert.match( - runtimeSource, - /flushKittyKeyboardReleases: clearKittyTransientInputState/, - ); -}); diff --git a/components/terminal/runtime/clearBufferPtySync.test.ts b/components/terminal/runtime/clearBufferPtySync.test.ts deleted file mode 100644 index ec7969da9..000000000 --- a/components/terminal/runtime/clearBufferPtySync.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -test("clearBuffer uses the guarded viewport and ConPTY sync helper", () => { - const runtimeSource = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8"); - const clearCaseIndex = runtimeSource.indexOf('case "clearBuffer"'); - assert.notEqual(clearCaseIndex, -1); - - const clearCase = runtimeSource.slice(clearCaseIndex, clearCaseIndex + 500); - assert.match(clearCase, /clearTerminalViewportAndSyncPty\(term,/); - assert.match(clearCase, /clearSessionPtyBuffer\?\.\(clearId\)/); -}); - -test("context-menu clear also uses the guarded viewport and ConPTY sync helper", () => { - const actionsSource = readFileSync( - new URL("../hooks/useTerminalContextActions.ts", import.meta.url), - "utf8", - ); - const onClearIndex = actionsSource.indexOf("const onClear = useCallback"); - assert.notEqual(onClearIndex, -1); - const onClear = actionsSource.slice(onClearIndex, onClearIndex + 650); - assert.match(onClear, /clearTerminalViewportAndSyncPty\(term,/); - assert.match(onClear, /clearSessionPtyBuffer\?\.\(id\)/); -}); diff --git a/components/terminal/runtime/createTerminalSessionStarters.mosh.test.ts b/components/terminal/runtime/createTerminalSessionStarters.mosh.test.ts index da2ceab56..acbae7436 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.mosh.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.mosh.test.ts @@ -1,5 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { createMockTerminalBackend, createStarterContext, createTermStub } from "./testSupport/starterHarness"; import { createTerminalSessionStarters, @@ -23,32 +24,17 @@ test("startMosh enables sudo autofill with the host saved password", async () => const detectionDone = new Promise((resolve) => { resolveDetected = resolve; }); let onData: ((data: string) => void) | null = null; const sent: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", + const terminalBackend = createMockTerminalBackend({ onMoshSessionReady: (_id: string, callback: () => void) => { ready = callback; return noop; }, getSessionDistroInfo: async () => { probes++; return { success: true, stdout: "ID=ubuntu" }; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const sudoAutofillRef = { current: null }; - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Target", @@ -57,40 +43,13 @@ test("startMosh enables sudo autofill with the host saved password", async () => password: "saved-secret", }, onOsDetected: (_id: string, distro: string) => { detected = distro; resolveDetected(); }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, sudoAutofillPassword: "saved-secret", onSudoHint: () => true, - sessionRef: { current: null }, hasConnectedRef: { current: true }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, sudoAutofillRef, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + }); + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); assert.equal(probes, 0, "wait for the Mosh handshake before probing"); @@ -108,30 +67,14 @@ test("startSSH accepts jump host local identity file paths with unreadable saved let capturedOptions: Record | null = null; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Target", @@ -139,7 +82,6 @@ test("startSSH accepts jump host local identity file paths with unreadable saved username: "alice", hostChain: { hostIds: ["jump-1"] }, }, - keys: [], resolvedChainHosts: [{ id: "jump-1", label: "Jump", @@ -149,35 +91,11 @@ test("startSSH accepts jump host local identity file paths with unreadable saved password: ENCRYPTED_CREDENTIAL_PLACEHOLDER, identityFilePaths: ["/Users/alice/.ssh/jump_ed25519"], }], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startSSH(term as never); @@ -192,30 +110,14 @@ test("startSSH does not use stale local key paths when selected key material is let capturedOptions: Record | null = null; let needsAuth = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Target", @@ -231,36 +133,11 @@ test("startSSH does not use stale local key paths when selected key material is source: "imported", privateKey: ENCRYPTED_CREDENTIAL_PLACEHOLDER, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, setNeedsAuth: (value: boolean) => { needsAuth = value; }, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startSSH(term as never); @@ -272,30 +149,14 @@ test("startSSH does not use stale jump host local key paths when selected key ma let capturedOptions: Record | null = null; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Target", @@ -318,35 +179,11 @@ test("startSSH does not use stale jump host local key paths when selected key ma identityFileId: "bad-jump-key", identityFilePaths: ["/Users/alice/.ssh/stale_jump_ed25519"], }], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startSSH(term as never); @@ -357,30 +194,14 @@ test("startSSH does not use stale jump host local key paths when selected key ma test("startMosh does not pass legacy configured mosh client paths to the backend", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async (options: Record) => { capturedOptions = options; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -388,40 +209,15 @@ test("startMosh does not pass legacy configured mosh client paths to the backend username: "alice", port: 2200, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", terminalSettings: { terminalEmulationType: "xterm-256color", moshClientPath: "/usr/local/bin/mosh-client", }, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -434,30 +230,14 @@ test("startMosh does not pass legacy configured mosh client paths to the backend test("startMosh passes the saved password to the mosh backend", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async (options: Record) => { capturedOptions = options; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -466,37 +246,11 @@ test("startMosh passes the saved password to the mosh backend", async () => { password: "saved-secret", port: 2200, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -508,30 +262,14 @@ test("startMosh passes the saved password to the mosh backend", async () => { test("startMosh passes configured key material to the mosh backend", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async (options: Record) => { capturedOptions = options; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -549,36 +287,10 @@ test("startMosh passes configured key material to the mosh backend", async () => privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey\n-----END OPENSSH PRIVATE KEY-----", passphrase: "key-passphrase", }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -595,30 +307,14 @@ test("startMosh asks for credential re-entry when saved key material cannot be d let needsAuth = false; let retryMessage: string | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -633,36 +329,12 @@ test("startMosh asks for credential re-entry when saved key material cannot be d label: "Deploy key", privateKey: "enc:v1:djEwdGVzdAAAAAAAAAAAAAAAAA==", }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, setNeedsAuth: (value: boolean) => { needsAuth = value; }, setAuthRetryMessage: (message: string | null) => { retryMessage = message; }, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -675,30 +347,14 @@ test("startMosh does not use stale local key paths when selected key material is let started = false; let needsAuth = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -714,36 +370,12 @@ test("startMosh does not use stale local key paths when selected key material is label: "Deploy key", privateKey: "enc:v1:djEwdGVzdAAAAAAAAAAAAAAAAA==", }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, setNeedsAuth: (value: boolean) => { needsAuth = value; }, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -754,30 +386,14 @@ test("startMosh does not use stale local key paths when selected key material is test("startMosh omits identity file paths when password auth is explicit", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async (options: Record) => { capturedOptions = options; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -789,37 +405,10 @@ test("startMosh omits identity file paths when password auth is explicit", async identityFilePaths: ["/should/not/be/used"], port: 2200, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -833,30 +422,14 @@ test("startMosh rejects missing saved proxy profiles", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -865,37 +438,11 @@ test("startMosh rejects missing saved proxy profiles", async () => { port: 2200, proxyProfileId: "missing-proxy", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -907,30 +454,14 @@ test("startMosh rejects missing proxy identities before the unsupported proxy gu let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -944,38 +475,11 @@ test("startMosh rejects missing proxy identities before the unsupported proxy gu identityId: "missing-identity", }, }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -988,30 +492,14 @@ test("startMosh rejects incomplete proxy identities before the unsupported proxy let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1025,7 +513,6 @@ test("startMosh rejects incomplete proxy identities before the unsupported proxy identityId: "identity-1", }, }, - keys: [], identities: [{ id: "identity-1", label: "Proxy login", @@ -1033,36 +520,11 @@ test("startMosh rejects incomplete proxy identities before the unsupported proxy authMethod: "password", created: 1, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -1075,30 +537,14 @@ test("startMosh does not connect when a proxy identity password is encrypted", a let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1112,7 +558,6 @@ test("startMosh does not connect when a proxy identity password is encrypted", a identityId: "identity-1", }, }, - keys: [], identities: [{ id: "identity-1", label: "Proxy login", @@ -1121,36 +566,11 @@ test("startMosh does not connect when a proxy identity password is encrypted", a password: ENCRYPTED_CREDENTIAL_PLACEHOLDER, created: 1, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -1162,30 +582,14 @@ test("startMosh rejects configured proxies instead of connecting directly", asyn let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1195,37 +599,11 @@ test("startMosh rejects configured proxies instead of connecting directly", asyn proxyProfileId: "proxy-1", proxyConfig: { type: "http", host: "proxy.example.com", port: 3128 }, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -1237,30 +615,14 @@ test("startMosh rejects jump host chains instead of connecting directly", async let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { started = true; return "mosh-session"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1269,37 +631,12 @@ test("startMosh rejects jump host chains instead of connecting directly", async hostChain: { hostIds: ["jump-1"] }, port: 2200, }, - keys: [], resolvedChainHosts: [{ id: "jump-1", hostname: "jump.example.test" }], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -1313,79 +650,42 @@ test("startMosh defers startup commands until mosh-client is ready", async () => let readyDisposed = false; let dataCb: ((data: string, meta?: { moshHandshake?: boolean }) => void) | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string, meta?: { moshHandshake?: boolean }) => void) => { dataCb = cb; return noop; }, - onSessionExit: () => noop, onMoshSessionReady: (_id: string, cb: (evt: { sessionId: string }) => void) => { readyCb = cb; return () => { readyDisposed = true; }; }, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", hostname: "example.test", username: "alice", }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", startupCommand: "echo from-snippet", terminalSettings: { startupCommandDelayMs: 0 }, terminalBackend, sessionRef: { current: null as string | null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, disposeDataRef: { current: null as (() => void) | null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, updateStatus: (status: string) => { if (status === "connected") ctx.hasConnectedRef.current = true; }, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, + const term = createTermStub({ modes: {}, options: {}, - }; + }); await createTerminalSessionStarters(ctx as never).startMosh(term as never); @@ -1410,71 +710,30 @@ test("startMosh defers startup commands until mosh-client is ready", async () => test("startMosh disposes ready subscription when startMoshSession rejects", async () => { let readyDisposed = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { throw new Error("mosh-client missing"); }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onMoshSessionReady: () => () => { readyDisposed = true; }, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", hostname: "example.test", username: "alice", }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", startupCommand: "echo startup", - terminalSettings: {}, terminalBackend, sessionRef: { current: null as string | null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, disposeDataRef: { current: null as (() => void) | null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startMosh(term as never); assert.equal(readyDisposed, true); @@ -1484,76 +743,38 @@ test("startMosh still runs startup when ready fires during startMoshSession awai const sent: string[] = []; let readyCb: ((evt: { sessionId: string }) => void) | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", + const terminalBackend = createMockTerminalBackend({ startMoshSession: async () => { // Simulate a fast handshake that emits ready before the await resumes. readyCb?.({ sessionId: "session-1" }); return "session-1"; }, - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onMoshSessionReady: (_id: string, cb: (evt: { sessionId: string }) => void) => { readyCb = cb; return noop; }, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", hostname: "example.test", username: "alice", }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", startupCommand: "echo startup", terminalSettings: { startupCommandDelayMs: 0 }, terminalBackend, sessionRef: { current: null as string | null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, disposeDataRef: { current: null as (() => void) | null }, disposeExitRef: { current: null as (() => void) | null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, + const term = createTermStub({ modes: {}, options: {}, - }; + }); await createTerminalSessionStarters(ctx as never).startMosh(term as never); await new Promise((resolve) => setTimeout(resolve, 5)); diff --git a/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts b/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts index 7f2039c04..01ea8742e 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.telnet.test.ts @@ -1,5 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { createMockTerminalBackend, createStarterContext, createTermStub } from "./testSupport/starterHarness"; import { createTerminalSessionStarters, @@ -14,30 +15,14 @@ test("startTelnet rejects missing saved proxy profiles", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { started = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -46,37 +31,11 @@ test("startTelnet rejects missing saved proxy profiles", async () => { telnetPort: 2323, proxyProfileId: "missing-proxy", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -88,30 +47,14 @@ test("startTelnet rejects missing proxy identities before connecting", async () let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { started = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -125,38 +68,11 @@ test("startTelnet rejects missing proxy identities before connecting", async () identityId: "missing-identity", }, }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -168,30 +84,14 @@ test("startTelnet rejects missing proxy identities before connecting", async () test("startTelnet passes saved telnet credentials without falling back after explicit clears", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -202,37 +102,10 @@ test("startTelnet passes saved telnet credentials without falling back after exp telnetPassword: "telnet-password", telnetPort: 2323, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -245,30 +118,14 @@ test("startTelnet passes saved telnet credentials without falling back after exp test("startTelnet preserves an explicitly cleared telnet password", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -279,37 +136,10 @@ test("startTelnet preserves an explicitly cleared telnet password", async () => telnetPassword: "", telnetPort: 2323, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -321,30 +151,14 @@ test("startTelnet preserves an explicitly cleared telnet password", async () => test("startTelnet uses selected telnet identity credentials when telnet fields are unset", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -356,7 +170,6 @@ test("startTelnet uses selected telnet identity credentials when telnet fields a telnetPassword: undefined, telnetPort: 2323, }, - keys: [], identities: [{ id: "ssh-identity", label: "SSH login", @@ -372,36 +185,10 @@ test("startTelnet uses selected telnet identity credentials when telnet fields a password: "telnet-identity-password", created: 2, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -413,30 +200,14 @@ test("startTelnet uses selected telnet identity credentials when telnet fields a test("startTelnet does not fall back to ssh identity credentials when telnet identity is unset", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -447,7 +218,6 @@ test("startTelnet does not fall back to ssh identity credentials when telnet ide telnetPassword: undefined, telnetPort: 2323, }, - keys: [], identities: [{ id: "ssh-identity", label: "SSH login", @@ -456,36 +226,10 @@ test("startTelnet does not fall back to ssh identity credentials when telnet ide password: "ssh-identity-password", created: 1, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -498,30 +242,14 @@ test("startTelnet rejects missing telnet identities before connecting", async () let didConnect = false; let error: string | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { didConnect = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -530,40 +258,13 @@ test("startTelnet rejects missing telnet identities before connecting", async () telnetIdentityId: "missing-telnet-identity", telnetPort: 2323, }, - keys: [], - identities: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -575,30 +276,14 @@ test("startTelnet rejects telnet identities without passwords before connecting" let didConnect = false; let error: string | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { didConnect = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -607,7 +292,6 @@ test("startTelnet rejects telnet identities without passwords before connecting" telnetIdentityId: "passwordless-telnet-identity", telnetPort: 2323, }, - keys: [], identities: [{ id: "passwordless-telnet-identity", label: "Passwordless", @@ -615,38 +299,13 @@ test("startTelnet rejects telnet identities without passwords before connecting" authMethod: "key", created: 1, }], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -658,64 +317,21 @@ test("startTelnet marks the session connected before the server sends output", a let status = "connecting"; let progressValue = 0; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + const terminalBackend = createMockTerminalBackend(); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", hostname: "example.test", telnetPort: 23, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, updateStatus: (next: string) => { status = next; }, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, setProgressValue: (value: number) => { progressValue = value; }, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -732,30 +348,14 @@ test("startTelnet rejects unreadable saved telnet passwords before connecting", let status = ""; const writes: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { started = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -766,29 +366,12 @@ test("startTelnet rejects unreadable saved telnet passwords before connecting", telnetPassword: ENCRYPTED_CREDENTIAL_PLACEHOLDER, telnetPort: 2323, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, updateStatus: (next: string) => { status = next; }, - setStatus: noop, setError: (message: string) => { error = message; }, setNeedsAuth: (value: boolean) => { needsAuth = value; }, setAuthRetryMessage: (message: string | null) => { retryMessage = message; }, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); const term = { cols: 120, @@ -819,24 +402,11 @@ test("startTelnet waits for auto-login before running the startup command", asyn resolveCommand = resolve; }); - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onTelnetAutoLoginComplete: (sessionId: string, cb: (evt: { sessionId: string }) => void) => { assert.equal(sessionId, "session-1"); autoLoginComplete = cb; @@ -845,15 +415,13 @@ test("startTelnet waits for auto-login before running the startup command", asyn onTelnetAutoLoginCancelled: () => () => { disposedAutoLoginCancelListener = true; }, - onChainProgress: () => noop, writeToSession: (_sessionId: string, data: string) => { writtenCommands.push(data); resolveCommand?.(); }, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -864,40 +432,13 @@ test("startTelnet waits for auto-login before running the startup command", asyn telnetPort: 2323, startupCommand: "show version", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, onCommandExecuted: (command: string) => { executedCommands.push(command); }, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); assert.ok(capturedOptions); @@ -924,21 +465,8 @@ test("startTelnet keeps Telnet echo subscription after auto-login is cancelled", let echoCallback: ((evt: { sessionId: string; remoteEcho: boolean; localEcho: boolean }) => void) | null = null; let echoDisposals = 0; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => "session-1", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onTelnetAutoLoginComplete: () => noop, onTelnetAutoLoginCancelled: (_sessionId: string, cb: (evt: { sessionId: string }) => void) => { autoLoginCancelled = cb; @@ -950,14 +478,11 @@ test("startTelnet keeps Telnet echo subscription after auto-login is cancelled", echoDisposals += 1; }; }, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const telnetLocalEchoRef = { current: false }; const disposeTelnetEchoModeRef = { current: null as (() => void) | null }; - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", protocol: "telnet", @@ -966,39 +491,12 @@ test("startTelnet keeps Telnet echo subscription after auto-login is cancelled", telnetUsername: "admin", startupCommand: "show version", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, telnetLocalEchoRef, disposeTelnetEchoModeRef, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -1015,69 +513,28 @@ test("startTelnet ignores stale replacement failures", async () => { let error: string | null = null; const statuses: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { throw new Error("Error invoking remote method 'netcatty:telnet:start': Error: Telnet session start was replaced"); }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onTelnetEchoMode: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", protocol: "telnet", label: "Example", hostname: "example.test", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, telnetLocalEchoRef: { current: false }, disposeTelnetEchoModeRef: { current: null }, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, updateStatus: (next: string) => { statuses.push(next); }, - setStatus: noop, setError: (message: string | null) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -1092,24 +549,11 @@ test("startTelnet runs a multi-line startup command in sequence when requested", let autoLoginComplete: ((evt: { sessionId: string }) => void) | null = null; let disposedAutoLoginCancelListener = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onTelnetAutoLoginComplete: (sessionId: string, cb: (evt: { sessionId: string }) => void) => { assert.equal(sessionId, "session-1"); autoLoginComplete = cb; @@ -1118,14 +562,12 @@ test("startTelnet runs a multi-line startup command in sequence when requested", onTelnetAutoLoginCancelled: () => () => { disposedAutoLoginCancelListener = true; }, - onChainProgress: () => noop, writeToSession: (_sessionId: string, data: string) => { writtenCommands.push(data); }, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1137,41 +579,15 @@ test("startTelnet runs a multi-line startup command in sequence when requested", startupCommand: "first cmd\nsecond cmd", startupCommandRunMode: "lineDelay", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", terminalSettings: { startupCommandDelayMs: 20 }, multiLineRunMode: "lineDelay", terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, onCommandExecuted: (command: string) => { executedCommands.push(command); }, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); assert.ok(capturedOptions); @@ -1197,24 +613,11 @@ test("startTelnet cancels pending startup command when user takes over", async ( let autoLoginComplete: ((evt: { sessionId: string }) => void) | null = null; let autoLoginCancelled: ((evt: { sessionId: string }) => void) | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onTelnetAutoLoginComplete: (_sessionId: string, cb: (evt: { sessionId: string }) => void) => { autoLoginComplete = cb; return noop; @@ -1223,14 +626,12 @@ test("startTelnet cancels pending startup command when user takes over", async ( autoLoginCancelled = cb; return noop; }, - onChainProgress: () => noop, writeToSession: (_sessionId: string, data: string) => { writtenCommands.push(data); }, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1239,37 +640,10 @@ test("startTelnet cancels pending startup command when user takes over", async ( telnetPassword: "secret", startupCommand: "show version", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); assert.ok(capturedOptions); @@ -1291,23 +665,11 @@ test("startTelnet does not run startup command if auto-login never completes", a let sessionExit: ((evt: { reason?: "closed" }) => void) | null = null; let disposedAutoLoginListener = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, onSessionExit: (_sessionId: string, cb: (evt: { reason?: "closed" }) => void) => { sessionExit = cb; return noop; @@ -1318,14 +680,12 @@ test("startTelnet does not run startup command if auto-login never completes", a disposedAutoLoginListener = true; }; }, - onChainProgress: () => noop, writeToSession: (_sessionId: string, data: string) => { writtenCommands.push(data); }, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1336,40 +696,13 @@ test("startTelnet does not run startup command if auto-login never completes", a telnetPort: 2323, startupCommand: "show version", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, onCommandExecuted: (command: string) => { executedCommands.push(command); }, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); assert.ok(capturedOptions); @@ -1389,32 +722,17 @@ test("startTelnet does not run startup command during manual login", async () => const writtenCommands: string[] = []; let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async (options: Record) => { capturedOptions = options; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_sessionId: string, data: string) => { writtenCommands.push(data); }, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1426,37 +744,10 @@ test("startTelnet does not run startup command during manual login", async () => port: 2222, startupCommand: "show version", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); await new Promise((resolve) => setTimeout(resolve, 700)); @@ -1470,30 +761,14 @@ test("startTelnet rejects configured proxies instead of connecting directly", as let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", + const terminalBackend = createMockTerminalBackend({ startTelnetSession: async () => { started = true; return "telnet-session"; }, - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", label: "Example", @@ -1503,37 +778,11 @@ test("startTelnet rejects configured proxies instead of connecting directly", as proxyProfileId: "proxy-1", proxyConfig: { type: "http", host: "proxy.example.com", port: 3128 }, }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, - sessionRef: { current: null }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, setError: (message: string) => { error = message; }, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); await createTerminalSessionStarters(ctx as never).startTelnet(term as never); @@ -1562,46 +811,20 @@ test("reattachSession refreshes Telnet echo-mode subscription", () => { const telnetLocalEchoRef = { current: false }; const disposeTelnetEchoModeRef = { current: null as (() => void) | null }; - const ctx = { + const ctx = createStarterContext({ host: { id: "host-1", protocol: "telnet", label: "Example", hostname: "example.test", }, - keys: [], - resolvedChainHosts: [], - sessionId: "session-1", - terminalSettings: {}, terminalBackend, telnetLocalEchoRef, disposeTelnetEchoModeRef, sessionRef: { current: "telnet-session" }, - hasConnectedRef: { current: false }, - hasRunStartupCommandRef: { current: false }, - disposeDataRef: { current: null }, - disposeExitRef: { current: null }, - fitAddonRef: { current: null }, - serializeAddonRef: { current: null }, - pendingAuthRef: { current: null }, - updateStatus: noop, - setStatus: noop, - setError: noop, - setNeedsAuth: noop, - setAuthRetryMessage: noop, - setAuthPassword: noop, - setProgressLogs: noop, - setProgressValue: noop, - setChainProgress: noop, - }; + }); - const term = { - cols: 120, - rows: 32, - write: noop, - writeln: noop, - scrollToBottom: noop, - }; + const term = createTermStub(); const starters = createTerminalSessionStarters(ctx as never); assert.equal(starters.reattachSession(term as never), true); diff --git a/components/terminal/runtime/createTerminalSessionStarters.test.ts b/components/terminal/runtime/createTerminalSessionStarters.test.ts index 79b8493bc..90ad80a6c 100644 --- a/components/terminal/runtime/createTerminalSessionStarters.test.ts +++ b/components/terminal/runtime/createTerminalSessionStarters.test.ts @@ -1,5 +1,6 @@ import test from "node:test"; import assert from "node:assert/strict"; +import { createMockTerminalBackend } from "./testSupport/starterHarness"; import { createTerminalSessionStarters, @@ -1663,28 +1664,12 @@ test("ET keeps automatic jump discovery available with an unreadable saved passw test("startSSH forwards custom ProxyCommand to the SSH bridge", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { id: "host-1", @@ -1745,28 +1730,12 @@ test("startSSH forwards custom ProxyCommand to the SSH bridge", async () => { test("startSSH resolves target proxy credentials from an identity", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -1804,28 +1773,12 @@ test("startSSH resolves target proxy credentials from an identity", async () => test("startSSH resolves jump host proxy credentials from an identity", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -1885,29 +1838,13 @@ test("startSSH shows jump-host auth failures without opening target auth retry", let retryMessage: string | null = "previous retry"; let status = ""; const progressLogs: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { const err = new Error('Jump host authentication failed for "Bastion": All configured authentication methods failed'); (err as Error & { isJumpHostAuthError?: boolean }).isJumpHostAuthError = true; throw err; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -1950,29 +1887,13 @@ test("startSSH shows jump-host auth failures without opening target auth retry", test("startSSH recognizes Electron-prefixed jump-host auth failures", async () => { let error = ""; let needsAuth = false; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { throw new Error( 'Error invoking remote method "netcatty:start": Error: Jump host authentication failed for "Bastion": All configured authentication methods failed', ); }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, setNeedsAuth: (value: boolean) => { needsAuth = value; }, @@ -1990,28 +1911,12 @@ test("startSSH does not open auth retry for socket errors mentioning auth in hos let needsAuth = false; let retryMessage: string | null = "previous retry"; let status = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { const err = new Error("Connection reset by auth-bastion.example.com"); throw err; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2046,27 +1951,11 @@ test("startSSH does not open auth retry for socket errors mentioning auth in hos test("startSSH does not open auth retry for non-login permission denied errors", async () => { let needsAuth = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { throw new Error("Permission denied opening channel to auth-bastion.example.com"); }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, setNeedsAuth: (value: boolean) => { needsAuth = value; }, @@ -2082,28 +1971,12 @@ test("startSSH does not open auth retry for non-login permission denied errors", test("startSSH rejects missing saved proxy profiles before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2125,28 +1998,12 @@ test("startSSH rejects missing saved proxy profiles before connecting", async () test("startSSH rejects missing saved proxy profiles on jump hosts before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2175,28 +2032,12 @@ test("startSSH rejects missing saved proxy profiles on jump hosts before connect test("startSSH rejects missing proxy identities before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2224,28 +2065,12 @@ test("startSSH rejects missing proxy identities before connecting", async () => test("startSSH rejects incomplete proxy identities before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2280,28 +2105,12 @@ test("startSSH rejects incomplete proxy identities before connecting", async () test("startSSH rejects proxy identities with blank usernames even when passwords are encrypted", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2337,28 +2146,12 @@ test("startSSH rejects proxy identities with blank usernames even when passwords test("startSSH rejects target proxy identity passwords that cannot be decrypted", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2393,28 +2186,12 @@ test("startSSH rejects target proxy identity passwords that cannot be decrypted" test("startSSH rejects missing jump host proxy identities before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2449,28 +2226,12 @@ test("startSSH rejects missing jump host proxy identities before connecting", as test("startSSH rejects incomplete jump host proxy identities before connecting", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2514,28 +2275,12 @@ test("startSSH rejects incomplete jump host proxy identities before connecting", test("startSSH rejects jump host proxy identity passwords that cannot be decrypted", async () => { let started = false; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { started = true; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ terminalBackend, host: { @@ -2578,29 +2323,13 @@ test("startSSH rejects jump host proxy identity passwords that cannot be decrypt test("startSSH sends key and password together in one connection for publickey+password MFA hosts", async () => { let capturedOptions: Record | null = null; let startCalls = 0; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { startCalls += 1; capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { id: "host-1", @@ -2664,13 +2393,7 @@ test("startSSH resets the TCP dial timeout state before password fallback", asyn let startCalls = 0; const startOptions: Record[] = []; const tcpDialState: boolean[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { startCalls += 1; startOptions.push(options); @@ -2680,20 +2403,11 @@ test("startSSH resets the TCP dial timeout state before password fallback", asyn } return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onChainProgress: (listener: typeof chainProgressListener) => { chainProgressListener = listener; return noop; }, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -2737,33 +2451,18 @@ test("startSSH resets the TCP dial timeout state when a jump host starts forward error?: string, ) => void = noop; const tcpDialState: boolean[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async () => { chainProgressListener("session-1", 1, 2, "bastion.example.test", "tcp-connected"); chainProgressListener("session-1", 1, 2, "bastion.example.test", "forwarding"); chainProgressListener("session-1", 2, 2, "target.example.test", "tcp-connected"); return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, onChainProgress: (listener: typeof chainProgressListener) => { chainProgressListener = listener; return noop; }, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -2793,28 +2492,12 @@ test("startSSH resets the TCP dial timeout state when a jump host starts forward test("startSSH forwards the saved sudo autofill password to the SSH bridge", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -2835,28 +2518,13 @@ test("startSSH forwards the saved sudo autofill password to the SSH bridge", asy test("startSSH enables sudo autofill only with the host saved password", async () => { let onData: ((data: string) => void) | null = null; const sent: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -2880,28 +2548,14 @@ test("startSSH does not use unsaved retry passwords for sudo autofill", async () let onData: ((data: string) => void) | null = null; const sent: string[] = []; let captured: NetcattySSHOptions | undefined; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: NetcattySSHOptions) => { captured = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -2950,28 +2604,13 @@ test("startSSH does not use unsaved retry passwords for sudo autofill", async () test("startSSH uses pending saved auth for sudo autofill on the first saved connection", async () => { let onData: ((data: string) => void) | null = null; const sent: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -3002,28 +2641,13 @@ test("startSSH uses pending saved auth for sudo autofill on the first saved conn test("startSSH does not use merged group default passwords for sudo autofill", async () => { let onData: ((data: string) => void) | null = null; const sent: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -3045,28 +2669,13 @@ test("startSSH does not use merged group default passwords for sudo autofill", a test("startSSH uses the provided sudo autofill password", async () => { let onData: ((data: string) => void) | null = null; const sent: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, writeToSession: (_id: string, data: string) => sent.push(data), - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { id: "host-1", @@ -3089,25 +2698,7 @@ test("startSerial captures direct connected banner in terminal log data", async const capturedLogData: string[] = []; const writtenData: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + const terminalBackend = createMockTerminalBackend(); const ctx = { host: { @@ -3175,28 +2766,12 @@ test("local session captures paste cleanup writes in terminal log data", async ( const writes: string[] = []; let onData: ((data: string) => void) | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -3301,27 +2876,11 @@ test("local session runs startup command after attaching", async () => { const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = []; const attached: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, + const terminalBackend = createMockTerminalBackend({ writeToSession: (id: string, data: string, options?: { automated?: boolean }) => { sessionWrites.push({ id, data, automated: options?.automated }); }, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { @@ -3618,27 +3177,11 @@ test("startup command suppression is consumed only when scheduling", () => { test("restored local reconnect runs the host startup command while automatic retry suppresses it", async () => { const sessionWrites: Array<{ id: string; data: string; automated?: boolean }> = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, + const terminalBackend = createMockTerminalBackend({ writeToSession: (id: string, data: string, options?: { automated?: boolean }) => { sessionWrites.push({ id, data, automated: options?.automated }); }, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { @@ -3890,28 +3433,12 @@ for (const { name, hostDirectory, globalDirectory, expectedDirectory } of [ ]) { test(`local session start ${name}`, async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", + const terminalBackend = createMockTerminalBackend({ startLocalSession: async (options: Record) => { capturedOptions = options; return "local-session"; }, - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = createStarterContext({ host: { @@ -3937,27 +3464,11 @@ test("local session restores cwd before startup command after attaching", async const executedCommands: string[] = []; const progressLogs: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, + const terminalBackend = createMockTerminalBackend({ writeToSession: (id: string, data: string, options?: { automated?: boolean }) => { sessionWrites.push({ id, data, automated: options?.automated }); }, - resizeSession: noop, - }; + }); const restoreCwdIntentRef = { current: { cwd: "/srv/app dir", command: "cd -- '/srv/app dir'" }, @@ -4001,27 +3512,11 @@ test("ssh session restores cwd before startup command after attaching", async () const progressLogs: string[] = []; const restoredCwds: string[] = []; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, + const terminalBackend = createMockTerminalBackend({ writeToSession: (id: string, data: string, options?: { automated?: boolean }) => { sessionWrites.push({ id, data, automated: options?.automated }); }, - resizeSession: noop, - }; + }); const restoreCwdIntentRef = { current: { cwd: "/srv/app dir", command: "cd -- '/srv/app dir'" }, @@ -4063,28 +3558,12 @@ test("local session keeps timestamp anchors for preserved scrollback when reusin let onData: ((data: string) => void) | null = null; let cursorLine = 0; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4175,28 +3654,12 @@ test("session data waits for prior terminal writes before evaluating prompt line let cursorX = 0; let lineText = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const promptState = createPromptLineBreakState(); promptState.lastPromptText = "$ "; @@ -4287,28 +3750,12 @@ test("prompt line break display insertion does not mutate captured session log d let cursorX = 0; let lineText = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; }, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const promptState = createPromptLineBreakState(); promptState.lastPromptText = "$ "; @@ -4397,19 +3844,7 @@ test("local session exit text waits for pending terminal output writes", async ( let onData: ((data: string) => void) | null = null; let onExit: ((evt: { reason?: "closed" }) => void) | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, - startSSHSession: async () => "ssh-session", - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), + const terminalBackend = createMockTerminalBackend({ onSessionData: (_id: string, cb: (data: string) => void) => { onData = cb; return noop; @@ -4418,10 +3853,7 @@ test("local session exit text waits for pending terminal output writes", async ( onExit = cb; return noop; }, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4486,28 +3918,12 @@ test("startSSH allows jump hosts that use reference key files with unavailable s let capturedOptions: Record | null = null; let error = ""; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4577,28 +3993,12 @@ test("startSSH allows jump hosts that use reference key files with unavailable s test("startSSH forwards per-host SSH settings to the native bridge", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4659,28 +4059,12 @@ test("startSSH forwards per-host SSH settings to the native bridge", async () => test("startSSH omits identity file paths when password auth is selected", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4743,28 +4127,12 @@ test("startSSH passes known host records to the SSH bridge", async () => { discoveredAt: 1, }]; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4820,28 +4188,12 @@ test("startSSH passes known host records to the SSH bridge", async () => { test("startSSH omits jump host identity file paths when password auth is selected", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { @@ -4903,28 +4255,12 @@ test("startSSH omits jump host identity file paths when password auth is selecte test("startSSH sends local identity file paths with saved passwords for key auth", async () => { let capturedOptions: Record | null = null; - const terminalBackend = { - backendAvailable: () => true, - telnetAvailable: () => true, - moshAvailable: () => true, - localAvailable: () => true, - serialAvailable: () => true, - execAvailable: () => true, + const terminalBackend = createMockTerminalBackend({ startSSHSession: async (options: Record) => { capturedOptions = options; return "ssh-session"; }, - startTelnetSession: async () => "telnet-session", - startMoshSession: async () => "mosh-session", - startLocalSession: async () => "local-session", - startSerialSession: async () => "serial-session", - execCommand: async () => ({}), - onSessionData: () => noop, - onSessionExit: () => noop, - onChainProgress: () => noop, - writeToSession: noop, - resizeSession: noop, - }; + }); const ctx = { host: { diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts index 48d5ebea7..5ee562c41 100644 --- a/components/terminal/runtime/createXTermRuntime.ts +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -69,7 +69,7 @@ import { installEraseInDisplayHandlers, } from "../clearTerminalViewport"; import { pulseCopyOnSelectUserCommand } from "../copyOnSelect"; -import { getTerminalSelectionForClipboard } from "../normalizeTerminalSelection"; +import { getTerminalSelectionForClipboard } from "../../../domain/terminalSelection"; import { createKittyKeyboardSessionStateStore, encodeKittyCompositionText, diff --git a/components/terminal/runtime/terminalBinaryInput.test.ts b/components/terminal/runtime/terminalBinaryInput.test.ts deleted file mode 100644 index 43dd38cba..000000000 --- a/components/terminal/runtime/terminalBinaryInput.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; -import { runInNewContext } from "node:vm"; - -const source = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8"); -const start = source.indexOf(" term.onBinary((data) => {"); -const end = source.indexOf(" const handleKittyKeyboardBroadcast =", start); -assert.ok(start >= 0 && end > start, "runtime must subscribe to xterm onBinary"); - -test("onBinary forwards unchanged bytes only to the current session without text handling", () => { - const writes: Array<{ id: string; data: string; binary: boolean }> = []; - const sessionRef: { current: string | null } = { current: "first" }; - let receive!: (data: string) => void; - runInNewContext(source.slice(start, end), { - term: { onBinary(callback: typeof receive) { receive = callback; } }, - ctx: { - sessionRef, - terminalBackend: { - writeToSession(id: string, data: string, options: { binary: boolean }) { - writes.push({ id, data, binary: options.binary }); - }, - }, - }, - handleTerminalInputData: () => assert.fail("binary reports must bypass text handling"), - }); - - const mouse = String.fromCharCode(0x1b, 0x5b, 0x4d, 0x20, 0x21, 0xc0); - receive(mouse); - sessionRef.current = "replacement"; - const allBytes = String.fromCharCode(...Array.from({ length: 256 }, (_, i) => i)); - receive(allBytes); - sessionRef.current = null; - receive(mouse); - - assert.deepEqual(writes, [ - { id: "first", data: mouse, binary: true }, - { id: "replacement", data: allBytes, binary: true }, - ]); -}); diff --git a/components/terminal/runtime/terminalDistroDetection.ts b/components/terminal/runtime/terminalDistroDetection.ts index 21a8d76f3..8ce39d46a 100644 --- a/components/terminal/runtime/terminalDistroDetection.ts +++ b/components/terminal/runtime/terminalDistroDetection.ts @@ -4,7 +4,7 @@ import { hostRestrictsExtraSshChannels, normalizeDistroId, } from "../../../domain/host"; -import { remoteSoftwareRequiresSingleChannel } from "../../../domain/singleChannelSshBanner.shared.mjs"; +import { remoteSoftwareRequiresSingleChannel } from "../../../domain/singleChannelSshBanner.shared.cjs"; import { logger } from "../../../lib/logger"; import type { TerminalSessionStartersContext } from "./createTerminalSessionStarters.types"; diff --git a/components/terminal/runtime/terminalHistoryScrollOverride.ts b/components/terminal/runtime/terminalHistoryScrollOverride.ts index a7316d10d..dbe69cfd7 100644 --- a/components/terminal/runtime/terminalHistoryScrollOverride.ts +++ b/components/terminal/runtime/terminalHistoryScrollOverride.ts @@ -1,4 +1,4 @@ -import { joinSoftWrappedRows } from "../normalizeTerminalSelection"; +import { joinSoftWrappedRows } from "../../../domain/terminalSelection"; type WheelLike = Pick< WheelEvent, diff --git a/components/terminal/runtime/terminalInterceptorInputSafety.test.ts b/components/terminal/runtime/terminalInterceptorInputSafety.test.ts deleted file mode 100644 index d6370a905..000000000 --- a/components/terminal/runtime/terminalInterceptorInputSafety.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const runtimeSource = readFileSync(new URL("./createXTermRuntime.ts", import.meta.url), "utf8"); -const autocompleteHookSource = readFileSync( - new URL("../autocomplete/useTerminalAutocomplete.ts", import.meta.url), - "utf8", -); -const attachmentSource = readFileSync(new URL("./terminalSessionAttachment.ts", import.meta.url), "utf8"); -const terminalSource = readFileSync(new URL("../../Terminal.tsx", import.meta.url), "utf8"); -const terminalLayerSource = readFileSync(new URL("../../TerminalLayer.tsx", import.meta.url), "utf8"); -const preloadSource = readFileSync( - new URL("../../../electron/preload/api.cjs", import.meta.url), - "utf8", -); -const scriptBridgeSource = readFileSync( - new URL("../../../electron/bridges/scriptBridge.cjs", import.meta.url), - "utf8", -); -const scriptCodegenSource = readFileSync( - new URL("../../../electron/scripts/scriptCodegen.cjs", import.meta.url), - "utf8", -); -const scriptDialogSource = readFileSync( - new URL("../../scripts/ScriptDialogHost.tsx", import.meta.url), - "utf8", -); - -test("password-prompt input is classified before prompt state reset and cannot broadcast", () => { - assert.match( - attachmentSource, - /typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput/u, - ); - assert.match( - terminalSource, - /typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput[\s\S]*?sensitivePromptOutputTailRef\.current = "";[\s\S]*?return;[\s\S]*?isUntrustedTerminalInputPrompt/u, - ); - assert.match( - runtimeSource, - /const sensitive = ctx\.passwordPromptActiveRef\?\.current === true[\s\S]*?const canBroadcastInput = shouldBroadcastDuringSensitivePrompt\(\{\s*sensitivePromptActive: sensitive,[\s\S]*?broadcastPasswordBypass: ctx\.broadcastPasswordBypassRef\?\.current === true && options\?\.sensitive !== true,[\s\S]*?\}\) &&[\s\S]*?const willBroadcastInput = canBroadcastInput && options\?\.skipBroadcast !== true;/u, - ); - assert.match( - runtimeSource, - /for \(const chunk of getTextInputWireChunks\(outData, usePerCharacterInput && options\?\.perCharacterWrites === true, \(ctx\.host\.protocol === undefined \|\| ctx\.host\.protocol === "ssh"\) && !ctx\.host\.moshEnabled && !ctx\.host\.etEnabled\)\) \{\s*ctx\.terminalBackend\.writeToSession\(id, chunk, \{\s*sensitive,\s*serialEraseChar,[\s\S]*?\}\);\s*\}/u, - ); - assert.match( - runtimeSource, - /writeToSession\(id, nextData, \{ sensitive \}\)/u, - ); - assert.match( - runtimeSource, - /const broadcastUserPasteData = \(\s*data: string,\s*options\?: TerminalBroadcastInputOptions,\s*\) => \{[\s\S]*?const dispatchingFromPasswordPrompt = ctx\.passwordPromptActiveRef\?\.current === true;[\s\S]*?const sourceSensitive = dispatchingFromPasswordPrompt \|\| options\?\.sensitive === true;[\s\S]*?broadcastPasswordBypass: ctx\.broadcastPasswordBypassRef\?\.current === true,[\s\S]*?onBroadcastInputRef\.current\(\s*data,\s*ctx\.sessionId,\s*sourceSensitive[\s\S]*?sourceSensitive: true/u, - ); - assert.match( - terminalSource, - /const sensitive = passwordPromptActiveRef\.current;[\s\S]*?shouldBroadcastDuringSensitivePrompt\(\{[\s\S]*?isBroadcastEnabledRef\.current[\s\S]*?writeToSession\(id, data, \{[\s\S]*?sensitive,/u, - ); -}); - -test("Ctrl+C clears renderer password-prompt classification before the next input", () => { - assert.match( - runtimeSource, - /clearTerminalInputStateForInterrupt\(\{[\s\S]*?passwordPromptActiveRef\.current = false;[\s\S]*?interruptSession/u, - ); -}); - -test("confirmed sudo credentials and preload transport preserve the sensitive marker", () => { - assert.match( - attachmentSource, - /writeToSession\(id, data, \{ automated: true, sensitive: true \}\)/u, - ); - assert.match(preloadSource, /sensitive: options\?\.sensitive === true/u); -}); - -test("OSC 52 clipboard replies bypass plugin input interception as sensitive host data", () => { - assert.match( - runtimeSource, - /writeToSession\(\s*sessionId,\s*`\\x1b\]52;\$\{target\};\$\{b64\}\\x07`,\s*\{ sensitive: true \},\s*\)/u, - ); -}); - -test("generated script credentials stay masked and preserve the sensitive marker", () => { - assert.match(scriptCodegenSource, /dialog\.prompt\([\s\S]*?\{ sensitive: true \}\)/u); - assert.match(scriptCodegenSource, /screen\.sendLine\([\s\S]*?\{ sensitive: true \}\)/u); - assert.match(scriptBridgeSource, /options\.sensitive === true \? \{ sensitive: true \} : \{\}/u); - assert.match(scriptDialogSource, /type=\{request\.sensitive \? 'password' : 'text'\}/u); -}); - -test("renderer flow control acknowledges host ingress rather than transformed display length", () => { - assert.match( - attachmentSource, - /const pluginPipelineIngressBytes = Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?const ingressBytes = pluginPipelineIngressBytes[\s\S]*?\?\? filtered\.acceptedBytes/u, - ); - assert.match( - attachmentSource, - /filtered\.accepted && !filtered\.data && pluginPipelineIngressBytes != null[\s\S]*?acknowledgeDroppedTerminalDisplayBytes\(ctx, pluginPipelineIngressBytes\)/u, - ); - assert.match( - attachmentSource, - /!filtered\.accepted && pluginPipelineIngressBytes != null[\s\S]*?\? pluginPipelineIngressBytes[\s\S]*?: pluginPipelineIngressBytes != null[\s\S]*?\? 0[\s\S]*?: filtered\.droppedBytes/u, - ); - assert.match( - attachmentSource, - /const displayBytes = data\.length;[\s\S]*?enqueueTerminalWrite\(term, displayBytes,[\s\S]*?dropBytes: ingressBytes/u, - ); - assert.match( - readFileSync(new URL("./createTerminalSessionStarters.ts", import.meta.url), "utf8"), - /const pluginPipelineIngressBytes = Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?!chunk && pluginPipelineIngressBytes > 0[\s\S]*?acknowledgeDroppedTerminalDisplayBytes\(ctx, pluginPipelineIngressBytes\)[\s\S]*?writeSessionData\(ctx, term, chunk, pluginPipelineIngressBytes, meta\)/u, - ); - assert.match( - terminalSource, - /beginHibernatedSessionListeners[\s\S]*?\(chunk, meta\) =>[\s\S]*?observeTerminalInputPrompt\(chunk, meta\)[\s\S]*?Number\.isFinite\(meta\?\.pluginPipelineIngressBytes\)[\s\S]*?ackTerminalSessionFlow\(terminalBackend, backendId, pluginPipelineIngressBytes\)/u, - ); -}); - -test("explicit plugin sensitivity is not treated as the heuristic prompt latch", () => { - const effectsSource = readFileSync(new URL("../useTerminalEffects.ts", import.meta.url), "utf8"); - assert.match( - terminalSource, - /passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput;[\s\S]*?passwordPromptActiveRef\.source = meta\.pluginPipelineSensitiveInput \? "explicit" : "heuristic";/, - ); - assert.match( - terminalSource, - /passwordPromptActiveRef\.current = payload\.passwordPromptActive;[\s\S]*?if \(payload\.passwordPromptActive\) passwordPromptActiveRef\.source = "explicit";/, - ); - assert.match( - effectsSource, - /passwordPromptActiveRef\.current = snap\.passwordPromptActive;[\s\S]*?if \(snap\.passwordPromptActive\) passwordPromptActiveRef\.source = "explicit";/, - ); - assert.match( - terminalSource, - /passwordPromptActiveRef\.current = true;[\s\S]*?passwordPromptActiveRef\.source = "heuristic";/, - ); - assert.match( - autocompleteHookSource, - /sensitiveSource: sensitiveInputActiveRef\?\.source,/, - ); -}); - -test("active and hibernated output share host-owned sensitive prompt classification", () => { - assert.match( - terminalSource, - /const observeTerminalInputPrompt = useCallback[\s\S]*?typeof meta\?\.pluginPipelineSensitiveInput === "boolean"[\s\S]*?passwordPromptActiveRef\.current = meta\.pluginPipelineSensitiveInput[\s\S]*?sensitivePromptOutputTailRef\.current = "";[\s\S]*?return;[\s\S]*?isUntrustedTerminalInputPrompt[\s\S]*?passwordPromptActiveRef\.current = false/u, - ); - assert.match( - terminalSource, - /beginHibernatedSessionListeners[\s\S]*?observeTerminalInputPrompt\(chunk, meta\)/u, - ); - assert.match( - terminalSource, - /onTerminalOutput: \(chunk: string, meta\?: TerminalSessionDataMeta\) => \{\s*observeTerminalInputPrompt\(chunk, meta\)/u, - ); -}); - -test("ordinary broadcast skips targets that are waiting for sensitive input", () => { - assert.match( - terminalLayerSource, - /if \(!passwordBypass && isTerminalSensitiveInputActive\(session\.id\)\) continue;[\s\S]*?writeToSession\(session\.id, data, \{[\s\S]*?sensitive: options\?\.sourceSensitive === true \|\| isTerminalSensitiveInputActive\(session\.id\),/u, - ); -}); diff --git a/components/terminal/runtime/terminalLineTimestamps.ts b/components/terminal/runtime/terminalLineTimestamps.ts index 34d047d43..135997576 100644 --- a/components/terminal/runtime/terminalLineTimestamps.ts +++ b/components/terminal/runtime/terminalLineTimestamps.ts @@ -75,8 +75,6 @@ type TimestampStore = { lastSeenBufferLength: number | null; /** Last seen cols; when cols change, reflow may have shifted bare line numbers. */ lastSeenCols: number | null; - /** @deprecated materialize path removed; always false. */ - ledgerMaterialized: boolean; /** * Markers dropped from `entries` but not yet disposed. Drained with a per-pass * budget so rewrite storms do not O(n²)-freeze on xterm marker list splices. @@ -494,7 +492,6 @@ const getTimestampStore = (term: XTerm): TimestampStore => { lastSeenBaseY: null, lastSeenBufferLength: null, lastSeenCols: null, - ledgerMaterialized: false, orphanedMarkers: [], listeners: new Set(), timestampOnlyPrefix: "", @@ -795,26 +792,6 @@ export const restoreTerminalLineTimestampAnchors = (term: XTerm): void => { notifyTimestampStore(store); }; -export const snapshotTerminalLineTimestampLedger = (term: XTerm): Array<{ - label: string; - secondKey: number; - line: number; -}> => getTimestampStore(term).ledger.map((entry) => ({ - label: entry.label, - secondKey: entry.secondKey, - line: entry.marker && !entry.marker.isDisposed ? entry.marker.line : entry.line, -})); - -export const restoreTerminalLineTimestampLedger = ( - term: XTerm, - snapshot: readonly { label: string; secondKey: number; line: number }[], -): void => { - const store = getTimestampStore(term); - store.ledger = snapshot.map((entry) => ({ ...entry })); - store.lastStampSecondKey = store.ledger.at(-1)?.secondKey ?? null; - restoreTerminalLineTimestampAnchors(term); -}; - /** * Refresh ledger.line from live sparse anchors. Drops entries whose markers * were disposed by scrollback trim. Bare (unanchored) lines keep their values @@ -1142,7 +1119,6 @@ const resetTimestampStore = (store: TimestampStore) => { store.lastSeenBaseY = null; store.lastSeenBufferLength = null; store.lastSeenCols = null; - store.ledgerMaterialized = false; store.orphanedMarkers = []; store.segmenter.reset(); store.timestampOnlyPrefix = ""; @@ -1176,7 +1152,6 @@ const _recordTerminalLineTimestamp = ( entry.disposeListener = undefined; }); store.entries.push(entry); - store.ledgerMaterialized = true; if (!options.skipPrune) { maybePruneTimestampEntries(term, store); } @@ -1186,18 +1161,6 @@ const _recordTerminalLineTimestamp = ( return true; }; -/** Test/diagnostics helper: live entry count after optional prune. */ -export const getTerminalLineTimestampEntryCount = ( - term: XTerm, - options: { prune?: boolean } = {}, -): number => { - const store = getTimestampStore(term); - if (options.prune !== false) { - pruneDisposedEntries(store, resolveTerminalLineTimestampCapacity(term)); - } - return store.entries.length; -}; - const _countLineFeeds = (data: string): number => { let count = 0; for (const char of data) { @@ -1224,29 +1187,6 @@ const _getTerminalWraparoundMode = (term: XTerm): boolean => ( ((term as XTerm & { modes?: { wraparoundMode?: boolean } }).modes?.wraparoundMode) !== false ); -/** - * True when DECSTBM (or equivalent) leaves a partial scrolling region. - * Bulk row-offset measurement assumes full-buffer advancement; inside a - * region, newlines recycle rows and measured offsets would invent fake - * history and evict still-valid scrollback timestamps. - */ -export const hasPartialScrollingRegion = (term: XTerm): boolean => { - const core = (term as XTerm & { - _core?: { buffer?: { scrollTop?: number; scrollBottom?: number } }; - })._core; - const scrollTop = core?.buffer?.scrollTop; - const scrollBottom = core?.buffer?.scrollBottom; - const rows = Number.isFinite(term.rows) && term.rows > 0 ? term.rows : 0; - if ( - !Number.isFinite(scrollTop) - || !Number.isFinite(scrollBottom) - || rows <= 0 - ) { - return false; - } - return Number(scrollTop) > 0 || Number(scrollBottom) < rows - 1; -}; - const isUnsafeGraphemeSequenceCodePoint = (codePoint: number): boolean => ( codePoint === 0x200d || codePoint === 0x20e3 @@ -1404,9 +1344,6 @@ const measureSimpleAsciiRows = ( /** Test-only: counts tryMeasureVisualRows invocations on the shipped path. */ let visualRowMeasureCountForTests = 0; export const getVisualRowMeasureCountForTests = (): number => visualRowMeasureCountForTests; -export const resetVisualRowMeasureCountForTests = (): void => { - visualRowMeasureCountForTests = 0; -}; export const tryMeasureVisualRows = ( term: XTerm, diff --git a/components/terminal/runtime/terminalPostConnectVisibility.test.ts b/components/terminal/runtime/terminalPostConnectVisibility.test.ts deleted file mode 100644 index 7ba1732fe..000000000 --- a/components/terminal/runtime/terminalPostConnectVisibility.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const attachmentSource = readFileSync(new URL('./terminalSessionAttachment.ts', import.meta.url), 'utf8'); -const startersSource = readFileSync(new URL('./createTerminalSessionStarters.ts', import.meta.url), 'utf8'); - -const hiddenPostConnectFitGuard = - /setTimeout\(\(\) => \{\s*if \(ctx\.isVisibleRef\?\.current === false\) \{\s*notePendingOutputScrollIfEnabled\(ctx\);\s*return;\s*\}\s*if \(!ctx\.fitAddonRef\.current\) return;[\s\S]*ctx\.fitAddonRef\.current\.fit\(\)/; - -test('reattached sessions do not fit hidden terminal panes after first output', () => { - assert.match(attachmentSource, hiddenPostConnectFitGuard); -}); - -test('local sessions do not fit hidden terminal panes after first output', () => { - assert.match(startersSource, hiddenPostConnectFitGuard); -}); - -test('hidden post-connect scroll recovery respects the scroll-on-output setting', () => { - assert.match( - attachmentSource, - /export const notePendingOutputScrollIfEnabled[\s\S]*shouldScrollOnTerminalOutput\(settings\)[\s\S]*ctx\.pendingOutputScrollRef\.current = true/, - ); -}); diff --git a/components/terminal/runtime/terminalSnippetBroadcast.test.mjs b/components/terminal/runtime/terminalSnippetBroadcast.test.mjs index 966773344..f26ef599d 100644 --- a/components/terminal/runtime/terminalSnippetBroadcast.test.mjs +++ b/components/terminal/runtime/terminalSnippetBroadcast.test.mjs @@ -15,7 +15,7 @@ const load = file => import(pathToFileURL(path.join(root, file)).href); const { normalizeLineEndings } = await load('lib/utils.ts'); const { shouldDelayAutoRunSnippetInput, AUTO_RUN_SNIPPET_LINE_DELAY_MS } = await load('components/terminal/terminalHelpers.ts'); const pacedHelpers = await load('components/terminal/runtime/terminalPacedBroadcast.ts'); -const { resolveTerminalBroadcastTargetIds } = await load('domain/terminalBroadcast.ts'); +const { resolveTerminalBroadcastTargetIds, shouldBroadcastDuringSensitivePrompt } = await load('domain/terminalBroadcast.ts'); const { canUseDirectSessionWriteFallback } = await load('components/terminalLayer/terminalLayerSessionRouting.ts'); const sourceAt = file => readFileSync(path.join(root, file), 'utf8'); const compile = source => ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText; @@ -80,7 +80,9 @@ for (const mode of ['paste', 'lineDelay']) { useCallback: callback => callback, terminalBackend, resolveTerminalBroadcastTargetIds, canUseDirectSessionWriteFallback, sessionsRef: { current: ['source', 'peer'].map(id => ({ id, protocol: 'telnet', status: 'connected' })) }, - isGlobalBroadcastEnabled: true, isTerminalSensitiveInputActive: () => false, + isGlobalBroadcastEnabled: true, + broadcastPasswordBypassRef: { current: false }, + isTerminalSensitiveInputActive: () => false, }; vm.runInNewContext(compile(extract(layerSource, ' const handleBroadcastInput = useCallback(', ' const handleCommandSubmitted') @@ -93,7 +95,11 @@ for (const mode of ['paste', 'lineDelay']) { passwordPromptActiveRef: { current: false }, isBroadcastEnabledRef: { current: true }, onBroadcastInputRef: { current: layerEnv.broadcast }, normalizeLineEndings, shouldDelayAutoRunSnippetInput, AUTO_RUN_SNIPPET_LINE_DELAY_MS, - disableBracketedPasteRef: { current: false }, prepareProgrammaticSudoInput: data => data, + disableBracketedPasteRef: { current: false }, + broadcastPasswordBypassRef: { current: false }, + isPromptSecurityAlternateScreenActive: () => false, + shouldBroadcastDuringSensitivePrompt, + prepareProgrammaticSudoInput: data => data, scrollToBottomAfterProgrammaticInput() {}, terminalBackend, host: { protocol: 'telnet' }, serialConfig: { lineMode: false }, }; diff --git a/components/terminal/runtime/testSupport/starterHarness.ts b/components/terminal/runtime/testSupport/starterHarness.ts new file mode 100644 index 000000000..5f7e9ea03 --- /dev/null +++ b/components/terminal/runtime/testSupport/starterHarness.ts @@ -0,0 +1,74 @@ +export const starterTestNoop = () => undefined; + +export const ENCRYPTED_CREDENTIAL_PLACEHOLDER = "enc:v1:djEwdGVzdAAAAAAAAAAAAAAAAA=="; + +export const armSudoPrompt = ( + autofill: { armForCommand: (command: string) => void } | null, + command = "sudo whoami", +): string => { + autofill?.armForCommand(command); + return "[sudo] password for alice: "; +}; + +export const createMockTerminalBackend = (overrides: Record = {}) => ({ + backendAvailable: () => true, + telnetAvailable: () => true, + moshAvailable: () => true, + localAvailable: () => true, + serialAvailable: () => true, + execAvailable: () => true, + startSSHSession: async () => "ssh-session", + startTelnetSession: async () => "telnet-session", + startMoshSession: async () => "mosh-session", + startLocalSession: async () => "local-session", + startSerialSession: async () => "serial-session", + execCommand: async () => ({}), + onSessionData: () => starterTestNoop, + onSessionExit: () => starterTestNoop, + onChainProgress: () => starterTestNoop, + writeToSession: starterTestNoop, + resizeSession: starterTestNoop, + ...overrides, +}); + +export const createTermStub = (overrides: Record = {}) => ({ + cols: 120, + rows: 32, + write: (_data: string, callback?: () => void) => callback?.(), + writeln: starterTestNoop, + scrollToBottom: starterTestNoop, + ...overrides, +}); + +export const createStarterContext = (overrides: Record = {}) => ({ + host: { + id: "host-1", + label: "Target", + hostname: "target.example.test", + username: "alice", + }, + keys: [], + identities: [], + knownHosts: [], + resolvedChainHosts: [], + sessionId: "session-1", + terminalSettings: {}, + sessionRef: { current: null }, + hasConnectedRef: { current: false }, + hasRunStartupCommandRef: { current: false }, + disposeDataRef: { current: null }, + disposeExitRef: { current: null }, + fitAddonRef: { current: null }, + serializeAddonRef: { current: null }, + pendingAuthRef: { current: null }, + updateStatus: starterTestNoop, + setStatus: starterTestNoop, + setError: starterTestNoop, + setNeedsAuth: starterTestNoop, + setAuthRetryMessage: starterTestNoop, + setAuthPassword: starterTestNoop, + setProgressLogs: starterTestNoop, + setProgressValue: starterTestNoop, + setChainProgress: starterTestNoop, + ...overrides, +}); diff --git a/components/terminal/terminalConnectionTimeoutIntegration.test.ts b/components/terminal/terminalConnectionTimeoutIntegration.test.ts deleted file mode 100644 index 528835b1a..000000000 --- a/components/terminal/terminalConnectionTimeoutIntegration.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - -test("direct terminal sessions reuse a stable empty jump-host list", () => { - assert.match(terminalSource, /const EMPTY_CHAIN_HOSTS: Host\[\] = \[\]/); - assert.match(terminalSource, /chainHosts = EMPTY_CHAIN_HOSTS/); - assert.doesNotMatch(terminalSource, /chainHosts = \[\]/); -}); diff --git a/components/terminal/terminalContinuousRendering.test.ts b/components/terminal/terminalContinuousRendering.test.ts deleted file mode 100644 index 3715e3b95..000000000 --- a/components/terminal/terminalContinuousRendering.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); -const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8"); -const supportSource = readFileSync(new URL("../terminalLayer/TerminalLayerSupport.tsx", import.meta.url), "utf8"); -const viewSource = readFileSync(new URL("../terminalLayer/TerminalLayerView.tsx", import.meta.url), "utf8"); -const tabBridgeSource = readFileSync(new URL("../terminalLayer/TerminalLayerTabBridge.tsx", import.meta.url), "utf8"); -const workspaceLayoutSource = readFileSync(new URL("../terminalLayer/useTerminalWorkspaceLayout.ts", import.meta.url), "utf8"); -const layerEffectsSource = readFileSync(new URL("../terminalLayer/useTerminalLayerEffects.ts", import.meta.url), "utf8"); - -test("renderer activity follows the hibernate setting instead of active-tab visibility", () => { - assert.match( - terminalSource, - /const isRendererActive = isVisible \|\| !hibernateEnabled/, - ); - assert.match(terminalSource, /isPaneVisibleRef: isVisibleRef/); - assert.match(terminalSource, /isVisibleRef: isRendererActiveRef/); - assert.match(terminalSource, /if \(!isRendererActiveRef\.current && !options\?\.allowHidden\)/); - assert.match( - effectsSource, - /const isRendererActive = isVisible \|\| !hibernateHiddenTabs;[\s\S]*const isRendererActiveRef = useRef\(isRendererActive\)/, - ); -}); - -test("inactive terminal surfaces remain mounted and non-interactive without hibernate", () => { - assert.match(supportSource, /resolveTerminalHibernateEnabledForProtocol\(terminalSettings, host\.protocol\)/); - assert.match( - supportSource, - /inert=\{isVisible && !isCoveredByMagnification \? undefined : true\}/, - ); - assert.match(viewSource, /ctx\.hibernateHiddenTabs/); - assert.match(viewSource, /inert=\{ctx\.isTerminalLayerVisible \? undefined : true\}/); -}); - -test("background split workspaces keep their live geometry without hibernate", () => { - assert.match( - tabBridgeSource, - /shouldKeepHiddenWorkspaceLaidOut/, - ); - assert.match( - workspaceLayoutSource, - /if \(shouldKeepHiddenWorkspaceLaidOut\(workspace\)\) \{[\s\S]*cachedSizeIsUsable[\s\S]*computeWorkspaceRects\(layoutWorkspace, layoutSize\)/, - ); - assert.match( - supportSource, - /const layoutWorkspaceId = activeWorkspaceId \?\? \(!hibernateHiddenTabs \? session\.workspaceId : undefined\)/, - ); - assert.match(supportSource, /inWorkspace=\{keepsWorkspacePresentation\}/); - assert.match( - supportSource, - /isWorkspaceComposeBarOpen=\{inActiveWorkspace \? isComposeBarOpen : undefined\}/, - ); - assert.match( - supportSource, - /shouldUseTerminalPaneSplitLayout\(\{[\s\S]*workspace: layoutWorkspace,[\s\S]*sessionId: session\.id,[\s\S]*isVisible,[\s\S]*hibernateHiddenTabs/, - ); - assert.match( - supportSource, - /const initializeHiddenFullSize = !hibernateHiddenTabs[\s\S]*&& !rect[\s\S]*&& !lastVisiblePaneSizeRef\.current;[\s\S]*bumpHiddenPaneSizeVersion/, - ); - // Split rects must never feed the hidden-pane pinned size, or a - // split -> focus viewMode switch pins hidden panes (and their PTYs) at the - // cached fragment width (#3046). - assert.match( - supportSource, - /if \(isVisible && !rect\) \{[\s\S]*const observer = new ResizeObserver\(\(\) => \{[\s\S]*capturePaneSize\(\)/, - ); - // A split-visible pane must drop the cached full-size measurement so a later - // hidden full-size layout re-measures the current area instead of pinning - // stale pixels (#3046). - assert.match( - supportSource, - /if \(isVisible\) \{[\s\S]{0,400}lastVisiblePaneSizeRef\.current = null;[\s\S]{0,20}return;/, - ); - assert.match( - layerEffectsSource, - /if \(!shouldMeasureTerminalLayerLayout\) return;[\s\S]*?remeasureWorkspaceArea\(\)/, - ); - assert.match( - tabBridgeSource, - /const keepHiddenLayoutActive = !hibernateHiddenTabs \|\| localWorkspaceIds\.size > 0/, - ); - assert.match( - tabBridgeSource, - /shouldMeasureTerminalLayerLayout: shouldMeasureTerminalLayerLayout\(\{[\s\S]*keepHiddenLayoutActive,[\s\S]*workspaceArea/, - ); - assert.doesNotMatch(tabBridgeSource, /isTerminalLayerRendererActive/); -}); diff --git a/components/terminal/terminalHibernateFlush.test.ts b/components/terminal/terminalHibernateFlush.test.ts deleted file mode 100644 index 0594431ba..000000000 --- a/components/terminal/terminalHibernateFlush.test.ts +++ /dev/null @@ -1,325 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const readFunctionBody = (source: string, marker: string): string => { - const start = source.indexOf(marker); - assert.notEqual(start, -1, `${marker} must exist`); - - const bodyStart = source.indexOf("{", start); - assert.notEqual(bodyStart, -1, `${marker} must have a body`); - - let depth = 0; - for (let index = bodyStart; index < source.length; index += 1) { - const char = source[index]; - if (char === "{") depth += 1; - if (char === "}") { - depth -= 1; - if (depth === 0) { - return source.slice(bodyStart, index + 1); - } - } - } - - assert.fail(`${marker} body must close`); -}; - -test("full hibernate flushes pending hidden output before taking the snapshot", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const body = readFunctionBody(source, "const fullHibernateRuntime = useCallback(async (): Promise =>"); - - const termCaptureIndex = body.indexOf("const term = termRef.current"); - const clearHiddenIndex = body.indexOf("terminalHiddenRendererStore.clearSoftHidden(sessionId)"); - const flushIndex = body.indexOf("flushPendingTerminalWritesBeforeHibernate(term)"); - const retryIndex = body.indexOf("scheduleHibernateRetry()"); - const alternateScreenSkipIndex = body.indexOf("shouldSkipHibernateForActiveAlternateScreen(term)"); - const snapshotIndex = body.indexOf("serializeTerminalForHibernate("); - const releaseIndex = body.indexOf("releaseTerminalFlowBeforeHibernate("); - - assert.notEqual(termCaptureIndex, -1, "hibernate must capture the active terminal once"); - assert.notEqual(clearHiddenIndex, -1, "hibernate must clear hidden renderer state"); - assert.notEqual(flushIndex, -1, "hibernate must flush pending terminal writes completely"); - assert.notEqual(retryIndex, -1, "hibernate must retry when pending writes are still draining"); - assert.notEqual(alternateScreenSkipIndex, -1, "hibernate must re-check alternate screen after draining output"); - assert.notEqual(snapshotIndex, -1, "hibernate must serialize a terminal snapshot"); - assert.notEqual(releaseIndex, -1, "hibernate must release flow after snapshot"); - assert.ok(termCaptureIndex < flushIndex, "flush must use the captured terminal"); - assert.ok(clearHiddenIndex < flushIndex, "clear hidden state before flushing pending writes"); - assert.ok(flushIndex < retryIndex, "retry can only be scheduled after the drain attempt"); - assert.ok(retryIndex < snapshotIndex, "retry branch must happen before snapshot"); - assert.ok(flushIndex < alternateScreenSkipIndex, "alternate screen must be checked after pending writes are drained"); - assert.ok(retryIndex < alternateScreenSkipIndex, "retry branch must run before the alternate-screen re-check"); - assert.ok(alternateScreenSkipIndex < snapshotIndex, "alternate-screen skip must happen before snapshot"); - assert.ok(flushIndex < snapshotIndex, "flush pending writes before snapshot"); - assert.ok(snapshotIndex < releaseIndex, "release flow only after snapshot"); -}); - -test("live context reads flush pending hidden output before reading the buffer", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const body = readFunctionBody( - source, - "const readTerminalContext = useCallback(async (request) =>", - ); - - const flushIndex = body.indexOf("await flushPendingTerminalWritesBeforeHibernate(targetTerm)"); - const drainGuardIndex = body.indexOf("if (!flushed)"); - const bufferReadIndex = body.indexOf("term.buffer.active"); - - assert.notEqual(flushIndex, -1, "context reads must flush pending terminal writes"); - assert.notEqual(drainGuardIndex, -1, "context reads must reject an incomplete drain"); - assert.notEqual(bufferReadIndex, -1, "context reads must inspect the live terminal buffer"); - assert.ok(flushIndex < drainGuardIndex, "check the drain result after flushing"); - assert.ok(flushIndex < bufferReadIndex, "flush pending writes before reading the live buffer"); -}); - -test("hibernate retry preserves normal hibernate blockers", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const body = readFunctionBody(source, "const scheduleHibernateRetry = useCallback(() =>"); - - const searchBlockerIndex = body.indexOf("isSearchOpenRef.current"); - const transferBlockerIndex = body.indexOf("hibernateFileTransferActiveRef.current"); - const retryIndex = body.indexOf("fullHibernateRuntimeRef.current?.()"); - - assert.notEqual(searchBlockerIndex, -1, "retry must skip hibernate while search is open"); - assert.notEqual(transferBlockerIndex, -1, "retry must skip hibernate while file transfer is active"); - assert.notEqual(retryIndex, -1, "retry must be able to resume hibernation"); - assert.ok(searchBlockerIndex < retryIndex, "search blocker must run before retrying hibernate"); - assert.ok(transferBlockerIndex < retryIndex, "file-transfer blocker must run before retrying hibernate"); -}); - -test("full hibernate rechecks live state after every asynchronous step", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const body = readFunctionBody(source, "const fullHibernateRuntime = useCallback(async (): Promise =>"); - - const statusCaptureIndex = body.indexOf("const hibernateStatus = statusRef.current"); - const flushIndex = body.indexOf("await flushPendingTerminalWritesBeforeHibernate(term)"); - const afterFlushGuardIndex = body.indexOf("if (!canFinishHibernate()) return false;", flushIndex); - const serializeIndex = body.indexOf("await serializeTerminalForHibernate("); - const afterSerializeGuardIndex = body.indexOf("if (!canFinishHibernate()) return false;", serializeIndex); - const releaseIndex = body.indexOf("releaseTerminalFlowBeforeHibernate("); - - assert.notEqual(statusCaptureIndex, -1, "hibernate must capture its starting lifecycle state"); - assert.match(body, /!isVisibleRef\.current/); - assert.match(body, /hibernateEnabledRef\.current/); - assert.match(body, /termRef\.current === term/); - assert.match(body, /statusRef\.current === hibernateStatus/); - assert.match(body, /sessionRef\.current === backendId/); - assert.ok(statusCaptureIndex < flushIndex, "capture lifecycle state before the first await"); - assert.ok(flushIndex < afterFlushGuardIndex, "visibility and settings must be rechecked after draining output"); - assert.ok(afterFlushGuardIndex < serializeIndex, "the post-drain guard must run before serialization"); - assert.ok(serializeIndex < afterSerializeGuardIndex, "visibility and settings must be rechecked after serialization"); - assert.ok(afterSerializeGuardIndex < releaseIndex, "the final guard must run before releasing the live runtime"); -}); - -test("ended hidden sessions release xterm without reopening dead backend listeners", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const fullHibernateBody = readFunctionBody( - source, - "const fullHibernateRuntime = useCallback(async (): Promise =>", - ); - const hibernateBody = readFunctionBody(source, "const hibernateRuntime = useCallback(() =>"); - - assert.match( - fullHibernateBody, - /canHibernateTerminalRuntimeSession\(hibernateStatus, backendId\)/, - ); - assert.match( - fullHibernateBody, - /statusRef\.current === hibernateStatus\s*&& sessionRef\.current === backendId/, - ); - assert.match( - fullHibernateBody, - /const connectedBackendId = hibernateStatus === "connected" \? backendId : null;\s*if \(connectedBackendId\) \{\s*releaseTerminalFlowBeforeHibernate\([\s\S]*?connectedBackendId\);\s*\}\s*disposeDataRef\.current\?\.\(\);[\s\S]*?disposeRuntimeOnly\(\);\s*if \(connectedBackendId\) \{\s*beginHibernatedSessionListeners\(connectedBackendId\);\s*\}/, - ); - assert.match( - hibernateBody, - /const keepCount = statusRef\.current === "connected"\s*\? resolveHibernateKeepRendererCount\(terminalSettings\)\s*: 0;/, - ); -}); - -test("reconnect preparation cancels an in-flight disconnected hibernate", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const fullHibernateBody = readFunctionBody( - source, - "const fullHibernateRuntime = useCallback(async (): Promise =>", - ); - const reconnectBody = readFunctionBody( - source, - 'const startReconnect = async (mode: "manual" | "auto" = "manual") =>', - ); - const startNewSessionBody = readFunctionBody( - source, - "const startNewSession = () =>", - ); - const updateStatusBody = readFunctionBody( - source, - 'const updateStatus = useCallback((next: TerminalSession["status"]) =>', - ); - - assert.match( - fullHibernateBody, - /reconnectPreparationTokenRef\.current === null/, - ); - - const claimIndex = reconnectBody.indexOf( - "reconnectPreparationTokenRef.current = retryToken", - ); - const cleanupIndex = reconnectBody.indexOf("await cleanupSession({ retainOwnership: true })"); - const startNewSessionIndex = reconnectBody.indexOf("const startNewSession = () =>"); - - assert.ok(claimIndex >= 0 && claimIndex < cleanupIndex); - assert.doesNotMatch( - reconnectBody.slice(cleanupIndex, startNewSessionIndex), - /reconnectPreparationTokenRef\.current = null/, - ); - assert.match( - startNewSessionBody, - /if \(!retryStillActive\(\)\) \{\s*finishReconnectPreparation\(\);\s*return;\s*\}\s*finishReconnectPreparation\(\);/, - ); - assert.match( - reconnectBody, - /term\.write\('\\x1b\[\?1049l', \(\) => \{\s*if \(!retryStillActive\(\)\) \{\s*finishReconnectPreparation\(\);\s*return;/, - ); - assert.match( - updateStatusBody, - /statusRef\.current = next;\s*setStatus\(next\);/, - ); -}); - -test("ended soft-hidden and alternate-screen sessions can fully hibernate", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const fullHibernateBody = readFunctionBody( - source, - "const fullHibernateRuntime = useCallback(async (): Promise =>", - ); - const hibernateBody = readFunctionBody( - source, - "const hibernateRuntime = useCallback(() =>", - ); - const alternateSkipBody = readFunctionBody( - source, - "const shouldSkipHibernateForActiveAlternateScreen = useCallback((term: XTerm): boolean =>", - ); - - assert.match( - fullHibernateBody, - /softHiddenRef\.current && statusRef\.current !== "disconnected"/, - ); - assert.match( - fullHibernateBody, - /!softHiddenRef\.current \|\| hibernateStatus === "disconnected"/, - ); - assert.match( - hibernateBody, - /if \(softHiddenRef\.current\) \{\s*const retainedKeepCount = statusRef\.current === "connected"\s*\? resolveHibernateKeepRendererCount\(terminalSettingsRef\.current\)\s*: 0;\s*if \(statusRef\.current === "disconnected" \|\| !\(retainedKeepCount > 0\)\) \{\s*upgradeSoftHiddenRuntimeToHibernate\(\);\s*\}\s*return;/, - ); - assert.match( - alternateSkipBody, - /if \(statusRef\.current !== "connected"\) return false;/, - ); -}); - -test("a cancelled soft-hidden upgrade resumes its renderer", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const hibernateBody = readFunctionBody(source, "const hibernateRuntime = useCallback(() =>"); - const upgradeBody = readFunctionBody(source, "const upgradeSoftHiddenRuntimeToHibernate = useCallback(() =>"); - const helperBody = readFunctionBody(source, "const resumeRendererAfterCancelledHibernateUpgrade = useCallback(() =>"); - - assert.match( - hibernateBody, - /if \(softHiddenRef\.current\) \{\s*const retainedKeepCount = statusRef\.current === "connected"\s*\? resolveHibernateKeepRendererCount\(terminalSettingsRef\.current\)\s*: 0;\s*if \(statusRef\.current === "disconnected" \|\| !\(retainedKeepCount > 0\)\) \{\s*upgradeSoftHiddenRuntimeToHibernate\(\);/, - ); - const wakeIndex = upgradeBody.indexOf("wakeSoftHiddenRuntimeRef.current?.()"); - const upgradeIndex = upgradeBody.indexOf("fullHibernateRuntime().then("); - const cancelResumeIndex = upgradeBody.indexOf("resumeRendererAfterCancelledHibernateUpgradeRef.current?.()", upgradeIndex); - assert.notEqual(wakeIndex, -1, "every soft-hidden upgrade must resume the renderer before upgrading"); - assert.notEqual(upgradeIndex, -1, "soft-hidden upgrades must await the full hibernate result"); - assert.ok(wakeIndex < upgradeIndex, "the renderer must be live throughout the asynchronous upgrade"); - assert.notEqual(cancelResumeIndex, -1, "a cancelled upgrade must resume the renderer again"); - assert.match(helperBody, /ensureWebglRenderer\(\)/); - assert.match(helperBody, /clearTextureAtlas\(\)/); - assert.match(helperBody, /safeFitRef\.current\(\{ force: true \}\)/); - const restoreGuard = "if (pendingEviction && !isVisibleRef.current && hibernateEnabledRef.current)"; - assert.equal( - upgradeBody.split(restoreGuard).length - 1, - 2, - "both the failed hibernate and the rejection path must skip soft-hide when the tab is visible or hibernate is off", - ); - assert.ok( - upgradeBody.indexOf(restoreGuard) > upgradeIndex, - "the visibility guard belongs on the settled upgrade, after the renderer was resumed", - ); -}); - -test("snapshot and handoff paths reject output that misses the settle deadline", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - - const drainWarningIndex = source.indexOf("Terminal output drain did not settle before the deadline"); - const drainReturnIndex = source.indexOf("return;", drainWarningIndex); - const drainResponseIndex = source.indexOf("respondTerminalOutputDrain", drainReturnIndex); - assert.ok(drainWarningIndex >= 0 && drainWarningIndex < drainReturnIndex); - assert.ok(drainReturnIndex < drainResponseIndex); - - const snapshotWarningIndex = source.indexOf("Terminal snapshot drain did not settle before the deadline"); - const snapshotReturnIndex = source.indexOf("return;", snapshotWarningIndex); - const snapshotSerializeIndex = source.indexOf("serializeAddonRef.current.serialize", snapshotReturnIndex); - assert.ok(snapshotWarningIndex >= 0 && snapshotWarningIndex < snapshotReturnIndex); - assert.ok(snapshotReturnIndex < snapshotSerializeIndex); - - const applyHandlerIndex = source.indexOf("onTerminalSessionApplySnapshot"); - const applyDrainIndex = source.indexOf("flushPendingTerminalWritesBeforeHibernate(term)", applyHandlerIndex); - const applyFailureIndex = source.indexOf("Terminal output did not settle before applying the snapshot", applyDrainIndex); - const applyMetadataIndex = source.indexOf("setKittyKeyboardProtocolEnabled", applyHandlerIndex); - const applyResetIndex = source.indexOf("term.reset()", applyHandlerIndex); - const applySnapshotWriteIndex = source.indexOf("term.write(payload.snapshot, resolve)", applyResetIndex); - const applyCursorHighlightRefreshIndex = source.indexOf( - "cursorLineHighlighter.refresh({ force: true })", - applyResetIndex, - ); - const applyScrollIndex = source.indexOf("term.scrollToBottom?.()", applyResetIndex); - assert.ok(applyHandlerIndex >= 0 && applyHandlerIndex < applyDrainIndex); - assert.ok(applyDrainIndex < applyFailureIndex); - assert.ok(applyFailureIndex < applyMetadataIndex, "failed drains must not mutate snapshot metadata"); - assert.ok(applyMetadataIndex < applyResetIndex); - assert.ok(applyResetIndex < applySnapshotWriteIndex); - assert.ok( - applySnapshotWriteIndex < applyCursorHighlightRefreshIndex, - "cursor-line highlighting must refresh after applying an optional snapshot", - ); - assert.ok(applyCursorHighlightRefreshIndex < applyScrollIndex); - assert.match( - source, - /const flushed = await flushPendingTerminalWritesBeforeHibernate\(snapshotTerm\);\s*if \(!flushed\) \{\s*throw new Error\("Terminal output did not settle before closing the attached display"\);\s*\}/, - ); -}); - -test("a full keep count soft-hides the leaving session instead of snapshotting it", () => { - const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8"); - const body = readFunctionBody(source, "const hibernateRuntime = useCallback(() =>"); - const imageGate = body.indexOf("if (runtimeHasInlineImages()) {"); - const alternateGate = body.indexOf("shouldSkipHibernateForActiveAlternateScreen(termRef.current)"); - const decision = body.indexOf("decideHiddenTabKeepCountAction("); - const softHide = body.indexOf('if (keepDecision.action === "soft-hide")'); - const hide = body.indexOf("hideRuntimeOnly();", softHide); - const full = body.indexOf("void fullHibernateRuntime()"); - - assert.ok(alternateGate !== -1 && alternateGate < imageGate); - assert.ok(imageGate !== -1 && imageGate < decision); - assert.ok(decision < softHide && softHide < hide && hide < full); - const awaited = body.indexOf("retainLeavingTabAfterEviction({"); - assert.ok(awaited > decision, "a full keep set retains the leaving tab from the application eviction walk"); - assert.match(body, /getSoftHiddenOccupancy\(\)/); - assert.match(body, /stillWantsRetention:/); - assert.match(body, /softHide: \(\) => hideRuntimeOnly\(\)/); - assert.match( - body, - /resolveKeepCount: \(\) => \(\s*statusRef\.current === "connected"\s*\? resolveHibernateKeepRendererCount\(terminalSettingsRef\.current\)\s*: 0\s*\)/, - "retention after eviction must read the live keep count, not the captured one", - ); - assert.doesNotMatch(body, /resolveHiddenTabEviction/); - assert.doesNotMatch(body, /requestEviction\(keepDecision/); - assert.match( - body, - /if \(softHiddenRef\.current\) \{\s*const retainedKeepCount = statusRef\.current === "connected"\s*\? resolveHibernateKeepRendererCount\(terminalSettingsRef\.current\)\s*: 0;\s*if \(statusRef\.current === "disconnected" \|\| !\(retainedKeepCount > 0\)\) \{\s*upgradeSoftHiddenRuntimeToHibernate\(\);\s*\}\s*return;\s*\}/, - ); -}); diff --git a/components/terminal/terminalPaneVisibilityPublish.test.ts b/components/terminal/terminalPaneVisibilityPublish.test.ts deleted file mode 100644 index ad42d5c1a..000000000 --- a/components/terminal/terminalPaneVisibilityPublish.test.ts +++ /dev/null @@ -1,18 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { readFileSync } from "node:fs"; - -test("TerminalPane publishes visibility before paint", () => { - const source = readFileSync( - new URL("../terminalLayer/TerminalLayerSupport.tsx", import.meta.url), - "utf8", - ); - assert.match( - source, - /useLayoutEffect\(\(\) => \{\s*setPaneVisible\(session\.id, isVisible\);\s*\}, \[session\.id, isVisible\]\);/, - ); - assert.doesNotMatch( - source, - /useEffect\(\(\) => \{\s*setPaneVisible\(session\.id, isVisible\);\s*\}, \[session\.id, isVisible\]\);/, - ); -}); diff --git a/components/terminal/terminalSafeFitVisibility.test.ts b/components/terminal/terminalSafeFitVisibility.test.ts deleted file mode 100644 index dcd67562b..000000000 --- a/components/terminal/terminalSafeFitVisibility.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('../Terminal.tsx', import.meta.url), 'utf8'); - -test('safeFit skips only renderers suspended by hibernate unless explicitly allowed', () => { - assert.match( - source, - /if \(!isRendererActiveRef\.current && !options\?\.allowHidden\) \{\s*lastFittedSizeRef\.current = null;\s*return;\s*\}/, - ); -}); - -test('safeFit can run synchronously for immediate layout changes', () => { - assert.match(source, /immediate\?: boolean/); - assert.match( - source, - /XTERM_PERFORMANCE_CONFIG\.resize\.useRAF &&\s*typeof requestAnimationFrame === "function" &&\s*!options\?\.immediate/, - ); -}); - -test('safeFit clears the WebGL atlas on pixel-only layout changes', () => { - // Opening the SFTP side panel often changes container px without changing - // cols/rows, so term.onResize (which clears the atlas) never fires. Without - // this else-branch recovery, WebGL paints stale glyphs as black squares (#2013). - assert.match( - source, - /if \(term\.cols !== dimensions\.cols \|\| term\.rows !== dimensions\.rows\) \{\s*term\.resize\(dimensions\.cols, dimensions\.rows\);\s*forceSyncRenderAfterResize\(term\);\s*\} else \{\s*[\s\S]*?xtermRuntimeRef\.current\?\.clearTextureAtlas\(\);\s*forceSyncRenderAfterResize\(term\);\s*\}/, - ); -}); - -test('safeFit waits for normal xterm callbacks before resizing', () => { - const pendingGuardIndex = source.indexOf('if (hasPendingTerminalWrites(term))'); - const settleIndex = source.indexOf('runWithTerminalOutputPausedAfterWritesSettle(', pendingGuardIndex); - const sessionGuardIndex = source.indexOf('sessionRef.current !== fitSessionId', settleIndex); - const immediateFitIndex = source.indexOf('safeFit({ ...fitRequest.options, immediate: true })', sessionGuardIndex); - const resizeIndex = source.indexOf('term.resize(dimensions.cols, dimensions.rows)', pendingGuardIndex); - - assert.ok(pendingGuardIndex >= 0); - assert.ok(settleIndex > pendingGuardIndex); - assert.ok(sessionGuardIndex > settleIndex); - assert.ok(immediateFitIndex > settleIndex); - assert.ok(resizeIndex > immediateFitIndex); -}); - -test('safeFit retries against a replacement backend session', () => { - const pendingGuardIndex = source.indexOf('if (hasPendingTerminalWrites(term))'); - const replacementGuardIndex = source.indexOf( - 'if (sessionRef.current !== fitSessionId)', - pendingGuardIndex, - ); - const clearIndex = source.indexOf('pendingWriteSafeFitRef.current = null', replacementGuardIndex); - const retryIndex = source.indexOf('setTimeout(() => safeFit(fitRequest.options), 0)', clearIndex); - - assert.ok(replacementGuardIndex > pendingGuardIndex); - assert.ok(clearIndex > replacementGuardIndex); - assert.ok(retryIndex > clearIndex); -}); diff --git a/components/terminal/terminalTabVisibilityRecovery.test.ts b/components/terminal/terminalTabVisibilityRecovery.test.ts deleted file mode 100644 index 14e1d0a50..000000000 --- a/components/terminal/terminalTabVisibilityRecovery.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./useTerminalEffects.ts', import.meta.url), 'utf8'); - -test('clears committed layout state when a terminal pane hides', () => { - assert.match(source, /if \(isVisible\) return;[\s\S]*lastCommittedVisibleLayoutKeyRef\.current = null/); - assert.match(source, /lastWebglRecoveryLayoutKeyRef\.current = null/); -}); - -test('forces full recovery when a terminal pane becomes visible again', () => { - assert.match(source, /const becameVisible = isVisible && !wasVisibleRef\.current/); - assert.match(source, /recoverTerminalAfterBecomeVisible\(\)/); - assert.match(source, /nudgeAlternateScreenRedraw\(term\)/); - assert.match(source, /syncPtySizeAfterLayout/); -}); - -test('layout recovery refit also syncs PTY size for full-screen TUIs', () => { - assert.match(source, /runImmediateRefit\(\{ force: true, repeatOnNextFrame: false \}\);\s*finishLayoutRecoveryAfterFit\(\)/); - assert.match(source, /finishLayoutRecoveryAfterFit/); -}); - -test('tab-switch suppression does not consume the visible recovery pass', () => { - assert.match(source, /const becameVisible = isVisible && !wasVisibleRef\.current/); - assert.match( - source, - /if \(!isVisible\) \{\s*wasVisibleRef\.current = false;\s*syncOutputPressureVisibility\(\);\s*return;\s*\}[\s\S]*if \(splitResizeActive\) return;[\s\S]*wasVisibleRef\.current = true;[\s\S]*recoverTerminalAfterBecomeVisible\(\)/, - ); - assert.doesNotMatch(source, /wasVisibleRef\.current = isVisible;\s*if \(!isVisible \|\| isResizing\) return/); -}); - -test('immediate visibility recovery does not wait for the next animation frame', () => { - assert.match(source, /safeFit\(\{ force, requireVisible: true, immediate: true \}\)/); - assert.match(source, /safeFit\(\{ force: true, requireVisible: true, immediate: true \}\)/); -}); - -test('visible tab recovery reuses a cached fit when the container size is unchanged', () => { - assert.match(source, /const currentContainerSizeAlreadyFit = \(\) => \{/); - assert.match( - source, - /if \(currentContainerSizeAlreadyFit\(\)\) \{\s*finishLayoutRecovery\(\);\s*flushPendingOutputScroll\(\);\s*commitVisibleLayout\(\);\s*return;\s*\}/, - ); -}); - -test('short unchanged tab reveals skip the recovery work entirely', () => { - const recoverIndex = source.indexOf('const recoverTerminalAfterBecomeVisible = () => {'); - const fastPathIndex = source.indexOf('getHiddenDurationMs() < CSS_ONLY_TAB_REVEAL_MAX_HIDDEN_MS', recoverIndex); - const fullRecoveryIndex = source.indexOf('xtermRuntimeRef.current?.clearTextureAtlas();', recoverIndex); - const fastPath = source.slice(fastPathIndex, fullRecoveryIndex); - - assert.ok(recoverIndex >= 0); - assert.ok(fastPathIndex > recoverIndex); - assert.ok(fullRecoveryIndex > fastPathIndex); - assert.match( - fastPath, - /currentContainerSizeAlreadyFit\(\)[\s\S]*lastWebglRecoveryLayoutKeyRef\.current = paneLayoutKey;[\s\S]*commitVisibleLayout\(\);[\s\S]*return;/, - ); - assert.doesNotMatch(fastPath, /runImmediateRefit|scheduleLayoutRecoveryRefit/); -}); - -// Chromium can reclaim a hidden pane's WebGL context at any time, and the -// context budget releases renderers of panes hidden for a while. The fast -// path must still bring a missing renderer back (a no-op when it is live). -test('short unchanged tab reveals still restore a lost WebGL renderer', () => { - const recoverIndex = source.indexOf('const recoverTerminalAfterBecomeVisible = () => {'); - const fastPathIndex = source.indexOf('getHiddenDurationMs() < CSS_ONLY_TAB_REVEAL_MAX_HIDDEN_MS', recoverIndex); - const fullRecoveryIndex = source.indexOf('xtermRuntimeRef.current?.clearTextureAtlas();', recoverIndex); - - assert.match( - source.slice(fastPathIndex, fullRecoveryIndex), - /xtermRuntimeRef\.current\?\.ensureWebglRenderer\(\);[\s\S]*commitVisibleLayout\(\);\s*return;/, - ); -}); - -test('pane visibility reaches the WebGL context budget before reveal recovery runs', () => { - const syncIndex = source.indexOf('xtermRuntimeRef.current?.syncPaneVisibility();'); - const revealEffectIndex = source.indexOf('const becameVisible = isVisible && !wasVisibleRef.current'); - assert.ok(syncIndex >= 0); - assert.ok(syncIndex < revealEffectIndex); - assert.match(source, /isPaneVisibleRef: isVisibleRef,/); -}); - -test('short unchanged tab reveals still flush pending hidden-output scroll', () => { - const recoverIndex = source.indexOf('const recoverTerminalAfterBecomeVisible = () => {'); - const fastPathIndex = source.indexOf('getHiddenDurationMs() < CSS_ONLY_TAB_REVEAL_MAX_HIDDEN_MS', recoverIndex); - const webglRecoveryIndex = source.indexOf('xtermRuntimeRef.current?.clearTextureAtlas();', recoverIndex); - const delayedSkipIndex = source.indexOf('lastWebglRecoveryLayoutKeyRef.current === paneLayoutKey', webglRecoveryIndex); - const delayedTimerIndex = source.indexOf('const timer = setTimeout', delayedSkipIndex); - - assert.match( - source, - /const flushPendingOutputScroll = \(\) => \{[\s\S]*pendingOutputScrollRef\.current[\s\S]*scrollToBottom\(\)[\s\S]*pendingOutputScrollRef\.current = false;/, - ); - assert.match( - source.slice(fastPathIndex, webglRecoveryIndex), - /flushPendingOutputScroll\(\);[\s\S]*commitVisibleLayout\(\);[\s\S]*return;/, - ); - assert.match( - source.slice(delayedSkipIndex, delayedTimerIndex), - /flushPendingOutputScroll\(\);\s*return;/, - ); -}); - -test('visible tab recovery drains hidden terminal writes before any fast-path return', () => { - const recoverIndex = source.indexOf('const recoverTerminalAfterBecomeVisible = () => {'); - const fastPathIndex = source.indexOf('getHiddenDurationMs() < CSS_ONLY_TAB_REVEAL_MAX_HIDDEN_MS', recoverIndex); - const flushCallIndex = source.indexOf('flushTerminalWritesAfterBecomeVisible();', recoverIndex); - - assert.ok(recoverIndex >= 0); - assert.ok(fastPathIndex > recoverIndex); - assert.ok(flushCallIndex > recoverIndex && flushCallIndex < fastPathIndex); -}); - -test('visible split-pane recovery no longer defers background panes', () => { - const effectIndex = source.indexOf('const becameVisible = isVisible && !wasVisibleRef.current'); - const effectEnd = source.indexOf('}, [isVisible, paneLayoutKey, splitResizeActive]);', effectIndex); - const effectSource = source.slice(effectIndex, effectEnd); - - assert.ok(effectIndex >= 0); - assert.ok(effectEnd > effectIndex); - assert.match( - source, - /if \(becameVisible\) \{\s*recoverTerminalAfterBecomeVisible\(\);\s*return;\s*\}/, - ); - assert.doesNotMatch(effectSource, /\binWorkspace\b/); - assert.doesNotMatch(effectSource, /\bisFocusMode\b/); - assert.doesNotMatch(effectSource, /\bisFocused\b/); - assert.doesNotMatch(source, /shouldRefitImmediatelyOnShow/); - assert.doesNotMatch(source, /shouldRecoverWebglOnShow/); - assert.doesNotMatch(source, /const runDeferred = \(\) => \{/); - assert.doesNotMatch(source, /scheduleLayoutRecoveryRefit\(\[120, 350\]\)/); -}); - -test('immediate tab recovery marks webgl recovery to skip the delayed duplicate pass', () => { - assert.match( - source, - /const recoverTerminalAfterBecomeVisible = \(\) => \{[\s\S]*xtermRuntimeRef\.current\?\.clearTextureAtlas\(\);\s*lastWebglRecoveryLayoutKeyRef\.current = paneLayoutKey;/, - ); - assert.match( - source, - /if \(lastWebglRecoveryLayoutKeyRef\.current === paneLayoutKey\) \{/, - ); -}); - -test('reveal does not claim recovery before the terminal runtime exists', () => { - const start = source.indexOf('const recoverTerminalAfterBecomeVisible = () => {'); - const end = source.indexOf('// Refit synchronously', start); - const recovery = source.slice(start, end); - const runtimeGuard = recovery.indexOf('if (!termRef.current || !xtermRuntimeRef.current) return;'); - const commit = recovery.indexOf('lastWebglRecoveryLayoutKeyRef.current = paneLayoutKey'); - assert.ok(runtimeGuard >= 0 && runtimeGuard < commit); -}); - -test('settling tab-layout probes do not force a fit when bounds are unchanged', () => { - const start = source.indexOf('const refitSettledLayout = () => {'); - const end = source.indexOf('}, [inWorkspace, isVisible]);', start); - const settling = source.slice(start, end); - assert.ok(start >= 0 && end > start); - assert.match(settling, /if \(!isVisibleRef\.current \|\| currentContainerSizeAlreadyFit\(\)\) return;/); - assert.match(settling, /safeFit\(\{ requireVisible: true \}\);/); - assert.doesNotMatch(settling, /force: true/); - assert.match(settling, /setTimeout\(refitSettledLayout, 100\)/); - assert.match(settling, /setTimeout\(refitSettledLayout, 350\)/); -}); diff --git a/components/terminal/useServerStats.test.ts b/components/terminal/useServerStats.test.ts deleted file mode 100644 index b176eb611..000000000 --- a/components/terminal/useServerStats.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -test("server stats retry can restart polling after give-up", () => { - const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); - const reconcileStart = source.indexOf("function reconcileSharedServerStatsSession"); - const shouldRestartCheck = source.indexOf("const shouldRestartPolling", reconcileStart); - const givenUpCheck = source.indexOf("if (session.givenUp) return;", shouldRestartCheck); - const markPollingActive = source.indexOf("session.pollingActive = true", shouldRestartCheck); - - assert.notEqual(reconcileStart, -1); - assert.notEqual(shouldRestartCheck, -1); - assert.notEqual(givenUpCheck, -1); - assert.notEqual(markPollingActive, -1); - assert.ok(givenUpCheck < markPollingActive); -}); - -test("server stats stale requests do not block a fresh visible fetch", () => { - const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); - - assert.match(source, /inflightGeneration: number \| null/); - assert.match(source, /session\.inflight && session\.inflightGeneration === session\.fetchGeneration/); - assert.match(source, /session\.inflightGeneration = generation/); -}); - -test("server stats polling does not stop when its terminal is in the background", () => { - const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); - - assert.doesNotMatch(source, /isVisible/); - assert.doesNotMatch(source, /getVisibleServerStatsClients/); - assert.doesNotMatch(source, /resuming from hidden/); -}); - -test("server stats keep last snapshot when all consumers pause", () => { - const source = readFileSync(new URL("../../application/state/useServerStats.ts", import.meta.url), "utf8"); - const reconcileStart = source.indexOf("function reconcileSharedServerStatsSession"); - const idleBranch = source.indexOf("if (activeClients.length === 0)", reconcileStart); - const nextFunction = source.indexOf("\nfunction ", reconcileStart + 1); - const idleBody = source.slice(idleBranch, nextFunction === -1 ? undefined : nextFunction); - - assert.notEqual(reconcileStart, -1); - assert.notEqual(idleBranch, -1); - // Pausing must not wipe lastUpdated stats (Overview tab-switch empty flash). - assert.match(idleBody, /clearServerStatsTimers\(session\)/); - assert.doesNotMatch(idleBody, /resetServerStatsSession\(session\)/); - assert.doesNotMatch(idleBody, /createInitialState/); - // But give-up must clear so resume can auto-retry after hard failure. - assert.match(idleBody, /session\.givenUp = false/); - assert.match(idleBody, /session\.consecutiveFailures = 0/); -}); diff --git a/components/terminalLayer/TerminalFocusSidebar.test.ts b/components/terminalLayer/TerminalFocusSidebar.test.ts deleted file mode 100644 index 87a6e6314..000000000 --- a/components/terminalLayer/TerminalFocusSidebar.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./TerminalFocusSidebar.tsx', import.meta.url), 'utf8'); - -test('focus sidebar row memo refreshes when dynamic title mode changes', () => { - assert.match(source, /prev\.dynamicTabTitleMode === next\.dynamicTabTitleMode/); -}); - -test('focus sidebar accepts host-id drops for append-to-workspace', () => { - assert.match(source, /onAppendHostToWorkspace/); - assert.match(source, /resolveFocusSidebarDragKind/); - assert.match(source, /appendHostFromWorkspaceDrop/); - assert.match(source, /dropEffect = 'copy'/); - assert.match(source, /data-host-drop-active/); -}); - -test('the entire focus sidebar is the host drop target', () => { - const sidebarStart = source.indexOf('data-section="terminal-workspace-sidebar"'); - const scrollAreaStart = source.indexOf('', sidebarStart); - assert.ok(sidebarStart >= 0 && scrollAreaStart > sidebarStart); - - const sidebarOpeningTag = source.slice(sidebarStart, scrollAreaStart); - assert.match(sidebarOpeningTag, /data-focus-sidebar-drop-zone/); - assert.match(sidebarOpeningTag, /onDragOver=\{handleFocusSidebarHostDragOver\}/); - assert.match(sidebarOpeningTag, /onDrop=\{handleFocusSidebarHostDrop\}/); - assert.doesNotMatch(source.slice(scrollAreaStart), /\sdata-focus-sidebar-drop-zone(?:\s|>)/); -}); - -test('focus sidebar clears host-drop feedback when the drag leaves from a session row', () => { - assert.match(source, /data-focus-sidebar-drop-zone/); - assert.match(source, /onDragLeave=\{handleFocusSidebarHostDragLeave\}/); - assert.match(source, /onHostDragLeave=\{handleFocusSidebarHostDragLeave\}/); - assert.match(source, /dropZone\?\.contains\(next\)/); - assert.match(source, /clearFocusSidebarHostDrop\(\)/); -}); diff --git a/components/terminalLayer/TerminalHostTreeSidebar.tsx b/components/terminalLayer/TerminalHostTreeSidebar.tsx index 0010dea78..7f81a15d0 100644 --- a/components/terminalLayer/TerminalHostTreeSidebar.tsx +++ b/components/terminalLayer/TerminalHostTreeSidebar.tsx @@ -39,7 +39,7 @@ import { import { themeFingerprint } from '../../application/state/useActiveChromeTheme'; import { buildHostTreeThemeFromTerminalTheme } from '../../infrastructure/theme/terminalAppearanceTokens'; import { cn } from '../../lib/utils'; -import { matchesHostSearchQuery, matchesSearchQuery } from '../../lib/searchMatcher'; +import { matchesHostSearchQuery, matchesSearchQuery } from '../../domain/searchMatcher'; import type { GroupConfig, GroupNode, Host, TerminalTheme } from '../../types'; import { HostTreeGroupContextMenuContent, HostTreeHostContextMenuContent } from '../host/HostTreeContextMenus'; import { HostTreeGroupInlineRenameInput } from '../host/HostTreeGroupInlineRenameInput'; diff --git a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts index 43f827718..d739b0afc 100644 --- a/components/terminalLayer/TerminalLayerSidePanelSection.test.ts +++ b/components/terminalLayer/TerminalLayerSidePanelSection.test.ts @@ -1,5 +1,4 @@ import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; import test from 'node:test'; import { JSDOM } from 'jsdom'; @@ -134,55 +133,6 @@ test('narrow side panels keep the active tool visible and move extra tools into assert.deepEqual(fitted.collapsed, ['browser', 'scripts', 'history', 'theme', 'system', 'notes']); }); -test('notes side panel forwards repeated open-note requests', () => { - const layerSource = readFileSync(new URL('../TerminalLayer.tsx', import.meta.url), 'utf8'); - const slotsSource = readFileSync(new URL('./terminalLayerSidePanelSlots.tsx', import.meta.url), 'utf8'); - - assert.match(layerSource, /notesOpenRequestIdRef\.current \+= 1/); - assert.match(layerSource, /next\.set\(tabId, \{ noteId, requestId \}\)/); - assert.match(slotsSource, /openNoteRequestId=\{openNoteRequest\?\.requestId \?\? null\}/); -}); - -test('system monitoring only pauses for hidden remote tabs when hibernation is enabled', () => { - const source = readFileSync(new URL('./terminalLayerSidePanelSlots.tsx', import.meta.url), 'utf8'); - - // resolveSystemSidebarSession feeds systemSession (via live overlay when active). - assert.match(source, /resolveSystemSidebarSession\(/); - assert.match(source, /const systemSession = /); - assert.match(source, /shouldKeepTerminalBackgroundWorkActive\([\s\S]*systemHost\?\.protocol,[\s\S]*isTabActive/); - assert.doesNotMatch(source, /useSidePanelLiveSnapshotForTab\(tabId, keepSystemWorkActive\)/); - assert.match(source, /isVisible=\{keepSystemWorkActive\}/); -}); - -test('side panel tab bar and borders use inline resolved terminal theme colors', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /buildSidePanelChromeThemeFromTerminalTheme/); - assert.match(sectionSource, /backgroundColor: sidePanelTheme\.termBg/); - assert.match(sectionSource, /borderBottom: `1px solid \$\{sidePanelTheme\.separator\}`/); - assert.match(sectionSource, /borderLeft: `1px solid \$\{sidePanelTheme\.separator\}`/); - assert.doesNotMatch(sectionSource, /terminalAppearanceSidePanelStyle/); - assert.doesNotMatch(sectionSource, /var\(--terminal-sidepanel-border\)/); -}); - -test('side panel content scopes app color utilities to the resolved terminal theme', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /buildTerminalSidePanelCssVars/); - assert.match(sectionSource, /\.\.\.sidePanelCssVars/); -}); - -test('side panel sets color-scheme from the terminal theme so native inputs match light panels', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - // When a light terminal theme remaps --background under a dark app chrome, - // form controls (Codex/AI composer textarea) still follow color-scheme. - assert.match( - sectionSource, - /colorScheme:\s*resolvedSidePanelTerminalTheme\.type/, - ); -}); - test('a visible tool without a ready pane host stays in the hidden parking host', () => { const parkingHost = { id: 'parking' }; const paneHost = { id: 'pane' }; @@ -241,147 +191,4 @@ test('moving a stable portal host restores focus to its active input', () => { } }); -test('the covered side-panel shell cannot receive keyboard focus', () => { - const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - assert.match(source, /const activeMagnifiedPane =/); - assert.match(source, /inert=\{activeMagnifiedPane \? true : undefined\}/); -}); - -test('split pane hosts strictly clip each tool and do not use the side panel root as a portal fallback', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - const slotsSource = readFileSync(new URL('./terminalLayerSidePanelSlots.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /terminal-side-panel-pane-content/); - assert.match(sectionSource, /overflow-hidden \[contain:strict\]/); - assert.match(sectionSource, /terminal-side-panel-parking/); - assert.match(slotsSource, /paneHosts\.get\(tool\)/); - assert.match(slotsSource, /document\.createElement\('div'\)/); - assert.match(slotsSource, /target\.appendChild\(mountNode\)/); - assert.match(slotsSource, /focusRestoreRef\.current/); - assert.match(slotsSource, /movePersistentPortalNode\(mountNode, target, focusedDescendant\)/); - assert.match(slotsSource, /createPortal\(children, mountNode, portalKey\)/); - assert.doesNotMatch(slotsSource, /document\.querySelector\([^)]*terminal-side-panel/); -}); - -test('the shared toolbar owns split controls while panes only render minimal chrome', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, / 1/); -}); - -test('split icons depict the same pane arrangement as their actions', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match( - sectionSource, - /direction === 'horizontal'\s*\? \s*: /, - ); -}); - -test('side panel layout state is initialized before callbacks read it', () => { - const layerSource = readFileSync(new URL('../TerminalLayer.tsx', import.meta.url), 'utf8'); - const layoutStateIndex = layerSource.indexOf('} = useTerminalSidePanelLayoutState();'); - const statusCallbackIndex = layerSource.indexOf('const handleStatusChange = useCallback'); - - assert.notEqual(layoutStateIndex, -1); - assert.notEqual(statusCallbackIndex, -1); - assert.ok(layoutStateIndex < statusCallbackIndex); -}); - -test('split dragging previews locally, commits once, and cleans up on every exit path', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /const updatePreview = \(\) => \{[\s\S]*setPreviewSizes\(next\)/); - assert.match(sectionSource, /const finish = \(\) => \{[\s\S]*onResize\(node\.id, latestSizes\)/); - const previewBody = sectionSource.slice( - sectionSource.indexOf('const updatePreview = () => {'), - sectionSource.indexOf('const onMouseMove = (moveEvent: MouseEvent) => {'), - ); - assert.doesNotMatch(previewBody, /onResize/); - assert.match(sectionSource, /window\.addEventListener\('blur', finish\)/); - assert.match(sectionSource, /resizeCleanupRef\.current\?\.\(\)/); - assert.match(sectionSource, /terminalLayoutSuppressStore\.end\(\)/); -}); - -test('split resizers do not consume visible gutter space', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /group relative w-px shrink-0 cursor-ew-resize/); - assert.match(sectionSource, /group relative h-px shrink-0 cursor-ns-resize/); - assert.match(sectionSource, /after:w-2/); - assert.match(sectionSource, /after:h-2/); - assert.doesNotMatch(sectionSource, /group relative w-1 shrink-0 cursor-ew-resize/); - assert.doesNotMatch(sectionSource, /group relative h-1 shrink-0 cursor-ns-resize/); -}); - -test('side panel resize uses the expanded width limit and protects terminal space', () => { - const layerSource = readFileSync(new URL('../TerminalLayer.tsx', import.meta.url), 'utf8'); - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(layerSource, /TERMINAL_SIDE_PANEL_MAX_WIDTH/); - assert.match(sectionSource, /clampTerminalSidePanelWidth/); - assert.match(sectionSource, /terminalLayer\.getBoundingClientRect\(\)\.width/); - assert.match(sectionSource, /terminal-workspace-sidebar/); - assert.match(sectionSource, /new ResizeObserver/); - assert.match(sectionSource, /shellRef\.current\?\.getBoundingClientRect\(\)\.width \?\? shellWidth/); - assert.doesNotMatch(sectionSource, /window\.innerWidth[,)\n]/); - assert.doesNotMatch(sectionSource, /100vw/); - assert.doesNotMatch(sectionSource, /const startWidth = sidePanelWidth/); - assert.doesNotMatch(sectionSource, /Math\.min\(800,/); -}); - -test('side panel width dragging cleans up on mouseup, blur, and unmount', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /shellResizeCleanupRef\.current\?\.\(\)/); - assert.match(sectionSource, /window\.addEventListener\('mouseup', finish\)/); - assert.match(sectionSource, /window\.addEventListener\('blur', finish\)/); - assert.match(sectionSource, /window\.removeEventListener\('blur', finish\)/); -}); - -test('split resizing preserves nested minimums without rerendering on every pixel', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /getSidePanelSplitResizeBounds/); - assert.match(sectionSource, /getSidePanelNodeMinimumPixels\(activeSidePanelLayout\.root, 'vertical'\)/); - assert.match(sectionSource, /focusedPaneSplitAvailability/); - assert.doesNotMatch(sectionSource, /focusedPaneSize/); -}); - -test('available-width observer releases a removed focus sidebar immediately', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - assert.match(sectionSource, /focusSidebar !== observedFocusSidebar/); - assert.match(sectionSource, /if \(observedFocusSidebar\) resizeObserver\.unobserve\(observedFocusSidebar\)/); - assert.match(sectionSource, /observedFocusSidebar = null/); -}); - -test('side panel close button stays visible at every panel width', () => { - const sectionSource = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - - // The toolbar close button is the panel's only dismiss control and the - // rightmost item of the nowrap toolbar row. Closing is a core function, so - // it must never be a flex-shrink victim and must never carry responsive - // hiding classes; secondary toolbar actions yield first instead. - const closeLabelIndex = sectionSource.indexOf("t('terminal.layer.closePanel')"); - assert.ok(closeLabelIndex > 0, 'close button tooltip label is rendered'); - const closeSlice = sectionSource.slice(Math.max(0, closeLabelIndex - 600), closeLabelIndex); - assert.match(closeSlice, /onClick=\{handleCloseSidePanel\}/); - assert.match(closeSlice, /className="h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"/); - assert.doesNotMatch(closeSlice, /\bhidden\b|max-(sm|md|lg|xl):/); -}); - -test('magnified side-panel chrome thickens the accent stroke on low-DPR displays', () => { - const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8'); - const overlay = source.slice( - source.indexOf('data-section="pane-magnification-overlay"'), - source.indexOf('data-section="pane-magnification-content"'), - ); - assert.match(overlay, /overflow-hidden rounded-md border bg-background shadow-2xl/); - assert.match(overlay, /borderColor: sidePanelTheme\.accent,/); - assert.match(overlay, /resolveMagnifiedChromeBorderWidth\(/); -}); diff --git a/components/terminalLayer/TerminalLayerSupport.tsx b/components/terminalLayer/TerminalLayerSupport.tsx index b2a1f7c47..61165db22 100644 --- a/components/terminalLayer/TerminalLayerSupport.tsx +++ b/components/terminalLayer/TerminalLayerSupport.tsx @@ -178,13 +178,6 @@ export function adjustSaturationToken(hsl: string, factor: number): string { return `${parts[0]} ${Math.round(newS * 10) / 10}% ${parts[2]}`; } -export type { TerminalThemePreviewState } from './terminalThemePreview'; -export { - emptyTerminalThemePreview, - listThemePreviewSessionIds, - resolvePaneThemePreviewId, -} from './terminalThemePreview'; - export const clearTerminalPreviewVars = (sessionId: string | null) => { if (!sessionId || typeof document === 'undefined') return; const pane = document.querySelector(`[data-session-id="${sessionId}"]`); diff --git a/components/terminalLayer/TerminalLayerTabBridge.test.ts b/components/terminalLayer/TerminalLayerTabBridge.test.ts deleted file mode 100644 index f68169eab..000000000 --- a/components/terminalLayer/TerminalLayerTabBridge.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const source = readFileSync(new URL('./TerminalLayerTabBridge.tsx', import.meta.url), 'utf8'); - -test('terminal layer bridge does not dock the shared host tree', () => { - assert.doesNotMatch(source, /hostTreeDockedInLayer/); -}); - -test('terminal layer is visible only for terminal sessions or workspaces', () => { - assert.match(source, /const isVisible = Boolean\(activeSession \|\| activeWorkspace \|\| s\.draggingSessionId\)/); -}); - -test('terminal panes can gate cwd restore per session host resolution', () => { - const supportSource = readFileSync(new URL('./TerminalLayerSupport.tsx', import.meta.url), 'utf8'); - const layerSource = readFileSync(new URL('../TerminalLayer.tsx', import.meta.url), 'utf8'); - - assert.match(supportSource, /sessionHostResolved: boolean/); - assert.match(supportSource, /restoreTerminalCwd=\{restoreTerminalCwd && sessionHostResolved\}/); - assert.match(layerSource, /session\.protocol === 'local'/); -}); - -test('terminal layer bridge refreshes when terminal settings change', () => { - assert.match(source, /terminalSettings: s\.terminalSettings/); - assert.match(source, /\[\s*[\s\S]*s\.terminalSettings[\s\S]*\]\);/); -}); - -test('terminal layer bridge passes vault open callbacks into the side panel context', () => { - assert.match(source, /onOpenVaultNoteFromChat: s\.onOpenVaultNoteFromChat/); - assert.match(source, /onOpenVaultHostFromChat: s\.onOpenVaultHostFromChat/); - assert.match(source, /onOpenVaultSectionFromChat: s\.onOpenVaultSectionFromChat/); -}); - -test('production terminal layer context forwards extension sidebar owner and pane callbacks', () => { - const contextProjection = source.slice(source.indexOf('const ctx = useMemo(')); - for (const callback of ['getActiveTerminalSessionId', 'handleSwitchSidePanelTab', 'handleWithdrawPluginSidebarPane']) { - assert.match(contextProjection, new RegExp(`${callback}: s\\.${callback}\\b`)); - } -}); - -test('terminal layer bridge updates side panel live state after render', () => { - assert.match(source, /const sidePanelLiveSnapshot = useMemo/); - assert.match( - source, - /useLayoutEffect\(\(\) => \{\s*sidePanelLiveStore\.update\(sidePanelLiveSnapshot\);\s*\}, \[sidePanelLiveSnapshot\]\);/, - ); - assert.doesNotMatch(source, /sidePanelLiveStore\.update\(\{\s*sftpActiveHost/); -}); diff --git a/components/terminalLayer/TerminalLayerWorkspaceSection.liveStore.test.ts b/components/terminalLayer/TerminalLayerWorkspaceSection.liveStore.test.ts deleted file mode 100644 index 9c52dcabc..000000000 --- a/components/terminalLayer/TerminalLayerWorkspaceSection.liveStore.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; - -const source = readFileSync( - new URL("./TerminalLayerWorkspaceSection.tsx", import.meta.url), - "utf8", -); - -test("workspace section uses live store only for activeWorkspace (no stale ctx fallback)", () => { - // After view memo omits activeWorkspace from equality, ctx can lag behind - // live when switching workspace → solo session (live clears to undefined). - // `live.x ?? ctx.x` would keep the old workspace for compose bar / resizers. - assert.match(source, /sidePanelLiveStore\.getSnapshot/); - assert.match(source, /const activeWorkspace = live\.activeWorkspace;/); - assert.match(source, /const focusedSessionId = live\.focusedSessionId;/); - assert.doesNotMatch(source, /live\.activeWorkspace\s*\?\?/); - assert.doesNotMatch(source, /live\.focusedSessionId\s*\?\?/); - assert.doesNotMatch(source, /ctx\.activeWorkspace/); - assert.doesNotMatch(source, /ctx\.focusedSessionId/); - // Focus mode must follow live workspace, not stale ctx.isFocusMode. - assert.match(source, /activeWorkspace\?\.viewMode === ['"]focus['"]/); -}); diff --git a/components/terminalLayer/terminalThemePreview.test.ts b/components/terminalLayer/terminalThemePreview.test.ts deleted file mode 100644 index 600a31a71..000000000 --- a/components/terminalLayer/terminalThemePreview.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; - -import { - emptyTerminalThemePreview, - listThemePreviewSessionIds, - resolvePaneThemePreviewId, -} from "./terminalThemePreview"; - -const preview = { - targetSessionId: "session-a", - targetHostId: "host-1", - globalPreview: false, - themeId: "dracula", -}; - -test("follow-app mode never applies per-pane theme preview ids", () => { - assert.equal( - resolvePaneThemePreviewId(true, preview, "session-a", "host-1"), - undefined, - ); -}); - -test("host-scoped preview applies to every session on the same host", () => { - assert.equal( - resolvePaneThemePreviewId(false, preview, "session-b", "host-1"), - "dracula", - ); - assert.equal( - resolvePaneThemePreviewId(false, preview, "session-c", "host-2"), - undefined, - ); -}); - -test("global preview applies to all sessions", () => { - const globalPreview = { ...preview, globalPreview: true, targetHostId: null }; - assert.equal( - resolvePaneThemePreviewId(false, globalPreview, "session-z", "host-9"), - "dracula", - ); -}); - -test("listThemePreviewSessionIds skips follow-app previews", () => { - const sessions = [{ id: "session-a" }, { id: "session-b" }]; - const sessionHostsMap = new Map([ - ["session-a", { id: "host-1" }], - ["session-b", { id: "host-1" }], - ]); - - assert.deepEqual( - listThemePreviewSessionIds(sessions, sessionHostsMap, preview, true), - [], - ); - assert.deepEqual( - listThemePreviewSessionIds(sessions, sessionHostsMap, preview, false), - ["session-a", "session-b"], - ); -}); - -test("emptyTerminalThemePreview returns a cleared preview state", () => { - assert.deepEqual(emptyTerminalThemePreview(), { - targetSessionId: null, - targetHostId: null, - globalPreview: false, - themeId: null, - }); -}); diff --git a/components/terminalLayer/terminalThemePreview.ts b/components/terminalLayer/terminalThemePreview.ts deleted file mode 100644 index 1cbb658bf..000000000 --- a/components/terminalLayer/terminalThemePreview.ts +++ /dev/null @@ -1,42 +0,0 @@ -export type TerminalThemePreviewState = { - targetSessionId: string | null; - targetHostId: string | null; - globalPreview: boolean; - themeId: string | null; -}; - -export const emptyTerminalThemePreview = (): TerminalThemePreviewState => ({ - targetSessionId: null, - targetHostId: null, - globalPreview: false, - themeId: null, -}); - -/** Which terminal panes should render a theme preview (sidebar list uses themeId separately). */ -export function resolvePaneThemePreviewId( - followAppTerminalTheme: boolean, - themePreview: TerminalThemePreviewState, - sessionId: string, - hostId: string, -): string | undefined { - if (followAppTerminalTheme || !themePreview.themeId) return undefined; - if (themePreview.globalPreview) return themePreview.themeId; - if (sessionId === themePreview.targetSessionId) return themePreview.themeId; - if (themePreview.targetHostId && hostId === themePreview.targetHostId) return themePreview.themeId; - return undefined; -} - -export function listThemePreviewSessionIds( - sessions: ReadonlyArray<{ id: string }>, - sessionHostsMap: Map, - themePreview: TerminalThemePreviewState, - followAppTerminalTheme: boolean, -): string[] { - if (followAppTerminalTheme || !themePreview.themeId) return []; - return sessions.flatMap((session) => { - const hostId = sessionHostsMap.get(session.id)?.id ?? ''; - return resolvePaneThemePreviewId(followAppTerminalTheme, themePreview, session.id, hostId) - ? [session.id] - : []; - }); -} diff --git a/components/terminalLayer/useTerminalAiContexts.ts b/components/terminalLayer/useTerminalAiContexts.ts deleted file mode 100644 index 7dde9e33a..000000000 --- a/components/terminalLayer/useTerminalAiContexts.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** @deprecated Import from `@/application/state/useTerminalAiContexts` instead. */ -export { useTerminalAiContexts } from "../../application/state/useTerminalAiContexts"; diff --git a/components/terminalLayer/useTerminalThemePanelState.test.ts b/components/terminalLayer/useTerminalThemePanelState.test.ts deleted file mode 100644 index f40c3792e..000000000 --- a/components/terminalLayer/useTerminalThemePanelState.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const source = readFileSync(new URL("./useTerminalThemePanelState.ts", import.meta.url), "utf8"); - -test("follow-app side panel theme changes delegate to ThemeRuntime pickTheme", () => { - assert.match(source, /pickTheme\(themeId\)/); - assert.match(source, /if \(followAppTerminalTheme\) \{/); - assert.doesNotMatch(source, /onUpdateFollowAppTerminalThemeId/); - assert.doesNotMatch(source, /setThemePreview/); - assert.doesNotMatch(source, /applyTerminalPreviewVars/); -}); - -test("manual side panel theme changes persist host overrides and use runtime pick intent", () => { - assert.match(source, /pickTheme\(themeId, \{/); - assert.match(source, /scopeHostId:/); - assert.match(source, /onUpdateHost\(\{ \.\.\.rawFocusedHost, theme: themeId, themeOverride: true \}\)/); - assert.doesNotMatch(source, /startTransition\(\(\) => \{[\s\S]*onUpdateHost\(\{ \.\.\.rawFocusedHost, theme: themeId/); -}); - -test("follow-app keeps runtime intent until the side panel closes", () => { - assert.match(source, /isSidePanelOpenForCurrentTab/); - assert.match(source, /if \(!followAppTerminalTheme && activeSidePanelTab !== 'theme'\)/); - assert.match(source, /clearIntent\(\)/); -}); - -test("follow-app theme list selection tracks global runtime theme id", () => { - assert.match(source, /listSelectedThemeId = followAppTerminalTheme/); - assert.match(source, /terminalTheme\.id/); -}); - -test("manual theme list selection reads focused appearance from runtime", () => { - assert.match(source, /resolveFocusedAppearance\(focusedHostScope\)/); - assert.match(source, /focusedAppearance\.themeId/); - assert.match(source, /resolvedPreviewTheme = focusedAppearance\.theme/); -}); - -test("focusedAppearance recomputes from appearanceChromeStore accent churn", () => { - assert.match(source, /useAppearanceChromeStore\(\)/); - assert.match(source, /appearanceChrome\.accentMode/); - assert.match(source, /appearanceChrome\.customAccent/); -}); - -test("closing the theme tab clears runtime user intent", () => { - assert.match(source, /if \(isSidePanelOpenForCurrentTab\)/); - assert.match(source, /clearIntent\(\)/); -}); diff --git a/components/terminalLayer/workspacePaneRearrange.test.ts b/components/terminalLayer/workspacePaneRearrange.test.ts deleted file mode 100644 index 6960b33b3..000000000 --- a/components/terminalLayer/workspacePaneRearrange.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -// Source-contract tests for issue #4037 (rearrange member panes within a -// workspace). The layout hook is render-heavy; these pin the wiring the way -// TerminalLayerTabBridge.test.ts pins its bridge. - -const layoutSource = readFileSync(new URL('./useTerminalWorkspaceLayout.ts', import.meta.url), 'utf8'); -const bridgeSource = readFileSync(new URL('./TerminalLayerTabBridge.tsx', import.meta.url), 'utf8'); -const stateSource = readFileSync(new URL('../../application/state/useSessionState.ts', import.meta.url), 'utf8'); - -test('drop handler rearranges same-workspace panes and still rejects cross-workspace drops', () => { - assert.match(layoutSource, /draggedSession\.workspaceId === activeWorkspace\.id/); - // Cross-workspace drops must fall through without calling either action: - // the branch only moves when the ids match, then returns unconditionally. - const dropBody = layoutSource.slice(layoutSource.indexOf('const handleWorkspaceDrop')); - assert.match(dropBody, /if \(draggedSession\.workspaceId === activeWorkspace\.id\) \{\s*onMoveWorkspacePane/); - assert.match(dropBody, /onAddSessionToWorkspace\(activeWorkspace\.id, draggedSessionId, hint\)/); -}); - -test('member pane drags drive the split-hint preview over the pointer stream', () => { - assert.match(layoutSource, /isMemberPaneDrag/); - assert.match(layoutSource, /window\.addEventListener\('pointermove', onPointerMove\)/); - // Release is owned by the pane gesture, not a competing window listener. - assert.match(bridgeSource, /onDropWorkspacePane: handleWorkspacePanePointerDrop/); - assert.doesNotMatch(layoutSource, /window\.addEventListener\('pointerup'/); -}); - -test('the bridge threads the move action and the dragged member session', () => { - assert.match(bridgeSource, /onMoveWorkspacePane: s\.onMoveWorkspacePane/); - assert.match(bridgeSource, /draggingSession: s\.draggingSessionId/); -}); - -test('moveWorkspacePane mutates only the workspace pane tree', () => { - const start = stateSource.indexOf('const moveWorkspacePane = useCallback'); - const end = stateSource.indexOf('const createWorkspaceFromSessions = useCallback', start); - assert.ok(start > -1 && end > start, 'moveWorkspacePane callback exists'); - const body = stateSource.slice(start, end); - assert.match(body, /moveWorkspacePaneInWorkspaces\(prev, workspaceId, sessionId, hint\)/); - // Identity guarantee: no session, tab-order, focus or AI-state writes. - assert.doesNotMatch(body, /setSessions|setTabOrder|setActiveTabId|setWorkspaceFocusedSession|anchorChat|activeSessionIdMap/); -}); diff --git a/components/test-support/domHarness.ts b/components/test-support/domHarness.ts new file mode 100644 index 000000000..b0814cb4f --- /dev/null +++ b/components/test-support/domHarness.ts @@ -0,0 +1,154 @@ +import { JSDOM } from "jsdom"; +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; + +export interface DomHarnessHandle { + dom: JSDOM; + window: Window & typeof globalThis; + document: Document; + container: HTMLDivElement; + render: (element: React.ReactElement) => Promise; + cleanup: () => Promise; +} + +const DOM_GLOBALS = [ + "window", + "document", + "navigator", + "HTMLElement", + "Element", + "Node", + "Event", + "CustomEvent", + "MouseEvent", + "KeyboardEvent", + "PointerEvent", + "FocusEvent", + "MutationObserver", + "ResizeObserver", + "getComputedStyle", + "requestAnimationFrame", + "cancelAnimationFrame", +] as const; + +/** + * Install an isolated JSDOM + React 19 createRoot environment and restore all globals on cleanup. + */ +export function createDomHarness(options: { url?: string; netcatty?: Record } = {}): DomHarnessHandle { + const dom = new JSDOM('
', { + pretendToBeVisual: true, + url: options.url ?? "http://localhost/", + }); + const win = dom.window as unknown as Window & typeof globalThis; + const previous = new Map(); + + const install = (key: string, value: unknown) => { + if (!previous.has(key)) { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + } + Object.defineProperty(globalThis, key, { + configurable: true, + writable: true, + value, + }); + }; + + install("IS_REACT_ACT_ENVIRONMENT", true); + for (const key of DOM_GLOBALS) { + const value = (win as Record)[key]; + if (value !== undefined) { + install(key, value); + } + } + if (!(globalThis as Record).ResizeObserver) { + install("ResizeObserver", class { + observe() {} + unobserve() {} + disconnect() {} + }); + } + if (options.netcatty) { + Object.defineProperty(win, "netcatty", { + configurable: true, + writable: true, + value: options.netcatty, + }); + } + + const container = win.document.getElementById("root") as HTMLDivElement; + let root: Root | null = null; + + return { + dom, + window: win, + document: win.document, + container, + render: async (element: React.ReactElement) => { + await act(async () => { + if (!root) { + root = createRoot(container); + } + root.render(element); + }); + }, + cleanup: async () => { + if (root) { + const activeRoot = root; + root = null; + await act(async () => { + activeRoot.unmount(); + }); + } + dom.window.close(); + for (const [key, descriptor] of previous.entries()) { + if (descriptor) { + Object.defineProperty(globalThis, key, descriptor); + } else { + delete (globalThis as Record)[key]; + } + } + }, + }; +} + +/** + * Install an in-memory localStorage mock on globalThis and return a restore function. + */ +export function installMemoryLocalStorage(initial: Record = {}): { + store: Map; + restore: () => void; +} { + const store = new Map(Object.entries(initial)); + const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); + const mockStorage: Storage = { + get length() { + return store.size; + }, + clear: () => store.clear(), + getItem: (key: string) => store.get(key) ?? null, + key: (index: number) => Array.from(store.keys())[index] ?? null, + removeItem: (key: string) => { + store.delete(key); + }, + setItem: (key: string, value: string) => { + store.set(key, String(value)); + }, + }; + + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + writable: true, + value: mockStorage, + }); + + return { + store, + restore: () => { + if (previous) { + Object.defineProperty(globalThis, "localStorage", previous); + } else { + delete (globalThis as Record).localStorage; + } + }, + }; +} diff --git a/components/themeContrastRegression.test.ts b/components/themeContrastRegression.test.ts deleted file mode 100644 index f0ea2b16e..000000000 --- a/components/themeContrastRegression.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const cloudSyncDialogsSource = readFileSync( - new URL('./cloud-sync/CloudSyncDialogs.tsx', import.meta.url), - 'utf8', -); - -test('cloud revision rows use a neutral hover surface for arbitrary accent colors', () => { - assert.match(cloudSyncDialogsSource, /hover:bg-muted\/50/); - assert.doesNotMatch(cloudSyncDialogsSource, /hover:bg-accent(?:\/50)?/); -}); diff --git a/components/ui/aside-panel.tsx b/components/ui/aside-panel.tsx index b382f9cd6..05d3a1c64 100644 --- a/components/ui/aside-panel.tsx +++ b/components/ui/aside-panel.tsx @@ -1,5 +1,5 @@ import { ArrowLeft, MoreVertical, X } from 'lucide-react'; -import React, { createContext, ReactNode, useCallback, useContext, useMemo, useState } from 'react'; +import React, { createContext, ReactNode, useCallback, useContext, useState } from 'react'; import { cn } from '../../lib/utils'; import { localStorageAdapter } from '@/infrastructure/persistence/localStorageAdapter'; import { Popover, PopoverContent, PopoverTrigger } from './popover'; @@ -43,35 +43,8 @@ function readPersistedAsideWidth(storageKey: string | undefined, fallback: numbe return clampAsideInlineWidth(stored); } -// Types -interface AsideContentItem { - id: string; - title: string; - subtitle?: string; - actions?: ReactNode; - content: ReactNode; -} - -interface AsidePanelContextType { - push: (item: AsideContentItem) => void; - pop: () => void; - replace: (item: AsideContentItem) => void; - clear: () => void; - canGoBack: boolean; - currentItem: AsideContentItem | null; -} - -const AsidePanelContext = createContext(null); const AsideActionMenuContext = createContext<(() => void) | null>(null); -export const useAsidePanel = () => { - const context = useContext(AsidePanelContext); - if (!context) { - throw new Error('useAsidePanel must be used within an AsidePanel'); - } - return context; -}; - // Props interface AsidePanelProps extends AsidePanelResizeProps { open: boolean; @@ -104,7 +77,7 @@ interface AsidePanelHeaderProps { } // Header Component -export const AsidePanelHeader: React.FC = ({ +const AsidePanelHeader: React.FC = ({ title, subtitle, actions, @@ -236,116 +209,8 @@ export const AsideActionMenuItem: React.FC<{ ); }; -// Main Panel Component with Stack Support -interface AsidePanelStackProps { - open: boolean; - onClose: () => void; - initialItem: AsideContentItem; - className?: string; - width?: string; - layout?: AsidePanelLayout; - /** - * Optional stable identifier emitted as `data-section` on the panel - * root. Used as a targeting hook for Custom CSS. - */ - dataSection?: string; -} - export type AsidePanelLayout = 'overlay' | 'inline'; -const resolveInlineWidth = (width: string) => { - const arbitraryWidthMatch = width.match(/w-\[(.+)\]/); - if (arbitraryWidthMatch) { - return arbitraryWidthMatch[1]; - } - - switch (width) { - case 'w-full': - return '100%'; - case 'w-screen': - return '100vw'; - default: - return '380px'; - } -}; - -export const AsidePanelStack: React.FC = ({ - open, - onClose, - initialItem, - className, - width = 'w-[380px]', - layout = 'overlay', - dataSection, -}) => { - const [stack, setStack] = useState([initialItem]); - - const push = useCallback((item: AsideContentItem) => { - setStack(prev => [...prev, item]); - }, []); - - const pop = useCallback(() => { - setStack(prev => { - if (prev.length > 1) { - return prev.slice(0, -1); - } - return prev; - }); - }, []); - - const replace = useCallback((item: AsideContentItem) => { - setStack([item]); - }, []); - - const clear = useCallback(() => { - setStack([initialItem]); - }, [initialItem]); - - const currentItem = stack[stack.length - 1]; - const canGoBack = stack.length > 1; - const inlineWidth = useMemo(() => resolveInlineWidth(width), [width]); - const inlineStyle = layout === 'inline' - ? ({ - width: inlineWidth, - ['--aside-inline-width' as string]: inlineWidth, - } as React.CSSProperties) - : undefined; - - // Reset stack when panel closes/opens - React.useEffect(() => { - if (open) { - setStack([initialItem]); - } - }, [open, initialItem]); - - if (!open) return null; - - return ( - -
- - {currentItem.content} -
-
- ); -}; - // Simple Panel Component (no stack) export const AsidePanel: React.FC = ({ open, diff --git a/components/ui/toast.test.ts b/components/ui/toast.test.ts deleted file mode 100644 index 1951c5d63..000000000 --- a/components/ui/toast.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import assert from "node:assert/strict"; -import { readFileSync } from "node:fs"; -import test from "node:test"; - -const toastSource = readFileSync(new URL("./toast.tsx", import.meta.url), "utf8"); - -test("toast surfaces follow app theme tokens instead of OS palette fills", () => { - const styles = toastSource.slice( - toastSource.indexOf("const TOAST_STYLES"), - toastSource.indexOf("export const ToastProvider"), - ); - - assert.match(styles, /success: 'border-emerald-600'/); - assert.match(styles, /error: 'border-red-600'/); - assert.match(styles, /warning: 'border-yellow-600'/); - assert.match(styles, /info: 'border-blue-600'/); - // `dark:` is prefers-color-scheme, so these fills stay pale while - // text-foreground / text-muted-foreground follow the `.dark` class. - assert.doesNotMatch(styles, /bg-(?:emerald|red|yellow|blue)-50/); - assert.doesNotMatch(styles, /dark:bg-(?:emerald|red|yellow|blue)-950/); - assert.match(toastSource, /"bg-card animate-in/); - assert.match(toastSource, /text-sm font-medium text-foreground/); - assert.match(toastSource, /text-sm text-muted-foreground break-words/); -}); diff --git a/components/ui/toast.tsx b/components/ui/toast.tsx index 55ec990e1..ff50b1dcb 100644 --- a/components/ui/toast.tsx +++ b/components/ui/toast.tsx @@ -27,25 +27,6 @@ interface ToastStateValue { const ToastActionsContext = createContext(null); const ToastStateContext = createContext(null); -/** Actions-only subscription — does not re-render when the toast list changes. */ -export const useToastActions = () => { - const context = useContext(ToastActionsContext); - if (!context) { - throw new Error('useToastActions must be used within a ToastProvider'); - } - return context; -}; - -/** Full toast API. Prefer useToastActions when you do not need the list. */ -export const useToast = () => { - const actions = useContext(ToastActionsContext); - const state = useContext(ToastStateContext); - if (!actions || !state) { - throw new Error('useToast must be used within a ToastProvider'); - } - return { ...state, ...actions }; -}; - // Simple hook for components that may not be inside ToastProvider let globalShowToast: ((toast: Omit) => void) | null = null; diff --git a/components/vault/ImportVaultDialog.pluginImporterLifecycle.test.ts b/components/vault/ImportVaultDialog.pluginImporterLifecycle.test.ts deleted file mode 100644 index 89a89116a..000000000 --- a/components/vault/ImportVaultDialog.pluginImporterLifecycle.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import test from 'node:test'; - -const dialogSource = readFileSync(new URL('./ImportVaultDialog.tsx', import.meta.url), 'utf8'); -const hookSource = readFileSync(new URL('../../application/state/usePluginVaultImporter.ts', import.meta.url), 'utf8'); - -test('closing the importer dialog invalidates, cancels, and clears an active plugin request', () => { - assert.match(hookSource, /pluginImportGenerationRef\.current \+= 1;/u); - assert.match(hookSource, /const requestId = activePluginImportRequestRef\.current;[\s\S]*activePluginImportRequestRef\.current = null;[\s\S]*pluginExtensionBridge\.cancelRequest\(requestId\)/u); - assert.match(hookSource, /setPluginPreview\(null\);[\s\S]*setPluginProgress\(null\);[\s\S]*setPluginBusy\(false\);/u); -}); - -test('late plugin importer results cannot repopulate state after close or replacement', () => { - assert.match(hookSource, /const generation = \+\+pluginImportGenerationRef\.current;/u); - assert.match(hookSource, /const isCurrent = \(\) => pluginImportGenerationRef\.current === generation;/u); - assert.match(hookSource, /if \(!selection \|\| !isCurrent\(\)\) return;/u); - assert.match(hookSource, /if \(isCurrent\(\)\) setPluginPreview\(preview\);/u); - assert.match(hookSource, /if \(isCurrent\(\)\) setPluginError/u); - assert.match(hookSource, /if \(selection && !consumed\)[\s\S]*releaseImporterFile\(selection\.selectionToken\)/u); -}); - -test('importer detection is cancellable before awaiting provider work', () => { - assert.match( - hookSource, - /requestId = crypto\.randomUUID\(\);[\s\S]*activePluginImportRequestRef\.current = requestId;[\s\S]*await pluginExtensionBridge\.detectImporter\(\{\s*requestId,/u, - ); -}); - -test('plugin importer bridge lifecycle is owned by application state, not the dialog component', () => { - assert.match(hookSource, /pluginExtensionBridge\.selectImporterFile/u); - assert.match(hookSource, /pluginExtensionBridge\.parseImporterFile/u); - assert.doesNotMatch(dialogSource, /pluginExtensionBridge/u); -}); diff --git a/components/vault/useVaultHostCollections.tsx b/components/vault/useVaultHostCollections.tsx index f057a5a02..8f2d0b5a6 100644 --- a/components/vault/useVaultHostCollections.tsx +++ b/components/vault/useVaultHostCollections.tsx @@ -3,7 +3,7 @@ import React, { useCallback, useMemo } from "react"; import { compareHostAddresses } from "../../domain/hostAddressSort"; import { upsertKnownHost } from "../../domain/knownHosts"; import { sortByVaultOrder, sortVaultStringsByOrder } from "../../domain/vaultOrder"; -import { matchesHostSearchQuery, matchesSearchQuery } from "../../lib/searchMatcher"; +import { matchesHostSearchQuery, matchesSearchQuery } from "../../domain/searchMatcher"; import type { GroupConfig, GroupNode, Host, KnownHost } from "../../types"; import KnownHostsManager from "../KnownHostsManager"; import type { SortMode } from "../ui/sort-dropdown"; diff --git a/components/vault/useVaultImportHandlers.ts b/components/vault/useVaultImportHandlers.ts deleted file mode 100644 index 5dbc97c3e..000000000 --- a/components/vault/useVaultImportHandlers.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** @deprecated Import from `@/application/state/useVaultImportHandlers` instead. */ -export { useVaultImportHandlers } from "../../application/state/useVaultImportHandlers"; diff --git a/components/workspace/AddToWorkspaceDialog.tsx b/components/workspace/AddToWorkspaceDialog.tsx index 802de9773..ed3ee5026 100644 --- a/components/workspace/AddToWorkspaceDialog.tsx +++ b/components/workspace/AddToWorkspaceDialog.tsx @@ -6,7 +6,7 @@ */ import { Check, Search, Terminal } from 'lucide-react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { matchesWorkspaceHostPickerQuery } from '../../lib/searchMatcher'; +import { matchesWorkspaceHostPickerQuery } from '../../domain/searchMatcher'; import { Host } from '../../types'; import { DistroAvatar } from '../DistroAvatar'; import { Button } from '../ui/button'; diff --git a/domain/globalHistory.test.ts b/domain/globalHistory.test.ts index e5cca67fc..0d906615e 100644 --- a/domain/globalHistory.test.ts +++ b/domain/globalHistory.test.ts @@ -10,7 +10,7 @@ import { toGlobalHistoryDisplayEntries, } from './globalHistory.ts'; import { NETCATTY_AI_HISTORY_MARKER } from './remoteHistory.ts'; -import { buildDockerExecShellCommand, buildDockerLogsCommand } from './systemManager/dockerShell.ts'; +import { buildContainerExecShellCommand, buildContainerLogsCommand } from './systemManager/containerRuntime.ts'; import { buildTmuxAttachCommand } from './systemManager/tmuxShell.ts'; import type { ShellHistoryEntry } from './models'; @@ -36,8 +36,8 @@ test('shouldRecordGlobalHistoryCommand: rejects empty and AI marker commands', ( }); test('shouldRecordGlobalHistoryCommand: rejects Netcatty managed Docker and tmux startup commands', () => { - assert.equal(shouldRecordGlobalHistoryCommand(buildDockerExecShellCommand('587abcdef123')), false); - assert.equal(shouldRecordGlobalHistoryCommand(buildDockerLogsCommand('587abcdef123')), false); + assert.equal(shouldRecordGlobalHistoryCommand(buildContainerExecShellCommand('docker', '587abcdef123')), false); + assert.equal(shouldRecordGlobalHistoryCommand(buildContainerLogsCommand('docker', '587abcdef123')), false); assert.equal(shouldRecordGlobalHistoryCommand(buildTmuxAttachCommand('my-session')), false); assert.equal(shouldRecordGlobalHistoryCommand(buildTmuxAttachCommand('my-session', 2)), false); assert.equal(shouldRecordGlobalHistoryCommand('docker ps -a'), true); @@ -59,7 +59,7 @@ test('mergeGlobalHistoryOnAppend: trims and prepends a new command', () => { test('sanitizeGlobalHistoryEntries: removes persisted Netcatty managed startup commands', () => { const entries = [ - baseEntry({ id: 'a', command: buildDockerLogsCommand('587abcdef123') }), + baseEntry({ id: 'a', command: buildContainerLogsCommand('docker', '587abcdef123') }), baseEntry({ id: 'b', command: 'docker ps -a' }), baseEntry({ id: 'c', command: buildTmuxAttachCommand('my-session') }), ]; diff --git a/domain/host.ts b/domain/host.ts index dfbb2fe7e..0601e006e 100644 --- a/domain/host.ts +++ b/domain/host.ts @@ -1,6 +1,6 @@ import { detectVendorFromSshVersion } from './sshServerVendor.mjs'; export { detectVendorFromSshVersion } from './sshServerVendor.mjs'; -import { remoteSoftwareRequiresSingleChannel } from './singleChannelSshBanner.shared.mjs'; +import { remoteSoftwareRequiresSingleChannel } from './singleChannelSshBanner.shared.cjs'; import { Host, Snippet, TerminalSettings } from './models'; import type { HostOperatingSystem, HostOsSelection } from './models/connection'; import { sanitizeHostIconFields } from './hostIcon'; diff --git a/domain/remoteHistory.test.ts b/domain/remoteHistory.test.ts index 3a343d244..daef4c590 100644 --- a/domain/remoteHistory.test.ts +++ b/domain/remoteHistory.test.ts @@ -10,7 +10,6 @@ import { isNetcattyAiHistoryCommand, isNetcattyManagedStartupHistoryCommand, } from './remoteHistory.ts'; -import { buildDockerExecShellCommand, buildDockerLogsCommand } from './systemManager/dockerShell.ts'; import { buildContainerExecShellCommand, buildContainerLogsCommand, @@ -204,8 +203,8 @@ test('isNetcattyAiHistoryCommand: detects AI PTY marker lines', () => { }); test('isNetcattyManagedStartupHistoryCommand: detects Docker and tmux terminal launch commands', () => { - assert.equal(isNetcattyManagedStartupHistoryCommand(buildDockerExecShellCommand('587abcdef123')), true); - assert.equal(isNetcattyManagedStartupHistoryCommand(buildDockerLogsCommand('587abcdef123')), true); + assert.equal(isNetcattyManagedStartupHistoryCommand(buildContainerExecShellCommand('docker', '587abcdef123')), true); + assert.equal(isNetcattyManagedStartupHistoryCommand(buildContainerLogsCommand('docker', '587abcdef123')), true); assert.equal(isNetcattyManagedStartupHistoryCommand(buildContainerLogsCommand('podman', '587abcdef123')), true); assert.equal( isNetcattyManagedStartupHistoryCommand(buildKubectlLogsCommand('kind-dev', 'default', 'api-0')), @@ -268,7 +267,7 @@ test('mergeRemoteHistory: drops Netcatty managed Docker and tmux startup lines', parseBashHistory( [ 'docker ps -a', - buildDockerLogsCommand('587abcdef123'), + buildContainerLogsCommand('docker', '587abcdef123'), buildTmuxAttachCommand('my-session'), 'history', ].join('\n'), @@ -285,7 +284,7 @@ test('mergeRemoteHistory: drops Netcatty managed startup lines from zsh and fish const zsh = parseZshHistory( [ ': 1700000000:0;git status', - `: 1700000100:0;${buildDockerExecShellCommand('587abcdef123')}`, + `: 1700000100:0;${buildContainerExecShellCommand('docker', '587abcdef123')}`, ].join('\n'), ); const fish = parseFishHistory( diff --git a/domain/searchMatcher.test.ts b/domain/searchMatcher.test.ts index 1d1a0580b..ac6264439 100644 --- a/domain/searchMatcher.test.ts +++ b/domain/searchMatcher.test.ts @@ -11,7 +11,7 @@ import { matchesWordPrefixQuery, matchesWorkspaceHostPickerQuery, resetPinyinCacheForTests, -} from "../lib/searchMatcher.ts"; +} from "./searchMatcher.ts"; test("shared pinyin search reaches later fields after a long first field", () => { const prefix = "a".repeat(256); diff --git a/lib/searchMatcher.ts b/domain/searchMatcher.ts similarity index 100% rename from lib/searchMatcher.ts rename to domain/searchMatcher.ts diff --git a/domain/sessionHistorySearch.ts b/domain/sessionHistorySearch.ts index b9abe2578..ccb6f66a1 100644 --- a/domain/sessionHistorySearch.ts +++ b/domain/sessionHistorySearch.ts @@ -4,7 +4,7 @@ import { prepareSearchFields, type PreparedSearchFields, type PreparedSearchQuery, -} from '../lib/searchMatcher'; +} from './searchMatcher'; /** * Minimal structural shapes for session history search. Declared here (not diff --git a/domain/settingsSearch.ts b/domain/settingsSearch.ts index 9db8c91fb..3b6a476f9 100644 --- a/domain/settingsSearch.ts +++ b/domain/settingsSearch.ts @@ -1,4 +1,4 @@ -import { matchesSearchQuery } from "../lib/searchMatcher"; +import { matchesSearchQuery } from "./searchMatcher"; import { SETTINGS_SEARCH_CATALOG, isSettingsEntryAvailableOn, diff --git a/domain/sftpDedicatedLogin.test.ts b/domain/sftpDedicatedLogin.test.ts index 1dc9f0bcf..2fe010cd8 100644 --- a/domain/sftpDedicatedLogin.test.ts +++ b/domain/sftpDedicatedLogin.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { remoteSoftwareRequiresSingleChannel } from "./singleChannelSshBanner.shared.mjs"; +import { remoteSoftwareRequiresSingleChannel } from "./singleChannelSshBanner.shared.cjs"; import { sftpRequiresDedicatedLogin } from "./sftpDedicatedLogin"; test("network-device mode forces a dedicated SFTP login before any banner", () => { diff --git a/domain/sftpDedicatedLogin.ts b/domain/sftpDedicatedLogin.ts index abc3bf24f..aa5e4b2d7 100644 --- a/domain/sftpDedicatedLogin.ts +++ b/domain/sftpDedicatedLogin.ts @@ -1,6 +1,6 @@ import { detectVendorFromSshVersion, hostRestrictsExtraSshChannels } from "./host"; import type { Host } from "./models"; -import { remoteSoftwareRequiresSingleChannel } from "./singleChannelSshBanner.shared.mjs"; +import { remoteSoftwareRequiresSingleChannel } from "./singleChannelSshBanner.shared.cjs"; export type SftpDedicatedLoginInput = { host?: Pick | null; diff --git a/domain/singleChannelSshBanner.shared.d.mts b/domain/singleChannelSshBanner.shared.d.mts deleted file mode 100644 index ed6722f59..000000000 --- a/domain/singleChannelSshBanner.shared.d.mts +++ /dev/null @@ -1,7 +0,0 @@ -export const SINGLE_CHANNEL_SOFTWARE_TOKENS: readonly string[]; -export function remoteSoftwareRequiresSingleChannel(remoteSshVersion?: string): boolean; -export function remoteDisallowsChunkedChannelWrite(remoteSshVersion?: string): boolean; -export function optionsForPeerSingleChannel( - options: T, - conn?: { _remoteVer?: string } | null, -): T; diff --git a/domain/singleChannelSshBanner.shared.mjs b/domain/singleChannelSshBanner.shared.mjs deleted file mode 100644 index 5a52adb32..000000000 --- a/domain/singleChannelSshBanner.shared.mjs +++ /dev/null @@ -1,78 +0,0 @@ -"use strict"; - -// SSH software tokens that allow one session channel per TCP connection. -// Match the identification software token only. Do not match product names, -// OpenSSH, JumpServer/KoKo, or a "term-sshd" substring inside another token. -// -// BHostSSH_7.0 — issue #3146 log field remoteSshVersion. PR #3313: a second -// exec channel tears down the first interactive session. Multi-character -// channel writes are also dropped on this banner. -// TERM-SSHD — issue #2923 comment 5314292157 logs remoteSshVersion -// "TERM-SSHD". PR #3030: a later session channel on that TCP is accepted -// and the shell exits 0. -// CLOUDBILITY-4.14 — PR #3458 reproduction note: SSH-2.0-CLOUDBILITY-4.14 -// drops the interactive shell when another session channel opens. No other -// public packet was found; do not add aliases. -// CloudLinker — issue #3592: the vendor identifies a single-channel gateway -// and proposes this distinctive banner. Older "Go" banners cannot identify it -// safely; this compatibility entry requires the vendor banner change. -// russh — issue #3973: russh returns CHANNEL_FAILURE for wantReply=false env -// requests, desynchronizing ssh2's callback FIFO so pty-req/shell appear to -// fail. Skip env via the single-channel path. No chunked-write evidence. -// JumpServer KoKo advertises Version "JumpServer" and multiplexes. Omit it. - -const SINGLE_CHANNEL_SOFTWARE_TOKENS = Object.freeze([ - "BHostSSH", - "TERM-SSHD", - "CLOUDBILITY", - "CLOUDLINKER", - "russh", -]); - -// #3146 also drops multi-character writes. That evidence is only for these -// two tokens, not for CLOUDBILITY or CLOUDLINKER. -const CHUNKED_WRITE_SOFTWARE_TOKENS = Object.freeze([ - "BHostSSH", - "TERM-SSHD", -]); - -function escapeRegExp(value) { - return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - -function softwareTokenMatches(remoteSshVersion, token) { - const software = String(remoteSshVersion || "").trim(); - if (!software) return false; - const pattern = new RegExp( - `(?:^|[^A-Za-z0-9])${escapeRegExp(token)}(?:[^A-Za-z0-9]|$)`, - "i", - ); - return pattern.test(software); -} - -function remoteSoftwareMatchesAny(remoteSshVersion, tokens) { - return tokens.some((token) => softwareTokenMatches(remoteSshVersion, token)); -} - -function remoteSoftwareRequiresSingleChannel(remoteSshVersion) { - return remoteSoftwareMatchesAny(remoteSshVersion, SINGLE_CHANNEL_SOFTWARE_TOKENS); -} - -function remoteDisallowsChunkedChannelWrite(remoteSshVersion) { - return remoteSoftwareMatchesAny(remoteSshVersion, CHUNKED_WRITE_SOFTWARE_TOKENS); -} - -function optionsForPeerSingleChannel(options, conn) { - const remoteSshVersion = conn && typeof conn._remoteVer === "string" ? conn._remoteVer : ""; - if (!options || options.singleChannelSsh === true || !remoteSoftwareRequiresSingleChannel(remoteSshVersion)) { - return options; - } - return { ...options, singleChannelSsh: true }; -} - -export { - SINGLE_CHANNEL_SOFTWARE_TOKENS, - remoteSoftwareRequiresSingleChannel, - remoteDisallowsChunkedChannelWrite, - optionsForPeerSingleChannel, -}; diff --git a/domain/singleChannelSshBanner.shared.test.cjs b/domain/singleChannelSshBanner.shared.test.cjs index ca6e64f69..c532c9473 100644 --- a/domain/singleChannelSshBanner.shared.test.cjs +++ b/domain/singleChannelSshBanner.shared.test.cjs @@ -89,18 +89,3 @@ test("optionsForPeerSingleChannel stamps the runtime flag from the peer banner", true, ); }); - -test("CommonJS and renderer modules agree on SSH banner behavior", async () => { - const browserModule = await import("./singleChannelSshBanner.shared.mjs"); - const nodeModule = require("./singleChannelSshBanner.shared.cjs"); - for (const version of [ - "BHostSSH_7.0", "TERM-SSHD", "CLOUDBILITY-4.14", "CloudLinker", "SSH-2.0-russh_0.45.0", "SSH-2.0-Go", "OpenSSH_9.6", "JumpServer", "", - ]) { - assert.equal(browserModule.remoteSoftwareRequiresSingleChannel(version), nodeModule.remoteSoftwareRequiresSingleChannel(version)); - assert.equal(browserModule.remoteDisallowsChunkedChannelWrite(version), nodeModule.remoteDisallowsChunkedChannelWrite(version)); - assert.deepEqual( - browserModule.optionsForPeerSingleChannel({ singleChannelSsh: false }, { _remoteVer: version }), - nodeModule.optionsForPeerSingleChannel({ singleChannelSsh: false }, { _remoteVer: version }), - ); - } -}); diff --git a/domain/snippetScript.ts b/domain/snippetScript.ts index 205e52b45..f452b893b 100644 --- a/domain/snippetScript.ts +++ b/domain/snippetScript.ts @@ -17,141 +17,6 @@ export const DEFAULT_RECORDING_PROMPT_TIMEOUT_MS = 30000; /** Regex matching a shell prompt on the last line (~# / ~$ / user@host:path#). */ export const SHELL_PROMPT_END_REGEX = /(?:~[#$]\s*|[@][^\n]{0,120}[:][^\n]{0,120}[#$%]\s*)$/m; -/** Minimal smoke script for verifying manual run and onOutput triggers. */ -export const SCRIPT_SMOKE_TEST = `// === Smoke test === -// Manual: trigger=manual, pick a target host, click "Run now" -// onOutput: trigger=onOutput, pattern=NETCATTY_SMOKE, save, connect to target host, then run: echo NETCATTY_SMOKE -// -await nct.screen.waitForPrompt(30000); -await nct.screen.sendLine('echo netcatty-smoke-ok'); -nct.log('Smoke test passed'); -await nct.dialog.alert('Netcatty script smoke test OK'); -`; - -/** Full integration test for onConnect / manual run; dialog API enabled by default. */ -export const SCRIPT_INTEGRATION_TEST = `// Netcatty Integration Test — onConnect / manual full API exercise -// Trigger: onConnect or Run now - -const CONFIG = { - SAMPLE_COUNT: 8, - SAMPLE_INTERVAL_MS: 2000, - PROMPT_TIMEOUT_MS: 60000, - STEP_TIMEOUT_MS: 20000, - RUN_DIALOGS: true, - RUN_SESSION_LOG: false, - RUN_SCREEN_CLEAR: false, -}; - -async function main() { - const tag = \`nc-it-\${Date.now().toString(36)}\`; - nct.log('=== Netcatty Integration Test START ==='); - nct.log(\`tag=\${tag} nct.version=\${nct.version}\`); - nct.log(\`session: name=\${nct.session.name} host=\${nct.session.hostname} user=\${nct.session.username} connected=\${nct.session.connected}\`); - - if (!nct.session.connected) { - throw new Error('Session not connected'); - } - - nct.log('[1/12] waitForPrompt'); - await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); - - nct.log('[2/12] sendLine + waitForText'); - await nct.screen.sendLine(\`echo "\${tag}_BOOTSTRAP_OK"\`); - await nct.screen.waitForText(\`\${tag}_BOOTSTRAP_OK\`, CONFIG.STEP_TIMEOUT_MS); - - nct.log('[3/12] waitForAny'); - await nct.screen.sendLine('echo ANY_CHECK && uname -s'); - await nct.screen.waitForAny(['ANY_CHECK', /Linux/], CONFIG.STEP_TIMEOUT_MS); - - nct.log('[4/12] getText / rows / cols / currentRow'); - const text = await nct.screen.getText(); - const lineCount = text.split('\\n').filter(Boolean).length; - nct.log(\`captured \${lineCount} lines, rows=\${nct.screen.rows} cols=\${nct.screen.cols} cursorRow=\${nct.screen.currentRow}\`); - - nct.log('[5/12] send raw + Enter'); - await nct.screen.send(\`echo -n "\${tag}_RAW"\`); - await nct.screen.sendLine(''); - await nct.screen.waitForText(\`\${tag}_RAW\`, CONFIG.STEP_TIMEOUT_MS); - - nct.log('[6/12] waitForRegex'); - await nct.screen.sendLine(\`echo BUILD_ID=\${tag}\`); - await nct.screen.waitForRegex(new RegExp(\`BUILD_ID=\${tag}\`), CONFIG.STEP_TIMEOUT_MS); - - nct.log('[7/12] session.sleep / nct.sleep'); - await nct.session.sleep(800); - await nct.sleep(800); - - nct.log('[8/12] progress loop health sampling'); - nct.progress.start('Health sampling', CONFIG.SAMPLE_COUNT); - for (let i = 1; i <= CONFIG.SAMPLE_COUNT; i += 1) { - const cmd = [ - \`echo "== Sample \${i}/\${CONFIG.SAMPLE_COUNT} =="\`, - 'date', - 'uptime', - "free -h | awk 'NR==2{print $1,$2,$3,$4,$7}'", - "df -h / | awk 'NR==2{print $1,$2,$3,$5,$6}'", - \`echo "\${tag}_SAMPLE_\${i}_DONE"\`, - ].join(' && '); - await nct.screen.sendLine(cmd); - await nct.screen.waitForRegex(new RegExp(\`\${tag}_SAMPLE_\${i}_DONE\`), CONFIG.STEP_TIMEOUT_MS); - await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); - nct.progress.step(\`sample \${i}/\${CONFIG.SAMPLE_COUNT}\`); - nct.log(\`sample \${i}/\${CONFIG.SAMPLE_COUNT} ok\`); - if (i < CONFIG.SAMPLE_COUNT) { - await nct.session.sleep(CONFIG.SAMPLE_INTERVAL_MS); - } - } - nct.progress.done(); - - nct.log('[9/12] nested loop activity mode'); - const checks = ['whoami', 'id -u', 'pwd', 'echo $SHELL']; - for (const check of checks) { - await nct.screen.sendLine(check); - await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); - } - - if (CONFIG.RUN_SESSION_LOG) { - nct.log('[10/12] startLog / stopLog'); - await nct.session.startLog(\`./netcatty-it-\${tag}.log\`); - await nct.screen.sendLine(\`echo "\${tag}_LOGGED"\`); - await nct.screen.waitForText(\`\${tag}_LOGGED\`, CONFIG.STEP_TIMEOUT_MS); - await nct.session.stopLog(); - } else { - nct.log('[10/12] startLog/stopLog skipped'); - } - - if (CONFIG.RUN_SCREEN_CLEAR) { - nct.log('[11/12] screen.clear'); - await nct.screen.clear(); - await nct.session.sleep(500); - await nct.screen.waitForPrompt(CONFIG.PROMPT_TIMEOUT_MS); - } else { - nct.log('[11/12] screen.clear skipped'); - } - - if (CONFIG.RUN_DIALOGS) { - nct.log('[12/12] dialog confirm / prompt / alert'); - const go = await nct.dialog.confirm(\`Integration test \${tag} finished OK. Continue to prompt/alert?\`); - nct.log(\`confirm => \${go}\`); - if (go) { - const note = await nct.dialog.prompt('Optional note:', 'all-good'); - nct.log(\`prompt => \${note}\`); - await nct.dialog.alert(\`Done. note=\${note}\`); - } else { - nct.log('confirm declined — skipping prompt/alert'); - } - } else { - nct.log('[12/12] dialog skipped'); - } - - await nct.screen.sendLine(\`echo "=== \${tag} ALL_PASSED ==="\`); - await nct.screen.waitForText(\`\${tag} ALL_PASSED\`, CONFIG.STEP_TIMEOUT_MS); - nct.log('=== Netcatty Integration Test PASSED ==='); -} - -await main(); -`; - export const DEFAULT_SCRIPT_TEMPLATE = `// Netcatty automation script - async JS in the active terminal session // // nct.screen.waitForPrompt(ms?) wait for shell prompt (# root / $ user) diff --git a/domain/systemManager/dockerShell.test.ts b/domain/systemManager/dockerShell.test.ts deleted file mode 100644 index 7ea1c39cc..000000000 --- a/domain/systemManager/dockerShell.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; - -import { buildDockerExecShellCommand, buildDockerLogsCommand } from './dockerShell.ts'; - -test('buildDockerExecShellCommand probes plain Docker before sudo fallback', () => { - const command = buildDockerExecShellCommand('587abcdef123'); - - assert.match(command, /^sh -c /); - assert.match(command, /printf .*\\033\[H\\033\[2J\\033\[3J/); - assert.match(command, /docker inspect 587abcdef123/); - assert.match(command, /exec docker exec -it 587abcdef123/); - assert.match(command, /exec sudo docker exec -it 587abcdef123/); - assert.match(command, /permission\\ denied.*docker.sock.*docker.sock.*permission\\ denied/); - assert.doesNotMatch(command, /sudo -S/); - assert.equal(command.includes('\n'), false); -}); - -test('buildDockerLogsCommand probes plain Docker before sudo fallback', () => { - const command = buildDockerLogsCommand('587abcdef123'); - - assert.match(command, /^sh -c /); - assert.match(command, /printf .*\\033\[H\\033\[2J\\033\[3J/); - assert.match(command, /docker inspect 587abcdef123/); - assert.match(command, /exec docker logs -f --tail 200 587abcdef123/); - assert.match(command, /exec sudo docker logs -f --tail 200 587abcdef123/); - assert.match(command, /permission\\ denied.*docker.sock.*docker.sock.*permission\\ denied/); - assert.doesNotMatch(command, /sudo -S/); - assert.equal(command.includes('\n'), false); -}); diff --git a/domain/systemManager/dockerShell.ts b/domain/systemManager/dockerShell.ts deleted file mode 100644 index f7cc01eab..000000000 --- a/domain/systemManager/dockerShell.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { - buildContainerExecShellCommand, - buildContainerLogsCommand, -} from "./containerRuntime.ts"; - -/** Sanitize Docker container/image IDs — must match electron/bridges/systemManager/dockerOps.cjs */ -export function sanitizeDockerContainerId(id: string): string { - return String(id || "").replace(/[^a-zA-Z0-9]/g, "").slice(0, 64); -} - -/** Interactive shell into a container — prefer bash, fall back to sh. */ -export function buildDockerExecShellCommand(containerId: string): string { - return buildContainerExecShellCommand("docker", containerId); -} - -export function buildDockerLogsCommand(containerId: string): string { - return buildContainerLogsCommand("docker", containerId); -} diff --git a/domain/terminalPromptSecurity.shared.cjs b/domain/terminalPromptSecurity.shared.cjs index be1bbf57b..d144a4c1b 100644 --- a/domain/terminalPromptSecurity.shared.cjs +++ b/domain/terminalPromptSecurity.shared.cjs @@ -170,4 +170,12 @@ function isUntrustedTerminalInputPrompt(value, options = {}) { return !isConfirmedTerminalShellPrompt(value, options); } -module.exports = { isUntrustedTerminalInputPrompt }; +module.exports = { + MAX_PROMPT_SECURITY_TAIL_CHARS, + stripTerminalControlSequences, + isSensitiveTerminalChallenge, + isConfirmedTerminalShellPrompt, + splitTerminalLogicalLines, + isBashPs2ContinuationLine, + isUntrustedTerminalInputPrompt, +}; diff --git a/domain/terminalPromptSecurity.shared.d.cts b/domain/terminalPromptSecurity.shared.d.cts new file mode 100644 index 000000000..aa506cf90 --- /dev/null +++ b/domain/terminalPromptSecurity.shared.d.cts @@ -0,0 +1,23 @@ +export interface ConfirmedPromptOptions { + /** Network-device shells commonly use a bare host name followed by `>`. */ + allowHostStyleGreaterThan?: boolean; + /** + * True when the terminal is on the alternate screen (DEC 1049). Used to + * tell vim's command-line `:` from a custom `sudo -p ':'` prompt. + */ + alternateScreen?: boolean; +} + +export const MAX_PROMPT_SECURITY_TAIL_CHARS: number; +export function stripTerminalControlSequences(value: string): string; +export function isSensitiveTerminalChallenge(value: string): boolean; +export function isConfirmedTerminalShellPrompt( + promptText: string, + options?: ConfirmedPromptOptions, +): boolean; +export function splitTerminalLogicalLines(value: string): string[]; +export function isBashPs2ContinuationLine(line: string): boolean; +export function isUntrustedTerminalInputPrompt( + value: string, + options?: ConfirmedPromptOptions, +): boolean; diff --git a/domain/terminalPromptSecurity.ts b/domain/terminalPromptSecurity.ts index d3bb9f0a4..c0b9a19cf 100644 --- a/domain/terminalPromptSecurity.ts +++ b/domain/terminalPromptSecurity.ts @@ -1,67 +1,16 @@ +import { + MAX_PROMPT_SECURITY_TAIL_CHARS, + isBashPs2ContinuationLine, + isConfirmedTerminalShellPrompt, + isSensitiveTerminalChallenge, + isUntrustedTerminalInputPrompt, + splitTerminalLogicalLines, + stripTerminalControlSequences, + type ConfirmedPromptOptions, +} from './terminalPromptSecurity.shared.cjs'; + const ESCAPE_SEQUENCE = "\\x" + "1b"; -const BELL_SEQUENCE = "\\x" + "07"; -const ANSI_CONTROL_PATTERN = new RegExp(`${ESCAPE_SEQUENCE}\\[[0-?]*[ -/]*[@-~]`, 'gu'); const CURSOR_POSITION_PATTERN = new RegExp(`${ESCAPE_SEQUENCE}\\[\\d*(?:;(\\d*))?[Hf]`, 'gu'); -const OSC_CONTROL_PATTERN = new RegExp( - `${ESCAPE_SEQUENCE}\\][^${BELL_SEQUENCE}]*(?:${BELL_SEQUENCE}|${ESCAPE_SEQUENCE}\\\\)`, - 'gu', -); -const MAX_PROMPT_SECURITY_TAIL_CHARS = 2_048; - -const SENSITIVE_ENGLISH_LABEL = [ - String.raw`pass(?:word|phrase|code)`, - String.raw`one[\s-]?time(?:\s+(?:password|passcode|code|token))?`, - String.raw`\botp\b`, - String.raw`verification(?:\s+(?:code|token|passcode))?`, - String.raw`authentication\s+(?:code|token|passcode)`, - String.raw`security\s+(?:code|token|passcode|pin)`, - String.raw`\bpin\b`, - String.raw`\btoken\b`, - String.raw`2fa`, - String.raw`two[\s-]?factor`, - String.raw`multi[\s-]?factor`, - String.raw`\bmfa\b`, - String.raw`second\s+factor`, - String.raw`secondary(?:\s+\w+){0,3}\s+passw(?:ord)?`, - String.raw`second(?:\s+\w+){0,3}\s+passw(?:ord)?`, - String.raw`additional(?:\s+\w+){0,3}\s+passw(?:ord)?`, - String.raw`re[-\s]?enter\s+passw(?:ord)?`, - String.raw`confirm\s+passw(?:ord)?`, - String.raw`\bedr\b`, - String.raw`\bduo\b`, -].join('|'); - -const SENSITIVE_CJK_LABEL = [ - '\u5bc6\u7801', - '\u53e3\u4ee4', - '\u52a8\u6001', - '\u4e00\u6b21\u6027', - '\u9a8c\u8bc1\u7801', - '\u9a8c\u8bc1\u4fe1\u606f', - '\u4ee4\u724c', - '\u53cc\u56e0\u7d20', - '\u591a\u56e0\u7d20', - '\u77ed\u4fe1\u9a8c\u8bc1', - '\u624b\u673a\u9a8c\u8bc1', - '\u4e8c\u6b21', - '\u5b89\u5168\u5bc6\u7801', - '\u6311\u6218\u7801', -].join('|'); - -const SENSITIVE_LABEL_PATTERN = new RegExp( - `(?:${SENSITIVE_ENGLISH_LABEL}|${SENSITIVE_CJK_LABEL})`, - 'iu', -); - -function stripTerminalControlSequences(value: string): string { - return value.replace(OSC_CONTROL_PATTERN, '').replace(ANSI_CONTROL_PATTERN, ''); -} - -function lastLogicalLine(value: string): string { - const plain = stripTerminalControlSequences(value); - const boundary = Math.max(plain.lastIndexOf('\n'), plain.lastIndexOf('\r')); - return plain.slice(boundary + 1).slice(-MAX_PROMPT_SECURITY_TAIL_CHARS); -} /** * Keep enough raw output to recognize authentication prompts split across @@ -84,26 +33,17 @@ function nextHeredocPromptOrigin(origin: string, completedLine: string): string * Current logical line with controls stripped for classification, plus the * heredoc opener when the line is a bare ">". `current` stays raw so partial * control sequences can be completed by the next transport chunk. - * `appendTerminalPromptSecurityTail` keeps only the current line, which is all - * `observeTerminalInputPrompt` used to pass in. The opener is the last - * completed non-PS2 line, so a long heredoc body does not have to be retained. */ export function foldTerminalPromptSecurityOutput( state: { origin: string; current: string; pendingCr?: boolean }, chunk: string, ): { origin: string; current: string; promptText: string; pendingCr: boolean } { - // A PTY can split CRLF across chunks. The LF is the rest of that break, - // not a second empty line that would drop the heredoc opener. let pendingCr = state.pendingCr === true; let input = chunk; if (pendingCr && input.startsWith('\n')) { input = input.slice(1); pendingCr = false; } - // Vim redraws lines with CUP/HVP + EL instead of CR/LF (#4107). A move - // to column one (also the default for an omitted/zero column) starts a - // new security line, so editor chrome cannot become part of its ":" prompt. - // Match after joining the raw tail to handle CSI split across PTY chunks. const combined = `${state.current}${input}`.replace( CURSOR_POSITION_PATTERN, (sequence, column: string | undefined) => Number(column || 1) <= 1 ? '\r' : sequence, @@ -113,8 +53,6 @@ export function foldTerminalPromptSecurityOutput( origin = nextHeredocPromptOrigin(origin, line); } const current = appendTerminalPromptSecurityTail('', combined); - // EL and cursor-visibility controls can precede/follow a colon in separate - // chunks. They must not hide vim ex from the observer's stale-latch reset. const plain = stripTerminalControlSequences(current); const promptText = plain.trim() === '>' && origin ? `${origin}\n${plain}` @@ -124,63 +62,6 @@ export function foldTerminalPromptSecurityOutput( return { origin, current, promptText, pendingCr }; } -/** - * Detect a prompt-shaped authentication challenge. Vocabulary intentionally - * matches the SSH keyboard-interactive boundary and also covers PIN/auth-code - * variants used by local, Mosh, bastion, and device sessions. - */ -export function isSensitiveTerminalChallenge(value: string): boolean { - const line = lastLogicalLine(value).trim(); - if (!line) return false; - const label = SENSITIVE_LABEL_PATTERN.exec(line); - if (!label) return false; - const prefix = line.slice(0, label.index ?? 0).trim(); - const suffix = line.slice((label.index ?? 0) + label[0].length); - if (suffix.trim().length === 0) { - return prefix.length === 0 - || /(?:^|\s)(?:enter|input|provide|type|scan|please|your|current|new|old)\s*$/iu.test(prefix) - || /(?:\u8f93\u5165|\u8bf7\u8f93\u5165|\u8bf7)\s*$/u.test(prefix); - } - if (/^\s+(?:for|of)\s+[^\r\n]{1,96}$/iu.test(suffix)) return true; - return /^[^\r\n::>›»]{0,96}[::>›»]\s*[^\r\n]{0,1024}$/u.test(suffix); -} - -type ConfirmedPromptOptions = { - /** Network-device shells commonly use a bare host name followed by `>`. */ - allowHostStyleGreaterThan?: boolean; - /** - * True when the terminal is on the alternate screen (DEC 1049). Used to - * tell vim's command-line `:` from a custom `sudo -p ':'` prompt. - */ - alternateScreen?: boolean; -}; - -/** - * Positive policy for data that may cross the ordinary completion Provider - * boundary. Generic prompt parsing remains permissive for host UX/history, - * while third-party Providers require a recognizable shell/device prompt. - */ -export function isConfirmedTerminalShellPrompt( - promptText: string, - options: ConfirmedPromptOptions = {}, -): boolean { - const prompt = lastLogicalLine(promptText).trim(); - if (!prompt || isSensitiveTerminalChallenge(prompt)) return false; - if (/[❯❮→➜➤⟩»›]/u.test(prompt)) return true; - for (const character of prompt) { - const code = character.charCodeAt(0); - if (code >= 0xE000 && code <= 0xF8FF) return true; - } - if (/[$#%]$/u.test(prompt)) return true; - // POSIX sh/bash/ksh default PS2. Trusted only with heredoc context (#3796). - if (prompt === '>') return isHeredocPs2Continuation(promptText, options); - if (!prompt.endsWith('>')) return false; - if (/^(?:PS\s+)?[A-Za-z]:[\\/].*>$/u.test(prompt)) return true; - if (/[@\\/~:]\S*>$/u.test(prompt)) return true; - return options.allowHostStyleGreaterThan === true - && /^[A-Za-z0-9_.-]+(?:\([^)]{1,128}\))?>$/u.test(prompt); -} - export function shouldUsePluginTerminalCompletionProvider(input: { sensitiveInputActive: boolean; promptText: string; @@ -193,131 +74,10 @@ export function shouldUsePluginTerminalCompletionProvider(input: { }); } -function splitTerminalLogicalLines(value: string): string[] { - const lines: string[] = []; - let start = 0; - for (let i = 0; i < value.length; i += 1) { - const ch = value[i]; - if (ch !== '\n' && ch !== '\r') continue; - lines.push(value.slice(start, i)); - if (ch === '\r' && value[i + 1] === '\n') i += 1; - start = i + 1; - } - lines.push(value.slice(start)); - return lines; -} - -/** Bash default PS2 echo: ">" or "> ...". Not "heredoc>" / "Custom>". */ -function isBashPs2ContinuationLine(line: string): boolean { - const trimmed = line.trim(); - return trimmed === '>' || trimmed.startsWith('> '); -} - -/** - * Command text after the first confirmed shell prompt on this line. - * Returns null when the line is not a confirmed prompt plus typed input. - */ -function commandAfterConfirmedShellPrompt( - line: string, - options: ConfirmedPromptOptions, -): string | null { - const text = line.trim(); - for (let i = 0; i < text.length - 1; i += 1) { - const ch = text[i]; - if (ch !== '$' && ch !== '#' && ch !== '%' && ch !== '>') continue; - const rest = text.slice(i + 1); - if (!/^\s+\S/u.test(rest)) continue; - const candidate = text.slice(0, i + 1); - if (!isConfirmedTerminalShellPrompt(candidate, options)) continue; - if ((ch === '$' || ch === '#' || ch === '%') && !isPlausibleShellPromptBody(candidate.slice(0, -1))) { - continue; - } - return rest; - } - return null; -} - -/** - * Bare ">" is bash PS2 only while output is still inside a heredoc opened by - * a confirmed shell command (#3796). Any other origin, including - * `read -s -p '> '`, stays fail-closed. - */ -function isHeredocPs2Continuation(value: string, options: ConfirmedPromptOptions): boolean { - const lines = splitTerminalLogicalLines(stripTerminalControlSequences(value)); - let index = lines.length - 2; - while (index >= 0 && isBashPs2ContinuationLine(lines[index])) index -= 1; - if (index < 0) return false; - const command = commandAfterConfirmedShellPrompt(lines[index], options); - return command != null && command.includes('<<'); -} - -/** - * Body text before a `$` / `#` / `%` terminator that is plausible as a shell - * PS1 (bare marker, user@host, path, shell-version, or lowercase identity). - * Rejects English challenge labels that only happen to end with those markers - * (`Challenge #`, `Account $`). - */ -function isPlausibleShellPromptBody(body: string): boolean { - const trimmed = body.trim(); - if (!trimmed) return true; - if (/@|[/\\~:]/u.test(trimmed)) return true; - if (/^(?:bash|zsh|sh|fish|ksh|csh|tcsh|dash)(?:-[\d.]+)?$/iu.test(trimmed)) return true; - // Single lowercase identity token: root, ubuntu, pi — not Title-Case labels. - return /^[a-z0-9_.-]+$/u.test(trimmed); -} - -/** - * True when a confirmed shell/device prompt is followed by typed text on the - * same logical line (e.g. `user@host:~$ lsof -i:`). Trailing `:` / `>` in that - * typed text is ordinary command input, not an authentication boundary. - * - * Requires a real prompt boundary (terminator + whitespace) so mid-label - * shapes like `Challenge #1:` stay fail-closed. For `$`/`#`/`%`, also requires - * a plausible PS1 body so `Challenge # 1:` / `Account $ code:` stay untrusted. - */ -function hasTypedInputAfterConfirmedPrompt( - line: string, - options: ConfirmedPromptOptions = {}, -): boolean { - for (let i = 0; i < line.length - 1; i += 1) { - const ch = line[i]; - // Only terminators that can end a confirmed prompt without relying on a - // glyph appearing later in the typed command. - if (ch !== '$' && ch !== '#' && ch !== '%' && ch !== '>') continue; - const rest = line.slice(i + 1); - // Prompt terminators are followed by whitespace before typed input. - if (!/^\s+\S/u.test(rest)) continue; - const candidate = line.slice(0, i + 1); - if (!isConfirmedTerminalShellPrompt(candidate, options)) continue; - if ((ch === '$' || ch === '#' || ch === '%') && !isPlausibleShellPromptBody(candidate.slice(0, -1))) { - continue; - } - return true; - } - return false; -} - -/** - * Fail closed for prompt-shaped input boundaries that are not positively - * identified as an ordinary shell/device prompt. This protects custom PAM, - * bastion, and appliance challenges whose labels contain no known vocabulary. - */ -export function isUntrustedTerminalInputPrompt( - value: string, - options: ConfirmedPromptOptions = {}, -): boolean { - const prompt = lastLogicalLine(value).trim(); - if (!prompt) return false; - if (isSensitiveTerminalChallenge(prompt)) return true; - // Vim command-mode entry on the alternate screen. A bare `:` on the - // primary screen stays fail-closed (`sudo -p ':'`). - if (options.alternateScreen && /^:\s*$/.test(prompt)) return false; - if (!/[::>›»]\s*$/u.test(prompt)) return false; - // Mid-command punctuation after a real shell prompt must keep broadcasting - // (#2709). Standalone `Label:` / `Custom>` challenges still fail closed. - if (hasTypedInputAfterConfirmedPrompt(prompt, options)) return false; - // Pass the original text so a bare ">" can see heredoc lines above it. - return !isConfirmedTerminalShellPrompt(value, options); -} - -export { MAX_PROMPT_SECURITY_TAIL_CHARS }; +export { + MAX_PROMPT_SECURITY_TAIL_CHARS, + isConfirmedTerminalShellPrompt, + isSensitiveTerminalChallenge, + isUntrustedTerminalInputPrompt, + type ConfirmedPromptOptions, +}; diff --git a/components/terminal/normalizeTerminalSelection.test.ts b/domain/terminalSelection.test.ts similarity index 99% rename from components/terminal/normalizeTerminalSelection.test.ts rename to domain/terminalSelection.test.ts index eea1a33c8..2fba261eb 100644 --- a/components/terminal/normalizeTerminalSelection.test.ts +++ b/domain/terminalSelection.test.ts @@ -9,7 +9,7 @@ import { trimWrittenPadding, type SelectionBufferLine, type SelectionTerminal, -} from "./normalizeTerminalSelection.ts"; +} from "./terminalSelection.ts"; const require = createRequire(import.meta.url); const { Terminal: XTerm } = require("@xterm/xterm") as { diff --git a/components/terminal/normalizeTerminalSelection.ts b/domain/terminalSelection.ts similarity index 100% rename from components/terminal/normalizeTerminalSelection.ts rename to domain/terminalSelection.ts diff --git a/domain/totpPrompt.shared.d.ts b/domain/totpPrompt.shared.d.cts similarity index 100% rename from domain/totpPrompt.shared.d.ts rename to domain/totpPrompt.shared.d.cts diff --git a/domain/totpPrompt.shared.mjs b/domain/totpPrompt.shared.mjs deleted file mode 100644 index 48b4985d5..000000000 --- a/domain/totpPrompt.shared.mjs +++ /dev/null @@ -1,4 +0,0 @@ -// SMS, email, RADIUS, menus, and confirmations must never be treated as a -// TOTP code prompt, even when earlier lines mention OTP. -// Keep this pattern identical to domain/totpPrompt.shared.cjs. -export const NON_TOTP_PROMPT = /SMS|EMAIL|RADIUS|PASSKEY|MFA_CUSTOM|短信|邮件|郵件|Option>|\[Y\/n\]/i; diff --git a/electron-builder.config.cjs b/electron-builder.config.cjs index 663352c80..8f7f330e6 100644 --- a/electron-builder.config.cjs +++ b/electron-builder.config.cjs @@ -78,7 +78,6 @@ module.exports = { // TypeScript under domain/ is excluded below, so the .cjs must be listed. 'domain/systemManager/containerRuntime.shared.cjs', 'domain/singleChannelSshBanner.shared.cjs', - 'domain/singleChannelSshBanner.shared.mjs', 'domain/sshServerVendor.mjs', // sshAuthHelper.cjs requires this at load. TypeScript under domain/ // is excluded below, so the shared TOTP runtime must be listed. diff --git a/electron/bridges/aiBridge/sdk/cursorCliDriver.cjs b/electron/bridges/aiBridge/sdk/cursorCliDriver.cjs index 72c286987..47c5d23fa 100644 --- a/electron/bridges/aiBridge/sdk/cursorCliDriver.cjs +++ b/electron/bridges/aiBridge/sdk/cursorCliDriver.cjs @@ -13,6 +13,7 @@ const path = require("node:path"); const { resolveCursorCliSpawnSpec } = require("../cursorCliSpawn.cjs"); const { mcpEnvPairsToObject } = require("./injectMcp.cjs"); const { encodeCursorCliModel } = require("./cursorDriver.cjs"); +const { closeReasoning } = require("./sdkDriverUtils.cjs"); const DEFAULT_CURSOR_CLI_MODEL = "auto"; const NETCATTY_MCP_NAME = "netcatty-remote-hosts"; @@ -299,13 +300,6 @@ function extractCliToolCall(event) { }; } -function closeReasoning(state, emitter) { - if (state?.reasoningOpen) { - emitter.reasoningEnd(); - state.reasoningOpen = false; - } -} - function translateCursorCliEvent(event, emitter, state = {}) { if (!event || typeof event !== "object") return false; diff --git a/electron/bridges/aiBridge/sdk/cursorDriver.cjs b/electron/bridges/aiBridge/sdk/cursorDriver.cjs index ee07d40a1..6abaa4e19 100644 --- a/electron/bridges/aiBridge/sdk/cursorDriver.cjs +++ b/electron/bridges/aiBridge/sdk/cursorDriver.cjs @@ -9,6 +9,7 @@ * Stopping a stalled SDK startup cannot block another chat or leak its tenant. */ const { mcpEnvPairsToObject } = require("./injectMcp.cjs"); +const { closeReasoning } = require("./sdkDriverUtils.cjs"); const { applyTemporaryProcessEnv, withExclusiveProcessEnv, @@ -166,13 +167,6 @@ async function logCursorApiKeyValidation(resolvedModule, apiKey) { } } -function closeReasoning(state, emitter) { - if (state?.reasoningOpen) { - emitter.reasoningEnd(); - state.reasoningOpen = false; - } -} - function emitCursorToolCallOnce(event, emitter, state, toolName, args, id) { if (!id) return false; if (!state.emittedToolCalls) state.emittedToolCalls = new Set(); diff --git a/electron/bridges/aiBridge/sdk/grokAcpDriver.cjs b/electron/bridges/aiBridge/sdk/grokAcpDriver.cjs index 46faff5bb..53e285cb1 100644 --- a/electron/bridges/aiBridge/sdk/grokAcpDriver.cjs +++ b/electron/bridges/aiBridge/sdk/grokAcpDriver.cjs @@ -19,6 +19,7 @@ const path = require("node:path"); const { spawn } = require("node:child_process"); const { StringDecoder } = require("node:string_decoder"); +const { closeReasoning } = require("./sdkDriverUtils.cjs"); const { GROK_MCP_MODE_DISALLOWED_LOCAL_TOOLS, createLineBuffer, @@ -617,13 +618,6 @@ function resultToText(result) { return String(result); } -function closeReasoning(state, emitter) { - if (state?.reasoningOpen) { - emitter.reasoningEnd(); - state.reasoningOpen = false; - } -} - /** * Map one ACP session/update payload (or x.ai notification) to emitter calls. * @returns {boolean} true when the stream should stop on error diff --git a/electron/bridges/aiBridge/sdk/grokDriver.cjs b/electron/bridges/aiBridge/sdk/grokDriver.cjs index de9c080e5..2c966d1ba 100644 --- a/electron/bridges/aiBridge/sdk/grokDriver.cjs +++ b/electron/bridges/aiBridge/sdk/grokDriver.cjs @@ -16,6 +16,7 @@ const fs = require("node:fs"); const path = require("node:path"); const { prepareCommandForSpawn } = require("../../ai/shellUtils.cjs"); const { mcpEnvPairsToObject } = require("./injectMcp.cjs"); +const { closeReasoning } = require("./sdkDriverUtils.cjs"); const NETCATTY_MCP_NAME = "netcatty-remote-hosts"; const GROK_ABORT_GRACE_MS = 1_500; @@ -375,13 +376,6 @@ function resultToText(result) { return String(result); } -function closeReasoning(state, emitter) { - if (state?.reasoningOpen) { - emitter.reasoningEnd(); - state.reasoningOpen = false; - } -} - /** * Normalize Grok/ACP plan entries to the shared activity shape: * items: [{ text, completed }], status: "running" | "completed" diff --git a/electron/bridges/aiBridge/sdk/mimoDriver.cjs b/electron/bridges/aiBridge/sdk/mimoDriver.cjs index d371c3cf0..27daaece3 100644 --- a/electron/bridges/aiBridge/sdk/mimoDriver.cjs +++ b/electron/bridges/aiBridge/sdk/mimoDriver.cjs @@ -19,12 +19,12 @@ * `createOpencodeClient` to the URL it reports. */ const fs = require("node:fs"); -const net = require("node:net"); const path = require("node:path"); const { randomBytes } = require("node:crypto"); const { spawn, spawnSync } = require("node:child_process"); const { prepareCommandForSpawn, resolveCliFromPath } = require("../../ai/shellUtils.cjs"); const { buildSdkAgentEnv } = require("./env.cjs"); +const { getAvailablePort: getSharedAvailablePort } = require("./sdkDriverUtils.cjs"); const { filterMimoTrustedSkillPaths } = require("./netcattySkillsOpenCodePermissions.cjs"); const { buildOpenCodeConfig, @@ -150,19 +150,7 @@ function stopMimoProcess(child, { } function getAvailablePort(host = "127.0.0.1") { - return new Promise((resolve, reject) => { - const server = net.createServer(); - server.unref(); - server.on("error", reject); - server.listen(0, host, () => { - const address = server.address(); - const port = typeof address === "object" && address ? address.port : 0; - server.close((error) => { - if (error) reject(error); - else resolve(port === DEFAULT_MIMO_PORT ? getAvailablePort(host) : port); - }); - }); - }); + return getSharedAvailablePort(host, DEFAULT_MIMO_PORT); } // Ask the same CLI that starts the server to resolve its configuration. This diff --git a/electron/bridges/aiBridge/sdk/opencodeDriver.cjs b/electron/bridges/aiBridge/sdk/opencodeDriver.cjs index ecd48d89c..215227dbb 100644 --- a/electron/bridges/aiBridge/sdk/opencodeDriver.cjs +++ b/electron/bridges/aiBridge/sdk/opencodeDriver.cjs @@ -1,11 +1,11 @@ "use strict"; -const net = require("node:net"); const fs = require("node:fs"); const path = require("node:path"); const { pathToFileURL } = require("node:url"); const { mcpEnvPairsToObject } = require("./injectMcp.cjs"); const { withExclusiveProcessEnv } = require("./processEnvGate.cjs"); +const { getAvailablePort: getSharedAvailablePort } = require("./sdkDriverUtils.cjs"); const { buildOpenCodeNativeSkillsPermissionRules, buildOpenCodeSkillsPermissionRules, @@ -451,19 +451,7 @@ function withOpenCodeProcessEnv(env, binPath, fn) { } function getAvailablePort(host = "127.0.0.1") { - return new Promise((resolve, reject) => { - const server = net.createServer(); - server.unref(); - server.on("error", reject); - server.listen(0, host, () => { - const address = server.address(); - const port = typeof address === "object" && address ? address.port : 0; - server.close((error) => { - if (error) reject(error); - else resolve(port === DEFAULT_OPENCODE_PORT ? getAvailablePort(host) : port); - }); - }); - }); + return getSharedAvailablePort(host, DEFAULT_OPENCODE_PORT); } async function withOpenCodeServerPort(options = {}) { diff --git a/electron/bridges/aiBridge/sdk/sdkDriverUtils.cjs b/electron/bridges/aiBridge/sdk/sdkDriverUtils.cjs new file mode 100644 index 000000000..96a1d7d80 --- /dev/null +++ b/electron/bridges/aiBridge/sdk/sdkDriverUtils.cjs @@ -0,0 +1,31 @@ +"use strict"; + +const net = require("node:net"); + +function closeReasoning(state, emitter) { + if (state?.reasoningOpen) { + emitter.reasoningEnd(); + state.reasoningOpen = false; + } +} + +function getAvailablePort(host = "127.0.0.1", avoidPort = 0) { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.unref(); + server.on("error", reject); + server.listen(0, host, () => { + const address = server.address(); + const port = typeof address === "object" && address ? address.port : 0; + server.close((error) => { + if (error) reject(error); + else resolve(avoidPort && port === avoidPort ? getAvailablePort(host, avoidPort) : port); + }); + }); + }); +} + +module.exports = { + closeReasoning, + getAvailablePort, +}; diff --git a/electron/bridges/appLockWindowsHelloHelper.test.cjs b/electron/bridges/appLockWindowsHelloHelper.test.cjs deleted file mode 100644 index 3a363e023..000000000 --- a/electron/bridges/appLockWindowsHelloHelper.test.cjs +++ /dev/null @@ -1,36 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const path = require("node:path"); - -const helperSource = fs.readFileSync( - path.join(__dirname, "windowsHelloHelper", "NetcattyWindowsHello.cpp"), - "utf8", -); - -test("Windows Hello helper uses desktop HWND interop", () => { - assert.match(helperSource, /IUserConsentVerifierInterop/); - assert.match(helperSource, /RequestVerificationForWindowAsync/); - assert.match(helperSource, /--hwnd/); - assert.doesNotMatch(helperSource, /UserConsentVerifier::RequestVerificationAsync/); -}); - -test("Windows Hello helper maps all expected verifier states", () => { - for (const state of [ - "Available", - "DeviceNotPresent", - "NotConfiguredForUser", - "DisabledByPolicy", - "DeviceBusy", - "RetriesExhausted", - "Canceled", - "Verified", - ]) { - assert.match(helperSource, new RegExp(state)); - } -}); - -test("Windows Hello helper uses a multi-threaded apartment for blocking waits", () => { - assert.match(helperSource, /init_apartment\(winrt::apartment_type::multi_threaded\)/); - assert.doesNotMatch(helperSource, /init_apartment\(winrt::apartment_type::single_threaded\)/); -}); diff --git a/electron/bridges/compressUploadBridge.cjs b/electron/bridges/compressUploadBridge.cjs index a678b751b..e8fe6635b 100644 --- a/electron/bridges/compressUploadBridge.cjs +++ b/electron/bridges/compressUploadBridge.cjs @@ -11,6 +11,7 @@ const { spawn } = require("node:child_process"); const { StringDecoder } = require("node:string_decoder"); const { getTempFilePath } = require("./tempDirBridge.cjs"); const { invalidateSshTransport } = require("./sshTransportInvalidation.cjs"); +const { registerWorkerHandle } = require("./workerIpcProxy.cjs"); /** * Escape shell arguments to prevent injection attacks @@ -1076,12 +1077,6 @@ async function checkCompressedUploadSupport(event, payload) { } } -function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { - ipcMain.handle(channel, (event, payload) => terminalWorkerManager.request(channel, payload, { - webContentsId: event?.sender?.id, - })); -} - /** * Register IPC handlers */ diff --git a/electron/bridges/externalMcp/claudeSetup.cjs b/electron/bridges/externalMcp/claudeSetup.cjs index f625acd6b..136d7aaff 100644 --- a/electron/bridges/externalMcp/claudeSetup.cjs +++ b/electron/bridges/externalMcp/claudeSetup.cjs @@ -12,27 +12,18 @@ const { formatDiscoveryEnvCliFlags, } = require("../../cli/externalMcpDiscoveryPath.cjs"); -function loadShellUtils() { - return require("../ai/shellUtils.cjs"); -} - -function loadDesktopCliResolver() { - return require("./desktopCliResolver.cjs"); -} +const { + loadShellUtils, + loadDesktopCliResolver, + formatCliCommandText, + pathsMatch, + extractCommandExecutable, + hasRequiredDiscoveryEnv, + summarizeFailure: summarizeCliFailure, +} = require("./cliSetupBase.cjs"); function formatClaudeCommandText(args, cliPath = "claude") { - const executable = typeof cliPath === "string" && cliPath.trim() - ? cliPath.trim() - : "claude"; - return [quoteCommandArg(executable), ...args.map(quoteCommandArg)].join(" "); -} - -function quoteCommandArg(value) { - if (typeof value !== "string" || value.length === 0) return '""'; - // Match ExternalMcpCard quoteShellArg so copyable commands stay shell-safe - // for paths with spaces, quotes, apostrophes, or backslashes. - if (!/[\s"'\\]/u.test(value)) return value; - return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`; + return formatCliCommandText(args, cliPath, "claude"); } function getCombinedOutput(result) { @@ -44,19 +35,6 @@ function isMissingClaudeServer(result) { return /No MCP server (?:found with name:|named)\s*["']?netcatty-external["']?/i.test(output); } -function normalizePathForCompare(value) { - if (typeof value !== "string") return ""; - let normalized = value.trim().replace(/^["']|["']$/gu, ""); - if (process.platform === "win32") { - normalized = normalized.replace(/\.cmd$/iu, ""); - } - return normalized; -} - -function pathsMatch(left, right) { - return normalizePathForCompare(left) === normalizePathForCompare(right); -} - function extractExistingCommand(result) { const output = getCombinedOutput(result); if (!output) return null; @@ -128,23 +106,6 @@ function buildClaudeAddArgs(launcherPath, discoveryEnv) { ]; } -function extractCommandExecutable(commandText) { - if (typeof commandText !== "string") return ""; - const trimmed = commandText.trim(); - if (!trimmed) return ""; - // Prefer the last path-like token so env flags before `--` do not confuse matching. - const dashDashIndex = trimmed.lastIndexOf(" -- "); - const candidate = dashDashIndex >= 0 - ? trimmed.slice(dashDashIndex + 4).trim() - : trimmed; - const match = candidate.match(/("(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]+)/u); - if (!match) return candidate; - // Extra args after the executable mean a different launch command. - const remainder = candidate.slice(match[0].length).trim(); - if (remainder) return ""; - return match[1]; -} - function extractExistingEnv(result) { const output = getCombinedOutput(result); if (!output) return null; @@ -183,14 +144,6 @@ function extractExistingEnv(result) { return Object.keys(env).length > 0 ? env : null; } -function hasRequiredDiscoveryEnv(entryEnv, discoveryEnv) { - const required = discoveryEnv && typeof discoveryEnv === "object" ? discoveryEnv : {}; - const keys = Object.keys(required).filter((key) => typeof required[key] === "string" && required[key]); - if (keys.length === 0) return true; - if (!entryEnv || typeof entryEnv !== "object") return false; - return keys.every((key) => String(entryEnv[key] || "") === String(required[key])); -} - function classifyClaudeExternalMcpStatus({ getResult, launcherPath, @@ -269,7 +222,7 @@ function classifyClaudeExternalMcpStatus({ } function summarizeFailure(result, fallback) { - return String(result?.stderr || result?.stdout || fallback || "Claude command failed").trim(); + return summarizeCliFailure(result, fallback, "Claude command failed"); } function createExternalMcpClaudeSetup(options = {}) { diff --git a/electron/bridges/externalMcp/cliSetupBase.cjs b/electron/bridges/externalMcp/cliSetupBase.cjs new file mode 100644 index 000000000..b8a70a9bb --- /dev/null +++ b/electron/bridges/externalMcp/cliSetupBase.cjs @@ -0,0 +1,78 @@ +"use strict"; + +function loadShellUtils() { + return require("../ai/shellUtils.cjs"); +} + +function loadDesktopCliResolver() { + return require("./desktopCliResolver.cjs"); +} + +function quoteCommandArg(value) { + if (typeof value !== "string" || value.length === 0) return '""'; + // Match ExternalMcpCard quoteShellArg so copyable commands stay shell-safe + // for paths with spaces, quotes, apostrophes, or backslashes. + if (!/[\s"'\\]/u.test(value)) return value; + return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`; +} + +function formatCliCommandText(args, cliPath, defaultCli) { + const executable = typeof cliPath === "string" && cliPath.trim() + ? cliPath.trim() + : defaultCli; + return [quoteCommandArg(executable), ...args.map(quoteCommandArg)].join(" "); +} + +function normalizePathForCompare(value) { + if (typeof value !== "string") return ""; + let normalized = value.trim().replace(/^["']|["']$/gu, ""); + if (process.platform === "win32") { + normalized = normalized.replace(/\.cmd$/iu, ""); + } + return normalized; +} + +function pathsMatch(left, right) { + return normalizePathForCompare(left) === normalizePathForCompare(right); +} + +function extractCommandExecutable(commandText) { + if (typeof commandText !== "string") return ""; + const trimmed = commandText.trim(); + if (!trimmed) return ""; + // Prefer the last path-like token so env flags before `--` do not confuse matching. + const dashDashIndex = trimmed.lastIndexOf(" -- "); + const candidate = dashDashIndex >= 0 + ? trimmed.slice(dashDashIndex + 4).trim() + : trimmed; + const match = candidate.match(/("(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]+)/u); + if (!match) return candidate; + // Extra args after the executable mean a different launch command. + const remainder = candidate.slice(match[0].length).trim(); + if (remainder) return ""; + return match[1]; +} + +function hasRequiredDiscoveryEnv(entryEnv, discoveryEnv) { + const required = discoveryEnv && typeof discoveryEnv === "object" ? discoveryEnv : {}; + const keys = Object.keys(required).filter((key) => typeof required[key] === "string" && required[key]); + if (keys.length === 0) return true; + if (!entryEnv || typeof entryEnv !== "object") return false; + return keys.every((key) => String(entryEnv[key] || "") === String(required[key])); +} + +function summarizeFailure(result, fallback, defaultMessage = "CLI command failed") { + return String(result?.stderr || result?.stdout || fallback || defaultMessage).trim(); +} + +module.exports = { + loadShellUtils, + loadDesktopCliResolver, + quoteCommandArg, + formatCliCommandText, + normalizePathForCompare, + pathsMatch, + extractCommandExecutable, + hasRequiredDiscoveryEnv, + summarizeFailure, +}; diff --git a/electron/bridges/externalMcp/codexSetup.cjs b/electron/bridges/externalMcp/codexSetup.cjs index dfaa4333f..13186680c 100644 --- a/electron/bridges/externalMcp/codexSetup.cjs +++ b/electron/bridges/externalMcp/codexSetup.cjs @@ -12,13 +12,14 @@ const { formatDiscoveryEnvCliFlags, } = require("../../cli/externalMcpDiscoveryPath.cjs"); -function loadShellUtils() { - return require("../ai/shellUtils.cjs"); -} - -function loadDesktopCliResolver() { - return require("./desktopCliResolver.cjs"); -} +const { + loadShellUtils, + loadDesktopCliResolver, + formatCliCommandText, + pathsMatch, + hasRequiredDiscoveryEnv, + summarizeFailure: summarizeCliFailure, +} = require("./cliSetupBase.cjs"); function parseCodexMcpList(rawOutput) { const parsed = JSON.parse(String(rawOutput || "[]")); @@ -38,18 +39,7 @@ function parseCodexMcpList(rawOutput) { } function formatCodexCommandText(args, cliPath = "codex") { - const executable = typeof cliPath === "string" && cliPath.trim() - ? cliPath.trim() - : "codex"; - return [quoteCommandArg(executable), ...args.map(quoteCommandArg)].join(" "); -} - -function quoteCommandArg(value) { - if (typeof value !== "string" || value.length === 0) return '""'; - // Match ExternalMcpCard quoteShellArg so copyable commands stay shell-safe - // for paths with spaces, quotes, apostrophes, or backslashes. - if (!/[\s"'\\]/u.test(value)) return value; - return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`; + return formatCliCommandText(args, cliPath, "codex"); } function formatExistingCommand(transport) { @@ -67,19 +57,6 @@ function formatExistingCommand(transport) { return null; } -function normalizePathForCompare(value) { - if (typeof value !== "string") return ""; - let normalized = value.trim().replace(/^["']|["']$/gu, ""); - if (process.platform === "win32") { - normalized = normalized.replace(/\.cmd$/iu, ""); - } - return normalized; -} - -function pathsMatch(left, right) { - return normalizePathForCompare(left) === normalizePathForCompare(right); -} - function buildCodexAddArgs(launcherPath, discoveryEnv) { return [ "mcp", @@ -98,14 +75,6 @@ function getCodexEntryEnv(entry) { return null; } -function hasRequiredDiscoveryEnv(entryEnv, discoveryEnv) { - const required = discoveryEnv && typeof discoveryEnv === "object" ? discoveryEnv : {}; - const keys = Object.keys(required).filter((key) => typeof required[key] === "string" && required[key]); - if (keys.length === 0) return true; - if (!entryEnv || typeof entryEnv !== "object") return false; - return keys.every((key) => String(entryEnv[key] || "") === String(required[key])); -} - function classifyCodexExternalMcpStatus({ entries, launcherPath, @@ -219,7 +188,7 @@ function createExternalMcpCodexSetup(options = {}) { } function summarizeFailure(result, fallback) { - return String(result?.stderr || result?.stdout || fallback || "Codex command failed").trim(); + return summarizeCliFailure(result, fallback, "Codex command failed"); } async function getStatus() { diff --git a/electron/bridges/externalMcp/grokSetup.cjs b/electron/bridges/externalMcp/grokSetup.cjs index 2b54a0309..eb703ed52 100644 --- a/electron/bridges/externalMcp/grokSetup.cjs +++ b/electron/bridges/externalMcp/grokSetup.cjs @@ -13,22 +13,19 @@ const { formatDiscoveryEnvCliFlags, } = require("../../cli/externalMcpDiscoveryPath.cjs"); -function loadShellUtils() { - return require("../ai/shellUtils.cjs"); -} +const { + loadShellUtils, + quoteCommandArg, + pathsMatch, + extractCommandExecutable, + hasRequiredDiscoveryEnv, + summarizeFailure: summarizeCliFailure, +} = require("./cliSetupBase.cjs"); function formatGrokCommandText(args) { return ["grok", ...args.map(quoteCommandArg)].join(" "); } -function quoteCommandArg(value) { - if (typeof value !== "string" || value.length === 0) return '""'; - // Match ExternalMcpCard quoteShellArg so copyable commands stay shell-safe - // for paths with spaces, quotes, apostrophes, or backslashes. - if (!/[\s"'\\]/u.test(value)) return value; - return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`; -} - function formatExistingCommand(entry) { if (!entry || typeof entry !== "object") return null; if (entry.transport && typeof entry.transport === "object") { @@ -121,34 +118,6 @@ function normalizeGrokListEntry(entry) { }; } -function normalizePathForCompare(value) { - if (typeof value !== "string") return ""; - let normalized = value.trim().replace(/^["']|["']$/gu, ""); - if (process.platform === "win32") { - normalized = normalized.replace(/\.cmd$/iu, ""); - } - return normalized; -} - -function pathsMatch(left, right) { - return normalizePathForCompare(left) === normalizePathForCompare(right); -} - -function extractCommandExecutable(commandText) { - if (typeof commandText !== "string") return ""; - const trimmed = commandText.trim(); - if (!trimmed) return ""; - const dashDashIndex = trimmed.lastIndexOf(" -- "); - const candidate = dashDashIndex >= 0 - ? trimmed.slice(dashDashIndex + 4).trim() - : trimmed; - const match = candidate.match(/("(?:\\.|[^"])*"|'(?:\\.|[^'])*'|[^\s]+)/u); - if (!match) return candidate; - const remainder = candidate.slice(match[0].length).trim(); - if (remainder) return ""; - return match[1]; -} - function getEntryCommand(entry) { if (!entry) return null; if (entry.transport?.type === "stdio" || entry.transport?.command) { @@ -165,14 +134,6 @@ function getEntryCommand(entry) { return formatExistingCommand(entry); } -function hasRequiredDiscoveryEnv(entryEnv, discoveryEnv) { - const required = discoveryEnv && typeof discoveryEnv === "object" ? discoveryEnv : {}; - const keys = Object.keys(required).filter((key) => typeof required[key] === "string" && required[key]); - if (keys.length === 0) return true; - if (!entryEnv || typeof entryEnv !== "object") return false; - return keys.every((key) => String(entryEnv[key] || "") === String(required[key])); -} - function getGrokEntryEnv(entry) { if (entry?.env && typeof entry.env === "object") return entry.env; if (entry?.transport?.env && typeof entry.transport.env === "object") return entry.transport.env; @@ -317,7 +278,7 @@ function createExternalMcpGrokSetup(options = {}) { } function summarizeFailure(result, fallback) { - return String(result?.stderr || result?.stdout || fallback || "Grok command failed").trim(); + return summarizeCliFailure(result, fallback, "Grok command failed"); } async function getStatus() { diff --git a/electron/bridges/fileWatcherBridge.cjs b/electron/bridges/fileWatcherBridge.cjs index b6667ad18..5deb40919 100644 --- a/electron/bridges/fileWatcherBridge.cjs +++ b/electron/bridges/fileWatcherBridge.cjs @@ -9,6 +9,7 @@ const fs = require("node:fs"); const path = require("node:path"); const crypto = require("node:crypto"); +const { registerWorkerHandle } = require("./workerIpcProxy.cjs"); // Map of watchId -> { watcher, localPath, remotePath, sftpId, lastModified, lastSize } const activeWatchers = new Map(); @@ -588,12 +589,6 @@ function listWatchers() { return watchers; } -function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { - ipcMain.handle(channel, (event, payload) => terminalWorkerManager.request(channel, payload, { - webContentsId: event?.sender?.id, - })); -} - /** * Register IPC handlers for file watching operations */ diff --git a/electron/bridges/githubAuthBridge.cjs b/electron/bridges/githubAuthBridge.cjs index 2521c10d3..c5c0a30ca 100644 --- a/electron/bridges/githubAuthBridge.cjs +++ b/electron/bridges/githubAuthBridge.cjs @@ -5,6 +5,8 @@ * This bridge proxies GitHub Device Flow endpoints via the main process. */ +const { resolveFetch, postOAuthForm } = require("./oauthHttpHelper.cjs"); + const GITHUB_CLIENT_ID = process.env.VITE_SYNC_GITHUB_CLIENT_ID || ""; const GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code"; const GITHUB_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"; @@ -29,36 +31,21 @@ function normalizeGistRawUrl(rawUrl) { * @param {import('electron')=} electronModule */ function registerHandlers(ipcMain, electronModule) { - const fetchImpl = - electronModule?.net?.fetch ? electronModule.net.fetch.bind(electronModule.net) : fetch; + const fetchImpl = resolveFetch(electronModule); ipcMain.handle("netcatty:github:deviceFlow:start", async (_event, payload) => { const clientId = payload?.clientId || GITHUB_CLIENT_ID; const scope = payload?.scope || "gist read:user"; - const res = await fetchImpl(GITHUB_DEVICE_CODE_URL, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: new URLSearchParams({ - client_id: clientId, - scope, - }).toString(), - }); - - const text = await res.text(); - if (!res.ok) { - throw new Error(`GitHub device flow failed: ${res.status} - ${text}`); - } - - let data; - try { - data = JSON.parse(text); - } catch { - throw new Error(`GitHub device flow invalid JSON: ${text.slice(0, 200)}`); - } + const data = await postOAuthForm( + fetchImpl, + GITHUB_DEVICE_CODE_URL, + new URLSearchParams({ client_id: clientId, scope }), + { + label: "GitHub device flow", + formatHttpError: (status, text) => `GitHub device flow failed: ${status} - ${text}`, + } + ); return { deviceCode: data.device_code, @@ -81,30 +68,20 @@ function registerHandlers(ipcMain, electronModule) { } try { - const res = await fetchImpl(GITHUB_ACCESS_TOKEN_URL, { - method: "POST", - signal: controller.signal, - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: new URLSearchParams({ + return await postOAuthForm( + fetchImpl, + GITHUB_ACCESS_TOKEN_URL, + new URLSearchParams({ client_id: clientId, device_code: deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code", - }).toString(), - }); - - const text = await res.text(); - if (!res.ok) { - throw new Error(`GitHub token polling failed: ${res.status} - ${text}`); - } - - try { - return JSON.parse(text); - } catch { - throw new Error(`GitHub token polling invalid JSON: ${text.slice(0, 200)}`); - } + }), + { + label: "GitHub token polling", + signal: controller.signal, + formatHttpError: (status, text) => `GitHub token polling failed: ${status} - ${text}`, + } + ); } finally { if (pollId) { pendingPollControllers.delete(pollId); diff --git a/electron/bridges/googleAuthBridge.cjs b/electron/bridges/googleAuthBridge.cjs index bc6de6b84..6c7866ece 100644 --- a/electron/bridges/googleAuthBridge.cjs +++ b/electron/bridges/googleAuthBridge.cjs @@ -11,24 +11,13 @@ const GOOGLE_DRIVE_API = "https://www.googleapis.com/drive/v3"; const GOOGLE_DRIVE_UPLOAD_API = "https://www.googleapis.com/upload/drive/v3"; const DEFAULT_SYNC_FILE_NAME = "netcatty-vault.json"; const { randomUUID } = require("node:crypto"); - -const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0; - -const describeNetworkError = (err) => { - const msg = err?.message || String(err); - const cause = err?.cause; - const causeCode = cause?.code ? ` (${cause.code})` : ""; - const causeMsg = cause?.message ? `: ${cause.message}` : ""; - return `${msg}${causeCode}${causeMsg}`.trim(); -}; - -const safeJsonParse = (text) => { - try { - return JSON.parse(text); - } catch { - return null; - } -}; +const { + isNonEmptyString, + safeJsonParse, + describeNetworkError, + resolveFetch, + postOAuthForm, +} = require("./oauthHttpHelper.cjs"); const describeGoogleApiError = (status, text) => { const data = safeJsonParse(text); @@ -45,8 +34,7 @@ const describeGoogleApiError = (status, text) => { * @param {import('electron')=} electronModule */ function registerHandlers(ipcMain, electronModule) { - const fetchImpl = - electronModule?.net?.fetch ? electronModule.net.fetch.bind(electronModule.net) : fetch; + const fetchImpl = resolveFetch(electronModule); ipcMain.handle("netcatty:google:oauth:exchange", async (_event, payload) => { const clientId = payload?.clientId; @@ -71,39 +59,10 @@ function registerHandlers(ipcMain, electronModule) { body.set("client_secret", clientSecret); } - let res; - try { - res = await fetchImpl(GOOGLE_TOKEN_URL, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: body.toString(), - }); - } catch (err) { - throw new Error( - `Google token exchange network error. Check your network/VPN and whether Google services are reachable. (${describeNetworkError(err)})` - ); - } - - const text = await res.text(); - if (!res.ok) { - let data; - try { - data = JSON.parse(text); - } catch { - data = { error: text }; - } - throw new Error(`Google token exchange failed: ${data.error_description || data.error || res.status}`); - } - - let data; - try { - data = JSON.parse(text); - } catch { - throw new Error(`Google token exchange invalid JSON: ${text.slice(0, 200)}`); - } + const data = await postOAuthForm(fetchImpl, GOOGLE_TOKEN_URL, body, { + label: "Google token exchange", + serviceLabel: "Google services", + }); return { accessToken: data.access_token, @@ -131,39 +90,10 @@ function registerHandlers(ipcMain, electronModule) { body.set("client_secret", clientSecret); } - let res; - try { - res = await fetchImpl(GOOGLE_TOKEN_URL, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: body.toString(), - }); - } catch (err) { - throw new Error( - `Google token refresh network error. Check your network/VPN and whether Google services are reachable. (${describeNetworkError(err)})` - ); - } - - const text = await res.text(); - if (!res.ok) { - let data; - try { - data = JSON.parse(text); - } catch { - data = { error: text }; - } - throw new Error(`Google token refresh failed: ${data.error_description || data.error || res.status}`); - } - - let data; - try { - data = JSON.parse(text); - } catch { - throw new Error(`Google token refresh invalid JSON: ${text.slice(0, 200)}`); - } + const data = await postOAuthForm(fetchImpl, GOOGLE_TOKEN_URL, body, { + label: "Google token refresh", + serviceLabel: "Google services", + }); return { accessToken: data.access_token, diff --git a/electron/bridges/mcpServerBridge.approvalTimeout.test.cjs b/electron/bridges/mcpServerBridge.approvalTimeout.test.cjs deleted file mode 100644 index 5baf2ae6b..000000000 --- a/electron/bridges/mcpServerBridge.approvalTimeout.test.cjs +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { EventEmitter } = require("node:events"); -const { setTimeout: delay } = require("node:timers/promises"); - -const mcpServerBridge = require("./mcpServerBridge.cjs"); - -function createFakeWindow() { - const contents = new EventEmitter(); - contents.id = Math.floor(Math.random() * 1e6); - contents.send = (channel, payload) => { - contents.emit("send", channel, payload); - }; - contents.isDestroyed = () => false; - return { - isDestroyed: () => false, - webContents: contents, - }; -} - -function stubNow(t, startMs) { - const realNow = Date.now; - let now = startMs; - Date.now = () => now; - t.after(() => { - Date.now = realNow; - }); - return { - advance: (deltaMs) => { - now += deltaMs; - }, - }; -} - -test("cancelApprovalTimeoutFromRenderer keeps the absolute MCP deadline armed", async (t) => { - const win = createFakeWindow(); - mcpServerBridge.setMainWindowGetter(() => win); - t.after(() => { - mcpServerBridge.clearPendingApprovals(); - mcpServerBridge.setMainWindowGetter(() => null); - }); - - const requests = []; - const cleared = []; - win.webContents.on("send", (channel, payload) => { - if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload); - if (channel === "netcatty:ai:mcp:approval-cleared") { - cleared.push(...(payload?.approvalIds || [])); - } - }); - - const clock = stubNow(t, 1_000_000); - const approvalPromise = mcpServerBridge.requestApprovalFromRenderer( - "terminal_execute", - { command: "echo hi" }, - "chat-mcp-absolute", - ); - - assert.equal(requests.length, 1); - const approvalId = requests[0].approvalId; - - // Jump close to the 110s absolute ceiling, then cancel idle. Remaining absolute ~40ms. - clock.advance(109_960); - assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), true); - assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), false); - - await delay(20); - assert.equal(cleared.includes(approvalId), false, "must stay pending before absolute expiry"); - - const outcome = await Promise.race([ - approvalPromise.then((approved) => ({ approved })), - delay(120).then(() => ({ approved: "timeout-wait" })), - ]); - assert.deepEqual(outcome, { approved: false }); - assert.ok(cleared.includes(approvalId)); -}); - -test("cancelApprovalTimeoutFromRenderer still allows explicit approve before absolute expiry", async (t) => { - const win = createFakeWindow(); - mcpServerBridge.setMainWindowGetter(() => win); - t.after(() => { - mcpServerBridge.clearPendingApprovals(); - mcpServerBridge.setMainWindowGetter(() => null); - }); - - const requests = []; - win.webContents.on("send", (channel, payload) => { - if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload); - }); - - stubNow(t, 2_000_000); - const approvalPromise = mcpServerBridge.requestApprovalFromRenderer( - "sftp_write", - { path: "/tmp/x" }, - "chat-mcp-approve", - ); - const approvalId = requests[0].approvalId; - - assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), true); - mcpServerBridge.resolveApprovalFromRenderer(approvalId, true); - assert.equal(await approvalPromise, true); -}); diff --git a/electron/bridges/mcpServerBridge.hostApproval.test.cjs b/electron/bridges/mcpServerBridge.approvalsAndTimeouts.test.cjs similarity index 65% rename from electron/bridges/mcpServerBridge.hostApproval.test.cjs rename to electron/bridges/mcpServerBridge.approvalsAndTimeouts.test.cjs index f29033494..302b47082 100644 --- a/electron/bridges/mcpServerBridge.hostApproval.test.cjs +++ b/electron/bridges/mcpServerBridge.approvalsAndTimeouts.test.cjs @@ -1,5 +1,130 @@ "use strict"; +require("./cliDiscoveryTestIsolation.cjs").isolateCliDiscoveryFile(); + +// --- merged from mcpServerBridge.commandTimeout.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const mcpServerBridge = require("./mcpServerBridge.cjs"); + +test("setCommandTimeout honors one-day command timeout", (t) => { + t.after(() => mcpServerBridge.setCommandTimeout(60)); + + mcpServerBridge.setCommandTimeout(86_400); + + assert.equal(mcpServerBridge.getCommandTimeoutMs(), 86_400_000); +}); +} + +// --- merged from mcpServerBridge.approvalTimeout.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const { setTimeout: delay } = require("node:timers/promises"); + +const mcpServerBridge = require("./mcpServerBridge.cjs"); + +function createFakeWindow() { + const contents = new EventEmitter(); + contents.id = Math.floor(Math.random() * 1e6); + contents.send = (channel, payload) => { + contents.emit("send", channel, payload); + }; + contents.isDestroyed = () => false; + return { + isDestroyed: () => false, + webContents: contents, + }; +} + +function stubNow(t, startMs) { + const realNow = Date.now; + let now = startMs; + Date.now = () => now; + t.after(() => { + Date.now = realNow; + }); + return { + advance: (deltaMs) => { + now += deltaMs; + }, + }; +} + +test("cancelApprovalTimeoutFromRenderer keeps the absolute MCP deadline armed", async (t) => { + const win = createFakeWindow(); + mcpServerBridge.setMainWindowGetter(() => win); + t.after(() => { + mcpServerBridge.clearPendingApprovals(); + mcpServerBridge.setMainWindowGetter(() => null); + }); + + const requests = []; + const cleared = []; + win.webContents.on("send", (channel, payload) => { + if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload); + if (channel === "netcatty:ai:mcp:approval-cleared") { + cleared.push(...(payload?.approvalIds || [])); + } + }); + + const clock = stubNow(t, 1_000_000); + const approvalPromise = mcpServerBridge.requestApprovalFromRenderer( + "terminal_execute", + { command: "echo hi" }, + "chat-mcp-absolute", + ); + + assert.equal(requests.length, 1); + const approvalId = requests[0].approvalId; + + // Jump close to the 110s absolute ceiling, then cancel idle. Remaining absolute ~40ms. + clock.advance(109_960); + assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), true); + assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), false); + + await delay(20); + assert.equal(cleared.includes(approvalId), false, "must stay pending before absolute expiry"); + + const outcome = await Promise.race([ + approvalPromise.then((approved) => ({ approved })), + delay(120).then(() => ({ approved: "timeout-wait" })), + ]); + assert.deepEqual(outcome, { approved: false }); + assert.ok(cleared.includes(approvalId)); +}); + +test("cancelApprovalTimeoutFromRenderer still allows explicit approve before absolute expiry", async (t) => { + const win = createFakeWindow(); + mcpServerBridge.setMainWindowGetter(() => win); + t.after(() => { + mcpServerBridge.clearPendingApprovals(); + mcpServerBridge.setMainWindowGetter(() => null); + }); + + const requests = []; + win.webContents.on("send", (channel, payload) => { + if (channel === "netcatty:ai:mcp:approval-request") requests.push(payload); + }); + + stubNow(t, 2_000_000); + const approvalPromise = mcpServerBridge.requestApprovalFromRenderer( + "sftp_write", + { path: "/tmp/x" }, + "chat-mcp-approve", + ); + const approvalId = requests[0].approvalId; + + assert.equal(mcpServerBridge.cancelApprovalTimeoutFromRenderer(approvalId), true); + mcpServerBridge.resolveApprovalFromRenderer(approvalId, true); + assert.equal(await approvalPromise, true); +}); +} + +// --- merged from mcpServerBridge.hostApproval.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); @@ -161,3 +286,4 @@ test("external MCP approval names the host and isolates connection and host gran assert.equal(bridge.resolveApprovalFromRenderer(staleRequest.approvalId, true), false); assert.equal((await staleCall).ok, false); }); +} diff --git a/electron/bridges/mcpServerBridge.commandTimeout.test.cjs b/electron/bridges/mcpServerBridge.commandTimeout.test.cjs deleted file mode 100644 index c4dbec63d..000000000 --- a/electron/bridges/mcpServerBridge.commandTimeout.test.cjs +++ /dev/null @@ -1,11 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const mcpServerBridge = require("./mcpServerBridge.cjs"); - -test("setCommandTimeout honors one-day command timeout", (t) => { - t.after(() => mcpServerBridge.setCommandTimeout(60)); - - mcpServerBridge.setCommandTimeout(86_400); - - assert.equal(mcpServerBridge.getCommandTimeoutMs(), 86_400_000); -}); diff --git a/electron/bridges/mcpServerBridge.cliDiscoveryIsolation.test.cjs b/electron/bridges/mcpServerBridge.discovery.test.cjs similarity index 50% rename from electron/bridges/mcpServerBridge.cliDiscoveryIsolation.test.cjs rename to electron/bridges/mcpServerBridge.discovery.test.cjs index 64aee4b69..74dd3ba93 100644 --- a/electron/bridges/mcpServerBridge.cliDiscoveryIsolation.test.cjs +++ b/electron/bridges/mcpServerBridge.discovery.test.cjs @@ -1,5 +1,7 @@ "use strict"; +// --- merged from mcpServerBridge.cliDiscoveryIsolation.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const crypto = require("node:crypto"); @@ -130,3 +132,139 @@ test("running a previously destructive test never touches the installed discover fs.rmSync(fakeRoot, { recursive: true, force: true }); } }); +} + +// --- merged from mcpServerBridge.discoverySelfHeal.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); + +const bridge = require("./mcpServerBridge.cjs"); + +function readDiscovery(discoveryPath) { + return JSON.parse(fs.readFileSync(discoveryPath, "utf8")); +} + +test("self-heals a deleted discovery file while the TCP host stays alive", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); + const discoveryPath = path.join(dir, "discovery.json"); + t.after(() => { + bridge.cleanup(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + bridge.init({ cliDiscoveryFilePath: discoveryPath }); + + const port = await bridge.getOrCreateHost(); + assert.ok(Number.isInteger(port) && port > 0); + assert.ok(fs.existsSync(discoveryPath)); + const original = readDiscovery(discoveryPath); + assert.equal(original.port, port); + assert.equal(original.pid, process.pid); + assert.ok(original.token); + + // Simulate an out-of-band deletion while the host is still listening. + fs.rmSync(discoveryPath, { force: true }); + assert.ok(!fs.existsSync(discoveryPath)); + + // The host reuse path repairs the file immediately from in-memory state. + const portAgain = await bridge.getOrCreateHost(); + assert.equal(portAgain, port); + assert.ok(fs.existsSync(discoveryPath)); + const repaired = readDiscovery(discoveryPath); + assert.equal(repaired.port, port); + assert.equal(repaired.token, original.token); + assert.equal(repaired.pid, process.pid); + + // A stale file (wrong port/token) is rewritten too. + fs.writeFileSync(discoveryPath, JSON.stringify({ port: 1, token: "stale", pid: 999 })); + bridge.ensureCliDiscoveryFile(); + const fixed = readDiscovery(discoveryPath); + assert.equal(fixed.port, port); + assert.equal(fixed.token, original.token); +}); + +test("self-heal rewrites files whose pid drifted and files that are invalid JSON", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); + const discoveryPath = path.join(dir, "discovery.json"); + t.after(() => { + bridge.cleanup(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + bridge.init({ cliDiscoveryFilePath: discoveryPath }); + const port = await bridge.getOrCreateHost(); + const current = readDiscovery(discoveryPath); + + // Correct port/token but a pid from a previous app instance: the file is + // stale from the CLI's perspective and must be rewritten. + fs.writeFileSync(discoveryPath, JSON.stringify({ + port, + token: current.token, + pid: process.pid + 1, + permissionMode: current.permissionMode, + updatedAt: "stale", + })); + bridge.ensureCliDiscoveryFile(); + const repid = readDiscovery(discoveryPath); + assert.equal(repid.pid, process.pid); + assert.equal(repid.port, port); + + // A file that cannot be parsed is treated as missing and rewritten. + fs.writeFileSync(discoveryPath, "{not json"); + bridge.ensureCliDiscoveryFile(); + const reparsed = readDiscovery(discoveryPath); + assert.equal(reparsed.port, port); + assert.equal(reparsed.token, current.token); + assert.equal(reparsed.pid, process.pid); +}); + +test("self-heal leaves a current discovery file untouched", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); + const discoveryPath = path.join(dir, "discovery.json"); + t.after(() => { + bridge.cleanup(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + bridge.init({ cliDiscoveryFilePath: discoveryPath }); + const port = await bridge.getOrCreateHost(); + const before = fs.readFileSync(discoveryPath, "utf8"); + + bridge.ensureCliDiscoveryFile(); + + const after = fs.readFileSync(discoveryPath, "utf8"); + assert.equal(after, before); + assert.equal(JSON.parse(after).port, port); +}); + +test("ensureCliDiscoveryFile does nothing while the host is down", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); + const discoveryPath = path.join(dir, "discovery.json"); + t.after(() => { + bridge.cleanup(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + bridge.init({ cliDiscoveryFilePath: discoveryPath }); + bridge.ensureCliDiscoveryFile(); + assert.ok(!fs.existsSync(discoveryPath)); + + const port = await bridge.getOrCreateHost(); + bridge.cleanup(); + + // cleanup removes the file and the host is gone; ensure must not revive it. + bridge.ensureCliDiscoveryFile(); + assert.ok(!fs.existsSync(discoveryPath)); + + // A fresh host can still be started after cleanup and rewrites discovery. + const newPort = await bridge.getOrCreateHost(); + assert.ok(Number.isInteger(newPort) && newPort > 0); + // Note: newPort may legitimately equal port (OS can reuse the ephemeral port + // once the old listener closed), so don't assert they differ. + assert.equal(readDiscovery(discoveryPath).port, newPort); +}); +} diff --git a/electron/bridges/mcpServerBridge.discoverySelfHeal.test.cjs b/electron/bridges/mcpServerBridge.discoverySelfHeal.test.cjs deleted file mode 100644 index 1231304f1..000000000 --- a/electron/bridges/mcpServerBridge.discoverySelfHeal.test.cjs +++ /dev/null @@ -1,131 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); - -const bridge = require("./mcpServerBridge.cjs"); - -function readDiscovery(discoveryPath) { - return JSON.parse(fs.readFileSync(discoveryPath, "utf8")); -} - -test("self-heals a deleted discovery file while the TCP host stays alive", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); - const discoveryPath = path.join(dir, "discovery.json"); - t.after(() => { - bridge.cleanup(); - fs.rmSync(dir, { recursive: true, force: true }); - }); - - bridge.init({ cliDiscoveryFilePath: discoveryPath }); - - const port = await bridge.getOrCreateHost(); - assert.ok(Number.isInteger(port) && port > 0); - assert.ok(fs.existsSync(discoveryPath)); - const original = readDiscovery(discoveryPath); - assert.equal(original.port, port); - assert.equal(original.pid, process.pid); - assert.ok(original.token); - - // Simulate an out-of-band deletion while the host is still listening. - fs.rmSync(discoveryPath, { force: true }); - assert.ok(!fs.existsSync(discoveryPath)); - - // The host reuse path repairs the file immediately from in-memory state. - const portAgain = await bridge.getOrCreateHost(); - assert.equal(portAgain, port); - assert.ok(fs.existsSync(discoveryPath)); - const repaired = readDiscovery(discoveryPath); - assert.equal(repaired.port, port); - assert.equal(repaired.token, original.token); - assert.equal(repaired.pid, process.pid); - - // A stale file (wrong port/token) is rewritten too. - fs.writeFileSync(discoveryPath, JSON.stringify({ port: 1, token: "stale", pid: 999 })); - bridge.ensureCliDiscoveryFile(); - const fixed = readDiscovery(discoveryPath); - assert.equal(fixed.port, port); - assert.equal(fixed.token, original.token); -}); - -test("self-heal rewrites files whose pid drifted and files that are invalid JSON", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); - const discoveryPath = path.join(dir, "discovery.json"); - t.after(() => { - bridge.cleanup(); - fs.rmSync(dir, { recursive: true, force: true }); - }); - - bridge.init({ cliDiscoveryFilePath: discoveryPath }); - const port = await bridge.getOrCreateHost(); - const current = readDiscovery(discoveryPath); - - // Correct port/token but a pid from a previous app instance: the file is - // stale from the CLI's perspective and must be rewritten. - fs.writeFileSync(discoveryPath, JSON.stringify({ - port, - token: current.token, - pid: process.pid + 1, - permissionMode: current.permissionMode, - updatedAt: "stale", - })); - bridge.ensureCliDiscoveryFile(); - const repid = readDiscovery(discoveryPath); - assert.equal(repid.pid, process.pid); - assert.equal(repid.port, port); - - // A file that cannot be parsed is treated as missing and rewritten. - fs.writeFileSync(discoveryPath, "{not json"); - bridge.ensureCliDiscoveryFile(); - const reparsed = readDiscovery(discoveryPath); - assert.equal(reparsed.port, port); - assert.equal(reparsed.token, current.token); - assert.equal(reparsed.pid, process.pid); -}); - -test("self-heal leaves a current discovery file untouched", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); - const discoveryPath = path.join(dir, "discovery.json"); - t.after(() => { - bridge.cleanup(); - fs.rmSync(dir, { recursive: true, force: true }); - }); - - bridge.init({ cliDiscoveryFilePath: discoveryPath }); - const port = await bridge.getOrCreateHost(); - const before = fs.readFileSync(discoveryPath, "utf8"); - - bridge.ensureCliDiscoveryFile(); - - const after = fs.readFileSync(discoveryPath, "utf8"); - assert.equal(after, before); - assert.equal(JSON.parse(after).port, port); -}); - -test("ensureCliDiscoveryFile does nothing while the host is down", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-discovery-test-")); - const discoveryPath = path.join(dir, "discovery.json"); - t.after(() => { - bridge.cleanup(); - fs.rmSync(dir, { recursive: true, force: true }); - }); - - bridge.init({ cliDiscoveryFilePath: discoveryPath }); - bridge.ensureCliDiscoveryFile(); - assert.ok(!fs.existsSync(discoveryPath)); - - const port = await bridge.getOrCreateHost(); - bridge.cleanup(); - - // cleanup removes the file and the host is gone; ensure must not revive it. - bridge.ensureCliDiscoveryFile(); - assert.ok(!fs.existsSync(discoveryPath)); - - // A fresh host can still be started after cleanup and rewrites discovery. - const newPort = await bridge.getOrCreateHost(); - assert.ok(Number.isInteger(newPort) && newPort > 0); - // Note: newPort may legitimately equal port (OS can reuse the ephemeral port - // once the old listener closed), so don't assert they differ. - assert.equal(readDiscovery(discoveryPath).port, newPort); -}); diff --git a/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs b/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs index 3a18f6504..b10612a2f 100644 --- a/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs +++ b/electron/bridges/mcpServerBridge.pluginDelegation.test.cjs @@ -1,5 +1,7 @@ "use strict"; +require("./cliDiscoveryTestIsolation.cjs").isolateCliDiscoveryFile(); + const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); diff --git a/electron/bridges/mcpServerBridge.privacy.test.cjs b/electron/bridges/mcpServerBridge.privacy.test.cjs index 23c14f9dc..b2d339e7b 100644 --- a/electron/bridges/mcpServerBridge.privacy.test.cjs +++ b/electron/bridges/mcpServerBridge.privacy.test.cjs @@ -1,5 +1,9 @@ "use strict"; +require("./cliDiscoveryTestIsolation.cjs").isolateCliDiscoveryFile(); + +// --- merged from mcpServerBridge.privacy.test.cjs --- +{ const { test } = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); @@ -118,3 +122,270 @@ test("privacy-disabled TCP preserves legacy multi-scope and unscoped calls on on assert.equal(one.hosts[0].hostname, "one.example"); assert.equal(two.hosts[0].hostname, "two.example"); }); +} + +// --- merged from mcpServerBridge.sftpPrivacy.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { createSftpHandlerApi } = require("./mcpServerBridge/sftpHandlers.cjs"); +const { createAiPrivacyService } = require("../shared/aiPrivacyService.cjs"); + +function deferred() { + let resolve; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +const operations = [ + ["handleSftpList", {}], + ["handleSftpRead", { path: "/synthetic" }], + ["handleSftpWrite", { path: "/synthetic", content: "synthetic" }], + ["handleSftpDownload", { remotePath: "/synthetic", localPath: "/synthetic-local" }], + ["handleSftpUpload", { remotePath: "/synthetic", localPath: "/synthetic-local" }], + ["handleSftpMkdir", { path: "/synthetic" }], + ["handleSftpDelete", { path: "/synthetic" }], + ["handleSftpRename", { oldPath: "/synthetic", newPath: "/synthetic-new" }], + ["handleSftpStat", { path: "/synthetic" }], + ["handleSftpChmod", { path: "/synthetic", mode: "600" }], + ["handleSftpHome", {}], +]; + +for (const worker of [false, true]) { + for (const [method, args] of operations) { + test(`${method} blocks a policy change during ${worker ? "worker" : "main"} SFTP open`, async () => { + const privacy = createAiPrivacyService(); + privacy.configure({ enabled: true }); + privacy.checkSession("chat"); + const entered = deferred(); + const release = deferred(); + const effects = []; + const closed = []; + const open = async () => { + entered.resolve(); + await release.promise; + return { sftpId: "synthetic-handle" }; + }; + const bridge = new Proxy({ + openSftpForSession: open, + closeSftp: async (_event, payload) => { closed.push(payload); }, + }, { + get: (target, key) => target[key] || (async (_event, payload) => { effects.push({ key, payload }); }), + }); + const api = createSftpHandlerApi({ + sessions: new Map(worker ? [] : [["ssh", {}]]), + terminalWorkerManager: worker ? { + request: async (channel, payload) => { + if (channel === "netcatty:sftp:openForSession") return open(); + if (channel === "netcatty:sftp:close") { closed.push(payload); return; } + effects.push({ channel, payload }); + }, + } : null, + sftpBridge: bridge, + transferBridge: null, + commandTimeoutMs: 1000, + registerSftpOp: () => () => {}, + createTransferId: () => "synthetic-transfer", + reportTransferEvent() {}, + }); + const pending = api[method]({ sessionId: "ssh", chatSessionId: "chat", ...args }, { + beforeExecute: () => privacy.restore("chat", []), + }); + const rejected = assert.rejects(pending, /start a new chat/); + await entered.promise; + privacy.configure({ enabled: false }); + release.resolve(); + await rejected; + assert.deepEqual(effects, []); + assert.equal(closed.length, 1, "the opened handle must still be released"); + }); + } +} + +for (const method of ["handleSftpDownload", "handleSftpUpload"]) { + for (const changePolicy of [false, true]) { + test(`${method} ${changePolicy ? "blocks changed" : "preserves unchanged"} privacy after main transfer admission`, async () => { + const privacy = createAiPrivacyService(); + privacy.configure({ enabled: true }); + privacy.checkSession("chat"); + const entered = deferred(); + const release = deferred(); + const effects = []; + const opens = []; + const closed = []; + const admitted = []; + const transferBridge = { + getGlobalTransferConcurrency: () => 1, + async runAdmittedTransfer(event, payload, _progress, runner) { + admitted.push(payload); + entered.resolve(); + await release.promise; + return runner + ? runner() + : transferBridge.startTransfer(event, { ...payload, skipAdmission: true }); + }, + startTransfer(event, payload) { + if (payload.skipAdmission !== true) { + return transferBridge.runAdmittedTransfer(event, payload); + } + effects.push(payload); + return Promise.resolve({ transferId: payload.transferId }); + }, + }; + const api = createSftpHandlerApi({ + sessions: new Map([["ssh", { hostId: "synthetic-host" }]]), + terminalWorkerManager: null, + sftpBridge: { + openSftpForSession: async (_event, payload) => { + opens.push(payload); + return { sftpId: "synthetic-handle" }; + }, + closeSftp: async (_event, payload) => { closed.push(payload); }, + }, + transferBridge, + commandTimeoutMs: 1000, + registerSftpOp: () => () => {}, + createTransferId: () => "synthetic-transfer", + reportTransferEvent() {}, + }); + const pending = api[method]({ + sessionId: "ssh", chatSessionId: "chat", + remotePath: "/synthetic-remote", localPath: "/synthetic-local", + }, { beforeExecute: () => privacy.restore("chat", []) }); + const rejected = changePolicy ? assert.rejects(pending, /start a new chat/) : null; + await entered.promise; + if (changePolicy) privacy.configure({ enabled: false }); + release.resolve(); + if (rejected) await rejected; + else assert.equal((await pending).ok, true); + assert.equal(admitted.length, 1, "the transfer must acquire only one admission slot"); + const hostField = method === "handleSftpDownload" ? "sourceHostId" : "targetHostId"; + assert.equal(admitted[0][hostField], "synthetic-host"); + assert.equal(admitted[0].globalConcurrency, 1); + assert.equal(effects.length, changePolicy ? 0 : 1); + assert.equal(opens.length, changePolicy ? 0 : 1); + assert.equal(closed.length, opens.length); + if (!changePolicy) assert.equal(effects[0].skipAdmission, true); + }); + } +} + +for (const method of ["handleSftpDownload", "handleSftpUpload"]) { + for (const cancelQueued of [false, true]) { + test(`${method} ${cancelQueued ? "cancels" : "completes"} through real admission with chat cleanup`, { timeout: 5000 }, async (t) => { + const realTransfers = require("./transferBridge.cjs"); + const { createBackgroundJobApi } = require("./mcpServerBridge/backgroundJobs.cjs"); + const previousLimit = realTransfers.getGlobalTransferConcurrency(); + realTransfers.setGlobalTransferConcurrency(1); + const hostId = `synthetic-${method}-${cancelQueued}`; + const transferId = `${hostId}-transfer`; + const releaseBlocker = deferred(); + const queued = deferred(); + const blocker = realTransfers.runAdmittedTransfer( + { sender: { send() {} } }, + { transferId: `${hostId}-blocker`, sourceHostId: hostId }, + undefined, + () => releaseBlocker.promise, + ); + const privacy = createAiPrivacyService(); + privacy.configure({ enabled: true }); + privacy.checkSession("chat"); + const registryContext = { + activeSessionSftpOps: new Map(), closingTerminalSessions: new Map(), activeSftpOpSeq: 0, + }; + const registry = createBackgroundJobApi(registryContext); + const effects = []; + const opens = []; + const closed = []; + const events = []; + let admissionCount = 0; + let registrationCount = 0; + let releaseCount = 0; + let cancelCount = 0; + let pending; + t.after(async () => { + releaseBlocker.resolve(); + await blocker; + await pending; + realTransfers.setGlobalTransferConcurrency(previousLimit); + }); + const api = createSftpHandlerApi({ + sessions: new Map([["ssh", { hostId }]]), + terminalWorkerManager: null, + sftpBridge: { + openSftpForSession: async () => { opens.push(true); return { sftpId: "synthetic-handle" }; }, + closeSftp: async () => { closed.push(true); }, + }, + transferBridge: { + getGlobalTransferConcurrency: () => 1, + runAdmittedTransfer: (...args) => { + admissionCount++; + return realTransfers.runAdmittedTransfer(...args); + }, + cancelTransfer: (...args) => { + cancelCount++; + return realTransfers.cancelTransfer(...args); + }, + startTransfer: async (_event, payload) => { + assert.equal(payload.skipAdmission, true); + effects.push(payload); + return { transferId }; + }, + }, + commandTimeoutMs: 1000, + registerSftpOp: (...args) => { + registrationCount++; + const unregister = registry.registerSftpOp(...args); + return () => { releaseCount++; unregister(); }; + }, + createTransferId: () => transferId, + reportTransferEvent: (event) => { + events.push(event); + if (event.type === "queued" && event.transferId === transferId) queued.resolve(); + }, + }); + let settled = false; + pending = api[method]({ + sessionId: "ssh", chatSessionId: "chat", + remotePath: "/synthetic-remote", localPath: "/synthetic-local", + }, { beforeExecute: () => privacy.restore("chat", []) }).then((result) => { + settled = true; + return result; + }); + await queued.promise; + assert.equal(opens.length, 0); + if (cancelQueued) { + await registry.cancelSftpOpsForSession("chat"); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, true, "queued cancellation must settle before the occupied slot is released"); + assert.deepEqual(await pending, { ok: false, cancelled: true, transferId }); + assert.equal(cancelCount, 1); + assert.equal(events.filter((event) => event.type === "cancelled").length, 1); + } else { + releaseBlocker.resolve(); + await blocker; + assert.equal((await pending).ok, true); + assert.equal(cancelCount, 0); + assert.equal(events.filter((event) => event.type === "completed").length, 1); + } + releaseBlocker.resolve(); + await blocker; + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(admissionCount, 1); + assert.equal(effects.length, cancelQueued ? 0 : 1); + assert.equal(opens.length, effects.length); + assert.equal(closed.length, opens.length); + assert.equal(registryContext.activeSessionSftpOps.size, 0); + assert.equal(registrationCount, cancelQueued ? 1 : 2); + assert.equal(releaseCount, registrationCount, "each cancellation registration is released exactly once"); + assert.equal(realTransfers._getPendingCancelCountForTests(), 0); + assert.equal(await realTransfers.runAdmittedTransfer( + { sender: { send() {} } }, + { transferId: `${hostId}-next`, sourceHostId: hostId }, + undefined, + async () => "slot released", + ), "slot released"); + }); + } +} +} diff --git a/electron/bridges/mcpServerBridge.sessionReconnect.test.cjs b/electron/bridges/mcpServerBridge.reconnect.test.cjs similarity index 56% rename from electron/bridges/mcpServerBridge.sessionReconnect.test.cjs rename to electron/bridges/mcpServerBridge.reconnect.test.cjs index 22bd05058..ab85c0b87 100644 --- a/electron/bridges/mcpServerBridge.sessionReconnect.test.cjs +++ b/electron/bridges/mcpServerBridge.reconnect.test.cjs @@ -1,5 +1,174 @@ "use strict"; +// --- merged from mcpServerBridge.reconnectingSession.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { isolateCliDiscoveryFile } = require("./cliDiscoveryTestIsolation.cjs"); +isolateCliDiscoveryFile(); + +function loadFreshBridge() { + const bridgePath = require.resolve("./mcpServerBridge.cjs"); + delete require.cache[bridgePath]; + return require("./mcpServerBridge.cjs"); +} + +function setup(t, { sessions } = {}) { + const bridge = loadFreshBridge(); + t.after(() => bridge.cleanup()); + bridge.init({ sessions: sessions || new Map(), electronModule: null }); + bridge.setPermissionMode("auto"); + return bridge; +} + +test('reusing a user tab adds visibility without ownership or idle tracking', async (t) => { + const bridge = setup(t); + bridge.setVaultAgentInvoker(async () => ({ ok: true, reused: true, sessionId: 'user-tab', hostId: 'host-b', status: 'connected' })); + await bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId: 'chat-b', hostId: 'host-b' }); + assert.deepEqual(bridge.getScopedSessionIds('chat-b'), ['user-tab']); + assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'user-tab', phase: 'touch' }), false); + const close = await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'chat-b', sessionId: 'user-tab' }); + assert.equal(close.ok, false); + assert.match(close.error, /not opened by the current AI scope/); +}); + +test('reuse keeps the original chat owner and its idle tracking', async (t) => { + const bridge = setup(t); + const calls = []; + bridge.setVaultAgentInvoker(async (op, params) => { + calls.push({ op, params }); + if (op === 'session.close') return { ok: true }; + return { ok: true, reused: params.chatSessionId !== 'owner', sessionId: 'shared-tab', hostId: 'host-b', status: 'connected' }; + }); + for (const chatSessionId of ['owner', 'borrower']) { + await bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId, hostId: 'host-b' }); + } + assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'shared-tab', phase: 'touch' }), true); + assert.equal((await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'borrower', sessionId: 'shared-tab' })).ok, false); + assert.equal((await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'owner', sessionId: 'shared-tab' })).ok, true); + assert.equal(calls.filter(({ op }) => op === 'session.close').length, 1); +}); + +test('a deleted chat cannot reclaim a reused tab or revive its own scope', async (t) => { + const bridge = setup(t); + let finishOpen; + const calls = []; + bridge.updateSessionMetadata([{ sessionId: 'user-tab', connected: true }], 'original'); + bridge.setVaultAgentInvoker((op) => { + calls.push(op); + return new Promise((resolve) => { finishOpen = resolve; }); + }); + const opening = bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId: 'deleted', hostId: 'host-b' }); + await bridge.cleanupScopedMetadata('deleted'); + bridge.mergeSessionMetadata([{ sessionId: 'user-tab', connected: true }], 'deleted'); + finishOpen({ ok: true, reused: true, sessionId: 'user-tab', status: 'connected' }); + const rejected = await opening; + assert.equal(rejected.ok, false); + assert.equal(rejected.code, 'SESSION_SCOPE_BIND_FAILED'); + assert.equal(rejected.sessionId, 'user-tab'); + assert.deepEqual(calls, ['host.open']); + assert.deepEqual(bridge.getScopedSessionIds('deleted'), []); + assert.deepEqual(bridge.getScopedSessionIds('original'), ['user-tab']); + assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'user-tab', phase: 'touch' }), false); +}); + +test("getContext keeps a scoped disconnected session visible with connected:false", async (t) => { + const bridge = setup(t); + bridge.updateSessionMetadata([ + { + sessionId: "sess-reconnecting", + hostname: "10.0.0.2", + label: "server-b", + connected: true, + hostId: "host-b", + protocol: "ssh", + }, + ], "chat-1"); + // Connection dropped: renderer pushes connected:false while the tab + // auto-reconnects. The scope keeps the same sessionId. + bridge.updateSessionMetadata([ + { + sessionId: "sess-reconnecting", + hostname: "10.0.0.2", + label: "server-b", + connected: false, + hostId: "host-b", + protocol: "ssh", + }, + ], "chat-1"); + + const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { + chatSessionId: "chat-1", + }); + const host = environment.hosts.find((entry) => entry.sessionId === "sess-reconnecting"); + assert.ok(host, "reconnecting session must stay visible to the agent"); + assert.equal(host.connected, false); +}); + +test("getContext keeps a live-map session without transport visible when scoped", async (t) => { + const bridge = setup(t, { + sessions: new Map([["sess-live", { hostname: "10.0.0.3", label: "server-c" }]]), + }); + bridge.updateSessionMetadata([ + { + sessionId: "sess-live", + hostname: "10.0.0.3", + label: "server-c", + connected: false, + hostId: "host-c", + protocol: "ssh", + }, + ], "chat-1"); + + const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { + chatSessionId: "chat-1", + }); + const host = environment.hosts.find((entry) => entry.sessionId === "sess-live"); + assert.ok(host, "reconnecting live-map session must stay visible"); + assert.equal(host.connected, false); +}); + +test("getContext still hides disconnected sessions outside the agent scope", async (t) => { + const bridge = setup(t); + bridge.updateSessionMetadata([ + { + sessionId: "foreign", + hostname: "10.0.0.9", + label: "foreign", + connected: false, + hostId: "host-x", + protocol: "ssh", + }, + ], "chat-other"); + + const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { + chatSessionId: "chat-1", + }); + assert.equal(environment.hosts.length, 0); +}); + +test("external context preserves reconnecting metadata beside another live transport", async (t) => { + const bridge = setup(t, { sessions: new Map([["online", { hostname: "online", stream: { write() {} } }]]) }); + const scope = bridge.EXTERNAL_MCP_CHAT_SESSION_ID; + bridge.setExternalMcpHooks({ isEnabled: () => true }); + bridge.updateSessionMetadata([ + { sessionId: "online", hostname: "online", connected: true }, + { sessionId: "retrying", hostname: "retrying", connected: false }, + ], scope); + const context = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: scope }); + assert.equal(context.hostCount, 2); + assert.equal(context.hosts.find(host => host.sessionId === "retrying")?.connected, false); + assert.equal(context.hosts.find(host => host.sessionId === "online")?.connected, true); + // A renderer-authoritative removal must still remove the closed tab. + bridge.updateSessionMetadata([{ sessionId: "online", connected: true }], scope); + const afterClose = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: scope }); + assert.deepEqual(afterClose.hosts.map(host => host.sessionId), ["online"]); +}); +} + +// --- merged from mcpServerBridge.sessionReconnect.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const { isolateCliDiscoveryFile } = require("./cliDiscoveryTestIsolation.cjs"); @@ -182,4 +351,4 @@ test('a hung worker readiness probe times out and recovery completes with an adv assert.ok(Date.now() - secondStartedAt < 15000, 'running lock was not released after the timeout'); assert.equal(inspections, 2); }); - +} diff --git a/electron/bridges/mcpServerBridge.reconnectingSession.test.cjs b/electron/bridges/mcpServerBridge.reconnectingSession.test.cjs deleted file mode 100644 index ef51a211f..000000000 --- a/electron/bridges/mcpServerBridge.reconnectingSession.test.cjs +++ /dev/null @@ -1,165 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { isolateCliDiscoveryFile } = require("./cliDiscoveryTestIsolation.cjs"); -isolateCliDiscoveryFile(); - -function loadFreshBridge() { - const bridgePath = require.resolve("./mcpServerBridge.cjs"); - delete require.cache[bridgePath]; - return require("./mcpServerBridge.cjs"); -} - -function setup(t, { sessions } = {}) { - const bridge = loadFreshBridge(); - t.after(() => bridge.cleanup()); - bridge.init({ sessions: sessions || new Map(), electronModule: null }); - bridge.setPermissionMode("auto"); - return bridge; -} - -test('reusing a user tab adds visibility without ownership or idle tracking', async (t) => { - const bridge = setup(t); - bridge.setVaultAgentInvoker(async () => ({ ok: true, reused: true, sessionId: 'user-tab', hostId: 'host-b', status: 'connected' })); - await bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId: 'chat-b', hostId: 'host-b' }); - assert.deepEqual(bridge.getScopedSessionIds('chat-b'), ['user-tab']); - assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'user-tab', phase: 'touch' }), false); - const close = await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'chat-b', sessionId: 'user-tab' }); - assert.equal(close.ok, false); - assert.match(close.error, /not opened by the current AI scope/); -}); - -test('reuse keeps the original chat owner and its idle tracking', async (t) => { - const bridge = setup(t); - const calls = []; - bridge.setVaultAgentInvoker(async (op, params) => { - calls.push({ op, params }); - if (op === 'session.close') return { ok: true }; - return { ok: true, reused: params.chatSessionId !== 'owner', sessionId: 'shared-tab', hostId: 'host-b', status: 'connected' }; - }); - for (const chatSessionId of ['owner', 'borrower']) { - await bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId, hostId: 'host-b' }); - } - assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'shared-tab', phase: 'touch' }), true); - assert.equal((await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'borrower', sessionId: 'shared-tab' })).ok, false); - assert.equal((await bridge.dispatchBuiltinRpc('public/session/close', { chatSessionId: 'owner', sessionId: 'shared-tab' })).ok, true); - assert.equal(calls.filter(({ op }) => op === 'session.close').length, 1); -}); - -test('a deleted chat cannot reclaim a reused tab or revive its own scope', async (t) => { - const bridge = setup(t); - let finishOpen; - const calls = []; - bridge.updateSessionMetadata([{ sessionId: 'user-tab', connected: true }], 'original'); - bridge.setVaultAgentInvoker((op) => { - calls.push(op); - return new Promise((resolve) => { finishOpen = resolve; }); - }); - const opening = bridge.dispatchBuiltinRpc('public/vault/hosts/open', { chatSessionId: 'deleted', hostId: 'host-b' }); - await bridge.cleanupScopedMetadata('deleted'); - bridge.mergeSessionMetadata([{ sessionId: 'user-tab', connected: true }], 'deleted'); - finishOpen({ ok: true, reused: true, sessionId: 'user-tab', status: 'connected' }); - const rejected = await opening; - assert.equal(rejected.ok, false); - assert.equal(rejected.code, 'SESSION_SCOPE_BIND_FAILED'); - assert.equal(rejected.sessionId, 'user-tab'); - assert.deepEqual(calls, ['host.open']); - assert.deepEqual(bridge.getScopedSessionIds('deleted'), []); - assert.deepEqual(bridge.getScopedSessionIds('original'), ['user-tab']); - assert.equal(bridge.reportOpenedSessionActivity({ sessionId: 'user-tab', phase: 'touch' }), false); -}); - -test("getContext keeps a scoped disconnected session visible with connected:false", async (t) => { - const bridge = setup(t); - bridge.updateSessionMetadata([ - { - sessionId: "sess-reconnecting", - hostname: "10.0.0.2", - label: "server-b", - connected: true, - hostId: "host-b", - protocol: "ssh", - }, - ], "chat-1"); - // Connection dropped: renderer pushes connected:false while the tab - // auto-reconnects. The scope keeps the same sessionId. - bridge.updateSessionMetadata([ - { - sessionId: "sess-reconnecting", - hostname: "10.0.0.2", - label: "server-b", - connected: false, - hostId: "host-b", - protocol: "ssh", - }, - ], "chat-1"); - - const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { - chatSessionId: "chat-1", - }); - const host = environment.hosts.find((entry) => entry.sessionId === "sess-reconnecting"); - assert.ok(host, "reconnecting session must stay visible to the agent"); - assert.equal(host.connected, false); -}); - -test("getContext keeps a live-map session without transport visible when scoped", async (t) => { - const bridge = setup(t, { - sessions: new Map([["sess-live", { hostname: "10.0.0.3", label: "server-c" }]]), - }); - bridge.updateSessionMetadata([ - { - sessionId: "sess-live", - hostname: "10.0.0.3", - label: "server-c", - connected: false, - hostId: "host-c", - protocol: "ssh", - }, - ], "chat-1"); - - const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { - chatSessionId: "chat-1", - }); - const host = environment.hosts.find((entry) => entry.sessionId === "sess-live"); - assert.ok(host, "reconnecting live-map session must stay visible"); - assert.equal(host.connected, false); -}); - -test("getContext still hides disconnected sessions outside the agent scope", async (t) => { - const bridge = setup(t); - bridge.updateSessionMetadata([ - { - sessionId: "foreign", - hostname: "10.0.0.9", - label: "foreign", - connected: false, - hostId: "host-x", - protocol: "ssh", - }, - ], "chat-other"); - - const environment = await bridge.dispatchBuiltinRpc("netcatty/getContext", { - chatSessionId: "chat-1", - }); - assert.equal(environment.hosts.length, 0); -}); - -test("external context preserves reconnecting metadata beside another live transport", async (t) => { - const bridge = setup(t, { sessions: new Map([["online", { hostname: "online", stream: { write() {} } }]]) }); - const scope = bridge.EXTERNAL_MCP_CHAT_SESSION_ID; - bridge.setExternalMcpHooks({ isEnabled: () => true }); - bridge.updateSessionMetadata([ - { sessionId: "online", hostname: "online", connected: true }, - { sessionId: "retrying", hostname: "retrying", connected: false }, - ], scope); - const context = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: scope }); - assert.equal(context.hostCount, 2); - assert.equal(context.hosts.find(host => host.sessionId === "retrying")?.connected, false); - assert.equal(context.hosts.find(host => host.sessionId === "online")?.connected, true); - // A renderer-authoritative removal must still remove the closed tab. - bridge.updateSessionMetadata([{ sessionId: "online", connected: true }], scope); - const afterClose = await bridge.dispatchBuiltinRpc("netcatty/getContext", { chatSessionId: scope }); - assert.deepEqual(afterClose.hosts.map(host => host.sessionId), ["online"]); -}); diff --git a/electron/bridges/mcpServerBridge.sftpPrivacy.test.cjs b/electron/bridges/mcpServerBridge.sftpPrivacy.test.cjs deleted file mode 100644 index 887534e46..000000000 --- a/electron/bridges/mcpServerBridge.sftpPrivacy.test.cjs +++ /dev/null @@ -1,264 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); -const { createSftpHandlerApi } = require("./mcpServerBridge/sftpHandlers.cjs"); -const { createAiPrivacyService } = require("../shared/aiPrivacyService.cjs"); - -function deferred() { - let resolve; - const promise = new Promise((done) => { resolve = done; }); - return { promise, resolve }; -} - -const operations = [ - ["handleSftpList", {}], - ["handleSftpRead", { path: "/synthetic" }], - ["handleSftpWrite", { path: "/synthetic", content: "synthetic" }], - ["handleSftpDownload", { remotePath: "/synthetic", localPath: "/synthetic-local" }], - ["handleSftpUpload", { remotePath: "/synthetic", localPath: "/synthetic-local" }], - ["handleSftpMkdir", { path: "/synthetic" }], - ["handleSftpDelete", { path: "/synthetic" }], - ["handleSftpRename", { oldPath: "/synthetic", newPath: "/synthetic-new" }], - ["handleSftpStat", { path: "/synthetic" }], - ["handleSftpChmod", { path: "/synthetic", mode: "600" }], - ["handleSftpHome", {}], -]; - -for (const worker of [false, true]) { - for (const [method, args] of operations) { - test(`${method} blocks a policy change during ${worker ? "worker" : "main"} SFTP open`, async () => { - const privacy = createAiPrivacyService(); - privacy.configure({ enabled: true }); - privacy.checkSession("chat"); - const entered = deferred(); - const release = deferred(); - const effects = []; - const closed = []; - const open = async () => { - entered.resolve(); - await release.promise; - return { sftpId: "synthetic-handle" }; - }; - const bridge = new Proxy({ - openSftpForSession: open, - closeSftp: async (_event, payload) => { closed.push(payload); }, - }, { - get: (target, key) => target[key] || (async (_event, payload) => { effects.push({ key, payload }); }), - }); - const api = createSftpHandlerApi({ - sessions: new Map(worker ? [] : [["ssh", {}]]), - terminalWorkerManager: worker ? { - request: async (channel, payload) => { - if (channel === "netcatty:sftp:openForSession") return open(); - if (channel === "netcatty:sftp:close") { closed.push(payload); return; } - effects.push({ channel, payload }); - }, - } : null, - sftpBridge: bridge, - transferBridge: null, - commandTimeoutMs: 1000, - registerSftpOp: () => () => {}, - createTransferId: () => "synthetic-transfer", - reportTransferEvent() {}, - }); - const pending = api[method]({ sessionId: "ssh", chatSessionId: "chat", ...args }, { - beforeExecute: () => privacy.restore("chat", []), - }); - const rejected = assert.rejects(pending, /start a new chat/); - await entered.promise; - privacy.configure({ enabled: false }); - release.resolve(); - await rejected; - assert.deepEqual(effects, []); - assert.equal(closed.length, 1, "the opened handle must still be released"); - }); - } -} - -for (const method of ["handleSftpDownload", "handleSftpUpload"]) { - for (const changePolicy of [false, true]) { - test(`${method} ${changePolicy ? "blocks changed" : "preserves unchanged"} privacy after main transfer admission`, async () => { - const privacy = createAiPrivacyService(); - privacy.configure({ enabled: true }); - privacy.checkSession("chat"); - const entered = deferred(); - const release = deferred(); - const effects = []; - const opens = []; - const closed = []; - const admitted = []; - const transferBridge = { - getGlobalTransferConcurrency: () => 1, - async runAdmittedTransfer(event, payload, _progress, runner) { - admitted.push(payload); - entered.resolve(); - await release.promise; - return runner - ? runner() - : transferBridge.startTransfer(event, { ...payload, skipAdmission: true }); - }, - startTransfer(event, payload) { - if (payload.skipAdmission !== true) { - return transferBridge.runAdmittedTransfer(event, payload); - } - effects.push(payload); - return Promise.resolve({ transferId: payload.transferId }); - }, - }; - const api = createSftpHandlerApi({ - sessions: new Map([["ssh", { hostId: "synthetic-host" }]]), - terminalWorkerManager: null, - sftpBridge: { - openSftpForSession: async (_event, payload) => { - opens.push(payload); - return { sftpId: "synthetic-handle" }; - }, - closeSftp: async (_event, payload) => { closed.push(payload); }, - }, - transferBridge, - commandTimeoutMs: 1000, - registerSftpOp: () => () => {}, - createTransferId: () => "synthetic-transfer", - reportTransferEvent() {}, - }); - const pending = api[method]({ - sessionId: "ssh", chatSessionId: "chat", - remotePath: "/synthetic-remote", localPath: "/synthetic-local", - }, { beforeExecute: () => privacy.restore("chat", []) }); - const rejected = changePolicy ? assert.rejects(pending, /start a new chat/) : null; - await entered.promise; - if (changePolicy) privacy.configure({ enabled: false }); - release.resolve(); - if (rejected) await rejected; - else assert.equal((await pending).ok, true); - assert.equal(admitted.length, 1, "the transfer must acquire only one admission slot"); - const hostField = method === "handleSftpDownload" ? "sourceHostId" : "targetHostId"; - assert.equal(admitted[0][hostField], "synthetic-host"); - assert.equal(admitted[0].globalConcurrency, 1); - assert.equal(effects.length, changePolicy ? 0 : 1); - assert.equal(opens.length, changePolicy ? 0 : 1); - assert.equal(closed.length, opens.length); - if (!changePolicy) assert.equal(effects[0].skipAdmission, true); - }); - } -} - -for (const method of ["handleSftpDownload", "handleSftpUpload"]) { - for (const cancelQueued of [false, true]) { - test(`${method} ${cancelQueued ? "cancels" : "completes"} through real admission with chat cleanup`, { timeout: 5000 }, async (t) => { - const realTransfers = require("./transferBridge.cjs"); - const { createBackgroundJobApi } = require("./mcpServerBridge/backgroundJobs.cjs"); - const previousLimit = realTransfers.getGlobalTransferConcurrency(); - realTransfers.setGlobalTransferConcurrency(1); - const hostId = `synthetic-${method}-${cancelQueued}`; - const transferId = `${hostId}-transfer`; - const releaseBlocker = deferred(); - const queued = deferred(); - const blocker = realTransfers.runAdmittedTransfer( - { sender: { send() {} } }, - { transferId: `${hostId}-blocker`, sourceHostId: hostId }, - undefined, - () => releaseBlocker.promise, - ); - const privacy = createAiPrivacyService(); - privacy.configure({ enabled: true }); - privacy.checkSession("chat"); - const registryContext = { - activeSessionSftpOps: new Map(), closingTerminalSessions: new Map(), activeSftpOpSeq: 0, - }; - const registry = createBackgroundJobApi(registryContext); - const effects = []; - const opens = []; - const closed = []; - const events = []; - let admissionCount = 0; - let registrationCount = 0; - let releaseCount = 0; - let cancelCount = 0; - let pending; - t.after(async () => { - releaseBlocker.resolve(); - await blocker; - await pending; - realTransfers.setGlobalTransferConcurrency(previousLimit); - }); - const api = createSftpHandlerApi({ - sessions: new Map([["ssh", { hostId }]]), - terminalWorkerManager: null, - sftpBridge: { - openSftpForSession: async () => { opens.push(true); return { sftpId: "synthetic-handle" }; }, - closeSftp: async () => { closed.push(true); }, - }, - transferBridge: { - getGlobalTransferConcurrency: () => 1, - runAdmittedTransfer: (...args) => { - admissionCount++; - return realTransfers.runAdmittedTransfer(...args); - }, - cancelTransfer: (...args) => { - cancelCount++; - return realTransfers.cancelTransfer(...args); - }, - startTransfer: async (_event, payload) => { - assert.equal(payload.skipAdmission, true); - effects.push(payload); - return { transferId }; - }, - }, - commandTimeoutMs: 1000, - registerSftpOp: (...args) => { - registrationCount++; - const unregister = registry.registerSftpOp(...args); - return () => { releaseCount++; unregister(); }; - }, - createTransferId: () => transferId, - reportTransferEvent: (event) => { - events.push(event); - if (event.type === "queued" && event.transferId === transferId) queued.resolve(); - }, - }); - let settled = false; - pending = api[method]({ - sessionId: "ssh", chatSessionId: "chat", - remotePath: "/synthetic-remote", localPath: "/synthetic-local", - }, { beforeExecute: () => privacy.restore("chat", []) }).then((result) => { - settled = true; - return result; - }); - await queued.promise; - assert.equal(opens.length, 0); - if (cancelQueued) { - await registry.cancelSftpOpsForSession("chat"); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(settled, true, "queued cancellation must settle before the occupied slot is released"); - assert.deepEqual(await pending, { ok: false, cancelled: true, transferId }); - assert.equal(cancelCount, 1); - assert.equal(events.filter((event) => event.type === "cancelled").length, 1); - } else { - releaseBlocker.resolve(); - await blocker; - assert.equal((await pending).ok, true); - assert.equal(cancelCount, 0); - assert.equal(events.filter((event) => event.type === "completed").length, 1); - } - releaseBlocker.resolve(); - await blocker; - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(admissionCount, 1); - assert.equal(effects.length, cancelQueued ? 0 : 1); - assert.equal(opens.length, effects.length); - assert.equal(closed.length, opens.length); - assert.equal(registryContext.activeSessionSftpOps.size, 0); - assert.equal(registrationCount, cancelQueued ? 1 : 2); - assert.equal(releaseCount, registrationCount, "each cancellation registration is released exactly once"); - assert.equal(realTransfers._getPendingCancelCountForTests(), 0); - assert.equal(await realTransfers.runAdmittedTransfer( - { sender: { send() {} } }, - { transferId: `${hostId}-next`, sourceHostId: hostId }, - undefined, - async () => "slot released", - ), "slot released"); - }); - } -} diff --git a/electron/bridges/oauthHttpHelper.cjs b/electron/bridges/oauthHttpHelper.cjs new file mode 100644 index 000000000..9cab7e36f --- /dev/null +++ b/electron/bridges/oauthHttpHelper.cjs @@ -0,0 +1,77 @@ +"use strict"; + +const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0; + +const safeJsonParse = (text) => { + try { + return JSON.parse(text); + } catch { + return null; + } +}; + +const describeNetworkError = (err) => { + const msg = err?.message || String(err); + const cause = err?.cause; + const causeCode = cause?.code ? ` (${cause.code})` : ""; + const causeMsg = cause?.message ? `: ${cause.message}` : ""; + return `${msg}${causeCode}${causeMsg}`.trim(); +}; + +const resolveFetch = (electronModule) => + electronModule?.net?.fetch ? electronModule.net.fetch.bind(electronModule.net) : fetch; + +/** + * Execute an x-www-form-urlencoded POST to an OAuth endpoint and parse the JSON + * response, surfacing standardized network / HTTP / invalid-JSON errors. + */ +async function postOAuthForm(fetchImpl, url, params, { + label, + serviceLabel, + signal, + formatHttpError, +}) { + let res; + try { + res = await fetchImpl(url, { + method: "POST", + ...(signal ? { signal } : {}), + headers: { + Accept: "application/json", + "Content-Type": "application/x-www-form-urlencoded", + }, + body: params.toString(), + }); + } catch (err) { + if (serviceLabel) { + throw new Error( + `${label} network error. Check your network/VPN and whether ${serviceLabel} are reachable. (${describeNetworkError(err)})` + ); + } + throw err; + } + + const text = await res.text(); + if (!res.ok) { + if (typeof formatHttpError === "function") { + throw new Error(formatHttpError(res.status, text)); + } + const data = safeJsonParse(text) || { error: text }; + throw new Error(`${label} failed: ${data.error_description || data.error || res.status}`); + } + + const data = safeJsonParse(text); + if (!data) { + throw new Error(`${label} invalid JSON: ${text.slice(0, 200)}`); + } + + return data; +} + +module.exports = { + isNonEmptyString, + safeJsonParse, + describeNetworkError, + resolveFetch, + postOAuthForm, +}; diff --git a/electron/bridges/onedriveAuthBridge.cjs b/electron/bridges/onedriveAuthBridge.cjs index 4b251ac32..04eef7d98 100644 --- a/electron/bridges/onedriveAuthBridge.cjs +++ b/electron/bridges/onedriveAuthBridge.cjs @@ -28,23 +28,13 @@ const REFRESH_REAUTH_ERROR_CODES = new Set([ "login_required", ]); -const isNonEmptyString = (v) => typeof v === "string" && v.trim().length > 0; - -const safeJsonParse = (text) => { - try { - return JSON.parse(text); - } catch { - return null; - } -}; - -const describeNetworkError = (err) => { - const msg = err?.message || String(err); - const cause = err?.cause; - const causeCode = cause?.code ? ` (${cause.code})` : ""; - const causeMsg = cause?.message ? `: ${cause.message}` : ""; - return `${msg}${causeCode}${causeMsg}`.trim(); -}; +const { + isNonEmptyString, + safeJsonParse, + describeNetworkError, + resolveFetch, + postOAuthForm, +} = require("./oauthHttpHelper.cjs"); const base64FromArrayBuffer = (buffer) => { return Buffer.from(buffer).toString("base64"); @@ -55,8 +45,7 @@ const base64FromArrayBuffer = (buffer) => { * @param {import('electron')=} electronModule */ function registerHandlers(ipcMain, electronModule) { - const fetchImpl = - electronModule?.net?.fetch ? electronModule.net.fetch.bind(electronModule.net) : fetch; + const fetchImpl = resolveFetch(electronModule); ipcMain.handle("netcatty:onedrive:oauth:exchange", async (_event, payload) => { const clientId = payload?.clientId; @@ -79,34 +68,10 @@ function registerHandlers(ipcMain, electronModule) { scope, }); - let res; - try { - res = await fetchImpl(ONEDRIVE_TOKEN_URL, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: body.toString(), - }); - } catch (err) { - throw new Error( - `OneDrive token exchange network error. Check your network/VPN and whether Microsoft services are reachable. (${describeNetworkError(err)})` - ); - } - - const text = await res.text(); - if (!res.ok) { - const data = safeJsonParse(text) || { error: text }; - throw new Error( - `OneDrive token exchange failed: ${data.error_description || data.error || res.status}` - ); - } - - const data = safeJsonParse(text); - if (!data) { - throw new Error(`OneDrive token exchange invalid JSON: ${text.slice(0, 200)}`); - } + const data = await postOAuthForm(fetchImpl, ONEDRIVE_TOKEN_URL, body, { + label: "OneDrive token exchange", + serviceLabel: "Microsoft services", + }); return { accessToken: data.access_token, @@ -132,38 +97,18 @@ function registerHandlers(ipcMain, electronModule) { scope, }); - let res; - try { - res = await fetchImpl(ONEDRIVE_TOKEN_URL, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }, - body: body.toString(), - }); - } catch (err) { - throw new Error( - `OneDrive token refresh network error. Check your network/VPN and whether Microsoft services are reachable. (${describeNetworkError(err)})` - ); - } - - const text = await res.text(); - if (!res.ok) { - const data = safeJsonParse(text) || { error: text }; - const reauthRequired = REFRESH_REAUTH_ERROR_CODES.has(data.error); - const description = data.error_description || data.error || res.status; - throw new Error( - reauthRequired + const data = await postOAuthForm(fetchImpl, ONEDRIVE_TOKEN_URL, body, { + label: "OneDrive token refresh", + serviceLabel: "Microsoft services", + formatHttpError: (status, text) => { + const parsed = safeJsonParse(text) || { error: text }; + const reauthRequired = REFRESH_REAUTH_ERROR_CODES.has(parsed.error); + const description = parsed.error_description || parsed.error || status; + return reauthRequired ? `${ONEDRIVE_REAUTH_REQUIRED_MARKER}: OneDrive session expired, please reconnect. (${description})` - : `OneDrive token refresh failed: ${description}` - ); - } - - const data = safeJsonParse(text); - if (!data) { - throw new Error(`OneDrive token refresh invalid JSON: ${text.slice(0, 200)}`); - } + : `OneDrive token refresh failed: ${description}`; + }, + }); return { accessToken: data.access_token, diff --git a/electron/bridges/portForwardingBridge.endpoint.test.cjs b/electron/bridges/portForwardingBridge.endpoint.test.cjs deleted file mode 100644 index 7e5ca4744..000000000 --- a/electron/bridges/portForwardingBridge.endpoint.test.cjs +++ /dev/null @@ -1,121 +0,0 @@ -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { - buildPortForwardEndpoint, - buildPortForwardEndpointFromStartPayload, -} = require("./portForwardingBridge.cjs"); -const { - buildConnectionReuseEndpoint, - buildEndpointKey, - normalizeEndpoint, -} = require("./sshConnectionPool.cjs"); - -const baseOptions = { - hostId: "pf-profile", - hostname: "pf-endpoint.test", - port: 22, - username: "alice", - authMethod: "key", - keyId: "pf-key", - privateKey: "PF_PRIVATE_SECRET", - publicKey: "ssh-ed25519 PF_PUBLIC_KEY", - passphrase: "PF_PASSPHRASE_SECRET", - identityFilePaths: ["/keys/pf"], - useSshAgent: true, - identityAgent: "/run/user/1000/pf-agent-a.sock", - identitiesOnly: true, - agentPublicKeys: ["ssh-ed25519 PF_AGENT_KEY_A"], - addKeysToAgent: "confirm", - useKeychain: true, - legacyAlgorithms: false, - skipEcdsaHostKey: false, - algorithmOverrides: { kex: ["curve25519-sha256"] }, - verifyHostKeys: true, - knownHosts: [{ - id: "kh-pf-endpoint", - hostname: "pf-endpoint.test", - port: 22, - keyType: "ssh-ed25519", - fingerprint: "SHA256:pf-endpoint-a", - publicKey: "ssh-ed25519 PF_KNOWN_HOST_KEY_A", - }], -}; - -function endpointKey(options = baseOptions) { - return buildEndpointKey(buildPortForwardEndpoint(options)); -} - -test("port-forward endpoint identity changes for every effective agent selection setting", () => { - const baseKey = endpointKey(); - const variants = [ - { identityAgent: "/run/user/1000/pf-agent-b.sock" }, - { identitiesOnly: false }, - { agentPublicKeys: ["ssh-ed25519 PF_AGENT_KEY_B"] }, - { addKeysToAgent: "yes" }, - { useKeychain: false }, - ]; - - for (const variant of variants) { - assert.notEqual(endpointKey({ ...baseOptions, ...variant }), baseKey); - } -}); - -test("port-forward endpoint identity changes for every effective algorithm setting", () => { - const baseKey = endpointKey(); - const variants = [ - { legacyAlgorithms: true }, - { skipEcdsaHostKey: true }, - { algorithmOverrides: { kex: ["diffie-hellman-group14-sha256"] } }, - ]; - - for (const variant of variants) { - assert.notEqual(endpointKey({ ...baseOptions, ...variant }), baseKey); - } -}); - -test("port-forward endpoint identity includes the effective known-host trust set", () => { - const baseKey = endpointKey(); - const rotatedKnownHosts = [{ - ...baseOptions.knownHosts[0], - fingerprint: "SHA256:pf-endpoint-b", - publicKey: "ssh-ed25519 PF_KNOWN_HOST_KEY_B", - }]; - - assert.notEqual(endpointKey({ ...baseOptions, knownHosts: rotatedKnownHosts }), baseKey); - assert.equal( - endpointKey(), - buildEndpointKey(buildConnectionReuseEndpoint(baseOptions, { sftpSudo: false })), - ); -}); - -test("port-forward endpoint normalizes to the common digest-only connection identity", () => { - const normalized = normalizeEndpoint(buildPortForwardEndpoint(baseOptions)); - const serialized = JSON.stringify(normalized); - - assert.ok(normalized?.authFingerprint); - for (const secret of [ - baseOptions.privateKey, - baseOptions.passphrase, - baseOptions.agentPublicKeys[0], - baseOptions.knownHosts[0].publicKey, - ]) { - assert.equal(serialized.includes(secret), false); - } -}); - -test("port-forward start identity uses the resolved keepalive policy", () => { - const payload = { - ...baseOptions, - resolvedKeepaliveInterval: 30, - resolvedKeepaliveCountMax: 10, - }; - assert.equal( - buildEndpointKey(buildPortForwardEndpointFromStartPayload(payload)), - buildEndpointKey(buildConnectionReuseEndpoint({ - ...baseOptions, - keepaliveInterval: 30, - keepaliveCountMax: 10, - })), - ); -}); diff --git a/electron/bridges/portForwardingBridge.lifecycle.test.cjs b/electron/bridges/portForwardingBridge.lifecycle.test.cjs new file mode 100644 index 000000000..fe0f30a36 --- /dev/null +++ b/electron/bridges/portForwardingBridge.lifecycle.test.cjs @@ -0,0 +1,487 @@ +"use strict"; + +// --- merged from portForwardingBridge.endpoint.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { + buildPortForwardEndpoint, + buildPortForwardEndpointFromStartPayload, +} = require("./portForwardingBridge.cjs"); +const { + buildConnectionReuseEndpoint, + buildEndpointKey, + normalizeEndpoint, +} = require("./sshConnectionPool.cjs"); + +const baseOptions = { + hostId: "pf-profile", + hostname: "pf-endpoint.test", + port: 22, + username: "alice", + authMethod: "key", + keyId: "pf-key", + privateKey: "PF_PRIVATE_SECRET", + publicKey: "ssh-ed25519 PF_PUBLIC_KEY", + passphrase: "PF_PASSPHRASE_SECRET", + identityFilePaths: ["/keys/pf"], + useSshAgent: true, + identityAgent: "/run/user/1000/pf-agent-a.sock", + identitiesOnly: true, + agentPublicKeys: ["ssh-ed25519 PF_AGENT_KEY_A"], + addKeysToAgent: "confirm", + useKeychain: true, + legacyAlgorithms: false, + skipEcdsaHostKey: false, + algorithmOverrides: { kex: ["curve25519-sha256"] }, + verifyHostKeys: true, + knownHosts: [{ + id: "kh-pf-endpoint", + hostname: "pf-endpoint.test", + port: 22, + keyType: "ssh-ed25519", + fingerprint: "SHA256:pf-endpoint-a", + publicKey: "ssh-ed25519 PF_KNOWN_HOST_KEY_A", + }], +}; + +function endpointKey(options = baseOptions) { + return buildEndpointKey(buildPortForwardEndpoint(options)); +} + +test("port-forward endpoint identity changes for every effective agent selection setting", () => { + const baseKey = endpointKey(); + const variants = [ + { identityAgent: "/run/user/1000/pf-agent-b.sock" }, + { identitiesOnly: false }, + { agentPublicKeys: ["ssh-ed25519 PF_AGENT_KEY_B"] }, + { addKeysToAgent: "yes" }, + { useKeychain: false }, + ]; + + for (const variant of variants) { + assert.notEqual(endpointKey({ ...baseOptions, ...variant }), baseKey); + } +}); + +test("port-forward endpoint identity changes for every effective algorithm setting", () => { + const baseKey = endpointKey(); + const variants = [ + { legacyAlgorithms: true }, + { skipEcdsaHostKey: true }, + { algorithmOverrides: { kex: ["diffie-hellman-group14-sha256"] } }, + ]; + + for (const variant of variants) { + assert.notEqual(endpointKey({ ...baseOptions, ...variant }), baseKey); + } +}); + +test("port-forward endpoint identity includes the effective known-host trust set", () => { + const baseKey = endpointKey(); + const rotatedKnownHosts = [{ + ...baseOptions.knownHosts[0], + fingerprint: "SHA256:pf-endpoint-b", + publicKey: "ssh-ed25519 PF_KNOWN_HOST_KEY_B", + }]; + + assert.notEqual(endpointKey({ ...baseOptions, knownHosts: rotatedKnownHosts }), baseKey); + assert.equal( + endpointKey(), + buildEndpointKey(buildConnectionReuseEndpoint(baseOptions, { sftpSudo: false })), + ); +}); + +test("port-forward endpoint normalizes to the common digest-only connection identity", () => { + const normalized = normalizeEndpoint(buildPortForwardEndpoint(baseOptions)); + const serialized = JSON.stringify(normalized); + + assert.ok(normalized?.authFingerprint); + for (const secret of [ + baseOptions.privateKey, + baseOptions.passphrase, + baseOptions.agentPublicKeys[0], + baseOptions.knownHosts[0].publicKey, + ]) { + assert.equal(serialized.includes(secret), false); + } +}); + +test("port-forward start identity uses the resolved keepalive policy", () => { + const payload = { + ...baseOptions, + resolvedKeepaliveInterval: 30, + resolvedKeepaliveCountMax: 10, + }; + assert.equal( + buildEndpointKey(buildPortForwardEndpointFromStartPayload(payload)), + buildEndpointKey(buildConnectionReuseEndpoint({ + ...baseOptions, + keepaliveInterval: 30, + keepaliveCountMax: 10, + })), + ); +}); +} + +// --- merged from portForwardingBridge.snapshot.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + publishTunnelStatus, + getPortForwardSnapshot, + subscribePortForwardRuntime, + unsubscribePortForwardRuntime, + cancelTunnel, + _resetPortForwardRuntimeMetaForTests: resetRuntimeMeta, + _seedPortForwardTunnelForTests: seedTunnel, + _clearPortForwardTunnelsForTests: clearTunnels, +} = require("./portForwardingBridge.cjs"); + +function createCapturingSender(onSend = () => {}, id = 1) { + return { + id, + isDestroyed: () => false, + send: (channel, payload) => onSend(channel, payload), + once() {}, + removeListener() {}, + }; +} + +test("snapshot exposes process epoch, revision, and rule-scoped records", () => { + resetRuntimeMeta(); + clearTunnels(); + const tunnelId = "snap-tunnel-1"; + const tunnel = { + ruleId: "rule-1", + status: "active", + subscribers: new Map(), + cleanupFailed: false, + }; + seedTunnel(tunnelId, tunnel); + + const before = getPortForwardSnapshot(); + assert.equal(typeof before.epoch, "string"); + assert.ok(before.epoch.length > 0); + assert.equal(before.records.length, 1); + assert.equal(before.records[0].ruleId, "rule-1"); + assert.equal(before.records[0].phase, "active"); + + publishTunnelStatus(tunnelId, tunnel, "error", "listener failed"); + const after = getPortForwardSnapshot(); + assert.equal(after.epoch, before.epoch); + assert.ok(after.revision > before.revision); + assert.equal(after.records[0].phase, "error"); + assert.equal(after.records[0].error, "listener failed"); + assert.equal(after.records[0].cleanupRequired, false); + + clearTunnels(); +}); + +test("subscribePortForwardRuntime returns snapshot and receives ordered events", () => { + resetRuntimeMeta(); + clearTunnels(); + const events = []; + const sender = createCapturingSender((channel, payload) => { + if (channel === "netcatty:portforward:runtime") events.push(payload); + }, 42); + + const snapshot = subscribePortForwardRuntime({ sender }); + assert.equal(typeof snapshot.epoch, "string"); + assert.equal(snapshot.revision, 0); + assert.deepEqual(snapshot.records, []); + + const tunnelId = "runtime-tunnel"; + const tunnel = { + ruleId: "rule-runtime", + status: "connecting", + subscribers: new Map([[sender.id, sender]]), + cleanupFailed: false, + }; + seedTunnel(tunnelId, tunnel); + publishTunnelStatus(tunnelId, tunnel, "active"); + + assert.equal(events.length, 1); + assert.equal(events[0].kind, "upsert"); + assert.equal(events[0].record.phase, "active"); + assert.equal(events[0].record.ruleId, "rule-runtime"); + assert.equal(events[0].revision, 1); + assert.equal(events[0].epoch, snapshot.epoch); + + unsubscribePortForwardRuntime({ sender }); + publishTunnelStatus(tunnelId, tunnel, "error", "boom"); + assert.equal(events.length, 1); + clearTunnels(); +}); + +test("successful cleanup publishes remove after inactive", async () => { + resetRuntimeMeta(); + clearTunnels(); + const events = []; + const sender = createCapturingSender((channel, payload) => { + if (channel === "netcatty:portforward:runtime") events.push(payload); + }, 7); + subscribePortForwardRuntime({ sender }); + + const tunnelId = "cleanup-tunnel"; + const tunnel = { + ruleId: "rule-cleanup", + status: "active", + subscribers: new Map(), + cleanupFailed: false, + cleanupInProgress: false, + }; + seedTunnel(tunnelId, tunnel); + + await cancelTunnel( + tunnelId, + tunnel, + (status, error) => publishTunnelStatus(tunnelId, tunnel, status, error), + { deleteEntry: true }, + ); + + assert.ok(events.some((event) => event.kind === "upsert" && event.record?.phase === "inactive")); + assert.ok(events.some((event) => event.kind === "remove" && event.tunnelId === tunnelId)); + assert.deepEqual(getPortForwardSnapshot().records, []); + unsubscribePortForwardRuntime({ sender }); + clearTunnels(); +}); +} + +// --- merged from portForwardingBridge.pipeLifecycle.test.cjs --- +{ +const assert = require("node:assert/strict"); +const { EventEmitter, once } = require("node:events"); +const net = require("node:net"); +const test = require("node:test"); + +const { + _bindPortForwardChannelsForTests: bindPortForwardChannels, + _attachTunnelPipeStreamForTests: attachTunnelPipeStream, + _clearPortForwardTunnelsForTests: clearPortForwardTunnels, + _destroyTunnelPipesForTests: destroyTunnelPipes, + _trackTunnelPipeForTests: trackTunnelPipe, + cancelTunnel, +} = require("./portForwardingBridge.cjs"); + +function fakeEndpoint() { + const endpoint = new EventEmitter(); + endpoint.destroyedByTest = false; + endpoint.destroyCalls = 0; + endpoint.destroy = () => { + endpoint.destroyCalls += 1; + endpoint.destroyedByTest = true; + }; + endpoint.end = () => { endpoint.destroyedByTest = true; }; + endpoint.close = () => { endpoint.destroyedByTest = true; }; + return endpoint; +} + +test("accepted sockets are tracked before forwardOut finishes and stop destroys them", () => { + const tunnel = { cancelled: false, activePipes: new Set() }; + const socket = fakeEndpoint(); + const entry = trackTunnelPipe(tunnel, socket); + assert.equal(tunnel.activePipes.size, 1); + + destroyTunnelPipes(tunnel); + assert.equal(socket.destroyedByTest, true); + assert.equal(entry.openAbortController, null); + assert.equal(tunnel.activePipes.size, 0); +}); + +test("client disconnect drops only its pending channel open", () => { + const tunnel = { cancelled: false, activePipes: new Set() }; + const socket = fakeEndpoint(); + const entry = trackTunnelPipe(tunnel, socket); + entry.openStarted = true; + let aborts = 0; + entry.openAbortController.signal.addEventListener("abort", () => { aborts += 1; }); + + socket.emit("close"); + + assert.equal(aborts, 0); + assert.equal(entry.closed, true); + assert.equal(entry.openAbortController.signal.aborted, false); + assert.equal(tunnel.activePipes.size, 1); + const destroyCalls = socket.destroyCalls; + + socket.emit("error", new Error("client closed")); + assert.equal(socket.destroyCalls, destroyCalls); + + destroyTunnelPipes(tunnel); + + assert.equal(aborts, 1); + assert.equal(tunnel.activePipes.size, 0); +}); + +test("a client disconnect does not close the local forwarding listener", async () => { + let finishForwardOut; + let transportEnds = 0; + let transportDestroys = 0; + const conn = new EventEmitter(); + conn.forwardOut = (_sourceAddress, _sourcePort, _targetAddress, _targetPort, callback) => { + finishForwardOut = callback; + }; + conn.end = () => { transportEnds += 1; }; + conn.destroy = () => { transportDestroys += 1; }; + const tunnel = { + tunnelId: "pf-client-disconnect", + cancelled: false, + activePipes: new Set(), + chainConnections: [], + sshTransportManaged: false, + }; + const sender = { id: 1, isDestroyed: () => false }; + + const started = await bindPortForwardChannels({ + type: "local", + conn, + tunnelId: tunnel.tunnelId, + tunnelState: tunnel, + sender, + bindAddress: "127.0.0.1", + localPort: 0, + remoteHost: "127.0.0.1", + remotePort: 22, + chainConnections: [], + sendStatus() {}, + }); + assert.equal(started.success, true); + + const client = net.connect(tunnel.server.address().port, "127.0.0.1"); + await once(client, "connect"); + client.destroy(); + await once(client, "close"); + assert.equal(tunnel.server.listening, true); + + finishForwardOut(new Error("client closed")); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(transportEnds, 0); + assert.equal(transportDestroys, 0); + + await new Promise((resolve, reject) => tunnel.server.close((error) => error ? reject(error) : resolve())); +}); + +test("a disconnected SOCKS client remains cancellable until its channel open settles", async () => { + let finishForwardOut; + let forwardOutStarted; + const conn = new EventEmitter(); + conn.forwardOut = (_sourceAddress, _sourcePort, _targetAddress, _targetPort, callback) => { + finishForwardOut = callback; + forwardOutStarted?.(); + }; + conn.end = () => {}; + conn.destroy = () => {}; + const tunnel = { + tunnelId: "pf-socks-client-disconnect", + cancelled: false, + activePipes: new Set(), + chainConnections: [], + sshTransportManaged: false, + }; + const sender = { id: 2, isDestroyed: () => false }; + + try { + const started = await bindPortForwardChannels({ + type: "dynamic", + conn, + tunnelId: tunnel.tunnelId, + tunnelState: tunnel, + sender, + bindAddress: "127.0.0.1", + localPort: 0, + remoteHost: "127.0.0.1", + remotePort: 22, + chainConnections: [], + sendStatus() {}, + }); + assert.equal(started.success, true); + + const client = net.connect(tunnel.server.address().port, "127.0.0.1"); + await once(client, "connect"); + client.write(Buffer.from([0x05, 0x01, 0x00])); + await once(client, "data"); + const channelStarted = new Promise((resolve) => { forwardOutStarted = resolve; }); + client.write(Buffer.from([0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0, 22])); + await channelStarted; + client.destroy(); + await once(client, "close"); + assert.equal(tunnel.server.listening, true); + assert.equal(tunnel.activePipes.size, 1); + + await cancelTunnel(tunnel.tunnelId, tunnel, () => {}); + assert.equal(tunnel.activePipes.size, 0); + } finally { + clearPortForwardTunnels(); + } +}); + +test("an invalid SOCKS client is removed before opening an SSH channel", async () => { + const conn = new EventEmitter(); + conn.end = () => {}; + conn.destroy = () => {}; + const tunnel = { + tunnelId: "pf-socks-invalid-client", + cancelled: false, + activePipes: new Set(), + chainConnections: [], + sshTransportManaged: false, + }; + const sender = { id: 3, isDestroyed: () => false }; + + try { + const started = await bindPortForwardChannels({ + type: "dynamic", + conn, + tunnelId: tunnel.tunnelId, + tunnelState: tunnel, + sender, + bindAddress: "127.0.0.1", + localPort: 0, + remoteHost: "127.0.0.1", + remotePort: 22, + chainConnections: [], + sendStatus() {}, + }); + assert.equal(started.success, true); + + const client = net.connect(tunnel.server.address().port, "127.0.0.1"); + await once(client, "connect"); + client.write(Buffer.from([0x04, 0x01, 0x00])); + await once(client, "close"); + assert.equal(tunnel.activePipes.size, 0); + assert.equal(tunnel.server.listening, true); + } finally { + await new Promise((resolve, reject) => tunnel.server.close((error) => error ? reject(error) : resolve())); + clearPortForwardTunnels(); + } +}); + +test("a late forwardOut stream after stop is rejected and destroyed", () => { + const tunnel = { cancelled: false, activePipes: new Set() }; + const socket = fakeEndpoint(); + const entry = trackTunnelPipe(tunnel, socket); + tunnel.cancelled = true; + const stream = fakeEndpoint(); + + assert.equal(attachTunnelPipeStream(tunnel, entry, stream), false); + assert.equal(socket.destroyedByTest, true); + assert.equal(stream.destroyedByTest, true); + assert.equal(tunnel.activePipes.size, 0); +}); + +test("closing either side tears down the paired endpoint and releases tracking", () => { + const tunnel = { cancelled: false, activePipes: new Set() }; + const socket = fakeEndpoint(); + const stream = fakeEndpoint(); + const entry = trackTunnelPipe(tunnel, socket); + assert.equal(attachTunnelPipeStream(tunnel, entry, stream), true); + + socket.emit("close"); + assert.equal(stream.destroyedByTest, true); + assert.equal(tunnel.activePipes.size, 0); +}); +} diff --git a/electron/bridges/portForwardingBridge.pipeLifecycle.test.cjs b/electron/bridges/portForwardingBridge.pipeLifecycle.test.cjs deleted file mode 100644 index d39a3c20b..000000000 --- a/electron/bridges/portForwardingBridge.pipeLifecycle.test.cjs +++ /dev/null @@ -1,231 +0,0 @@ -const assert = require("node:assert/strict"); -const { EventEmitter, once } = require("node:events"); -const net = require("node:net"); -const test = require("node:test"); - -const { - _bindPortForwardChannelsForTests: bindPortForwardChannels, - _attachTunnelPipeStreamForTests: attachTunnelPipeStream, - _clearPortForwardTunnelsForTests: clearPortForwardTunnels, - _destroyTunnelPipesForTests: destroyTunnelPipes, - _trackTunnelPipeForTests: trackTunnelPipe, - cancelTunnel, -} = require("./portForwardingBridge.cjs"); - -function fakeEndpoint() { - const endpoint = new EventEmitter(); - endpoint.destroyedByTest = false; - endpoint.destroyCalls = 0; - endpoint.destroy = () => { - endpoint.destroyCalls += 1; - endpoint.destroyedByTest = true; - }; - endpoint.end = () => { endpoint.destroyedByTest = true; }; - endpoint.close = () => { endpoint.destroyedByTest = true; }; - return endpoint; -} - -test("accepted sockets are tracked before forwardOut finishes and stop destroys them", () => { - const tunnel = { cancelled: false, activePipes: new Set() }; - const socket = fakeEndpoint(); - const entry = trackTunnelPipe(tunnel, socket); - assert.equal(tunnel.activePipes.size, 1); - - destroyTunnelPipes(tunnel); - assert.equal(socket.destroyedByTest, true); - assert.equal(entry.openAbortController, null); - assert.equal(tunnel.activePipes.size, 0); -}); - -test("client disconnect drops only its pending channel open", () => { - const tunnel = { cancelled: false, activePipes: new Set() }; - const socket = fakeEndpoint(); - const entry = trackTunnelPipe(tunnel, socket); - entry.openStarted = true; - let aborts = 0; - entry.openAbortController.signal.addEventListener("abort", () => { aborts += 1; }); - - socket.emit("close"); - - assert.equal(aborts, 0); - assert.equal(entry.closed, true); - assert.equal(entry.openAbortController.signal.aborted, false); - assert.equal(tunnel.activePipes.size, 1); - const destroyCalls = socket.destroyCalls; - - socket.emit("error", new Error("client closed")); - assert.equal(socket.destroyCalls, destroyCalls); - - destroyTunnelPipes(tunnel); - - assert.equal(aborts, 1); - assert.equal(tunnel.activePipes.size, 0); -}); - -test("a client disconnect does not close the local forwarding listener", async () => { - let finishForwardOut; - let transportEnds = 0; - let transportDestroys = 0; - const conn = new EventEmitter(); - conn.forwardOut = (_sourceAddress, _sourcePort, _targetAddress, _targetPort, callback) => { - finishForwardOut = callback; - }; - conn.end = () => { transportEnds += 1; }; - conn.destroy = () => { transportDestroys += 1; }; - const tunnel = { - tunnelId: "pf-client-disconnect", - cancelled: false, - activePipes: new Set(), - chainConnections: [], - sshTransportManaged: false, - }; - const sender = { id: 1, isDestroyed: () => false }; - - const started = await bindPortForwardChannels({ - type: "local", - conn, - tunnelId: tunnel.tunnelId, - tunnelState: tunnel, - sender, - bindAddress: "127.0.0.1", - localPort: 0, - remoteHost: "127.0.0.1", - remotePort: 22, - chainConnections: [], - sendStatus() {}, - }); - assert.equal(started.success, true); - - const client = net.connect(tunnel.server.address().port, "127.0.0.1"); - await once(client, "connect"); - client.destroy(); - await once(client, "close"); - assert.equal(tunnel.server.listening, true); - - finishForwardOut(new Error("client closed")); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(transportEnds, 0); - assert.equal(transportDestroys, 0); - - await new Promise((resolve, reject) => tunnel.server.close((error) => error ? reject(error) : resolve())); -}); - -test("a disconnected SOCKS client remains cancellable until its channel open settles", async () => { - let finishForwardOut; - let forwardOutStarted; - const conn = new EventEmitter(); - conn.forwardOut = (_sourceAddress, _sourcePort, _targetAddress, _targetPort, callback) => { - finishForwardOut = callback; - forwardOutStarted?.(); - }; - conn.end = () => {}; - conn.destroy = () => {}; - const tunnel = { - tunnelId: "pf-socks-client-disconnect", - cancelled: false, - activePipes: new Set(), - chainConnections: [], - sshTransportManaged: false, - }; - const sender = { id: 2, isDestroyed: () => false }; - - try { - const started = await bindPortForwardChannels({ - type: "dynamic", - conn, - tunnelId: tunnel.tunnelId, - tunnelState: tunnel, - sender, - bindAddress: "127.0.0.1", - localPort: 0, - remoteHost: "127.0.0.1", - remotePort: 22, - chainConnections: [], - sendStatus() {}, - }); - assert.equal(started.success, true); - - const client = net.connect(tunnel.server.address().port, "127.0.0.1"); - await once(client, "connect"); - client.write(Buffer.from([0x05, 0x01, 0x00])); - await once(client, "data"); - const channelStarted = new Promise((resolve) => { forwardOutStarted = resolve; }); - client.write(Buffer.from([0x05, 0x01, 0x00, 0x01, 127, 0, 0, 1, 0, 22])); - await channelStarted; - client.destroy(); - await once(client, "close"); - assert.equal(tunnel.server.listening, true); - assert.equal(tunnel.activePipes.size, 1); - - await cancelTunnel(tunnel.tunnelId, tunnel, () => {}); - assert.equal(tunnel.activePipes.size, 0); - } finally { - clearPortForwardTunnels(); - } -}); - -test("an invalid SOCKS client is removed before opening an SSH channel", async () => { - const conn = new EventEmitter(); - conn.end = () => {}; - conn.destroy = () => {}; - const tunnel = { - tunnelId: "pf-socks-invalid-client", - cancelled: false, - activePipes: new Set(), - chainConnections: [], - sshTransportManaged: false, - }; - const sender = { id: 3, isDestroyed: () => false }; - - try { - const started = await bindPortForwardChannels({ - type: "dynamic", - conn, - tunnelId: tunnel.tunnelId, - tunnelState: tunnel, - sender, - bindAddress: "127.0.0.1", - localPort: 0, - remoteHost: "127.0.0.1", - remotePort: 22, - chainConnections: [], - sendStatus() {}, - }); - assert.equal(started.success, true); - - const client = net.connect(tunnel.server.address().port, "127.0.0.1"); - await once(client, "connect"); - client.write(Buffer.from([0x04, 0x01, 0x00])); - await once(client, "close"); - assert.equal(tunnel.activePipes.size, 0); - assert.equal(tunnel.server.listening, true); - } finally { - await new Promise((resolve, reject) => tunnel.server.close((error) => error ? reject(error) : resolve())); - clearPortForwardTunnels(); - } -}); - -test("a late forwardOut stream after stop is rejected and destroyed", () => { - const tunnel = { cancelled: false, activePipes: new Set() }; - const socket = fakeEndpoint(); - const entry = trackTunnelPipe(tunnel, socket); - tunnel.cancelled = true; - const stream = fakeEndpoint(); - - assert.equal(attachTunnelPipeStream(tunnel, entry, stream), false); - assert.equal(socket.destroyedByTest, true); - assert.equal(stream.destroyedByTest, true); - assert.equal(tunnel.activePipes.size, 0); -}); - -test("closing either side tears down the paired endpoint and releases tracking", () => { - const tunnel = { cancelled: false, activePipes: new Set() }; - const socket = fakeEndpoint(); - const stream = fakeEndpoint(); - const entry = trackTunnelPipe(tunnel, socket); - assert.equal(attachTunnelPipeStream(tunnel, entry, stream), true); - - socket.emit("close"); - assert.equal(stream.destroyedByTest, true); - assert.equal(tunnel.activePipes.size, 0); -}); diff --git a/electron/bridges/portForwardingBridge.snapshot.test.cjs b/electron/bridges/portForwardingBridge.snapshot.test.cjs deleted file mode 100644 index 4991ec623..000000000 --- a/electron/bridges/portForwardingBridge.snapshot.test.cjs +++ /dev/null @@ -1,122 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { - publishTunnelStatus, - getPortForwardSnapshot, - subscribePortForwardRuntime, - unsubscribePortForwardRuntime, - cancelTunnel, - _resetPortForwardRuntimeMetaForTests: resetRuntimeMeta, - _seedPortForwardTunnelForTests: seedTunnel, - _clearPortForwardTunnelsForTests: clearTunnels, -} = require("./portForwardingBridge.cjs"); - -function createCapturingSender(onSend = () => {}, id = 1) { - return { - id, - isDestroyed: () => false, - send: (channel, payload) => onSend(channel, payload), - once() {}, - removeListener() {}, - }; -} - -test("snapshot exposes process epoch, revision, and rule-scoped records", () => { - resetRuntimeMeta(); - clearTunnels(); - const tunnelId = "snap-tunnel-1"; - const tunnel = { - ruleId: "rule-1", - status: "active", - subscribers: new Map(), - cleanupFailed: false, - }; - seedTunnel(tunnelId, tunnel); - - const before = getPortForwardSnapshot(); - assert.equal(typeof before.epoch, "string"); - assert.ok(before.epoch.length > 0); - assert.equal(before.records.length, 1); - assert.equal(before.records[0].ruleId, "rule-1"); - assert.equal(before.records[0].phase, "active"); - - publishTunnelStatus(tunnelId, tunnel, "error", "listener failed"); - const after = getPortForwardSnapshot(); - assert.equal(after.epoch, before.epoch); - assert.ok(after.revision > before.revision); - assert.equal(after.records[0].phase, "error"); - assert.equal(after.records[0].error, "listener failed"); - assert.equal(after.records[0].cleanupRequired, false); - - clearTunnels(); -}); - -test("subscribePortForwardRuntime returns snapshot and receives ordered events", () => { - resetRuntimeMeta(); - clearTunnels(); - const events = []; - const sender = createCapturingSender((channel, payload) => { - if (channel === "netcatty:portforward:runtime") events.push(payload); - }, 42); - - const snapshot = subscribePortForwardRuntime({ sender }); - assert.equal(typeof snapshot.epoch, "string"); - assert.equal(snapshot.revision, 0); - assert.deepEqual(snapshot.records, []); - - const tunnelId = "runtime-tunnel"; - const tunnel = { - ruleId: "rule-runtime", - status: "connecting", - subscribers: new Map([[sender.id, sender]]), - cleanupFailed: false, - }; - seedTunnel(tunnelId, tunnel); - publishTunnelStatus(tunnelId, tunnel, "active"); - - assert.equal(events.length, 1); - assert.equal(events[0].kind, "upsert"); - assert.equal(events[0].record.phase, "active"); - assert.equal(events[0].record.ruleId, "rule-runtime"); - assert.equal(events[0].revision, 1); - assert.equal(events[0].epoch, snapshot.epoch); - - unsubscribePortForwardRuntime({ sender }); - publishTunnelStatus(tunnelId, tunnel, "error", "boom"); - assert.equal(events.length, 1); - clearTunnels(); -}); - -test("successful cleanup publishes remove after inactive", async () => { - resetRuntimeMeta(); - clearTunnels(); - const events = []; - const sender = createCapturingSender((channel, payload) => { - if (channel === "netcatty:portforward:runtime") events.push(payload); - }, 7); - subscribePortForwardRuntime({ sender }); - - const tunnelId = "cleanup-tunnel"; - const tunnel = { - ruleId: "rule-cleanup", - status: "active", - subscribers: new Map(), - cleanupFailed: false, - cleanupInProgress: false, - }; - seedTunnel(tunnelId, tunnel); - - await cancelTunnel( - tunnelId, - tunnel, - (status, error) => publishTunnelStatus(tunnelId, tunnel, status, error), - { deleteEntry: true }, - ); - - assert.ok(events.some((event) => event.kind === "upsert" && event.record?.phase === "inactive")); - assert.ok(events.some((event) => event.kind === "remove" && event.tunnelId === tunnelId)); - assert.deepEqual(getPortForwardSnapshot().records, []); - unsubscribePortForwardRuntime({ sender }); - clearTunnels(); -}); diff --git a/electron/bridges/sftpBridge.cleanup.test.cjs b/electron/bridges/sftpBridge.cleanup.test.cjs index 63c0037ec..990170636 100644 --- a/electron/bridges/sftpBridge.cleanup.test.cjs +++ b/electron/bridges/sftpBridge.cleanup.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from sftpBridge.cleanup.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const { EventEmitter } = require("node:events"); @@ -574,3 +578,180 @@ test("single-channel directory delete does not open a shell exec", async () => { assert.equal(removed, false); assert.equal(execCalls, 0); }); +} + +// --- merged from sftpBridge.ownerCleanup.test.cjs --- +{ +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const test = require("node:test"); + +const { + _createRendererSftpOwnershipForTests: createRendererSftpOwnership, + init, + registerHandlers, +} = require("./sftpBridge.cjs"); + +function sender(id) { + const value = new EventEmitter(); + value.id = id; + value.isDestroyed = () => value.destroyed === true; + value.destroyed = false; + value.destroy = () => { + value.destroyed = true; + value.emit("destroyed"); + }; + return value; +} + +function registerWorkerHandlers(request, reportOpenedSessionActivity) { + const handlers = new Map(); + init({ + electronModule: null, + reportOpenedSessionActivity, + sessions: new Map(), + sftpClients: new Map(), + }); + registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }, { + terminalWorkerManager: { request }, + }); + return handlers; +} + +test("destroying a renderer closes every SFTP handle it opened", async () => { + const closed = []; + const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); + const owner = sender(1); + await ownership.run("netcatty:sftp:open", { sender: owner }, {}, async () => ({ sftpId: "sftp-1" })); + + owner.destroy(); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(closed, ["sftp-1"]); +}); + +test("an SFTP open that finishes after renderer destruction is closed immediately", async () => { + const closed = []; + const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); + const owner = sender(2); + let finishOpen; + const pending = ownership.run("netcatty:sftp:open", { sender: owner }, {}, () => ( + new Promise((resolve) => { finishOpen = resolve; }) + )); + + owner.destroy(); + finishOpen({ sftpId: "sftp-late" }); + await pending; + assert.deepEqual(closed, ["sftp-late"]); +}); + +test("an explicitly closed SFTP handle is not closed again on renderer destruction", async () => { + const closed = []; + const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); + const owner = sender(3); + await ownership.run("netcatty:sftp:open", { sender: owner }, {}, async () => ({ sftpId: "sftp-3" })); + await ownership.run( + "netcatty:sftp:close", + { sender: owner }, + { sftpId: "sftp-3" }, + async () => ({ success: true }), + ); + + owner.destroy(); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(closed, []); +}); + +test("renderer destruction does not close an SFTP handle again while explicit close is pending", async () => { + const ownerCleanupCloses = []; + const ownership = createRendererSftpOwnership(async (sftpId) => { + ownerCleanupCloses.push(sftpId); + }); + const owner = sender(31); + await ownership.run( + "netcatty:sftp:open", + { sender: owner }, + {}, + async () => ({ sftpId: "sftp-pending-close" }), + ); + let finishExplicitClose; + let explicitCloseCalls = 0; + const explicitClose = ownership.run( + "netcatty:sftp:close", + { sender: owner }, + { sftpId: "sftp-pending-close" }, + () => { + explicitCloseCalls += 1; + return new Promise((resolve) => { finishExplicitClose = resolve; }); + }, + ); + + owner.destroy(); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(ownerCleanupCloses, []); + + finishExplicitClose({ success: true }); + await explicitClose; + assert.equal(explicitCloseCalls, 1); + assert.deepEqual(ownerCleanupCloses, []); +}); + +test("renderer destruction removes the source-session association for its SFTP handle", async () => { + const activity = []; + const closed = []; + const handlers = registerWorkerHandlers(async (channel, payload) => { + if (channel === "netcatty:sftp:openForSession") return { sftpId: "sftp-owned" }; + if (channel === "netcatty:sftp:close") closed.push(payload.sftpId); + return { success: true }; + }, (event) => activity.push(event)); + const owner = sender(4); + + await handlers.get("netcatty:sftp:openForSession")( + { sender: owner }, + { sessionId: "terminal-source" }, + ); + owner.destroy(); + await new Promise((resolve) => setImmediate(resolve)); + + activity.length = 0; + await handlers.get("netcatty:sftp:list")( + { sender: sender(40) }, + { sftpId: "sftp-owned", path: "/" }, + ); + assert.deepEqual(closed, ["sftp-owned"]); + assert.deepEqual(activity, []); +}); + +test("a late SFTP open does not restore its destroyed renderer source-session association", async () => { + const activity = []; + const closed = []; + let finishOpen; + const handlers = registerWorkerHandlers((channel, payload) => { + if (channel === "netcatty:sftp:openForSession") { + return new Promise((resolve) => { finishOpen = resolve; }); + } + if (channel === "netcatty:sftp:close") closed.push(payload.sftpId); + return Promise.resolve({ success: true }); + }, (event) => activity.push(event)); + const owner = sender(5); + + const pending = handlers.get("netcatty:sftp:openForSession")( + { sender: owner }, + { sessionId: "terminal-late-source" }, + ); + owner.destroy(); + finishOpen({ sftpId: "sftp-late-owned" }); + await pending; + + activity.length = 0; + await handlers.get("netcatty:sftp:list")( + { sender: sender(50) }, + { sftpId: "sftp-late-owned", path: "/" }, + ); + assert.deepEqual(closed, ["sftp-late-owned"]); + assert.deepEqual(activity, []); +}); +} diff --git a/electron/bridges/sftpBridge.fallback.test.cjs b/electron/bridges/sftpBridge.fallback.test.cjs deleted file mode 100644 index 9933bb624..000000000 --- a/electron/bridges/sftpBridge.fallback.test.cjs +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const { EventEmitter } = require("node:events"); -const test = require("node:test"); -const bridge = require("./sftpBridge.cjs"); - -for (const loggerThrows of [false, true]) { - test(`Auto fallback reports the channel failure; loggerThrows=${loggerThrows}`, async () => { - const failure = Object.assign(new Error("subsystem request rejected"), { code: "CHANNEL_OPEN_FAILURE" }); - const reports = []; - const conn = { - sftp(callback) { callback(failure); }, - exec(command, callback) { - const stream = new EventEmitter(); - stream.stderr = new EventEmitter(); - stream.close = () => {}; - callback(null, stream); - queueMicrotask(() => { - if (!command.includes("command -v scp")) { - stream.emit("data", Buffer.from("RAW:/home/test\n")); - } - stream.emit("close", 0); - }); - }, - }; - bridge.init({ - electronModule: { webContents: { fromId: () => null } }, - sessions: new Map([["fallback-session", { conn }]]), - sftpClients: new Map(), - reportSuppressedError(...args) { - reports.push(args); - if (loggerThrows) throw new Error("logger unavailable"); - }, - }); - const opened = await bridge.openSftpForSession(null, { sessionId: "fallback-session" }); - try { - assert.equal(opened.fileProtocol, "scp"); - assert.equal(reports.length, 1); - assert.equal(reports[0][0], "sftpBridge.openSftpForSession"); - assert.equal(reports[0][1], failure); - assert.match(reports[0][2], /fallback-session.*SCP mode \(auto\)/); - } finally { - await bridge.closeSftp(null, { sftpId: opened.sftpId }); - } - }); -} diff --git a/electron/bridges/sftpBridge.operations.test.cjs b/electron/bridges/sftpBridge.operations.test.cjs new file mode 100644 index 000000000..d426ebed0 --- /dev/null +++ b/electron/bridges/sftpBridge.operations.test.cjs @@ -0,0 +1,438 @@ +"use strict"; + +// --- merged from sftpBridge.fallback.test.cjs --- +{ +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const test = require("node:test"); +const bridge = require("./sftpBridge.cjs"); + +for (const loggerThrows of [false, true]) { + test(`Auto fallback reports the channel failure; loggerThrows=${loggerThrows}`, async () => { + const failure = Object.assign(new Error("subsystem request rejected"), { code: "CHANNEL_OPEN_FAILURE" }); + const reports = []; + const conn = { + sftp(callback) { callback(failure); }, + exec(command, callback) { + const stream = new EventEmitter(); + stream.stderr = new EventEmitter(); + stream.close = () => {}; + callback(null, stream); + queueMicrotask(() => { + if (!command.includes("command -v scp")) { + stream.emit("data", Buffer.from("RAW:/home/test\n")); + } + stream.emit("close", 0); + }); + }, + }; + bridge.init({ + electronModule: { webContents: { fromId: () => null } }, + sessions: new Map([["fallback-session", { conn }]]), + sftpClients: new Map(), + reportSuppressedError(...args) { + reports.push(args); + if (loggerThrows) throw new Error("logger unavailable"); + }, + }); + const opened = await bridge.openSftpForSession(null, { sessionId: "fallback-session" }); + try { + assert.equal(opened.fileProtocol, "scp"); + assert.equal(reports.length, 1); + assert.equal(reports[0][0], "sftpBridge.openSftpForSession"); + assert.equal(reports[0][1], failure); + assert.match(reports[0][2], /fallback-session.*SCP mode \(auto\)/); + } finally { + await bridge.closeSftp(null, { sftpId: opened.sftpId }); + } + }); +} +} + +// --- merged from sftpBridge.sessionActivity.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const sftpBridge = require("./sftpBridge.cjs"); + +test("renderer SFTP operations keep their source terminal session active", async () => { + const handlers = new Map(); + const activity = []; + const requests = []; + const ipcMain = { + handle(channel, handler) { + handlers.set(channel, handler); + }, + }; + const terminalWorkerManager = { + async request(channel, payload) { + requests.push({ channel, payload }); + if (channel === "netcatty:sftp:openForSession") { + return { sftpId: "sftp-1", sourceSessionId: "terminal-2" }; + } + if (channel === "netcatty:sftp:list") return []; + if (channel === "netcatty:sftp:close") return { ok: true }; + throw new Error(`Unexpected channel: ${channel}`); + }, + }; + sftpBridge.init({ + sessions: new Map(), + sftpClients: new Map(), + electronModule: {}, + reportOpenedSessionActivity: (event) => activity.push(event), + }); + sftpBridge.registerHandlers(ipcMain, { terminalWorkerManager }); + const event = { sender: { id: 7 } }; + + await handlers.get("netcatty:sftp:openForSession")(event, { sessionId: "terminal-1" }); + await handlers.get("netcatty:sftp:list")(event, { sftpId: "sftp-1", path: "/tmp" }); + await handlers.get("netcatty:sftp:close")(event, { sftpId: "sftp-1" }); + + assert.deepEqual(requests.map((entry) => entry.channel), [ + "netcatty:sftp:openForSession", + "netcatty:sftp:list", + "netcatty:sftp:close", + ]); + assert.deepEqual(activity, [ + { sessionId: "terminal-1", phase: "begin" }, + { sessionId: "terminal-2", phase: "touch" }, + { sessionId: "terminal-1", phase: "end" }, + { sessionId: "terminal-2", phase: "begin" }, + { sessionId: "terminal-2", phase: "end" }, + { sessionId: "terminal-2", phase: "begin" }, + { sessionId: "terminal-2", phase: "end" }, + ]); +}); +} + +// --- merged from sftpBridge.relativePaths.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const sftpBridge = require("./sftpBridge.cjs"); + +function createSftpChannel(existingPaths = []) { + const existing = new Set(existingPaths); + const calls = { + mkdir: [], + realpath: [], + rmdir: [], + stat: [], + }; + const channel = { + readdir(_targetPath, callback) { + callback(null, []); + }, + stat(targetPath, callback) { + calls.stat.push(targetPath); + if (existing.has(targetPath)) { + callback(null, { isDirectory: () => true }); + return; + } + const error = new Error(`No such file: ${targetPath}`); + error.code = 2; + callback(error); + }, + mkdir(targetPath, callback) { + calls.mkdir.push(targetPath); + existing.add(targetPath); + callback(null); + }, + rmdir(targetPath, callback) { + calls.rmdir.push(targetPath); + existing.delete(targetPath); + callback(null); + }, + unlink(_targetPath, callback) { + callback(null); + }, + realpath(targetPath, callback) { + calls.realpath.push(targetPath); + callback(null, targetPath === ".." ? "/home" : "/home/alice"); + }, + }; + return { calls, channel }; +} + +test("mkdir preserves hidden relative names and resolves explicit dot segments", async () => { + const { calls, channel } = createSftpChannel(["/home", "/home/alice"]); + const client = { + sftp: channel, + realPath: (targetPath) => new Promise((resolve, reject) => { + channel.realpath(targetPath, (error, resolvedPath) => ( + error ? reject(error) : resolve(resolvedPath) + )); + }), + }; + sftpBridge.init({ + electronModule: {}, + sessions: new Map(), + sftpClients: new Map([["mkdir-test", client]]), + }); + + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: ".config/app", + encoding: "utf-8", + }); + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: "..staging/cache", + encoding: "utf-8", + }); + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: "./logs", + encoding: "utf-8", + }); + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: "../shared", + encoding: "utf-8", + }); + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: ".\\windows-logs", + encoding: "utf-8", + }); + await sftpBridge.mkdirSftp(null, { + sftpId: "mkdir-test", + path: "..\\windows-shared", + encoding: "utf-8", + }); + + assert.deepEqual(calls.realpath, [".", "..", ".", ".."]); + assert.deepEqual(calls.mkdir, [ + ".config", + ".config/app", + "..staging", + "..staging/cache", + "/home/alice/logs", + "/home/shared", + "/home/alice/windows-logs", + "/home/windows-shared", + ]); +}); + +test("session-backed recursive delete preserves a hidden directory name", async () => { + const { calls, channel } = createSftpChannel([".cache"]); + const connection = { + sftp(callback) { + callback(null, channel); + }, + }; + const sftpClients = new Map(); + sftpBridge.init({ + electronModule: {}, + sessions: new Map([["session-1", { conn: connection }]]), + sftpClients, + }); + const opened = await sftpBridge.openSftpForSession(null, { sessionId: "session-1" }); + + await sftpBridge.deleteSftp(null, { + sftpId: opened.sftpId, + path: ".cache", + encoding: "utf-8", + }); + + assert.deepEqual(calls.realpath, []); + assert.deepEqual(calls.rmdir, [".cache"]); +}); +} + +// --- merged from sftpBridge.readLimit.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { Readable } = require("node:stream"); +const { EventEmitter } = require("node:events"); + +const { createFileOpsApi } = require("./sftpBridge/fileOps.cjs"); + +const MAX_IN_MEMORY_READ_BYTES = 10 * 1024 * 1024; + +function createApi(client, overrides = {}) { + return createFileOpsApi({ + sftpClients: new Map([["sftp-1", client]]), + resolveEncodingForRequest: () => "utf-8", + encodePath: (value) => value, + Buffer, + ...overrides, + }); +} + +test("SFTP text reads reject oversized files before opening the data stream", async () => { + let streamOpened = false; + const sftp = { + createReadStream() { + streamOpened = true; + throw new Error("oversized file stream should not open"); + }, + }; + const api = createApi({}, { + requireSftpChannel: async () => sftp, + statAsync: async () => ({ size: MAX_IN_MEMORY_READ_BYTES + 1 }), + }); + + await assert.rejects( + api.readSftp(null, { sftpId: "sftp-1", path: "/large.log" }), + /10 MB.*download.*external app/i, + ); + assert.equal(streamOpened, false); +}); + +test("SFTP text reads still stream ordinary files", async () => { + const sftp = { + createReadStream() { + return Readable.from([Buffer.from("hel"), Buffer.from("lo")]); + }, + }; + const api = createApi({}, { + requireSftpChannel: async () => sftp, + statAsync: async () => ({ size: 5 }), + }); + + assert.equal( + await api.readSftp(null, { sftpId: "sftp-1", path: "/small.txt" }), + "hello", + ); +}); + +test("SFTP binary reads reject oversized files before opening the data stream", async () => { + let streamOpened = false; + const sftp = { + createReadStream() { + streamOpened = true; + throw new Error("oversized file stream should not open"); + }, + }; + const api = createApi({}, { + requireSftpChannel: async () => sftp, + statAsync: async () => ({ size: MAX_IN_MEMORY_READ_BYTES + 1 }), + }); + + await assert.rejects( + api.readSftpBinary(null, { sftpId: "sftp-1", path: "/large.bin" }), + /10 MB.*download.*external app/i, + ); + assert.equal(streamOpened, false); +}); + +test("SFTP reads stop at the byte limit when the remote file grows after stat", async () => { + let legacyGetCalled = false; + const stream = Readable.from([ + Buffer.alloc(MAX_IN_MEMORY_READ_BYTES), + Buffer.from("x"), + ]); + const sftp = { + createReadStream() { + return stream; + }, + }; + const api = createApi({ + async get() { + legacyGetCalled = true; + return Buffer.alloc(MAX_IN_MEMORY_READ_BYTES + 1); + }, + }, { + requireSftpChannel: async () => sftp, + statAsync: async () => ({ size: 1 }), + }); + + await assert.rejects( + api.readSftp(null, { sftpId: "sftp-1", path: "/growing.log" }), + /10 MB.*download.*external app/i, + ); + assert.equal(legacyGetCalled, false); + assert.equal(stream.destroyed, true); + assert.equal(stream.listenerCount("data"), 0); + assert.equal(stream.listenerCount("end"), 0); + assert.equal(stream.listenerCount("error"), 0); + assert.equal(stream.listenerCount("close"), 0); +}); + +test("SCP reads reject oversized files before starting the transfer", async () => { + let readStarted = false; + const backend = { + async stat() { + return { size: MAX_IN_MEMORY_READ_BYTES + 1 }; + }, + async readFile() { + readStarted = true; + throw new Error("oversized SCP transfer should not start"); + }, + }; + const api = createApi({ + __netcattyFileProtocol: "scp", + __netcattyScpBackend: backend, + }); + + await assert.rejects( + api.readSftp(null, { sftpId: "sftp-1", path: "/large.log" }), + /10 MB.*download.*external app/i, + ); + assert.equal(readStarted, false); +}); + +test("the total in-memory SFTP read deadline also bounds a stalled stat", async () => { + const api = createApi({}, { + requireSftpChannel: async () => ({}), + statAsync: async () => new Promise(() => {}), + }); + + await assert.rejects( + Promise.race([ + api.readSftp(null, { sftpId: "sftp-1", path: "/stalled.txt", timeoutMs: 5 }), + new Promise((_, reject) => setTimeout(() => reject(new Error("test watchdog")), 100)), + ]), + /SFTP in-memory read timed out/i, + ); +}); + +test("a timed-out in-memory SFTP stream is destroyed and releases every listener", async () => { + const stream = new EventEmitter(); + let destroyed = 0; + stream.destroy = () => { destroyed += 1; }; + stream.close = () => { destroyed += 1; }; + const api = createApi({}, { + requireSftpChannel: async () => ({ createReadStream: () => stream }), + statAsync: async () => ({ size: 1 }), + }); + + await assert.rejects( + Promise.race([ + api.readSftpBinary(null, { sftpId: "sftp-1", path: "/stalled.bin", timeoutMs: 5 }), + new Promise((_, reject) => setTimeout(() => reject(new Error("test watchdog")), 100)), + ]), + /SFTP in-memory read timed out/i, + ); + assert.ok(destroyed > 0); + assert.equal(stream.listenerCount("data"), 0); + assert.equal(stream.listenerCount("end"), 0); + assert.equal(stream.listenerCount("error"), 0); + assert.equal(stream.listenerCount("close"), 0); +}); + +test("in-memory SFTP stream error and premature close both release listeners", async () => { + for (const terminalEvent of ["error", "close"]) { + const stream = new EventEmitter(); + stream.destroy = () => {}; + stream.close = () => {}; + const api = createApi({}, { + requireSftpChannel: async () => ({ createReadStream: () => stream }), + statAsync: async () => ({ size: 1 }), + }); + const reading = api.readSftp(null, { sftpId: "sftp-1", path: "/broken.txt", timeoutMs: 100 }); + process.nextTick(() => { + if (terminalEvent === "error") stream.emit("error", new Error("read failed")); + else stream.emit("close"); + }); + await assert.rejects(reading, /read failed|closed before/i); + assert.equal(stream.listenerCount("data"), 0); + assert.equal(stream.listenerCount("end"), 0); + assert.equal(stream.listenerCount("error"), 0); + assert.equal(stream.listenerCount("close"), 0); + } +}); +} diff --git a/electron/bridges/sftpBridge.ownerCleanup.test.cjs b/electron/bridges/sftpBridge.ownerCleanup.test.cjs deleted file mode 100644 index 9ef6ffb98..000000000 --- a/electron/bridges/sftpBridge.ownerCleanup.test.cjs +++ /dev/null @@ -1,172 +0,0 @@ -const assert = require("node:assert/strict"); -const { EventEmitter } = require("node:events"); -const test = require("node:test"); - -const { - _createRendererSftpOwnershipForTests: createRendererSftpOwnership, - init, - registerHandlers, -} = require("./sftpBridge.cjs"); - -function sender(id) { - const value = new EventEmitter(); - value.id = id; - value.isDestroyed = () => value.destroyed === true; - value.destroyed = false; - value.destroy = () => { - value.destroyed = true; - value.emit("destroyed"); - }; - return value; -} - -function registerWorkerHandlers(request, reportOpenedSessionActivity) { - const handlers = new Map(); - init({ - electronModule: null, - reportOpenedSessionActivity, - sessions: new Map(), - sftpClients: new Map(), - }); - registerHandlers({ - handle(channel, handler) { - handlers.set(channel, handler); - }, - }, { - terminalWorkerManager: { request }, - }); - return handlers; -} - -test("destroying a renderer closes every SFTP handle it opened", async () => { - const closed = []; - const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); - const owner = sender(1); - await ownership.run("netcatty:sftp:open", { sender: owner }, {}, async () => ({ sftpId: "sftp-1" })); - - owner.destroy(); - await new Promise((resolve) => setImmediate(resolve)); - assert.deepEqual(closed, ["sftp-1"]); -}); - -test("an SFTP open that finishes after renderer destruction is closed immediately", async () => { - const closed = []; - const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); - const owner = sender(2); - let finishOpen; - const pending = ownership.run("netcatty:sftp:open", { sender: owner }, {}, () => ( - new Promise((resolve) => { finishOpen = resolve; }) - )); - - owner.destroy(); - finishOpen({ sftpId: "sftp-late" }); - await pending; - assert.deepEqual(closed, ["sftp-late"]); -}); - -test("an explicitly closed SFTP handle is not closed again on renderer destruction", async () => { - const closed = []; - const ownership = createRendererSftpOwnership(async (sftpId) => { closed.push(sftpId); }); - const owner = sender(3); - await ownership.run("netcatty:sftp:open", { sender: owner }, {}, async () => ({ sftpId: "sftp-3" })); - await ownership.run( - "netcatty:sftp:close", - { sender: owner }, - { sftpId: "sftp-3" }, - async () => ({ success: true }), - ); - - owner.destroy(); - await new Promise((resolve) => setImmediate(resolve)); - assert.deepEqual(closed, []); -}); - -test("renderer destruction does not close an SFTP handle again while explicit close is pending", async () => { - const ownerCleanupCloses = []; - const ownership = createRendererSftpOwnership(async (sftpId) => { - ownerCleanupCloses.push(sftpId); - }); - const owner = sender(31); - await ownership.run( - "netcatty:sftp:open", - { sender: owner }, - {}, - async () => ({ sftpId: "sftp-pending-close" }), - ); - let finishExplicitClose; - let explicitCloseCalls = 0; - const explicitClose = ownership.run( - "netcatty:sftp:close", - { sender: owner }, - { sftpId: "sftp-pending-close" }, - () => { - explicitCloseCalls += 1; - return new Promise((resolve) => { finishExplicitClose = resolve; }); - }, - ); - - owner.destroy(); - await new Promise((resolve) => setImmediate(resolve)); - assert.deepEqual(ownerCleanupCloses, []); - - finishExplicitClose({ success: true }); - await explicitClose; - assert.equal(explicitCloseCalls, 1); - assert.deepEqual(ownerCleanupCloses, []); -}); - -test("renderer destruction removes the source-session association for its SFTP handle", async () => { - const activity = []; - const closed = []; - const handlers = registerWorkerHandlers(async (channel, payload) => { - if (channel === "netcatty:sftp:openForSession") return { sftpId: "sftp-owned" }; - if (channel === "netcatty:sftp:close") closed.push(payload.sftpId); - return { success: true }; - }, (event) => activity.push(event)); - const owner = sender(4); - - await handlers.get("netcatty:sftp:openForSession")( - { sender: owner }, - { sessionId: "terminal-source" }, - ); - owner.destroy(); - await new Promise((resolve) => setImmediate(resolve)); - - activity.length = 0; - await handlers.get("netcatty:sftp:list")( - { sender: sender(40) }, - { sftpId: "sftp-owned", path: "/" }, - ); - assert.deepEqual(closed, ["sftp-owned"]); - assert.deepEqual(activity, []); -}); - -test("a late SFTP open does not restore its destroyed renderer source-session association", async () => { - const activity = []; - const closed = []; - let finishOpen; - const handlers = registerWorkerHandlers((channel, payload) => { - if (channel === "netcatty:sftp:openForSession") { - return new Promise((resolve) => { finishOpen = resolve; }); - } - if (channel === "netcatty:sftp:close") closed.push(payload.sftpId); - return Promise.resolve({ success: true }); - }, (event) => activity.push(event)); - const owner = sender(5); - - const pending = handlers.get("netcatty:sftp:openForSession")( - { sender: owner }, - { sessionId: "terminal-late-source" }, - ); - owner.destroy(); - finishOpen({ sftpId: "sftp-late-owned" }); - await pending; - - activity.length = 0; - await handlers.get("netcatty:sftp:list")( - { sender: sender(50) }, - { sftpId: "sftp-late-owned", path: "/" }, - ); - assert.deepEqual(closed, ["sftp-late-owned"]); - assert.deepEqual(activity, []); -}); diff --git a/electron/bridges/sftpBridge.readLimit.test.cjs b/electron/bridges/sftpBridge.readLimit.test.cjs deleted file mode 100644 index f401b07b6..000000000 --- a/electron/bridges/sftpBridge.readLimit.test.cjs +++ /dev/null @@ -1,194 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); -const { Readable } = require("node:stream"); -const { EventEmitter } = require("node:events"); - -const { createFileOpsApi } = require("./sftpBridge/fileOps.cjs"); - -const MAX_IN_MEMORY_READ_BYTES = 10 * 1024 * 1024; - -function createApi(client, overrides = {}) { - return createFileOpsApi({ - sftpClients: new Map([["sftp-1", client]]), - resolveEncodingForRequest: () => "utf-8", - encodePath: (value) => value, - Buffer, - ...overrides, - }); -} - -test("SFTP text reads reject oversized files before opening the data stream", async () => { - let streamOpened = false; - const sftp = { - createReadStream() { - streamOpened = true; - throw new Error("oversized file stream should not open"); - }, - }; - const api = createApi({}, { - requireSftpChannel: async () => sftp, - statAsync: async () => ({ size: MAX_IN_MEMORY_READ_BYTES + 1 }), - }); - - await assert.rejects( - api.readSftp(null, { sftpId: "sftp-1", path: "/large.log" }), - /10 MB.*download.*external app/i, - ); - assert.equal(streamOpened, false); -}); - -test("SFTP text reads still stream ordinary files", async () => { - const sftp = { - createReadStream() { - return Readable.from([Buffer.from("hel"), Buffer.from("lo")]); - }, - }; - const api = createApi({}, { - requireSftpChannel: async () => sftp, - statAsync: async () => ({ size: 5 }), - }); - - assert.equal( - await api.readSftp(null, { sftpId: "sftp-1", path: "/small.txt" }), - "hello", - ); -}); - -test("SFTP binary reads reject oversized files before opening the data stream", async () => { - let streamOpened = false; - const sftp = { - createReadStream() { - streamOpened = true; - throw new Error("oversized file stream should not open"); - }, - }; - const api = createApi({}, { - requireSftpChannel: async () => sftp, - statAsync: async () => ({ size: MAX_IN_MEMORY_READ_BYTES + 1 }), - }); - - await assert.rejects( - api.readSftpBinary(null, { sftpId: "sftp-1", path: "/large.bin" }), - /10 MB.*download.*external app/i, - ); - assert.equal(streamOpened, false); -}); - -test("SFTP reads stop at the byte limit when the remote file grows after stat", async () => { - let legacyGetCalled = false; - const stream = Readable.from([ - Buffer.alloc(MAX_IN_MEMORY_READ_BYTES), - Buffer.from("x"), - ]); - const sftp = { - createReadStream() { - return stream; - }, - }; - const api = createApi({ - async get() { - legacyGetCalled = true; - return Buffer.alloc(MAX_IN_MEMORY_READ_BYTES + 1); - }, - }, { - requireSftpChannel: async () => sftp, - statAsync: async () => ({ size: 1 }), - }); - - await assert.rejects( - api.readSftp(null, { sftpId: "sftp-1", path: "/growing.log" }), - /10 MB.*download.*external app/i, - ); - assert.equal(legacyGetCalled, false); - assert.equal(stream.destroyed, true); - assert.equal(stream.listenerCount("data"), 0); - assert.equal(stream.listenerCount("end"), 0); - assert.equal(stream.listenerCount("error"), 0); - assert.equal(stream.listenerCount("close"), 0); -}); - -test("SCP reads reject oversized files before starting the transfer", async () => { - let readStarted = false; - const backend = { - async stat() { - return { size: MAX_IN_MEMORY_READ_BYTES + 1 }; - }, - async readFile() { - readStarted = true; - throw new Error("oversized SCP transfer should not start"); - }, - }; - const api = createApi({ - __netcattyFileProtocol: "scp", - __netcattyScpBackend: backend, - }); - - await assert.rejects( - api.readSftp(null, { sftpId: "sftp-1", path: "/large.log" }), - /10 MB.*download.*external app/i, - ); - assert.equal(readStarted, false); -}); - -test("the total in-memory SFTP read deadline also bounds a stalled stat", async () => { - const api = createApi({}, { - requireSftpChannel: async () => ({}), - statAsync: async () => new Promise(() => {}), - }); - - await assert.rejects( - Promise.race([ - api.readSftp(null, { sftpId: "sftp-1", path: "/stalled.txt", timeoutMs: 5 }), - new Promise((_, reject) => setTimeout(() => reject(new Error("test watchdog")), 100)), - ]), - /SFTP in-memory read timed out/i, - ); -}); - -test("a timed-out in-memory SFTP stream is destroyed and releases every listener", async () => { - const stream = new EventEmitter(); - let destroyed = 0; - stream.destroy = () => { destroyed += 1; }; - stream.close = () => { destroyed += 1; }; - const api = createApi({}, { - requireSftpChannel: async () => ({ createReadStream: () => stream }), - statAsync: async () => ({ size: 1 }), - }); - - await assert.rejects( - Promise.race([ - api.readSftpBinary(null, { sftpId: "sftp-1", path: "/stalled.bin", timeoutMs: 5 }), - new Promise((_, reject) => setTimeout(() => reject(new Error("test watchdog")), 100)), - ]), - /SFTP in-memory read timed out/i, - ); - assert.ok(destroyed > 0); - assert.equal(stream.listenerCount("data"), 0); - assert.equal(stream.listenerCount("end"), 0); - assert.equal(stream.listenerCount("error"), 0); - assert.equal(stream.listenerCount("close"), 0); -}); - -test("in-memory SFTP stream error and premature close both release listeners", async () => { - for (const terminalEvent of ["error", "close"]) { - const stream = new EventEmitter(); - stream.destroy = () => {}; - stream.close = () => {}; - const api = createApi({}, { - requireSftpChannel: async () => ({ createReadStream: () => stream }), - statAsync: async () => ({ size: 1 }), - }); - const reading = api.readSftp(null, { sftpId: "sftp-1", path: "/broken.txt", timeoutMs: 100 }); - process.nextTick(() => { - if (terminalEvent === "error") stream.emit("error", new Error("read failed")); - else stream.emit("close"); - }); - await assert.rejects(reading, /read failed|closed before/i); - assert.equal(stream.listenerCount("data"), 0); - assert.equal(stream.listenerCount("end"), 0); - assert.equal(stream.listenerCount("error"), 0); - assert.equal(stream.listenerCount("close"), 0); - } -}); diff --git a/electron/bridges/sftpBridge.relativePaths.test.cjs b/electron/bridges/sftpBridge.relativePaths.test.cjs deleted file mode 100644 index 60250698c..000000000 --- a/electron/bridges/sftpBridge.relativePaths.test.cjs +++ /dev/null @@ -1,132 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const sftpBridge = require("./sftpBridge.cjs"); - -function createSftpChannel(existingPaths = []) { - const existing = new Set(existingPaths); - const calls = { - mkdir: [], - realpath: [], - rmdir: [], - stat: [], - }; - const channel = { - readdir(_targetPath, callback) { - callback(null, []); - }, - stat(targetPath, callback) { - calls.stat.push(targetPath); - if (existing.has(targetPath)) { - callback(null, { isDirectory: () => true }); - return; - } - const error = new Error(`No such file: ${targetPath}`); - error.code = 2; - callback(error); - }, - mkdir(targetPath, callback) { - calls.mkdir.push(targetPath); - existing.add(targetPath); - callback(null); - }, - rmdir(targetPath, callback) { - calls.rmdir.push(targetPath); - existing.delete(targetPath); - callback(null); - }, - unlink(_targetPath, callback) { - callback(null); - }, - realpath(targetPath, callback) { - calls.realpath.push(targetPath); - callback(null, targetPath === ".." ? "/home" : "/home/alice"); - }, - }; - return { calls, channel }; -} - -test("mkdir preserves hidden relative names and resolves explicit dot segments", async () => { - const { calls, channel } = createSftpChannel(["/home", "/home/alice"]); - const client = { - sftp: channel, - realPath: (targetPath) => new Promise((resolve, reject) => { - channel.realpath(targetPath, (error, resolvedPath) => ( - error ? reject(error) : resolve(resolvedPath) - )); - }), - }; - sftpBridge.init({ - electronModule: {}, - sessions: new Map(), - sftpClients: new Map([["mkdir-test", client]]), - }); - - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: ".config/app", - encoding: "utf-8", - }); - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: "..staging/cache", - encoding: "utf-8", - }); - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: "./logs", - encoding: "utf-8", - }); - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: "../shared", - encoding: "utf-8", - }); - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: ".\\windows-logs", - encoding: "utf-8", - }); - await sftpBridge.mkdirSftp(null, { - sftpId: "mkdir-test", - path: "..\\windows-shared", - encoding: "utf-8", - }); - - assert.deepEqual(calls.realpath, [".", "..", ".", ".."]); - assert.deepEqual(calls.mkdir, [ - ".config", - ".config/app", - "..staging", - "..staging/cache", - "/home/alice/logs", - "/home/shared", - "/home/alice/windows-logs", - "/home/windows-shared", - ]); -}); - -test("session-backed recursive delete preserves a hidden directory name", async () => { - const { calls, channel } = createSftpChannel([".cache"]); - const connection = { - sftp(callback) { - callback(null, channel); - }, - }; - const sftpClients = new Map(); - sftpBridge.init({ - electronModule: {}, - sessions: new Map([["session-1", { conn: connection }]]), - sftpClients, - }); - const opened = await sftpBridge.openSftpForSession(null, { sessionId: "session-1" }); - - await sftpBridge.deleteSftp(null, { - sftpId: opened.sftpId, - path: ".cache", - encoding: "utf-8", - }); - - assert.deepEqual(calls.realpath, []); - assert.deepEqual(calls.rmdir, [".cache"]); -}); diff --git a/electron/bridges/sftpBridge.sessionActivity.test.cjs b/electron/bridges/sftpBridge.sessionActivity.test.cjs deleted file mode 100644 index 898b394b1..000000000 --- a/electron/bridges/sftpBridge.sessionActivity.test.cjs +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); -const sftpBridge = require("./sftpBridge.cjs"); - -test("renderer SFTP operations keep their source terminal session active", async () => { - const handlers = new Map(); - const activity = []; - const requests = []; - const ipcMain = { - handle(channel, handler) { - handlers.set(channel, handler); - }, - }; - const terminalWorkerManager = { - async request(channel, payload) { - requests.push({ channel, payload }); - if (channel === "netcatty:sftp:openForSession") { - return { sftpId: "sftp-1", sourceSessionId: "terminal-2" }; - } - if (channel === "netcatty:sftp:list") return []; - if (channel === "netcatty:sftp:close") return { ok: true }; - throw new Error(`Unexpected channel: ${channel}`); - }, - }; - sftpBridge.init({ - sessions: new Map(), - sftpClients: new Map(), - electronModule: {}, - reportOpenedSessionActivity: (event) => activity.push(event), - }); - sftpBridge.registerHandlers(ipcMain, { terminalWorkerManager }); - const event = { sender: { id: 7 } }; - - await handlers.get("netcatty:sftp:openForSession")(event, { sessionId: "terminal-1" }); - await handlers.get("netcatty:sftp:list")(event, { sftpId: "sftp-1", path: "/tmp" }); - await handlers.get("netcatty:sftp:close")(event, { sftpId: "sftp-1" }); - - assert.deepEqual(requests.map((entry) => entry.channel), [ - "netcatty:sftp:openForSession", - "netcatty:sftp:list", - "netcatty:sftp:close", - ]); - assert.deepEqual(activity, [ - { sessionId: "terminal-1", phase: "begin" }, - { sessionId: "terminal-2", phase: "touch" }, - { sessionId: "terminal-1", phase: "end" }, - { sessionId: "terminal-2", phase: "begin" }, - { sessionId: "terminal-2", phase: "end" }, - { sessionId: "terminal-2", phase: "begin" }, - { sessionId: "terminal-2", phase: "end" }, - ]); -}); diff --git a/electron/bridges/sftpBridge/archiveCreate.test.cjs b/electron/bridges/sftpBridge/archiveCreate.test.cjs deleted file mode 100644 index f7e7bd68d..000000000 --- a/electron/bridges/sftpBridge/archiveCreate.test.cjs +++ /dev/null @@ -1,258 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const test = require("node:test"); -const { - validateArchiveCreateOptions, - buildCreateArchiveCommand, - parseCreateArchiveResult, -} = require("./archiveCreate.cjs"); - -const posix = process.platform !== "win32"; -const baseOptions = { directory: "/tmp/example", paths: ["file"], archiveName: "bundle.tar.gz", format: "tar.gz" }; - -function fixture(t) { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-archive-create-")); - t.after(() => fs.rmSync(directory, { recursive: true, force: true })); - return directory; -} - -function execute(options, env = {}) { - return spawnSync("/bin/sh", ["-c", buildCreateArchiveCommand(options)], { - encoding: "utf8", - timeout: 20_000, - env: { ...process.env, ...env }, - }); -} - -function assertNoStaging(directory) { - assert.deepEqual(fs.readdirSync(directory).filter((entry) => entry.startsWith(".netcatty-archive.")), []); -} - -function executablePath(name) { - const result = spawnSync("/bin/sh", ["-c", `command -v ${name}`], { encoding: "utf8" }); - assert.equal(result.status, 0, `Missing test prerequisite ${name}`); - return result.stdout.trim(); -} - -function writeTool(directory, name, body) { - const bin = path.join(directory, "bin"); - fs.mkdirSync(bin, { recursive: true }); - fs.writeFileSync(path.join(bin, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 }); - return `${bin}${path.delimiter}${process.env.PATH}`; -} - -test("archive sources are relative, bounded, deduplicated and cannot contain the output", () => { - assert.deepEqual(validateArchiveCreateOptions({ ...baseOptions, paths: ["dir/child", "dir", "./other", "other"] }).paths, ["dir", "other"]); - for (const paths of [[], ["."], ["dir/.."], ["../file"], ["/file"], ["dir/../../file"], ["bundle.tar.gz"], ["bundle.tar.gz/file"], ["bad\\name"], ["bad\nname"], ["bad\0name"]]) { - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, paths })); - } - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, paths: Array(1001).fill("file") })); - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, directory: "." })); - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, overwrite: "yes" })); -}); - -test("archive names are simple names matching an explicitly allowed format", () => { - for (const archiveName of ["", ".", "..", ".tar.gz", "../x.tar.gz", "sub/x.tar.gz", "sub\\x.tar.gz", "a\n.tar.gz", "x.zip"]) { - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, archiveName })); - } - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, format: "rar" })); - assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, format: "zip", archiveName: ".zip" })); - assert.doesNotThrow(() => validateArchiveCreateOptions({ ...baseOptions, archiveName: "-quoted ' $(touch nope).tar.gz" })); -}); - -test("the remote result must contain a completion marker, with a distinct conflict result", () => { - assert.deepEqual(parseCreateArchiveResult("banner\nNETCATTY_ARCHIVE_RESULT:OK\n"), { success: true }); - assert.equal(parseCreateArchiveResult("NETCATTY_ARCHIVE_RESULT:EEXIST\n").code, "EEXIST"); - assert.throws(() => parseCreateArchiveResult(""), /did not confirm/); - assert.throws(() => parseCreateArchiveResult("ordinary output"), /did not confirm/); -}); - -test("GB18030 paths use the existing encoded shell quoting", () => { - const command = buildCreateArchiveCommand({ ...baseOptions, paths: ["\u6d4b\u8bd5.txt"] }, { encoding: "gb18030" }); - const iconv = require("iconv-lite"); - assert.ok(command.includes(iconv.encode("./\u6d4b\u8bd5.txt", "gb18030").toString("base64"))); - assert.ok(command.includes("base64 -d")); - assert.ok(!command.includes("\u6d4b\u8bd5.txt")); -}); - -for (const format of ["tar.gz", "zip"]) { - test(`${format}: real archive round trip preserves selected files, folders and symlinks`, { skip: !posix }, (t) => { - const directory = fixture(t); - const names = ["simple.txt", "space ' quote.txt", "$(touch HACKED).txt", "`touch HACKED2`.txt", "-option", "literal*.txt", "[abc].txt", "\u4e2d\u6587.txt"]; - for (const name of names) fs.writeFileSync(path.join(directory, name), `contents of ${name}`); - fs.writeFileSync(path.join(directory, "literal-other.txt"), "unselected"); - fs.writeFileSync(path.join(directory, "a.txt"), "unselected"); - fs.mkdirSync(path.join(directory, "folder", "empty"), { recursive: true }); - fs.writeFileSync(path.join(directory, "folder", "nested.txt"), "nested data"); - fs.mkdirSync(path.join(directory, "tree")); - fs.writeFileSync(path.join(directory, "tree", "selected.txt"), "nested selection"); - fs.writeFileSync(path.join(directory, "tree", "excluded.txt"), "not selected"); - fs.symlinkSync(".", path.join(directory, "loop")); - fs.symlinkSync("missing-target", path.join(directory, "broken")); - const archiveName = `-backup ' quoted.${format}`; - const result = execute({ directory, paths: [...names, "folder", "folder/nested.txt", "tree/selected.txt", "loop", "broken"], archiveName, format }); - assert.equal(result.status, 0, result.stderr); - assert.deepEqual(parseCreateArchiveResult(result.stdout), { success: true }); - const output = path.join(directory, "unpacked"); - fs.mkdirSync(output); - const unpack = format === "zip" - ? spawnSync("unzip", ["-q", path.join(directory, archiveName), "-d", output], { encoding: "utf8" }) - : spawnSync("tar", ["-xzf", path.join(directory, archiveName), "-C", output], { encoding: "utf8" }); - assert.equal(unpack.status, 0, unpack.stderr); - for (const name of names) { - assert.equal(fs.readFileSync(path.join(output, name), "utf8"), `contents of ${name}`); - assert.equal(fs.readFileSync(path.join(directory, name), "utf8"), `contents of ${name}`); - } - assert.equal(fs.readFileSync(path.join(output, "folder", "nested.txt"), "utf8"), "nested data"); - assert.ok(fs.statSync(path.join(output, "folder", "empty")).isDirectory()); - assert.equal(fs.readFileSync(path.join(output, "tree", "selected.txt"), "utf8"), "nested selection"); - for (const missing of ["literal-other.txt", "a.txt", "tree/excluded.txt", "HACKED", "HACKED2", archiveName]) { - assert.equal(fs.existsSync(path.join(output, missing)), false, missing); - } - assert.equal(fs.readlinkSync(path.join(output, "loop")), "."); - assert.equal(fs.readlinkSync(path.join(output, "broken")), "missing-target"); - assert.equal(fs.existsSync(path.join(directory, "HACKED")), false); - assert.equal(fs.existsSync(path.join(directory, "HACKED2")), false); - assertNoStaging(directory); - }); -} - -test("existing output requires confirmation; confirmed replacement leaves original inputs intact", { skip: !posix }, (t) => { - const directory = fixture(t); - const options = { ...baseOptions, directory }; - fs.writeFileSync(path.join(directory, "file"), "source"); - fs.writeFileSync(path.join(directory, options.archiveName), "old archive"); - const conflict = execute(options); - assert.equal(conflict.status, 0, conflict.stderr); - assert.equal(parseCreateArchiveResult(conflict.stdout).code, "EEXIST"); - assert.equal(fs.readFileSync(path.join(directory, options.archiveName), "utf8"), "old archive"); - const replacement = execute({ ...options, overwrite: true }); - assert.equal(replacement.status, 0, replacement.stderr); - assert.deepEqual(parseCreateArchiveResult(replacement.stdout), { success: true }); - assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); - const listed = spawnSync("tar", ["-tzf", path.join(directory, options.archiveName)], { encoding: "utf8" }); - assert.equal(listed.status, 0, listed.stderr); - assert.match(listed.stdout, /file/); - assertNoStaging(directory); -}); - -test("directories and symbolic-link outputs are never overwritten", { skip: !posix }, (t) => { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - fs.writeFileSync(path.join(directory, "important"), "untouched"); - fs.mkdirSync(path.join(directory, "directory.tar.gz")); - fs.symlinkSync("important", path.join(directory, "symlink.tar.gz")); - fs.symlinkSync("missing", path.join(directory, "broken.tar.gz")); - for (const archiveName of ["directory.tar.gz", "symlink.tar.gz", "broken.tar.gz"]) { - const result = execute({ ...baseOptions, directory, archiveName, overwrite: true }); - assert.notEqual(result.status, 0); - assert.match(result.stderr, /regular file/); - } - assert.equal(fs.readFileSync(path.join(directory, "important"), "utf8"), "untouched"); - assert.equal(fs.readlinkSync(path.join(directory, "symlink.tar.gz")), "important"); - assertNoStaging(directory); -}); - -test("a nested tree selection cannot traverse a symbolic link", { skip: !posix }, (t) => { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - fs.symlinkSync(".", path.join(directory, "loop")); - const result = execute({ ...baseOptions, directory, paths: ["loop/file"] }); - assert.notEqual(result.status, 0); - assert.match(result.stderr, /traverses a symbolic link/); - assert.equal(fs.existsSync(path.join(directory, baseOptions.archiveName)), false); -}); - -test("an output that aliases a selected source cannot be replaced", { skip: !posix }, (t) => { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - fs.linkSync(path.join(directory, "file"), path.join(directory, baseOptions.archiveName)); - const result = execute({ ...baseOptions, directory, overwrite: true }); - assert.notEqual(result.status, 0); - assert.match(result.stderr, /refers to a selected source/); - assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); - assert.equal(fs.readFileSync(path.join(directory, baseOptions.archiveName), "utf8"), "source"); - assertNoStaging(directory); -}); - -test("missing tools and missing inputs fail without creating an output", { skip: !posix }, (t) => { - const directory = fixture(t); - const missing = execute({ ...baseOptions, directory }); - assert.notEqual(missing.status, 0); - assert.match(missing.stderr, /source no longer exists/); - fs.writeFileSync(path.join(directory, "file"), "source"); - for (const format of ["tar.gz", "zip"]) { - const noTool = execute({ ...baseOptions, directory, archiveName: `bundle.${format}`, format }, { PATH: directory }); - assert.notEqual(noTool.status, 0); - assert.match(noTool.stderr, /(?:tar|zip) is not installed/); - } - assert.equal(fs.existsSync(path.join(directory, baseOptions.archiveName)), false); - assertNoStaging(directory); -}); - -test("compression and publication failures preserve the previous archive and clean staging", { skip: !posix }, (t) => { - for (const tool of ["tar", "zip", "mv"]) { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - const format = tool === "zip" ? "zip" : "tar.gz"; - const archiveName = `bundle.${format}`; - fs.writeFileSync(path.join(directory, archiveName), "old archive"); - const envPath = writeTool(directory, tool, "echo 'intentional failure' >&2\nexit 9"); - const result = execute({ ...baseOptions, directory, archiveName, format, overwrite: true }, { PATH: envPath }); - assert.notEqual(result.status, 0); - assert.equal(fs.readFileSync(path.join(directory, archiveName), "utf8"), "old archive"); - assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); - assertNoStaging(directory); - } -}); - -test("unreadable nested files fail the real tools instead of publishing a partial archive", { - skip: !posix || process.getuid?.() === 0, -}, (t) => { - for (const format of ["tar.gz", "zip"]) { - const directory = fixture(t); - fs.mkdirSync(path.join(directory, "folder")); - fs.writeFileSync(path.join(directory, "folder", "readable"), "readable data"); - const unreadable = path.join(directory, "folder", "unreadable"); - fs.writeFileSync(unreadable, "protected data", { mode: 0o000 }); - t.after(() => { try { fs.chmodSync(unreadable, 0o600); } catch { /* fixture may already be removed */ } }); - const archiveName = `bundle.${format}`; - fs.writeFileSync(path.join(directory, archiveName), "previous archive"); - const result = execute({ directory, paths: ["folder"], archiveName, format, overwrite: true }); - assert.notEqual(result.status, 0, `${format} must report unreadable input`); - assert.equal(fs.readFileSync(path.join(directory, archiveName), "utf8"), "previous archive"); - assertNoStaging(directory); - } -}); - -test("a competing creator immediately before publication cannot be overwritten", { skip: !posix }, (t) => { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - const realLn = executablePath("ln"); - const envPath = writeTool(directory, "ln", `printf 'competing archive' > './bundle.tar.gz'\nexec '${realLn}' "$@"`); - const result = execute({ ...baseOptions, directory }, { PATH: envPath }); - assert.equal(result.status, 0, result.stderr); - assert.equal(parseCreateArchiveResult(result.stdout).code, "EEXIST"); - assert.equal(fs.readFileSync(path.join(directory, baseOptions.archiveName), "utf8"), "competing archive"); - assertNoStaging(directory); -}); - -test("publication never redirects into a directory or directory symlink created concurrently", { skip: !posix }, (t) => { - for (const symlink of [false, true]) { - const directory = fixture(t); - fs.writeFileSync(path.join(directory, "file"), "source"); - fs.mkdirSync(path.join(directory, "other")); - const realLn = executablePath("ln"); - const setup = symlink ? `'${realLn}' -s other bundle.tar.gz` : "mkdir bundle.tar.gz"; - const envPath = writeTool(directory, "ln", `${setup}\nexec '${realLn}' "$@"`); - const result = execute({ ...baseOptions, directory }, { PATH: envPath }); - assert.notEqual(result.status, 0); - assert.deepEqual(fs.readdirSync(path.join(directory, symlink ? "other" : "bundle.tar.gz")), []); - assertNoStaging(directory); - } -}); diff --git a/electron/bridges/sftpBridge/archiveExtract.test.cjs b/electron/bridges/sftpBridge/archiveExtract.test.cjs deleted file mode 100644 index 9032e1f94..000000000 --- a/electron/bridges/sftpBridge/archiveExtract.test.cjs +++ /dev/null @@ -1,188 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { - getArchiveKind, - isExtractableArchive, - posixParentDir, - stripCompressionSuffix, - computeExtractTimeoutMs, - buildExtractCommand, - buildLocalExtractPlan, - EXTRACT_MAX_TIMEOUT_MS, -} = require("./archiveExtract.cjs"); - -test("detects compound archive suffixes before single-file compression", () => { - assert.equal(getArchiveKind("backup.tar.gz"), "tar.gz"); - assert.equal(getArchiveKind("/var/a.tgz"), "tar.gz"); - assert.equal(getArchiveKind("logs.tar.bz2"), "tar.bz2"); - assert.equal(getArchiveKind("src.tar.xz"), "tar.xz"); - assert.equal(getArchiveKind("app.tar"), "tar"); - assert.equal(getArchiveKind("payload.zip"), "zip"); - assert.equal(getArchiveKind("notes.txt.gz"), "gz"); - assert.equal(getArchiveKind("notes.txt"), null); - assert.equal(getArchiveKind(".gz"), null); - assert.equal(isExtractableArchive("bundle.tgz"), true); - assert.equal(isExtractableArchive("readme.md"), false); -}); - -test("posix parent and gzip output stay in the archive directory", () => { - assert.equal(posixParentDir("/home/app/a.tar.gz"), "/home/app"); - assert.equal(posixParentDir("/a.zip"), "/"); - assert.equal(stripCompressionSuffix("/home/app/notes.txt.gz", "gz"), "/home/app/notes.txt"); - assert.equal(stripCompressionSuffix("/notes.txt.gz", "gz"), "/notes.txt"); -}); - -test("extract commands quote spaces and single quotes", () => { - const tarCmd = buildExtractCommand("/tmp/my files/app's.tgz"); - assert.match(tarCmd, /tar -xzf '/); - assert.match(tarCmd, /'\/tmp\/my files\/app'\\''s\.tgz'/); - assert.match(tarCmd, /-C '\/tmp\/my files'/); - - const zipCmd = buildExtractCommand("/opt/build/out.zip"); - assert.match(zipCmd, /unzip -qo '\/opt\/build\/out\.zip' -d '\/opt\/build' >\/dev\/null/); - assert.match(zipCmd, /tar -xf '\/opt\/build\/out\.zip' -C '\/opt\/build'/); - - const gzCmd = buildExtractCommand("/var/log/syslog.gz"); - assert.match(gzCmd, /out='\/var\/log\/syslog'/); - assert.match(gzCmd, /archive='\/var\/log\/syslog\.gz'/); - assert.match(gzCmd, /trap 'rm -f -- "\$stage"' EXIT/); - assert.match(gzCmd, /gzip -dc -- "\$archive" > "\$stage"/); - assert.match(gzCmd, /if \[ -d "\$out" \]/); - assert.match(gzCmd, /mv -f -- "\$stage" "\$out"/); - - const spacedGz = buildExtractCommand("/tmp/my file.txt.gz"); - assert.match(spacedGz, /out='\/tmp\/my file\.txt'/); - assert.match(spacedGz, /archive='\/tmp\/my file\.txt\.gz'/); - assert.doesNotMatch(spacedGz, /trap 'rm -f -- '/); -}); - -test("generated gzip extract script can install its EXIT trap with spaces in the path", () => { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - const { spawnSync } = require("node:child_process"); - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-trap-")); - const archive = path.join(dir, "my file.txt.gz"); - fs.writeFileSync(archive, "x"); - const cmd = buildExtractCommand(archive); - const prefix = []; - for (const line of cmd.split("\n")) { - prefix.push(line); - if (line.startsWith("trap ")) break; - } - prefix.push("trap - EXIT"); - prefix.push("rm -f -- \"$stage\""); - const ran = spawnSync("sh", ["-c", prefix.join("\n")], { encoding: "utf8" }); - assert.equal(ran.status, 0, ran.stderr); - fs.rmSync(dir, { recursive: true, force: true }); -}); - -test("extract command rejects newlines and unknown types", () => { - assert.throws(() => buildExtractCommand("/tmp/bad\n.tar.gz"), /NUL or newlines/); - assert.throws(() => buildExtractCommand("/tmp/notes.txt"), /Unsupported archive type/); -}); - -test("local extract plan uses unzip with tar fallback off Windows", () => { - const unixZip = buildLocalExtractPlan("/tmp/a.zip", "linux"); - assert.deepEqual(unixZip.command, "unzip"); - assert.deepEqual(unixZip.args, ["-qo", "/tmp/a.zip", "-d", "/tmp"]); - assert.deepEqual(unixZip.fallback, { command: "tar", args: ["-xf", "/tmp/a.zip", "-C", "/tmp"] }); - - const winZip = buildLocalExtractPlan("C:\\tmp\\a.zip", "win32"); - assert.equal(winZip.command, "tar"); - assert.ok(winZip.args.includes("-xf")); - - const gz = buildLocalExtractPlan("/tmp/notes.txt.gz", "win32"); - assert.equal(gz.builtin, "gunzip"); - assert.equal(gz.archivePath, "/tmp/notes.txt.gz"); - assert.equal(gz.stdoutFile, "/tmp/notes.txt"); -}); - -test("unknown archive size uses the maximum extract timeout", () => { - assert.equal(computeExtractTimeoutMs(undefined), EXTRACT_MAX_TIMEOUT_MS); - assert.ok(computeExtractTimeoutMs(1024) < EXTRACT_MAX_TIMEOUT_MS); -}); - -test("extractLocalArchiveFile unpacks a tar.gz next to the archive", async () => { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - const { spawnSync } = require("node:child_process"); - const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-")); - const source = path.join(dir, "hello.txt"); - const archive = path.join(dir, "hello.tgz"); - fs.writeFileSync(source, "hello-extract"); - const packed = spawnSync("tar", ["-czf", archive, "-C", dir, "hello.txt"], { encoding: "utf8" }); - assert.equal(packed.status, 0, packed.stderr); - fs.unlinkSync(source); - - await extractLocalArchiveFile(archive); - assert.equal(fs.readFileSync(source, "utf8"), "hello-extract"); - fs.rmSync(dir, { recursive: true, force: true }); -}); - -test("failed gzip extract leaves an existing sibling file intact", async () => { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-keep-")); - const dest = path.join(dir, "notes.txt"); - const archive = path.join(dir, "notes.txt.gz"); - fs.writeFileSync(dest, "keep-me"); - fs.writeFileSync(archive, "this-is-not-gzip"); - - await assert.rejects(() => extractLocalArchiveFile(archive), /Local extraction failed/); - assert.equal(fs.readFileSync(dest, "utf8"), "keep-me"); - assert.deepEqual( - fs.readdirSync(dir).filter((name) => name.includes(".netcatty-extract")), - [], - ); - fs.rmSync(dir, { recursive: true, force: true }); -}); - -test("extractLocalArchiveFile gunzips with Node zlib and keeps a sibling staging name", async () => { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - const zlib = require("node:zlib"); - const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-gz-")); - const dest = path.join(dir, "notes.txt"); - const archive = path.join(dir, "notes.txt.gz"); - const sibling = `${dest}.netcatty-extract`; - fs.writeFileSync(sibling, "do-not-touch"); - fs.writeFileSync(archive, zlib.gzipSync("hello-gzip")); - - await extractLocalArchiveFile(archive); - assert.equal(fs.readFileSync(dest, "utf8"), "hello-gzip"); - assert.equal(fs.readFileSync(sibling, "utf8"), "do-not-touch"); - fs.rmSync(dir, { recursive: true, force: true }); -}); - -test("failed gzip extract leaves a sibling directory target intact", async () => { - const fs = require("node:fs"); - const os = require("node:os"); - const path = require("node:path"); - const zlib = require("node:zlib"); - const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); - - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-dir-")); - const dest = path.join(dir, "notes.txt"); - const archive = path.join(dir, "notes.txt.gz"); - fs.mkdirSync(dest); - fs.writeFileSync(path.join(dest, "keep.txt"), "inside"); - fs.writeFileSync(archive, zlib.gzipSync("hello-gzip")); - - await assert.rejects(() => extractLocalArchiveFile(archive), /directory/); - assert.equal(fs.readFileSync(path.join(dest, "keep.txt"), "utf8"), "inside"); - fs.rmSync(dir, { recursive: true, force: true }); -}); diff --git a/electron/bridges/sftpBridge/archives.test.cjs b/electron/bridges/sftpBridge/archives.test.cjs new file mode 100644 index 000000000..0b905c841 --- /dev/null +++ b/electron/bridges/sftpBridge/archives.test.cjs @@ -0,0 +1,771 @@ +"use strict"; + +// --- merged from archiveCreate.test.cjs --- +{ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const test = require("node:test"); +const { + validateArchiveCreateOptions, + buildCreateArchiveCommand, + parseCreateArchiveResult, +} = require("./archiveCreate.cjs"); + +const posix = process.platform !== "win32"; +const baseOptions = { directory: "/tmp/example", paths: ["file"], archiveName: "bundle.tar.gz", format: "tar.gz" }; + +function fixture(t) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-archive-create-")); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + return directory; +} + +function execute(options, env = {}) { + return spawnSync("/bin/sh", ["-c", buildCreateArchiveCommand(options)], { + encoding: "utf8", + timeout: 20_000, + env: { ...process.env, ...env }, + }); +} + +function assertNoStaging(directory) { + assert.deepEqual(fs.readdirSync(directory).filter((entry) => entry.startsWith(".netcatty-archive.")), []); +} + +function executablePath(name) { + const result = spawnSync("/bin/sh", ["-c", `command -v ${name}`], { encoding: "utf8" }); + assert.equal(result.status, 0, `Missing test prerequisite ${name}`); + return result.stdout.trim(); +} + +function writeTool(directory, name, body) { + const bin = path.join(directory, "bin"); + fs.mkdirSync(bin, { recursive: true }); + fs.writeFileSync(path.join(bin, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 }); + return `${bin}${path.delimiter}${process.env.PATH}`; +} + +test("archive sources are relative, bounded, deduplicated and cannot contain the output", () => { + assert.deepEqual(validateArchiveCreateOptions({ ...baseOptions, paths: ["dir/child", "dir", "./other", "other"] }).paths, ["dir", "other"]); + for (const paths of [[], ["."], ["dir/.."], ["../file"], ["/file"], ["dir/../../file"], ["bundle.tar.gz"], ["bundle.tar.gz/file"], ["bad\\name"], ["bad\nname"], ["bad\0name"]]) { + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, paths })); + } + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, paths: Array(1001).fill("file") })); + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, directory: "." })); + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, overwrite: "yes" })); +}); + +test("archive names are simple names matching an explicitly allowed format", () => { + for (const archiveName of ["", ".", "..", ".tar.gz", "../x.tar.gz", "sub/x.tar.gz", "sub\\x.tar.gz", "a\n.tar.gz", "x.zip"]) { + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, archiveName })); + } + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, format: "rar" })); + assert.throws(() => validateArchiveCreateOptions({ ...baseOptions, format: "zip", archiveName: ".zip" })); + assert.doesNotThrow(() => validateArchiveCreateOptions({ ...baseOptions, archiveName: "-quoted ' $(touch nope).tar.gz" })); +}); + +test("the remote result must contain a completion marker, with a distinct conflict result", () => { + assert.deepEqual(parseCreateArchiveResult("banner\nNETCATTY_ARCHIVE_RESULT:OK\n"), { success: true }); + assert.equal(parseCreateArchiveResult("NETCATTY_ARCHIVE_RESULT:EEXIST\n").code, "EEXIST"); + assert.throws(() => parseCreateArchiveResult(""), /did not confirm/); + assert.throws(() => parseCreateArchiveResult("ordinary output"), /did not confirm/); +}); + +test("GB18030 paths use the existing encoded shell quoting", () => { + const command = buildCreateArchiveCommand({ ...baseOptions, paths: ["\u6d4b\u8bd5.txt"] }, { encoding: "gb18030" }); + const iconv = require("iconv-lite"); + assert.ok(command.includes(iconv.encode("./\u6d4b\u8bd5.txt", "gb18030").toString("base64"))); + assert.ok(command.includes("base64 -d")); + assert.ok(!command.includes("\u6d4b\u8bd5.txt")); +}); + +for (const format of ["tar.gz", "zip"]) { + test(`${format}: real archive round trip preserves selected files, folders and symlinks`, { skip: !posix }, (t) => { + const directory = fixture(t); + const names = ["simple.txt", "space ' quote.txt", "$(touch HACKED).txt", "`touch HACKED2`.txt", "-option", "literal*.txt", "[abc].txt", "\u4e2d\u6587.txt"]; + for (const name of names) fs.writeFileSync(path.join(directory, name), `contents of ${name}`); + fs.writeFileSync(path.join(directory, "literal-other.txt"), "unselected"); + fs.writeFileSync(path.join(directory, "a.txt"), "unselected"); + fs.mkdirSync(path.join(directory, "folder", "empty"), { recursive: true }); + fs.writeFileSync(path.join(directory, "folder", "nested.txt"), "nested data"); + fs.mkdirSync(path.join(directory, "tree")); + fs.writeFileSync(path.join(directory, "tree", "selected.txt"), "nested selection"); + fs.writeFileSync(path.join(directory, "tree", "excluded.txt"), "not selected"); + fs.symlinkSync(".", path.join(directory, "loop")); + fs.symlinkSync("missing-target", path.join(directory, "broken")); + const archiveName = `-backup ' quoted.${format}`; + const result = execute({ directory, paths: [...names, "folder", "folder/nested.txt", "tree/selected.txt", "loop", "broken"], archiveName, format }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(parseCreateArchiveResult(result.stdout), { success: true }); + const output = path.join(directory, "unpacked"); + fs.mkdirSync(output); + const unpack = format === "zip" + ? spawnSync("unzip", ["-q", path.join(directory, archiveName), "-d", output], { encoding: "utf8" }) + : spawnSync("tar", ["-xzf", path.join(directory, archiveName), "-C", output], { encoding: "utf8" }); + assert.equal(unpack.status, 0, unpack.stderr); + for (const name of names) { + assert.equal(fs.readFileSync(path.join(output, name), "utf8"), `contents of ${name}`); + assert.equal(fs.readFileSync(path.join(directory, name), "utf8"), `contents of ${name}`); + } + assert.equal(fs.readFileSync(path.join(output, "folder", "nested.txt"), "utf8"), "nested data"); + assert.ok(fs.statSync(path.join(output, "folder", "empty")).isDirectory()); + assert.equal(fs.readFileSync(path.join(output, "tree", "selected.txt"), "utf8"), "nested selection"); + for (const missing of ["literal-other.txt", "a.txt", "tree/excluded.txt", "HACKED", "HACKED2", archiveName]) { + assert.equal(fs.existsSync(path.join(output, missing)), false, missing); + } + assert.equal(fs.readlinkSync(path.join(output, "loop")), "."); + assert.equal(fs.readlinkSync(path.join(output, "broken")), "missing-target"); + assert.equal(fs.existsSync(path.join(directory, "HACKED")), false); + assert.equal(fs.existsSync(path.join(directory, "HACKED2")), false); + assertNoStaging(directory); + }); +} + +test("existing output requires confirmation; confirmed replacement leaves original inputs intact", { skip: !posix }, (t) => { + const directory = fixture(t); + const options = { ...baseOptions, directory }; + fs.writeFileSync(path.join(directory, "file"), "source"); + fs.writeFileSync(path.join(directory, options.archiveName), "old archive"); + const conflict = execute(options); + assert.equal(conflict.status, 0, conflict.stderr); + assert.equal(parseCreateArchiveResult(conflict.stdout).code, "EEXIST"); + assert.equal(fs.readFileSync(path.join(directory, options.archiveName), "utf8"), "old archive"); + const replacement = execute({ ...options, overwrite: true }); + assert.equal(replacement.status, 0, replacement.stderr); + assert.deepEqual(parseCreateArchiveResult(replacement.stdout), { success: true }); + assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); + const listed = spawnSync("tar", ["-tzf", path.join(directory, options.archiveName)], { encoding: "utf8" }); + assert.equal(listed.status, 0, listed.stderr); + assert.match(listed.stdout, /file/); + assertNoStaging(directory); +}); + +test("directories and symbolic-link outputs are never overwritten", { skip: !posix }, (t) => { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + fs.writeFileSync(path.join(directory, "important"), "untouched"); + fs.mkdirSync(path.join(directory, "directory.tar.gz")); + fs.symlinkSync("important", path.join(directory, "symlink.tar.gz")); + fs.symlinkSync("missing", path.join(directory, "broken.tar.gz")); + for (const archiveName of ["directory.tar.gz", "symlink.tar.gz", "broken.tar.gz"]) { + const result = execute({ ...baseOptions, directory, archiveName, overwrite: true }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /regular file/); + } + assert.equal(fs.readFileSync(path.join(directory, "important"), "utf8"), "untouched"); + assert.equal(fs.readlinkSync(path.join(directory, "symlink.tar.gz")), "important"); + assertNoStaging(directory); +}); + +test("a nested tree selection cannot traverse a symbolic link", { skip: !posix }, (t) => { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + fs.symlinkSync(".", path.join(directory, "loop")); + const result = execute({ ...baseOptions, directory, paths: ["loop/file"] }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /traverses a symbolic link/); + assert.equal(fs.existsSync(path.join(directory, baseOptions.archiveName)), false); +}); + +test("an output that aliases a selected source cannot be replaced", { skip: !posix }, (t) => { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + fs.linkSync(path.join(directory, "file"), path.join(directory, baseOptions.archiveName)); + const result = execute({ ...baseOptions, directory, overwrite: true }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /refers to a selected source/); + assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); + assert.equal(fs.readFileSync(path.join(directory, baseOptions.archiveName), "utf8"), "source"); + assertNoStaging(directory); +}); + +test("missing tools and missing inputs fail without creating an output", { skip: !posix }, (t) => { + const directory = fixture(t); + const missing = execute({ ...baseOptions, directory }); + assert.notEqual(missing.status, 0); + assert.match(missing.stderr, /source no longer exists/); + fs.writeFileSync(path.join(directory, "file"), "source"); + for (const format of ["tar.gz", "zip"]) { + const noTool = execute({ ...baseOptions, directory, archiveName: `bundle.${format}`, format }, { PATH: directory }); + assert.notEqual(noTool.status, 0); + assert.match(noTool.stderr, /(?:tar|zip) is not installed/); + } + assert.equal(fs.existsSync(path.join(directory, baseOptions.archiveName)), false); + assertNoStaging(directory); +}); + +test("compression and publication failures preserve the previous archive and clean staging", { skip: !posix }, (t) => { + for (const tool of ["tar", "zip", "mv"]) { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + const format = tool === "zip" ? "zip" : "tar.gz"; + const archiveName = `bundle.${format}`; + fs.writeFileSync(path.join(directory, archiveName), "old archive"); + const envPath = writeTool(directory, tool, "echo 'intentional failure' >&2\nexit 9"); + const result = execute({ ...baseOptions, directory, archiveName, format, overwrite: true }, { PATH: envPath }); + assert.notEqual(result.status, 0); + assert.equal(fs.readFileSync(path.join(directory, archiveName), "utf8"), "old archive"); + assert.equal(fs.readFileSync(path.join(directory, "file"), "utf8"), "source"); + assertNoStaging(directory); + } +}); + +test("unreadable nested files fail the real tools instead of publishing a partial archive", { + skip: !posix || process.getuid?.() === 0, +}, (t) => { + for (const format of ["tar.gz", "zip"]) { + const directory = fixture(t); + fs.mkdirSync(path.join(directory, "folder")); + fs.writeFileSync(path.join(directory, "folder", "readable"), "readable data"); + const unreadable = path.join(directory, "folder", "unreadable"); + fs.writeFileSync(unreadable, "protected data", { mode: 0o000 }); + t.after(() => { try { fs.chmodSync(unreadable, 0o600); } catch { /* fixture may already be removed */ } }); + const archiveName = `bundle.${format}`; + fs.writeFileSync(path.join(directory, archiveName), "previous archive"); + const result = execute({ directory, paths: ["folder"], archiveName, format, overwrite: true }); + assert.notEqual(result.status, 0, `${format} must report unreadable input`); + assert.equal(fs.readFileSync(path.join(directory, archiveName), "utf8"), "previous archive"); + assertNoStaging(directory); + } +}); + +test("a competing creator immediately before publication cannot be overwritten", { skip: !posix }, (t) => { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + const realLn = executablePath("ln"); + const envPath = writeTool(directory, "ln", `printf 'competing archive' > './bundle.tar.gz'\nexec '${realLn}' "$@"`); + const result = execute({ ...baseOptions, directory }, { PATH: envPath }); + assert.equal(result.status, 0, result.stderr); + assert.equal(parseCreateArchiveResult(result.stdout).code, "EEXIST"); + assert.equal(fs.readFileSync(path.join(directory, baseOptions.archiveName), "utf8"), "competing archive"); + assertNoStaging(directory); +}); + +test("publication never redirects into a directory or directory symlink created concurrently", { skip: !posix }, (t) => { + for (const symlink of [false, true]) { + const directory = fixture(t); + fs.writeFileSync(path.join(directory, "file"), "source"); + fs.mkdirSync(path.join(directory, "other")); + const realLn = executablePath("ln"); + const setup = symlink ? `'${realLn}' -s other bundle.tar.gz` : "mkdir bundle.tar.gz"; + const envPath = writeTool(directory, "ln", `${setup}\nexec '${realLn}' "$@"`); + const result = execute({ ...baseOptions, directory }, { PATH: envPath }); + assert.notEqual(result.status, 0); + assert.deepEqual(fs.readdirSync(path.join(directory, symlink ? "other" : "bundle.tar.gz")), []); + assertNoStaging(directory); + } +}); +} + +// --- merged from archiveExtract.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { + getArchiveKind, + isExtractableArchive, + posixParentDir, + stripCompressionSuffix, + computeExtractTimeoutMs, + buildExtractCommand, + buildLocalExtractPlan, + EXTRACT_MAX_TIMEOUT_MS, +} = require("./archiveExtract.cjs"); + +test("detects compound archive suffixes before single-file compression", () => { + assert.equal(getArchiveKind("backup.tar.gz"), "tar.gz"); + assert.equal(getArchiveKind("/var/a.tgz"), "tar.gz"); + assert.equal(getArchiveKind("logs.tar.bz2"), "tar.bz2"); + assert.equal(getArchiveKind("src.tar.xz"), "tar.xz"); + assert.equal(getArchiveKind("app.tar"), "tar"); + assert.equal(getArchiveKind("payload.zip"), "zip"); + assert.equal(getArchiveKind("notes.txt.gz"), "gz"); + assert.equal(getArchiveKind("notes.txt"), null); + assert.equal(getArchiveKind(".gz"), null); + assert.equal(isExtractableArchive("bundle.tgz"), true); + assert.equal(isExtractableArchive("readme.md"), false); +}); + +test("posix parent and gzip output stay in the archive directory", () => { + assert.equal(posixParentDir("/home/app/a.tar.gz"), "/home/app"); + assert.equal(posixParentDir("/a.zip"), "/"); + assert.equal(stripCompressionSuffix("/home/app/notes.txt.gz", "gz"), "/home/app/notes.txt"); + assert.equal(stripCompressionSuffix("/notes.txt.gz", "gz"), "/notes.txt"); +}); + +test("extract commands quote spaces and single quotes", () => { + const tarCmd = buildExtractCommand("/tmp/my files/app's.tgz"); + assert.match(tarCmd, /tar -xzf '/); + assert.match(tarCmd, /'\/tmp\/my files\/app'\\''s\.tgz'/); + assert.match(tarCmd, /-C '\/tmp\/my files'/); + + const zipCmd = buildExtractCommand("/opt/build/out.zip"); + assert.match(zipCmd, /unzip -qo '\/opt\/build\/out\.zip' -d '\/opt\/build' >\/dev\/null/); + assert.match(zipCmd, /tar -xf '\/opt\/build\/out\.zip' -C '\/opt\/build'/); + + const gzCmd = buildExtractCommand("/var/log/syslog.gz"); + assert.match(gzCmd, /out='\/var\/log\/syslog'/); + assert.match(gzCmd, /archive='\/var\/log\/syslog\.gz'/); + assert.match(gzCmd, /trap 'rm -f -- "\$stage"' EXIT/); + assert.match(gzCmd, /gzip -dc -- "\$archive" > "\$stage"/); + assert.match(gzCmd, /if \[ -d "\$out" \]/); + assert.match(gzCmd, /mv -f -- "\$stage" "\$out"/); + + const spacedGz = buildExtractCommand("/tmp/my file.txt.gz"); + assert.match(spacedGz, /out='\/tmp\/my file\.txt'/); + assert.match(spacedGz, /archive='\/tmp\/my file\.txt\.gz'/); + assert.doesNotMatch(spacedGz, /trap 'rm -f -- '/); +}); + +test("generated gzip extract script can install its EXIT trap with spaces in the path", () => { + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + const { spawnSync } = require("node:child_process"); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-trap-")); + const archive = path.join(dir, "my file.txt.gz"); + fs.writeFileSync(archive, "x"); + const cmd = buildExtractCommand(archive); + const prefix = []; + for (const line of cmd.split("\n")) { + prefix.push(line); + if (line.startsWith("trap ")) break; + } + prefix.push("trap - EXIT"); + prefix.push("rm -f -- \"$stage\""); + const ran = spawnSync("sh", ["-c", prefix.join("\n")], { encoding: "utf8" }); + assert.equal(ran.status, 0, ran.stderr); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("extract command rejects newlines and unknown types", () => { + assert.throws(() => buildExtractCommand("/tmp/bad\n.tar.gz"), /NUL or newlines/); + assert.throws(() => buildExtractCommand("/tmp/notes.txt"), /Unsupported archive type/); +}); + +test("local extract plan uses unzip with tar fallback off Windows", () => { + const unixZip = buildLocalExtractPlan("/tmp/a.zip", "linux"); + assert.deepEqual(unixZip.command, "unzip"); + assert.deepEqual(unixZip.args, ["-qo", "/tmp/a.zip", "-d", "/tmp"]); + assert.deepEqual(unixZip.fallback, { command: "tar", args: ["-xf", "/tmp/a.zip", "-C", "/tmp"] }); + + const winZip = buildLocalExtractPlan("C:\\tmp\\a.zip", "win32"); + assert.equal(winZip.command, "tar"); + assert.ok(winZip.args.includes("-xf")); + + const gz = buildLocalExtractPlan("/tmp/notes.txt.gz", "win32"); + assert.equal(gz.builtin, "gunzip"); + assert.equal(gz.archivePath, "/tmp/notes.txt.gz"); + assert.equal(gz.stdoutFile, "/tmp/notes.txt"); +}); + +test("unknown archive size uses the maximum extract timeout", () => { + assert.equal(computeExtractTimeoutMs(undefined), EXTRACT_MAX_TIMEOUT_MS); + assert.ok(computeExtractTimeoutMs(1024) < EXTRACT_MAX_TIMEOUT_MS); +}); + +test("extractLocalArchiveFile unpacks a tar.gz next to the archive", async () => { + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + const { spawnSync } = require("node:child_process"); + const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-")); + const source = path.join(dir, "hello.txt"); + const archive = path.join(dir, "hello.tgz"); + fs.writeFileSync(source, "hello-extract"); + const packed = spawnSync("tar", ["-czf", archive, "-C", dir, "hello.txt"], { encoding: "utf8" }); + assert.equal(packed.status, 0, packed.stderr); + fs.unlinkSync(source); + + await extractLocalArchiveFile(archive); + assert.equal(fs.readFileSync(source, "utf8"), "hello-extract"); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("failed gzip extract leaves an existing sibling file intact", async () => { + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-keep-")); + const dest = path.join(dir, "notes.txt"); + const archive = path.join(dir, "notes.txt.gz"); + fs.writeFileSync(dest, "keep-me"); + fs.writeFileSync(archive, "this-is-not-gzip"); + + await assert.rejects(() => extractLocalArchiveFile(archive), /Local extraction failed/); + assert.equal(fs.readFileSync(dest, "utf8"), "keep-me"); + assert.deepEqual( + fs.readdirSync(dir).filter((name) => name.includes(".netcatty-extract")), + [], + ); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("extractLocalArchiveFile gunzips with Node zlib and keeps a sibling staging name", async () => { + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + const zlib = require("node:zlib"); + const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-gz-")); + const dest = path.join(dir, "notes.txt"); + const archive = path.join(dir, "notes.txt.gz"); + const sibling = `${dest}.netcatty-extract`; + fs.writeFileSync(sibling, "do-not-touch"); + fs.writeFileSync(archive, zlib.gzipSync("hello-gzip")); + + await extractLocalArchiveFile(archive); + assert.equal(fs.readFileSync(dest, "utf8"), "hello-gzip"); + assert.equal(fs.readFileSync(sibling, "utf8"), "do-not-touch"); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("failed gzip extract leaves a sibling directory target intact", async () => { + const fs = require("node:fs"); + const os = require("node:os"); + const path = require("node:path"); + const zlib = require("node:zlib"); + const { extractLocalArchiveFile } = require("./archiveExtract.cjs"); + + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nc-extract-dir-")); + const dest = path.join(dir, "notes.txt"); + const archive = path.join(dir, "notes.txt.gz"); + fs.mkdirSync(dest); + fs.writeFileSync(path.join(dest, "keep.txt"), "inside"); + fs.writeFileSync(archive, zlib.gzipSync("hello-gzip")); + + await assert.rejects(() => extractLocalArchiveFile(archive), /directory/); + assert.equal(fs.readFileSync(path.join(dest, "keep.txt"), "utf8"), "inside"); + fs.rmSync(dir, { recursive: true, force: true }); +}); +} + +// --- merged from fileOps.createArchive.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { createFileOpsApi } = require("./fileOps.cjs"); +const { createPreloadApi } = require("../../preload/api.cjs"); + +const options = { directory: "/home/app", paths: ["file", "folder"], archiveName: "backup.tar.gz", format: "tar.gz" }; + +function createApi({ client = { client: { exec() {} } }, stdout = "NETCATTY_ARCHIVE_RESULT:OK\n", error, encoding = "utf-8" } = {}) { + const calls = []; + const api = createFileOpsApi({ + sftpClients: new Map(client ? [["sftp-1", client]] : []), + resolveEncodingForRequest: () => encoding, + throwIfAborted(signal) { if (signal?.aborted) throw new Error("Aborted"); }, + execRemoteShellCommand: async (sshClient, command, execOptions) => { + calls.push({ sshClient, command, options: execOptions }); + if (error) throw error; + return { stdout, code: 0 }; + }, + }); + return { api, calls }; +} + +test("archive creation passes options through preload and the bounded remote executor", async () => { + const { api, calls } = createApi(); + let invoked; + const bridge = createPreloadApi({ + ipcRenderer: { + on() {}, + invoke(channel, payload) { + invoked = { channel, payload }; + return api.createSftpArchive(null, payload); + }, + }, + webUtils: {}, + }); + assert.deepEqual(await bridge.createSftpArchive("sftp-1", options, "utf-8"), { success: true }); + assert.equal(invoked.channel, "netcatty:sftp:createArchive"); + assert.deepEqual(invoked.payload, { sftpId: "sftp-1", options, encoding: "utf-8" }); + assert.equal(calls.length, 1); + assert.match(calls[0].command, /tar -czf/); + assert.equal(calls[0].options.openingTimeoutMs, 15_000); + assert.equal(calls[0].options.runTimeoutMs, 30 * 60_000); + assert.equal(calls[0].options.maxOutputBytes, 64 * 1024); +}); + +test("archive conflicts survive IPC as structured EEXIST results", async () => { + const { api } = createApi({ stdout: "NETCATTY_ARCHIVE_RESULT:EEXIST\n" }); + const result = await api.createSftpArchive(null, { sftpId: "sftp-1", options }); + assert.equal(result.success, false); + assert.equal(result.code, "EEXIST"); +}); + +test("archive creation requires a session and exec channel", async () => { + const missing = createApi({ client: null }); + await assert.rejects(() => missing.api.createSftpArchive(null, { sftpId: "none", options }), /session not found/); + const noExec = createApi({ client: {} }); + await assert.rejects(() => noExec.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /SSH exec unavailable/); + assert.equal(missing.calls.length + noExec.calls.length, 0); +}); + +test("archive creation never opens a second channel on single-channel SSH", async () => { + for (const client of [ + { __netcattySingleChannelSsh: true, client: { exec() {} } }, + { client: { __netcattySingleChannelSsh: true, exec() {} } }, + ]) { + const { api, calls } = createApi({ client }); + await assert.rejects( + () => api.createSftpArchive(null, { sftpId: "sftp-1", options }), + (error) => error.code === "ERR_SFTP_SINGLE_CHANNEL_EXEC", + ); + assert.equal(calls.length, 0); + } +}); + +test("invalid sources and cancelled requests never execute a shell command", async () => { + const { api, calls } = createApi(); + await assert.rejects(() => api.createSftpArchive(null, { sftpId: "sftp-1", options: { ...options, paths: ["../outside"] } }), /inside/); + const abort = new AbortController(); + abort.abort(); + await assert.rejects(() => api.createSftpArchive(null, { sftpId: "sftp-1", options, abortSignal: abort.signal }), /Aborted/); + assert.equal(calls.length, 0); +}); + +test("remote errors or missing completion acknowledgements cannot report success", async () => { + const failure = createApi({ error: new Error("zip unavailable") }); + await assert.rejects(() => failure.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /zip unavailable/); + const incomplete = createApi({ stdout: "" }); + await assert.rejects(() => incomplete.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /did not confirm/); +}); + +test("archive creation resolves the session's filename encoding", async () => { + const { api, calls } = createApi({ encoding: "gb18030" }); + await api.createSftpArchive(null, { sftpId: "sftp-1", options: { ...options, paths: ["\u4e2d\u6587"] }, encoding: "auto" }); + assert.match(calls[0].command, /base64 -d/); + assert.ok(!calls[0].command.includes("\u4e2d\u6587")); +}); +} + +// --- merged from fileOps.createArchive.ssh.test.cjs --- +{ +const assert = require("node:assert/strict"); +const { createHash, generateKeyPairSync, randomBytes } = require("node:crypto"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawn, spawnSync } = require("node:child_process"); +const test = require("node:test"); +const { Client, Server, utils } = require("ssh2"); +const { createFileOpsApi } = require("./fileOps.cjs"); +const { _execRemoteShellCommandForTests: execRemoteShellCommand } = require("../sftpBridge.cjs"); + +function sha256(filePath) { + return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); +} + +/** A real encrypted loopback SSH transport; exec runs only inside our fixture. */ +async function connectFixture(t) { + const hostKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }); + const hostFingerprint = createHash("sha256").update(utils.parseKey(hostKey).getPublicSSH()).digest("hex"); + const password = randomBytes(16).toString("hex"); + const connections = new Set(); + const children = new Set(); + const fixture = { env: process.env, commands: 0 }; + const server = new Server({ hostKeys: [hostKey] }, (connection) => { + connections.add(connection); + connection.on("close", () => connections.delete(connection)); + connection.on("error", () => {}); + connection.on("authentication", (context) => { + if (context.method === "password" && context.username === "archive-test" && context.password === password) context.accept(); + else context.reject(); + }); + connection.on("ready", () => connection.on("session", (accept) => { + const session = accept(); + session.on("exec", (acceptExec, _reject, info) => { + fixture.commands += 1; + const channel = acceptExec(); + const child = spawn("/bin/sh", ["-c", info.command], { env: fixture.env, stdio: ["ignore", "pipe", "pipe"] }); + children.add(child); + child.stdout.pipe(channel, { end: false }); + child.stderr.pipe(channel.stderr, { end: false }); + channel.on("error", () => {}); + child.on("error", (error) => { + channel.stderr.write(error.message); + channel.exit(127); + channel.end(() => channel.close()); + }); + child.on("close", (code) => { + children.delete(child); + channel.exit(code ?? 1); + channel.end(() => channel.close()); + }); + channel.on("close", () => { if (child.exitCode === null) child.kill("SIGKILL"); }); + }); + })); + }); + const client = new Client(); + t.after(async () => { + client.destroy(); + for (const child of children) child.kill("SIGKILL"); + for (const connection of connections) connection.end(); + await new Promise((resolve) => server.close(resolve)); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + await new Promise((resolve, reject) => { + client.once("ready", resolve); + client.once("error", reject); + client.connect({ + host: "127.0.0.1", + port: server.address().port, + username: "archive-test", + password, + hostHash: "sha256", + hostVerifier: (hash) => hash === hostFingerprint, + readyTimeout: 5000, + }); + }); + const api = createFileOpsApi({ + sftpClients: new Map([["loopback", { client }]]), + resolveEncodingForRequest: () => "utf-8", + throwIfAborted(signal) { if (signal?.aborted) throw new Error("Aborted"); }, + execRemoteShellCommand, + }); + return { ...fixture, setEnv: (env) => { fixture.env = env; }, getCommandCount: () => fixture.commands, api }; +} + +test("archive creation traverses real SSH, preserves payloads, and handles conflict/replace/failure", { + skip: process.platform === "win32", + timeout: 30_000, +}, async (t) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-archive-ssh-")); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + fs.mkdirSync(path.join(directory, "folder")); + const binary = randomBytes(65_537); + fs.writeFileSync(path.join(directory, "folder", "binary.bin"), binary); + const sourceName = "\u4e2d\u6587 ' $(touch should-not-exist).txt"; + fs.writeFileSync(path.join(directory, sourceName), "before replacement"); + const { api, setEnv, getCommandCount } = await connectFixture(t); + for (const format of ["tar.gz", "zip"]) { + const archiveName = `transport.${format}`; + const options = { directory, paths: [sourceName, "folder"], archiveName, format }; + const invoke = (patch = {}) => api.createSftpArchive(null, { sftpId: "loopback", options: { ...options, ...patch } }); + assert.deepEqual(await invoke(), { success: true }); + const archivePath = path.join(directory, archiveName); + const firstDigest = sha256(archivePath); + fs.writeFileSync(path.join(directory, sourceName), `after replacement ${format}`); + assert.equal((await invoke()).code, "EEXIST"); + assert.equal(sha256(archivePath), firstDigest); + assert.deepEqual(await invoke({ overwrite: true }), { success: true }); + assert.notEqual(sha256(archivePath), firstDigest); + const unpacked = path.join(directory, `unpacked-${format}`); + fs.mkdirSync(unpacked); + const unpack = format === "zip" + ? spawnSync("unzip", ["-q", archivePath, "-d", unpacked], { encoding: "utf8" }) + : spawnSync("tar", ["-xzf", archivePath, "-C", unpacked], { encoding: "utf8" }); + assert.equal(unpack.status, 0, unpack.stderr); + assert.deepEqual(fs.readFileSync(path.join(unpacked, "folder", "binary.bin")), binary); + assert.equal(fs.readFileSync(path.join(unpacked, sourceName), "utf8"), `after replacement ${format}`); + assert.equal(fs.existsSync(path.join(directory, "should-not-exist")), false); + const completedDigest = sha256(archivePath); + await assert.rejects(() => invoke({ overwrite: true, paths: ["missing"] }), /source no longer exists/); + assert.equal(sha256(archivePath), completedDigest); + setEnv({ ...process.env, PATH: directory }); + await assert.rejects(() => invoke({ overwrite: true }), /is not installed on the remote host/); + setEnv(process.env); + assert.equal(sha256(archivePath), completedDigest); + assert.deepEqual(fs.readdirSync(directory).filter((entry) => entry.startsWith(".netcatty-archive.")), []); + } + assert.equal(getCommandCount(), 10); +}); +} + +// --- merged from fileOps.extract.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { createFileOpsApi } = require("./fileOps.cjs"); + +function createExtractApi({ execImpl, clients } = {}) { + const commands = []; + const optionsLog = []; + const api = createFileOpsApi({ + sftpClients: clients || new Map([ + ["sftp-1", { client: { exec() {} } }], + ]), + resolveEncodingForRequest: () => "utf-8", + throwIfAborted: () => {}, + encodePath: (value) => value, + requireSftpChannel: async () => ({}), + lstatAsync: async () => ({ size: 1024 }), + isScpModeClient: () => false, + execRemoteShellCommand: async (_ssh, command, options) => { + commands.push(command); + optionsLog.push(options); + if (typeof execImpl === "function") return execImpl(command); + return { stdout: "", stderr: "", code: 0 }; + }, + }); + return { api, commands, optionsLog }; +} + +test("extractSftpArchive runs a quoted remote tar command", async () => { + const { api, commands, optionsLog } = createExtractApi(); + const result = await api.extractSftpArchive(null, { + sftpId: "sftp-1", + path: "/home/app/backup.tar.gz", + }); + assert.deepEqual(result, { success: true }); + assert.equal(commands.length, 1); + assert.match(commands[0], /tar -xzf '\/home\/app\/backup\.tar\.gz' -C '\/home\/app'/); + assert.equal(optionsLog[0].discardStdout, true); +}); + +test("extractSftpArchive rejects unsupported files", async () => { + const { api, commands } = createExtractApi(); + await assert.rejects( + () => api.extractSftpArchive(null, { sftpId: "sftp-1", path: "/home/app/notes.txt" }), + /Unsupported archive type/, + ); + assert.equal(commands.length, 0); +}); + +test("extractSftpArchive requires an open SFTP session", async () => { + const { api } = createExtractApi({ clients: new Map() }); + await assert.rejects( + () => api.extractSftpArchive(null, { sftpId: "missing", path: "/tmp/a.zip" }), + /SFTP session not found/, + ); +}); + + +test("extractSftpArchive refuses a second channel on single-channel SSH", async () => { + let execCalls = 0; + const { api, commands } = createExtractApi({ + clients: new Map([[ + "sftp-1", + { + __netcattySingleChannelSsh: true, + __netcattyEndpointKey: "ep-extract", + client: { exec() { execCalls += 1; } }, + }, + ]]), + }); + await assert.rejects( + () => api.extractSftpArchive(null, { + sftpId: "sftp-1", + path: "/home/app/backup.tar.gz", + }), + (err) => err && err.code === "ERR_SFTP_SINGLE_CHANNEL_EXEC", + ); + assert.equal(commands.length, 0); + assert.equal(execCalls, 0); +}); +} diff --git a/electron/bridges/sftpBridge/fileOps.createArchive.ssh.test.cjs b/electron/bridges/sftpBridge/fileOps.createArchive.ssh.test.cjs deleted file mode 100644 index 765667fae..000000000 --- a/electron/bridges/sftpBridge/fileOps.createArchive.ssh.test.cjs +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const { createHash, generateKeyPairSync, randomBytes } = require("node:crypto"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { spawn, spawnSync } = require("node:child_process"); -const test = require("node:test"); -const { Client, Server, utils } = require("ssh2"); -const { createFileOpsApi } = require("./fileOps.cjs"); -const { _execRemoteShellCommandForTests: execRemoteShellCommand } = require("../sftpBridge.cjs"); - -function sha256(filePath) { - return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); -} - -/** A real encrypted loopback SSH transport; exec runs only inside our fixture. */ -async function connectFixture(t) { - const hostKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs1", format: "pem" }); - const hostFingerprint = createHash("sha256").update(utils.parseKey(hostKey).getPublicSSH()).digest("hex"); - const password = randomBytes(16).toString("hex"); - const connections = new Set(); - const children = new Set(); - const fixture = { env: process.env, commands: 0 }; - const server = new Server({ hostKeys: [hostKey] }, (connection) => { - connections.add(connection); - connection.on("close", () => connections.delete(connection)); - connection.on("error", () => {}); - connection.on("authentication", (context) => { - if (context.method === "password" && context.username === "archive-test" && context.password === password) context.accept(); - else context.reject(); - }); - connection.on("ready", () => connection.on("session", (accept) => { - const session = accept(); - session.on("exec", (acceptExec, _reject, info) => { - fixture.commands += 1; - const channel = acceptExec(); - const child = spawn("/bin/sh", ["-c", info.command], { env: fixture.env, stdio: ["ignore", "pipe", "pipe"] }); - children.add(child); - child.stdout.pipe(channel, { end: false }); - child.stderr.pipe(channel.stderr, { end: false }); - channel.on("error", () => {}); - child.on("error", (error) => { - channel.stderr.write(error.message); - channel.exit(127); - channel.end(() => channel.close()); - }); - child.on("close", (code) => { - children.delete(child); - channel.exit(code ?? 1); - channel.end(() => channel.close()); - }); - channel.on("close", () => { if (child.exitCode === null) child.kill("SIGKILL"); }); - }); - })); - }); - const client = new Client(); - t.after(async () => { - client.destroy(); - for (const child of children) child.kill("SIGKILL"); - for (const connection of connections) connection.end(); - await new Promise((resolve) => server.close(resolve)); - }); - await new Promise((resolve, reject) => { - server.once("error", reject); - server.listen(0, "127.0.0.1", resolve); - }); - await new Promise((resolve, reject) => { - client.once("ready", resolve); - client.once("error", reject); - client.connect({ - host: "127.0.0.1", - port: server.address().port, - username: "archive-test", - password, - hostHash: "sha256", - hostVerifier: (hash) => hash === hostFingerprint, - readyTimeout: 5000, - }); - }); - const api = createFileOpsApi({ - sftpClients: new Map([["loopback", { client }]]), - resolveEncodingForRequest: () => "utf-8", - throwIfAborted(signal) { if (signal?.aborted) throw new Error("Aborted"); }, - execRemoteShellCommand, - }); - return { ...fixture, setEnv: (env) => { fixture.env = env; }, getCommandCount: () => fixture.commands, api }; -} - -test("archive creation traverses real SSH, preserves payloads, and handles conflict/replace/failure", { - skip: process.platform === "win32", - timeout: 30_000, -}, async (t) => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-archive-ssh-")); - t.after(() => fs.rmSync(directory, { recursive: true, force: true })); - fs.mkdirSync(path.join(directory, "folder")); - const binary = randomBytes(65_537); - fs.writeFileSync(path.join(directory, "folder", "binary.bin"), binary); - const sourceName = "\u4e2d\u6587 ' $(touch should-not-exist).txt"; - fs.writeFileSync(path.join(directory, sourceName), "before replacement"); - const { api, setEnv, getCommandCount } = await connectFixture(t); - for (const format of ["tar.gz", "zip"]) { - const archiveName = `transport.${format}`; - const options = { directory, paths: [sourceName, "folder"], archiveName, format }; - const invoke = (patch = {}) => api.createSftpArchive(null, { sftpId: "loopback", options: { ...options, ...patch } }); - assert.deepEqual(await invoke(), { success: true }); - const archivePath = path.join(directory, archiveName); - const firstDigest = sha256(archivePath); - fs.writeFileSync(path.join(directory, sourceName), `after replacement ${format}`); - assert.equal((await invoke()).code, "EEXIST"); - assert.equal(sha256(archivePath), firstDigest); - assert.deepEqual(await invoke({ overwrite: true }), { success: true }); - assert.notEqual(sha256(archivePath), firstDigest); - const unpacked = path.join(directory, `unpacked-${format}`); - fs.mkdirSync(unpacked); - const unpack = format === "zip" - ? spawnSync("unzip", ["-q", archivePath, "-d", unpacked], { encoding: "utf8" }) - : spawnSync("tar", ["-xzf", archivePath, "-C", unpacked], { encoding: "utf8" }); - assert.equal(unpack.status, 0, unpack.stderr); - assert.deepEqual(fs.readFileSync(path.join(unpacked, "folder", "binary.bin")), binary); - assert.equal(fs.readFileSync(path.join(unpacked, sourceName), "utf8"), `after replacement ${format}`); - assert.equal(fs.existsSync(path.join(directory, "should-not-exist")), false); - const completedDigest = sha256(archivePath); - await assert.rejects(() => invoke({ overwrite: true, paths: ["missing"] }), /source no longer exists/); - assert.equal(sha256(archivePath), completedDigest); - setEnv({ ...process.env, PATH: directory }); - await assert.rejects(() => invoke({ overwrite: true }), /is not installed on the remote host/); - setEnv(process.env); - assert.equal(sha256(archivePath), completedDigest); - assert.deepEqual(fs.readdirSync(directory).filter((entry) => entry.startsWith(".netcatty-archive.")), []); - } - assert.equal(getCommandCount(), 10); -}); diff --git a/electron/bridges/sftpBridge/fileOps.createArchive.test.cjs b/electron/bridges/sftpBridge/fileOps.createArchive.test.cjs deleted file mode 100644 index 9a9147dc4..000000000 --- a/electron/bridges/sftpBridge/fileOps.createArchive.test.cjs +++ /dev/null @@ -1,98 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); -const { createFileOpsApi } = require("./fileOps.cjs"); -const { createPreloadApi } = require("../../preload/api.cjs"); - -const options = { directory: "/home/app", paths: ["file", "folder"], archiveName: "backup.tar.gz", format: "tar.gz" }; - -function createApi({ client = { client: { exec() {} } }, stdout = "NETCATTY_ARCHIVE_RESULT:OK\n", error, encoding = "utf-8" } = {}) { - const calls = []; - const api = createFileOpsApi({ - sftpClients: new Map(client ? [["sftp-1", client]] : []), - resolveEncodingForRequest: () => encoding, - throwIfAborted(signal) { if (signal?.aborted) throw new Error("Aborted"); }, - execRemoteShellCommand: async (sshClient, command, execOptions) => { - calls.push({ sshClient, command, options: execOptions }); - if (error) throw error; - return { stdout, code: 0 }; - }, - }); - return { api, calls }; -} - -test("archive creation passes options through preload and the bounded remote executor", async () => { - const { api, calls } = createApi(); - let invoked; - const bridge = createPreloadApi({ - ipcRenderer: { - on() {}, - invoke(channel, payload) { - invoked = { channel, payload }; - return api.createSftpArchive(null, payload); - }, - }, - webUtils: {}, - }); - assert.deepEqual(await bridge.createSftpArchive("sftp-1", options, "utf-8"), { success: true }); - assert.equal(invoked.channel, "netcatty:sftp:createArchive"); - assert.deepEqual(invoked.payload, { sftpId: "sftp-1", options, encoding: "utf-8" }); - assert.equal(calls.length, 1); - assert.match(calls[0].command, /tar -czf/); - assert.equal(calls[0].options.openingTimeoutMs, 15_000); - assert.equal(calls[0].options.runTimeoutMs, 30 * 60_000); - assert.equal(calls[0].options.maxOutputBytes, 64 * 1024); -}); - -test("archive conflicts survive IPC as structured EEXIST results", async () => { - const { api } = createApi({ stdout: "NETCATTY_ARCHIVE_RESULT:EEXIST\n" }); - const result = await api.createSftpArchive(null, { sftpId: "sftp-1", options }); - assert.equal(result.success, false); - assert.equal(result.code, "EEXIST"); -}); - -test("archive creation requires a session and exec channel", async () => { - const missing = createApi({ client: null }); - await assert.rejects(() => missing.api.createSftpArchive(null, { sftpId: "none", options }), /session not found/); - const noExec = createApi({ client: {} }); - await assert.rejects(() => noExec.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /SSH exec unavailable/); - assert.equal(missing.calls.length + noExec.calls.length, 0); -}); - -test("archive creation never opens a second channel on single-channel SSH", async () => { - for (const client of [ - { __netcattySingleChannelSsh: true, client: { exec() {} } }, - { client: { __netcattySingleChannelSsh: true, exec() {} } }, - ]) { - const { api, calls } = createApi({ client }); - await assert.rejects( - () => api.createSftpArchive(null, { sftpId: "sftp-1", options }), - (error) => error.code === "ERR_SFTP_SINGLE_CHANNEL_EXEC", - ); - assert.equal(calls.length, 0); - } -}); - -test("invalid sources and cancelled requests never execute a shell command", async () => { - const { api, calls } = createApi(); - await assert.rejects(() => api.createSftpArchive(null, { sftpId: "sftp-1", options: { ...options, paths: ["../outside"] } }), /inside/); - const abort = new AbortController(); - abort.abort(); - await assert.rejects(() => api.createSftpArchive(null, { sftpId: "sftp-1", options, abortSignal: abort.signal }), /Aborted/); - assert.equal(calls.length, 0); -}); - -test("remote errors or missing completion acknowledgements cannot report success", async () => { - const failure = createApi({ error: new Error("zip unavailable") }); - await assert.rejects(() => failure.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /zip unavailable/); - const incomplete = createApi({ stdout: "" }); - await assert.rejects(() => incomplete.api.createSftpArchive(null, { sftpId: "sftp-1", options }), /did not confirm/); -}); - -test("archive creation resolves the session's filename encoding", async () => { - const { api, calls } = createApi({ encoding: "gb18030" }); - await api.createSftpArchive(null, { sftpId: "sftp-1", options: { ...options, paths: ["\u4e2d\u6587"] }, encoding: "auto" }); - assert.match(calls[0].command, /base64 -d/); - assert.ok(!calls[0].command.includes("\u4e2d\u6587")); -}); diff --git a/electron/bridges/sftpBridge/fileOps.extract.test.cjs b/electron/bridges/sftpBridge/fileOps.extract.test.cjs deleted file mode 100644 index 73d1c91ac..000000000 --- a/electron/bridges/sftpBridge/fileOps.extract.test.cjs +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { createFileOpsApi } = require("./fileOps.cjs"); - -function createExtractApi({ execImpl, clients } = {}) { - const commands = []; - const optionsLog = []; - const api = createFileOpsApi({ - sftpClients: clients || new Map([ - ["sftp-1", { client: { exec() {} } }], - ]), - resolveEncodingForRequest: () => "utf-8", - throwIfAborted: () => {}, - encodePath: (value) => value, - requireSftpChannel: async () => ({}), - lstatAsync: async () => ({ size: 1024 }), - isScpModeClient: () => false, - execRemoteShellCommand: async (_ssh, command, options) => { - commands.push(command); - optionsLog.push(options); - if (typeof execImpl === "function") return execImpl(command); - return { stdout: "", stderr: "", code: 0 }; - }, - }); - return { api, commands, optionsLog }; -} - -test("extractSftpArchive runs a quoted remote tar command", async () => { - const { api, commands, optionsLog } = createExtractApi(); - const result = await api.extractSftpArchive(null, { - sftpId: "sftp-1", - path: "/home/app/backup.tar.gz", - }); - assert.deepEqual(result, { success: true }); - assert.equal(commands.length, 1); - assert.match(commands[0], /tar -xzf '\/home\/app\/backup\.tar\.gz' -C '\/home\/app'/); - assert.equal(optionsLog[0].discardStdout, true); -}); - -test("extractSftpArchive rejects unsupported files", async () => { - const { api, commands } = createExtractApi(); - await assert.rejects( - () => api.extractSftpArchive(null, { sftpId: "sftp-1", path: "/home/app/notes.txt" }), - /Unsupported archive type/, - ); - assert.equal(commands.length, 0); -}); - -test("extractSftpArchive requires an open SFTP session", async () => { - const { api } = createExtractApi({ clients: new Map() }); - await assert.rejects( - () => api.extractSftpArchive(null, { sftpId: "missing", path: "/tmp/a.zip" }), - /SFTP session not found/, - ); -}); - - -test("extractSftpArchive refuses a second channel on single-channel SSH", async () => { - let execCalls = 0; - const { api, commands } = createExtractApi({ - clients: new Map([[ - "sftp-1", - { - __netcattySingleChannelSsh: true, - __netcattyEndpointKey: "ep-extract", - client: { exec() { execCalls += 1; } }, - }, - ]]), - }); - await assert.rejects( - () => api.extractSftpArchive(null, { - sftpId: "sftp-1", - path: "/home/app/backup.tar.gz", - }), - (err) => err && err.code === "ERR_SFTP_SINGLE_CHANNEL_EXEC", - ); - assert.equal(commands.length, 0); - assert.equal(execCalls, 0); -}); diff --git a/electron/bridges/sftpBridge/scpProtocol.test.cjs b/electron/bridges/sftpBridge/scpProtocolAndSessionOps.test.cjs similarity index 51% rename from electron/bridges/sftpBridge/scpProtocol.test.cjs rename to electron/bridges/sftpBridge/scpProtocolAndSessionOps.test.cjs index ca52aa80c..a79dce77f 100644 --- a/electron/bridges/sftpBridge/scpProtocol.test.cjs +++ b/electron/bridges/sftpBridge/scpProtocolAndSessionOps.test.cjs @@ -1,5 +1,7 @@ "use strict"; +// --- merged from scpProtocol.test.cjs --- +{ const { describe, it } = require("node:test"); const assert = require("node:assert/strict"); const { @@ -230,3 +232,233 @@ describe("scpShell quoting and commands", () => { assert.equal(normalizeFileProtocol("other"), "auto"); }); }); +} + +// --- merged from scpSessionOps.test.cjs --- +{ +/** + * Integration-style tests: SCP-mode clients registered in sftpClients are + * reachable through the same list/mkdir/write entry points the UI and AI tools use. + */ +"use strict"; + +const { describe, it, beforeEach, afterEach } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { EventEmitter } = require("node:events"); +const { createScpBackend, isScpModeClient } = require("./scpBackend.cjs"); +const { createFileOpsApi } = require("./fileOps.cjs"); +const { SCP_OK, buildFileControlLine } = require("./scpProtocol.cjs"); + +function createMockStream() { + const ee = new EventEmitter(); + ee.writable = true; + ee.readable = true; + ee.stderr = new EventEmitter(); + ee.write = (buf, cb) => { + ee.emit("_write", Buffer.from(buf)); + if (typeof cb === "function") cb(); + return true; + }; + ee.end = (cb) => { if (typeof cb === "function") cb(); }; + ee.close = () => ee.emit("close"); + ee.destroy = () => ee.emit("close"); + ee.pushFromRemote = (buf) => ee.emit("data", Buffer.from(buf)); + return ee; +} + +describe("SCP-mode session ops via fileOps entry points (AI/UI shared path)", () => { + let sftpClients; + let api; + let commands; + let tmpDir; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-scp-session-")); + sftpClients = new Map(); + commands = []; + + const backend = createScpBackend({ + exec: async (command) => { + commands.push(command); + if (command.includes("for f in") || command.includes("cd ")) { + const name = Buffer.from("agent.txt").toString("base64"); + return { + stdout: `f|-rw-r--r--|4|1700000000|${name}\n`, + stderr: "", + code: 0, + }; + } + if (command.includes("mkdir")) return { stdout: "", stderr: "", code: 0 }; + if (command.includes("rm ") || command.includes("rmdir")) return { stdout: "", stderr: "", code: 0 }; + if (command.includes("mv ")) return { stdout: "", stderr: "", code: 0 }; + if (command.includes("$HOME") || command.startsWith("printf")) { + return { stdout: "/home/agent\n", stderr: "", code: 0 }; + } + if (command.includes("if [ ! -e")) { + return { + stdout: "f|-rw-r--r--|4|1700000000|/home/agent/agent.txt\n", + stderr: "", + code: 0, + }; + } + return { stdout: "", stderr: "", code: 0 }; + }, + execStream: async (command) => { + commands.push(command); + const stream = createMockStream(); + if (command.includes("scp -t")) { + setImmediate(() => stream.pushFromRemote(Buffer.from([SCP_OK]))); + stream.on("_write", (buf) => { + const text = buf.toString("utf8"); + if (text.startsWith("C") || (buf.length === 1 && buf[0] === 0x00)) { + setImmediate(() => stream.pushFromRemote(Buffer.from([SCP_OK]))); + } + }); + } else if (command.includes("scp -f")) { + let ackCount = 0; + stream.on("_write", (buf) => { + if (!(buf[0] === SCP_OK && buf.length === 1)) return; + ackCount += 1; + if (ackCount === 1) { + setImmediate(() => { + stream.pushFromRemote(buildFileControlLine({ mode: 0o644, size: 4, name: "agent.txt" })); + }); + } else if (ackCount === 2) { + setImmediate(() => { + stream.pushFromRemote(Buffer.concat([Buffer.from("data"), Buffer.from([0x00])])); + }); + } + }); + } + return stream; + }, + }); + + const client = { + client: { exec: () => {} }, + sftp: null, + __netcattyFileProtocol: "scp", + __netcattyScpBackend: backend, + async end() {}, + }; + sftpClients.set("scp-session-1", client); + + // Minimal ctx for createFileOpsApi — only what list/mkdir/rename/delete/write need + api = createFileOpsApi({ + get sftpClients() { return sftpClients; }, + get electronModule() { + return { + webContents: { fromId: () => ({ send: () => {} }) }, + }; + }, + fileWatcherBridge: { stopWatchersForSession: () => {} }, + fs, + path, + Buffer, + console, + setTimeout, + clearTimeout, + jumpConnectionsMap: new Map(), + sftpEncodingState: new Map(), + normalizeEncoding: (e) => e || "utf-8", + isAsciiString: () => true, + requireSftpChannel: async () => { throw new Error("should not use SFTP channel in SCP mode"); }, + resolveEncodingForRequest: () => "utf-8", + updateResolvedEncoding: () => "utf-8", + encodePath: (p) => p, + decodeName: (n) => n, + detectEncodingFromList: () => null, + statResultFromAttrs: (a) => a, + normalizeRemotePathString: async (_c, p) => p, + collectReadable: async () => Buffer.alloc(0), + writeToWritable: async () => {}, + throwIfAborted: () => {}, + pipeStreams: async () => {}, + ensureRemoteDirForSession: async () => true, + removeRemotePathInternal: async () => {}, + renameRemotePath: async () => {}, + realpathAsync: async () => "/", + statAsync: async () => ({}), + readdirAsync: async () => [], + mkdirAsync: async () => {}, + rmdirAsync: async () => {}, + unlinkAsync: async () => {}, + openFileAsync: async () => ({}), + writeFileChunkAsync: async () => {}, + closeFileAsync: async () => {}, + createAbortError: (s, m) => new Error(m), + copySftpEncodingState: () => {}, + clearSftpEncodingState: () => {}, + safeSend: () => {}, + tempDirBridge: { getTempFilePath: (n) => path.join(tmpDir, n) }, + randomUUID: () => "test-uuid", + }); + }); + + afterEach(() => { + try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ } + }); + + it("marks clients as SCP-mode", () => { + assert.equal(isScpModeClient(sftpClients.get("scp-session-1")), true); + }); + + it("list works for SCP-mode session id (AI sftp.list path)", async () => { + const entries = await api.listSftp(null, { sftpId: "scp-session-1", path: "/home/agent" }); + assert.equal(entries.length, 1); + assert.equal(entries[0].name, "agent.txt"); + assert.ok(commands.some((c) => c.includes("cd ") || c.includes("for f in"))); + }); + + it("mkdir write-class op works for SCP-mode session (AI sftp.mkdir path)", async () => { + const ok = await api.mkdirSftp(null, { sftpId: "scp-session-1", path: "/home/agent/newdir" }); + assert.equal(ok, true); + assert.ok(commands.some((c) => c.includes("mkdir") && c.includes("/home/agent/newdir"))); + }); + + it("rename and delete work for SCP-mode session", async () => { + await api.renameSftp(null, { + sftpId: "scp-session-1", + oldPath: "/home/agent/a", + newPath: "/home/agent/b", + }); + await api.deleteSftp(null, { sftpId: "scp-session-1", path: "/home/agent/b" }); + assert.ok(commands.some((c) => c.includes("mv --"))); + assert.ok(commands.some((c) => c.includes("rm "))); + }); + + it("write + homeDir work for SCP-mode session", async () => { + await api.writeSftp(null, { + sftpId: "scp-session-1", + path: "/home/agent/out.txt", + content: "hi\n", + }); + assert.ok(commands.some((c) => c.includes("scp -t"))); + const home = await api.getSftpHomeDir(null, { sftpId: "scp-session-1" }); + assert.equal(home.success, true); + assert.equal(home.homeDir, "/home/agent"); + }); + + it("capability catalog still exposes stable sftp.* CLI verbs", () => { + const { SFTP_CAPABILITIES } = require("../../capabilities/catalog/sftp.cjs"); + const ids = SFTP_CAPABILITIES.map((c) => c.id); + for (const id of [ + "sftp.list", + "sftp.mkdir", + "sftp.write", + "sftp.upload", + "sftp.download", + "sftp.delete", + "sftp.rename", + ]) { + assert.ok(ids.includes(id), `missing capability ${id}`); + } + const listCap = SFTP_CAPABILITIES.find((c) => c.id === "sftp.list"); + assert.deepEqual(listCap.surfaces.cli.command, ["sftp", "list"]); + assert.match(listCap.description, /SCP-mode/i); + }); +}); +} diff --git a/electron/bridges/sftpBridge/scpSessionOps.test.cjs b/electron/bridges/sftpBridge/scpSessionOps.test.cjs deleted file mode 100644 index 4be8d2169..000000000 --- a/electron/bridges/sftpBridge/scpSessionOps.test.cjs +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Integration-style tests: SCP-mode clients registered in sftpClients are - * reachable through the same list/mkdir/write entry points the UI and AI tools use. - */ -"use strict"; - -const { describe, it, beforeEach, afterEach } = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { EventEmitter } = require("node:events"); -const { createScpBackend, isScpModeClient } = require("./scpBackend.cjs"); -const { createFileOpsApi } = require("./fileOps.cjs"); -const { SCP_OK, buildFileControlLine } = require("./scpProtocol.cjs"); - -function createMockStream() { - const ee = new EventEmitter(); - ee.writable = true; - ee.readable = true; - ee.stderr = new EventEmitter(); - ee.write = (buf, cb) => { - ee.emit("_write", Buffer.from(buf)); - if (typeof cb === "function") cb(); - return true; - }; - ee.end = (cb) => { if (typeof cb === "function") cb(); }; - ee.close = () => ee.emit("close"); - ee.destroy = () => ee.emit("close"); - ee.pushFromRemote = (buf) => ee.emit("data", Buffer.from(buf)); - return ee; -} - -describe("SCP-mode session ops via fileOps entry points (AI/UI shared path)", () => { - let sftpClients; - let api; - let commands; - let tmpDir; - - beforeEach(() => { - tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-scp-session-")); - sftpClients = new Map(); - commands = []; - - const backend = createScpBackend({ - exec: async (command) => { - commands.push(command); - if (command.includes("for f in") || command.includes("cd ")) { - const name = Buffer.from("agent.txt").toString("base64"); - return { - stdout: `f|-rw-r--r--|4|1700000000|${name}\n`, - stderr: "", - code: 0, - }; - } - if (command.includes("mkdir")) return { stdout: "", stderr: "", code: 0 }; - if (command.includes("rm ") || command.includes("rmdir")) return { stdout: "", stderr: "", code: 0 }; - if (command.includes("mv ")) return { stdout: "", stderr: "", code: 0 }; - if (command.includes("$HOME") || command.startsWith("printf")) { - return { stdout: "/home/agent\n", stderr: "", code: 0 }; - } - if (command.includes("if [ ! -e")) { - return { - stdout: "f|-rw-r--r--|4|1700000000|/home/agent/agent.txt\n", - stderr: "", - code: 0, - }; - } - return { stdout: "", stderr: "", code: 0 }; - }, - execStream: async (command) => { - commands.push(command); - const stream = createMockStream(); - if (command.includes("scp -t")) { - setImmediate(() => stream.pushFromRemote(Buffer.from([SCP_OK]))); - stream.on("_write", (buf) => { - const text = buf.toString("utf8"); - if (text.startsWith("C") || (buf.length === 1 && buf[0] === 0x00)) { - setImmediate(() => stream.pushFromRemote(Buffer.from([SCP_OK]))); - } - }); - } else if (command.includes("scp -f")) { - let ackCount = 0; - stream.on("_write", (buf) => { - if (!(buf[0] === SCP_OK && buf.length === 1)) return; - ackCount += 1; - if (ackCount === 1) { - setImmediate(() => { - stream.pushFromRemote(buildFileControlLine({ mode: 0o644, size: 4, name: "agent.txt" })); - }); - } else if (ackCount === 2) { - setImmediate(() => { - stream.pushFromRemote(Buffer.concat([Buffer.from("data"), Buffer.from([0x00])])); - }); - } - }); - } - return stream; - }, - }); - - const client = { - client: { exec: () => {} }, - sftp: null, - __netcattyFileProtocol: "scp", - __netcattyScpBackend: backend, - async end() {}, - }; - sftpClients.set("scp-session-1", client); - - // Minimal ctx for createFileOpsApi — only what list/mkdir/rename/delete/write need - api = createFileOpsApi({ - get sftpClients() { return sftpClients; }, - get electronModule() { - return { - webContents: { fromId: () => ({ send: () => {} }) }, - }; - }, - fileWatcherBridge: { stopWatchersForSession: () => {} }, - fs, - path, - Buffer, - console, - setTimeout, - clearTimeout, - jumpConnectionsMap: new Map(), - sftpEncodingState: new Map(), - normalizeEncoding: (e) => e || "utf-8", - isAsciiString: () => true, - requireSftpChannel: async () => { throw new Error("should not use SFTP channel in SCP mode"); }, - resolveEncodingForRequest: () => "utf-8", - updateResolvedEncoding: () => "utf-8", - encodePath: (p) => p, - decodeName: (n) => n, - detectEncodingFromList: () => null, - statResultFromAttrs: (a) => a, - normalizeRemotePathString: async (_c, p) => p, - collectReadable: async () => Buffer.alloc(0), - writeToWritable: async () => {}, - throwIfAborted: () => {}, - pipeStreams: async () => {}, - ensureRemoteDirForSession: async () => true, - removeRemotePathInternal: async () => {}, - renameRemotePath: async () => {}, - realpathAsync: async () => "/", - statAsync: async () => ({}), - readdirAsync: async () => [], - mkdirAsync: async () => {}, - rmdirAsync: async () => {}, - unlinkAsync: async () => {}, - openFileAsync: async () => ({}), - writeFileChunkAsync: async () => {}, - closeFileAsync: async () => {}, - createAbortError: (s, m) => new Error(m), - copySftpEncodingState: () => {}, - clearSftpEncodingState: () => {}, - safeSend: () => {}, - tempDirBridge: { getTempFilePath: (n) => path.join(tmpDir, n) }, - randomUUID: () => "test-uuid", - }); - }); - - afterEach(() => { - try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* ignore */ } - }); - - it("marks clients as SCP-mode", () => { - assert.equal(isScpModeClient(sftpClients.get("scp-session-1")), true); - }); - - it("list works for SCP-mode session id (AI sftp.list path)", async () => { - const entries = await api.listSftp(null, { sftpId: "scp-session-1", path: "/home/agent" }); - assert.equal(entries.length, 1); - assert.equal(entries[0].name, "agent.txt"); - assert.ok(commands.some((c) => c.includes("cd ") || c.includes("for f in"))); - }); - - it("mkdir write-class op works for SCP-mode session (AI sftp.mkdir path)", async () => { - const ok = await api.mkdirSftp(null, { sftpId: "scp-session-1", path: "/home/agent/newdir" }); - assert.equal(ok, true); - assert.ok(commands.some((c) => c.includes("mkdir") && c.includes("/home/agent/newdir"))); - }); - - it("rename and delete work for SCP-mode session", async () => { - await api.renameSftp(null, { - sftpId: "scp-session-1", - oldPath: "/home/agent/a", - newPath: "/home/agent/b", - }); - await api.deleteSftp(null, { sftpId: "scp-session-1", path: "/home/agent/b" }); - assert.ok(commands.some((c) => c.includes("mv --"))); - assert.ok(commands.some((c) => c.includes("rm "))); - }); - - it("write + homeDir work for SCP-mode session", async () => { - await api.writeSftp(null, { - sftpId: "scp-session-1", - path: "/home/agent/out.txt", - content: "hi\n", - }); - assert.ok(commands.some((c) => c.includes("scp -t"))); - const home = await api.getSftpHomeDir(null, { sftpId: "scp-session-1" }); - assert.equal(home.success, true); - assert.equal(home.homeDir, "/home/agent"); - }); - - it("capability catalog still exposes stable sftp.* CLI verbs", () => { - const { SFTP_CAPABILITIES } = require("../../capabilities/catalog/sftp.cjs"); - const ids = SFTP_CAPABILITIES.map((c) => c.id); - for (const id of [ - "sftp.list", - "sftp.mkdir", - "sftp.write", - "sftp.upload", - "sftp.download", - "sftp.delete", - "sftp.rename", - ]) { - assert.ok(ids.includes(id), `missing capability ${id}`); - } - const listCap = SFTP_CAPABILITIES.find((c) => c.id === "sftp.list"); - assert.deepEqual(listCap.surfaces.cli.command, ["sftp", "list"]); - assert.match(listCap.description, /SCP-mode/i); - }); -}); diff --git a/electron/bridges/sshAuthHelper.identityFile.test.cjs b/electron/bridges/sshAuthHelper.keys.test.cjs similarity index 57% rename from electron/bridges/sshAuthHelper.identityFile.test.cjs rename to electron/bridges/sshAuthHelper.keys.test.cjs index 83af16270..2e66dd37d 100644 --- a/electron/bridges/sshAuthHelper.identityFile.test.cjs +++ b/electron/bridges/sshAuthHelper.keys.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from sshAuthHelper.identityFile.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); @@ -296,3 +300,186 @@ test("preparePrivateKeyForAuth throws when the passphrase prompt is cancelled", (err) => isPassphraseCancelledError(err), ); }); +} + +// --- merged from sshAuthHelper.pkcs8.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const crypto = require("node:crypto"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const { utils: sshUtils } = require("ssh2"); + +const { + preparePrivateKeyForAuth, + loadIdentityFileForAuth, +} = require("./sshAuthHelper.cjs"); +const passphraseHandler = require("./passphraseHandler.cjs"); + +function genRsaPkcs8(passphrase) { + return crypto.generateKeyPairSync("rsa", { + modulusLength: 2048, + privateKeyEncoding: passphrase + ? { type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase } + : { type: "pkcs8", format: "pem" }, + publicKeyEncoding: { type: "spki", format: "pem" }, + }).privateKey; +} + +function isParseable(key) { + const parsed = sshUtils.parseKey(key); + return !!parsed && !(parsed instanceof Error); +} + +const sender = { isDestroyed: () => false, send: () => {} }; + +test("preparePrivateKeyForAuth converts an unencrypted PKCS#8 key for ssh2", async () => { + const result = await preparePrivateKeyForAuth({ + sender, + privateKey: genRsaPkcs8(), + keyName: "oracle.key", + hostname: "example.test", + logPrefix: "[Test]", + }); + + assert.ok(result, "expected a prepared key"); + assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); +}); + +test("preparePrivateKeyForAuth decrypts and converts an encrypted PKCS#8 key", async (t) => { + const original = passphraseHandler.requestPassphrase; + t.after(() => { + passphraseHandler.requestPassphrase = original; + }); + + let calls = 0; + passphraseHandler.requestPassphrase = async () => { + calls += 1; + return calls === 1 ? { passphrase: "secret" } : { passphrase: null }; + }; + + const result = await preparePrivateKeyForAuth({ + sender, + privateKey: genRsaPkcs8("secret"), + keyName: "oracle.key", + hostname: "example.test", + logPrefix: "[Test]", + }); + + assert.ok(result, "expected a prepared key"); + assert.equal(calls, 1, "correct passphrase should not be re-prompted"); + assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); + assert.equal(result.passphrase, undefined, "passphrase is unnecessary after conversion"); +}); + +test("loadIdentityFileForAuth converts an unencrypted PKCS#8 identity file", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-pkcs8-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const keyPath = path.join(dir, "oracle.key"); + fs.writeFileSync(keyPath, genRsaPkcs8(), "utf8"); + + const result = await loadIdentityFileForAuth({ + sender, + keyPath, + hostname: "example.test", + logPrefix: "[Test]", + }); + + assert.ok(result, "expected a loaded identity file"); + assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); +}); + +test("preparePrivateKeyForAuth recovers a mangled encrypted OpenSSH key via passphrase prompt", async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-mangled-openssh-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const keyPath = path.join(dir, "id_ed25519"); + const gen = spawnSync( + "ssh-keygen", + ["-q", "-t", "ed25519", "-N", "secret", "-f", keyPath, "-C", "netcatty-test"], + { encoding: "utf8" }, + ); + if (gen.status !== 0) { + t.skip("ssh-keygen is unavailable"); + return; + } + // Simulate a key whose line breaks were flattened into literal "\n" on paste. + const mangled = fs.readFileSync(keyPath, "utf8").replace(/\n/g, "\\n"); + + const originalRequest = passphraseHandler.requestPassphrase; + t.after(() => { + passphraseHandler.requestPassphrase = originalRequest; + }); + let prompts = 0; + passphraseHandler.requestPassphrase = async () => { + prompts += 1; + return { passphrase: "secret" }; + }; + + const result = await preparePrivateKeyForAuth({ + sender, + privateKey: mangled, + keyName: "id_ed25519", + hostname: "example.test", + logPrefix: "[Test]", + }); + + assert.ok(result, "expected a prepared key"); + assert.equal(prompts, 1, "the encrypted key should trigger exactly one passphrase prompt"); + assert.equal(result.passphrase, "secret"); + const parsed = sshUtils.parseKey(result.privateKey, result.passphrase); + assert.ok(parsed && !(parsed instanceof Error), "prepared key + passphrase should parse in ssh2"); +}); +} + +// --- merged from sshAuthHelper.userConfiguredKey.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { hasUserConfiguredKey } = require("./sshAuthHelper.cjs"); + +test("hasUserConfiguredKey is true for inline private key material", () => { + assert.equal(hasUserConfiguredKey({ privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----" }), true); +}); + +test("hasUserConfiguredKey is false for empty or whitespace inline keys", () => { + assert.equal(hasUserConfiguredKey({ privateKey: "" }), false); + assert.equal(hasUserConfiguredKey({ privateKey: " " }), false); + assert.equal(hasUserConfiguredKey({}), false); +}); + +test("hasUserConfiguredKey is true for Keychain reference identity file paths", () => { + assert.equal( + hasUserConfiguredKey({ identityFilePaths: ["/Users/alice/.ssh/id_ed25519"] }), + true, + ); +}); + +test("hasUserConfiguredKey is false for empty identity file path lists", () => { + assert.equal(hasUserConfiguredKey({ identityFilePaths: [] }), false); + assert.equal(hasUserConfiguredKey({ identityFilePaths: null }), false); +}); + +test("hasUserConfiguredKey prefers explicit inline key over empty paths", () => { + assert.equal( + hasUserConfiguredKey({ + privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----", + identityFilePaths: [], + }), + true, + ); +}); + +test("isPasswordProvided accepts whitespace-only passwords (#2036)", () => { + const { isPasswordProvided } = require("./sshAuthHelper.cjs"); + assert.equal(isPasswordProvided(""), false); + assert.equal(isPasswordProvided(" "), true); + assert.equal(isPasswordProvided(" "), true); + assert.equal(isPasswordProvided("secret"), true); + assert.equal(isPasswordProvided(null), false); + assert.equal(isPasswordProvided(undefined), false); +}); +} diff --git a/electron/bridges/sshAuthHelper.passwordOnly.test.cjs b/electron/bridges/sshAuthHelper.passwordAndTotp.test.cjs similarity index 68% rename from electron/bridges/sshAuthHelper.passwordOnly.test.cjs rename to electron/bridges/sshAuthHelper.passwordAndTotp.test.cjs index 0c765ad3b..dec048caf 100644 --- a/electron/bridges/sshAuthHelper.passwordOnly.test.cjs +++ b/electron/bridges/sshAuthHelper.passwordAndTotp.test.cjs @@ -1,5 +1,7 @@ "use strict"; +// --- merged from sshAuthHelper.passwordOnly.test.cjs --- +{ /** * Password-only auth must not probe default ~/.ssh keys (issues #266 / #2079). * Jump hosts and SFTP share buildAuthHandler; a wrong host password used to @@ -279,3 +281,152 @@ test("buildAuthHandler password-only may still attach unlocked encrypted keys fo `jump-chain retry may still offer unlocked keys; offered=${labels.join(",")}`, ); }); +} + +// --- merged from sshAuthHelper.totp.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { createKeyboardInteractiveHandler } = require("./sshAuthHelper.cjs"); +const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs"); +const { encodeBase32, generateTotp } = require("../../domain/totp.shared.cjs"); + +const SECRET = Buffer.from("12345678901234567890", "ascii"); +const TOTP = { + uri: `otpauth://totp/JumpServer:root?secret=${encodeBase32(SECRET)}&digits=8&period=30`, + autoSubmit: true, +}; + +const createSender = () => { + const sent = []; + return { + sent, + sender: { + id: 7, + isDestroyed: () => false, + send: (channel, payload) => sent.push({ channel, payload }), + }, + }; +}; + +const drainPendingRequests = (sent, senderId = 7) => { + for (const event of sent) { + if (event.channel !== "netcatty:keyboard-interactive") continue; + const requestId = event.payload?.requestId; + if (requestId) { + keyboardInteractiveHandler.handleResponse({ sender: { id: senderId } }, { requestId, cancelled: true }); + } + } +}; + +const invoke = (handler, prompt, instructions = "") => { + let finished = null; + handler("root", instructions, "", [{ prompt, echo: true }], (responses) => { + finished = responses; + }); + return finished; +}; + +test("TOTP auto-submit runs once per connection attempt, then falls back to the dialog", () => { + const { sender, sent } = createSender(); + const handler = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-1", + hostname: "jumpserver.example", + totp: TOTP, + now: () => 15_000, + }); + const expected = generateTotp({ + secret: SECRET, + algorithm: "SHA1", + digits: 8, + period: 30, + timestamp: 15_000, + }); + + assert.deepEqual(invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."), [expected]); + assert.equal(sent.length, 0); + + const retry = invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."); + assert.equal(retry, null); + assert.equal(sent.length, 1); + assert.equal(sent[0].channel, "netcatty:keyboard-interactive"); + assert.equal(sent[0].payload.totpUri, TOTP.uri); + drainPendingRequests(sent); +}); + +test("keyboard-interactive dialog omits an encrypted TOTP placeholder", () => { + const { sender, sent } = createSender(); + const handler = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-enc", + hostname: "jumpserver.example", + totp: { uri: "enc:v1:placeholder" }, + now: () => 15_000, + }); + assert.equal(invoke(handler, "[OTP Code]: "), null); + assert.equal(sent.length, 1); + assert.equal(sent[0].payload.totpUri, undefined); + drainPendingRequests(sent); +}); + +test("a non-matching prompt does not consume the one TOTP auto-submit", () => { + const { sender, sent } = createSender(); + const handler = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-2", + hostname: "jumpserver.example", + totp: TOTP, + now: () => 15_000, + }); + + assert.equal(invoke(handler, "\n1. OTP\n2. SMS\nOption> ", "Please Select MFA Option"), null); + assert.equal(sent.length, 1); + assert.equal(sent[0].payload.totpUri, TOTP.uri); + drainPendingRequests(sent); + + const code = invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."); + assert.equal(code?.[0]?.length, 8); + assert.equal(sent.length, 1); +}); + +test("SMS, email, and confirmation prompts are never auto-answered", () => { + const { sender, sent } = createSender(); + const handler = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-3", + hostname: "jumpserver.example", + totp: TOTP, + now: () => 15_000, + }); + for (const prompt of ["[SMS Code]: ", "[EMAIL Code]: ", "Do you want to continue [Y/n]? : "]) { + assert.equal(invoke(handler, prompt), null); + } + assert.equal(sent.length, 3); + drainPendingRequests(sent); +}); + +test("legacy JumpServer and PAM prompts auto-submit, and a later mismatch opens the dialog", () => { + const { sender, sent } = createSender(); + const handler = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-4", + hostname: "pam.example", + totp: TOTP, + now: () => 15_000, + }); + assert.equal(invoke(handler, "[MFA auth]: ")?.[0]?.length, 8); + const fresh = createKeyboardInteractiveHandler({ + sender, + sessionId: "session-5", + hostname: "pam.example", + totp: { ...TOTP }, + now: () => 15_000, + }); + assert.equal(invoke(fresh, "Verification code: ")?.[0]?.length, 8); + assert.equal(invoke(fresh, "Password:"), null); + assert.equal(sent.length, 1); + drainPendingRequests(sent); +}); +} diff --git a/electron/bridges/sshAuthHelper.pkcs8.test.cjs b/electron/bridges/sshAuthHelper.pkcs8.test.cjs deleted file mode 100644 index 0641b03ba..000000000 --- a/electron/bridges/sshAuthHelper.pkcs8.test.cjs +++ /dev/null @@ -1,128 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const crypto = require("node:crypto"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const { utils: sshUtils } = require("ssh2"); - -const { - preparePrivateKeyForAuth, - loadIdentityFileForAuth, -} = require("./sshAuthHelper.cjs"); -const passphraseHandler = require("./passphraseHandler.cjs"); - -function genRsaPkcs8(passphrase) { - return crypto.generateKeyPairSync("rsa", { - modulusLength: 2048, - privateKeyEncoding: passphrase - ? { type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase } - : { type: "pkcs8", format: "pem" }, - publicKeyEncoding: { type: "spki", format: "pem" }, - }).privateKey; -} - -function isParseable(key) { - const parsed = sshUtils.parseKey(key); - return !!parsed && !(parsed instanceof Error); -} - -const sender = { isDestroyed: () => false, send: () => {} }; - -test("preparePrivateKeyForAuth converts an unencrypted PKCS#8 key for ssh2", async () => { - const result = await preparePrivateKeyForAuth({ - sender, - privateKey: genRsaPkcs8(), - keyName: "oracle.key", - hostname: "example.test", - logPrefix: "[Test]", - }); - - assert.ok(result, "expected a prepared key"); - assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); -}); - -test("preparePrivateKeyForAuth decrypts and converts an encrypted PKCS#8 key", async (t) => { - const original = passphraseHandler.requestPassphrase; - t.after(() => { - passphraseHandler.requestPassphrase = original; - }); - - let calls = 0; - passphraseHandler.requestPassphrase = async () => { - calls += 1; - return calls === 1 ? { passphrase: "secret" } : { passphrase: null }; - }; - - const result = await preparePrivateKeyForAuth({ - sender, - privateKey: genRsaPkcs8("secret"), - keyName: "oracle.key", - hostname: "example.test", - logPrefix: "[Test]", - }); - - assert.ok(result, "expected a prepared key"); - assert.equal(calls, 1, "correct passphrase should not be re-prompted"); - assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); - assert.equal(result.passphrase, undefined, "passphrase is unnecessary after conversion"); -}); - -test("loadIdentityFileForAuth converts an unencrypted PKCS#8 identity file", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-pkcs8-")); - t.after(() => fs.rmSync(dir, { recursive: true, force: true })); - const keyPath = path.join(dir, "oracle.key"); - fs.writeFileSync(keyPath, genRsaPkcs8(), "utf8"); - - const result = await loadIdentityFileForAuth({ - sender, - keyPath, - hostname: "example.test", - logPrefix: "[Test]", - }); - - assert.ok(result, "expected a loaded identity file"); - assert.ok(isParseable(result.privateKey), "prepared key should be parseable by ssh2"); -}); - -test("preparePrivateKeyForAuth recovers a mangled encrypted OpenSSH key via passphrase prompt", async (t) => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-mangled-openssh-")); - t.after(() => fs.rmSync(dir, { recursive: true, force: true })); - const keyPath = path.join(dir, "id_ed25519"); - const gen = spawnSync( - "ssh-keygen", - ["-q", "-t", "ed25519", "-N", "secret", "-f", keyPath, "-C", "netcatty-test"], - { encoding: "utf8" }, - ); - if (gen.status !== 0) { - t.skip("ssh-keygen is unavailable"); - return; - } - // Simulate a key whose line breaks were flattened into literal "\n" on paste. - const mangled = fs.readFileSync(keyPath, "utf8").replace(/\n/g, "\\n"); - - const originalRequest = passphraseHandler.requestPassphrase; - t.after(() => { - passphraseHandler.requestPassphrase = originalRequest; - }); - let prompts = 0; - passphraseHandler.requestPassphrase = async () => { - prompts += 1; - return { passphrase: "secret" }; - }; - - const result = await preparePrivateKeyForAuth({ - sender, - privateKey: mangled, - keyName: "id_ed25519", - hostname: "example.test", - logPrefix: "[Test]", - }); - - assert.ok(result, "expected a prepared key"); - assert.equal(prompts, 1, "the encrypted key should trigger exactly one passphrase prompt"); - assert.equal(result.passphrase, "secret"); - const parsed = sshUtils.parseKey(result.privateKey, result.passphrase); - assert.ok(parsed && !(parsed instanceof Error), "prepared key + passphrase should parse in ssh2"); -}); diff --git a/electron/bridges/sshAuthHelper.totp.test.cjs b/electron/bridges/sshAuthHelper.totp.test.cjs deleted file mode 100644 index 96e7f6aa1..000000000 --- a/electron/bridges/sshAuthHelper.totp.test.cjs +++ /dev/null @@ -1,144 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { createKeyboardInteractiveHandler } = require("./sshAuthHelper.cjs"); -const keyboardInteractiveHandler = require("./keyboardInteractiveHandler.cjs"); -const { encodeBase32, generateTotp } = require("../../domain/totp.shared.cjs"); - -const SECRET = Buffer.from("12345678901234567890", "ascii"); -const TOTP = { - uri: `otpauth://totp/JumpServer:root?secret=${encodeBase32(SECRET)}&digits=8&period=30`, - autoSubmit: true, -}; - -const createSender = () => { - const sent = []; - return { - sent, - sender: { - id: 7, - isDestroyed: () => false, - send: (channel, payload) => sent.push({ channel, payload }), - }, - }; -}; - -const drainPendingRequests = (sent, senderId = 7) => { - for (const event of sent) { - if (event.channel !== "netcatty:keyboard-interactive") continue; - const requestId = event.payload?.requestId; - if (requestId) { - keyboardInteractiveHandler.handleResponse({ sender: { id: senderId } }, { requestId, cancelled: true }); - } - } -}; - -const invoke = (handler, prompt, instructions = "") => { - let finished = null; - handler("root", instructions, "", [{ prompt, echo: true }], (responses) => { - finished = responses; - }); - return finished; -}; - -test("TOTP auto-submit runs once per connection attempt, then falls back to the dialog", () => { - const { sender, sent } = createSender(); - const handler = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-1", - hostname: "jumpserver.example", - totp: TOTP, - now: () => 15_000, - }); - const expected = generateTotp({ - secret: SECRET, - algorithm: "SHA1", - digits: 8, - period: 30, - timestamp: 15_000, - }); - - assert.deepEqual(invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."), [expected]); - assert.equal(sent.length, 0); - - const retry = invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."); - assert.equal(retry, null); - assert.equal(sent.length, 1); - assert.equal(sent[0].channel, "netcatty:keyboard-interactive"); - assert.equal(sent[0].payload.totpUri, TOTP.uri); - drainPendingRequests(sent); -}); - -test("keyboard-interactive dialog omits an encrypted TOTP placeholder", () => { - const { sender, sent } = createSender(); - const handler = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-enc", - hostname: "jumpserver.example", - totp: { uri: "enc:v1:placeholder" }, - now: () => 15_000, - }); - assert.equal(invoke(handler, "[OTP Code]: "), null); - assert.equal(sent.length, 1); - assert.equal(sent[0].payload.totpUri, undefined); - drainPendingRequests(sent); -}); - -test("a non-matching prompt does not consume the one TOTP auto-submit", () => { - const { sender, sent } = createSender(); - const handler = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-2", - hostname: "jumpserver.example", - totp: TOTP, - now: () => 15_000, - }); - - assert.equal(invoke(handler, "\n1. OTP\n2. SMS\nOption> ", "Please Select MFA Option"), null); - assert.equal(sent.length, 1); - assert.equal(sent[0].payload.totpUri, TOTP.uri); - drainPendingRequests(sent); - - const code = invoke(handler, "[OTP Code]: ", "Please Enter MFA Code."); - assert.equal(code?.[0]?.length, 8); - assert.equal(sent.length, 1); -}); - -test("SMS, email, and confirmation prompts are never auto-answered", () => { - const { sender, sent } = createSender(); - const handler = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-3", - hostname: "jumpserver.example", - totp: TOTP, - now: () => 15_000, - }); - for (const prompt of ["[SMS Code]: ", "[EMAIL Code]: ", "Do you want to continue [Y/n]? : "]) { - assert.equal(invoke(handler, prompt), null); - } - assert.equal(sent.length, 3); - drainPendingRequests(sent); -}); - -test("legacy JumpServer and PAM prompts auto-submit, and a later mismatch opens the dialog", () => { - const { sender, sent } = createSender(); - const handler = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-4", - hostname: "pam.example", - totp: TOTP, - now: () => 15_000, - }); - assert.equal(invoke(handler, "[MFA auth]: ")?.[0]?.length, 8); - const fresh = createKeyboardInteractiveHandler({ - sender, - sessionId: "session-5", - hostname: "pam.example", - totp: { ...TOTP }, - now: () => 15_000, - }); - assert.equal(invoke(fresh, "Verification code: ")?.[0]?.length, 8); - assert.equal(invoke(fresh, "Password:"), null); - assert.equal(sent.length, 1); - drainPendingRequests(sent); -}); diff --git a/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs b/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs deleted file mode 100644 index 56c1206a4..000000000 --- a/electron/bridges/sshAuthHelper.userConfiguredKey.test.cjs +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { hasUserConfiguredKey } = require("./sshAuthHelper.cjs"); - -test("hasUserConfiguredKey is true for inline private key material", () => { - assert.equal(hasUserConfiguredKey({ privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----" }), true); -}); - -test("hasUserConfiguredKey is false for empty or whitespace inline keys", () => { - assert.equal(hasUserConfiguredKey({ privateKey: "" }), false); - assert.equal(hasUserConfiguredKey({ privateKey: " " }), false); - assert.equal(hasUserConfiguredKey({}), false); -}); - -test("hasUserConfiguredKey is true for Keychain reference identity file paths", () => { - assert.equal( - hasUserConfiguredKey({ identityFilePaths: ["/Users/alice/.ssh/id_ed25519"] }), - true, - ); -}); - -test("hasUserConfiguredKey is false for empty identity file path lists", () => { - assert.equal(hasUserConfiguredKey({ identityFilePaths: [] }), false); - assert.equal(hasUserConfiguredKey({ identityFilePaths: null }), false); -}); - -test("hasUserConfiguredKey prefers explicit inline key over empty paths", () => { - assert.equal( - hasUserConfiguredKey({ - privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----", - identityFilePaths: [], - }), - true, - ); -}); - -test("isPasswordProvided accepts whitespace-only passwords (#2036)", () => { - const { isPasswordProvided } = require("./sshAuthHelper.cjs"); - assert.equal(isPasswordProvided(""), false); - assert.equal(isPasswordProvided(" "), true); - assert.equal(isPasswordProvided(" "), true); - assert.equal(isPasswordProvided("secret"), true); - assert.equal(isPasswordProvided(null), false); - assert.equal(isPasswordProvided(undefined), false); -}); diff --git a/electron/bridges/sshBridge.agentFallback.test.cjs b/electron/bridges/sshBridge.agentFallback.test.cjs index 3d9569a8b..922f31501 100644 --- a/electron/bridges/sshBridge.agentFallback.test.cjs +++ b/electron/bridges/sshBridge.agentFallback.test.cjs @@ -1,5 +1,7 @@ "use strict"; +// --- merged from sshBridge.agentFallback.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const crypto = require("node:crypto"); @@ -191,3 +193,83 @@ test("normal SSH startup preserves fallback after an unavailable system agent", assert.equal(result.shells, 0); }); }); +} + +// --- merged from sshBridge.strictAgentRetry.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { + _canFailedHopRetryWithEncryptedDefaultKeys, + _canRetryWithEncryptedDefaultKeys, + _isStrictAgentAuthFailure, +} = require("./sshBridge.cjs"); + +test("strict agent failures skip encrypted default-key prompts", () => { + const jumpHosts = [ + { hostname: "shared.example", useSshAgent: false }, + { hostname: "shared.example", useSshAgent: true, identitiesOnly: true }, + ]; + assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { + isJumpHostAuthError: true, + jumpHostIndex: 1, + jumpHostHostname: "shared.example", + }), true); + assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { + isJumpHostAuthError: true, + jumpHostIndex: 0, + jumpHostHostname: "shared.example", + }), false); + assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { + isJumpHostAuthError: true, + jumpHostHostname: "shared.example", + }), false, "ambiguous legacy errors must not guess the failed hop"); +}); + +test("encrypted default-key retry is limited to automatic or legacy hops", () => { + assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "password" }), false); + assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "key" }), false); + assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "certificate" }), false); + assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "auto" }), true); + assert.equal(_canRetryWithEncryptedDefaultKeys({ + authMethod: "password", + jumpHosts: [{ authMethod: "auto" }], + }), true); + assert.equal(_canRetryWithEncryptedDefaultKeys({ + authMethod: "password", + jumpHosts: [{ authMethod: "password" }, { authMethod: "key" }], + }), false); + assert.equal(_canRetryWithEncryptedDefaultKeys({ + authMethod: "auto", + _unlockedEncryptedKeys: [{ keyName: "id_work" }], + }), false); +}); + +test("encrypted default-key prompts follow the hop that actually failed", () => { + const automaticJumpExplicitTarget = { + authMethod: "password", + jumpHosts: [{ authMethod: "auto", hostname: "jump.example" }], + }; + assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( + automaticJumpExplicitTarget, + { level: "client-authentication" }, + ), false); + assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( + automaticJumpExplicitTarget, + { isJumpHostAuthError: true, jumpHostIndex: 0 }, + ), true); + + const automaticTargetExplicitJump = { + authMethod: "auto", + jumpHosts: [{ authMethod: "key", hostname: "jump.example" }], + }; + assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( + automaticTargetExplicitJump, + { level: "client-authentication" }, + ), true); + assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( + automaticTargetExplicitJump, + { isJumpHostAuthError: true, jumpHostIndex: 0 }, + ), false); +}); +} diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 929decc77..bdab2bd51 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -21,6 +21,8 @@ const { createProxySocket, runWhenProxyConnectionReady } = require("./proxyUtils const { attachX11Forwarding } = require("./x11Forwarding.cjs"); const { createPtyOutputBuffer } = require("./ptyOutputBuffer.cjs"); const { + PREFERRED_KEY_NAMES, + SSH_KEY_PATTERN, buildAuthHandler, createKeyboardInteractiveHandler, createOrderedStringAuthHandler, @@ -31,6 +33,9 @@ const { applyAuthToConnOpts, safeSend: authSafeSend, requestPassphrasesForEncryptedKeys, + isKeyEncrypted, + findDefaultPrivateKey, + findAllDefaultPrivateKeys, findAllDefaultPrivateKeys: findAllDefaultPrivateKeysFromHelper, getSshAgentSocket, getAvailableAgentSocket: getAvailableSystemAgentSocket, @@ -62,11 +67,6 @@ const { createSshPingLatencyProbe } = require("./sshBridge/sshPingLatency.cjs"); const { configureTerminalSessionDataEmitter, } = require("./emitTerminalSessionData.cjs"); - -// Default SSH key names in priority order (preferred keys tried first) -const PREFERRED_KEY_NAMES = ["id_ed25519", "id_ecdsa", "id_rsa"]; -// Match any private key file: id_* but not *.pub -const SSH_KEY_PATTERN = /^id_[\w-]+$/; const { createStartSessionApi, cancelTestConnection, @@ -84,168 +84,6 @@ function hasUsableProxy(proxy) { return !!(proxy.host && proxy.port); } -/** - * Quick check if file content looks like an SSH private key. - * Rejects non-key files that happen to match the id_* filename pattern. - */ -function looksLikePrivateKey(content) { - if (!content || typeof content !== "string") return false; - const trimmed = content.trimStart(); - return trimmed.startsWith("-----BEGIN") || - trimmed.startsWith("openssh-key-v1") || - trimmed.startsWith("PuTTY-User-Key-File"); -} - -/** - * Check if an SSH private key is encrypted (requires passphrase) - * @param {string} keyContent - The content of the private key file - * @returns {boolean} - True if the key is encrypted - */ -function isKeyEncrypted(keyContent) { - // Check for PuTTY PPK encrypted format - const ppkEncMatch = keyContent.match(/^Encryption:\s*(.+)$/m); - if (ppkEncMatch && ppkEncMatch[1].trim() !== "none") { - return true; - } - - // Check for PKCS#8 encrypted format (-----BEGIN ENCRYPTED PRIVATE KEY-----) - if (keyContent.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")) { - return true; - } - - // Check for legacy PEM format encryption (e.g., RSA PRIVATE KEY with encryption) - if (keyContent.includes("Proc-Type:") && keyContent.includes("ENCRYPTED")) { - return true; - } - - // Check for OpenSSH format keys - if (keyContent.includes("-----BEGIN OPENSSH PRIVATE KEY-----")) { - try { - // Extract the base64 content between the markers - const base64Match = keyContent.match( - /-----BEGIN OPENSSH PRIVATE KEY-----\s*([\s\S]*?)\s*-----END OPENSSH PRIVATE KEY-----/ - ); - if (base64Match) { - const base64Content = base64Match[1].replace(/\s/g, ""); - const keyBuffer = Buffer.from(base64Content, "base64"); - - // OpenSSH key format: "openssh-key-v1\0" followed by cipher name - // If ciphername is "none", the key is not encrypted - const authMagic = "openssh-key-v1\0"; - if (keyBuffer.toString("ascii", 0, authMagic.length) === authMagic) { - // After magic, read ciphername (length-prefixed string) - let offset = authMagic.length; - const cipherNameLen = keyBuffer.readUInt32BE(offset); - offset += 4; - const cipherName = keyBuffer.toString("ascii", offset, offset + cipherNameLen); - return cipherName !== "none"; - } - } - } catch { - // If parsing fails, assume it might be encrypted to be safe - return true; - } - } - - return false; -} - -/** - * Find default SSH private key from user's ~/.ssh directory - * Skips encrypted keys that require a passphrase to allow password/keyboard-interactive auth - * @returns {Promise<{ privateKey: string, keyPath: string, keyName: string } | null>} - */ -async function findDefaultPrivateKey() { - const sshDir = path.join(os.homedir(), ".ssh"); - // Scan ~/.ssh/ for all files matching id_* (same as Tabby/OpenSSH), - // with preferred key types tried first - let allNames = []; - try { - const entries = await fs.promises.readdir(sshDir); - allNames = entries.filter(f => SSH_KEY_PATTERN.test(f)); - } catch { - return null; - } - // Sort: preferred keys first (in order), then rest alphabetically - const preferred = PREFERRED_KEY_NAMES.filter(n => allNames.includes(n)); - const rest = allNames.filter(n => !PREFERRED_KEY_NAMES.includes(n)).sort(); - const sorted = [...preferred, ...rest]; - log("Searching for default SSH keys", { sshDir, found: sorted }); - - for (const name of sorted) { - const keyPath = path.join(sshDir, name); - try { - const privateKey = await readFileNoFollow(keyPath); - if (!privateKey) continue; - if (!looksLikePrivateKey(privateKey)) { - log("Skipping non-key file", { keyPath, keyName: name }); - continue; - } - const encrypted = isKeyEncrypted(privateKey); - log("Key file read", { keyPath, keyName: name, encrypted, keyLength: privateKey.length }); - if (encrypted) { - log("Skipping encrypted default key", { keyPath, keyName: name }); - continue; - } - log("Found default key", { keyPath, keyName: name }); - return { privateKey, keyPath, keyName: name }; - } catch (e) { - log("Failed to read default key", { keyPath, error: e.message }); - continue; - } - } - log("No suitable default SSH key found"); - return null; -} - -/** - * Find ALL default SSH private keys from user's ~/.ssh directory - * Returns all non-encrypted keys for fallback authentication - * @returns {Promise>} - */ -async function findAllDefaultPrivateKeys() { - const sshDir = path.join(os.homedir(), ".ssh"); - let allNames = []; - try { - const entries = await fs.promises.readdir(sshDir); - allNames = entries.filter(f => SSH_KEY_PATTERN.test(f)); - } catch { - return []; - } - const preferred = PREFERRED_KEY_NAMES.filter(n => allNames.includes(n)); - const rest = allNames.filter(n => !PREFERRED_KEY_NAMES.includes(n)).sort(); - const sorted = [...preferred, ...rest]; - log("Searching for ALL default SSH keys", { sshDir, found: sorted }); - - const promises = sorted.map(async (name) => { - const keyPath = path.join(sshDir, name); - try { - const privateKey = await readFileNoFollow(keyPath); - if (!privateKey) return null; - if (!looksLikePrivateKey(privateKey)) { - log("Skipping non-key file", { keyPath, keyName: name }); - return null; - } - const encrypted = isKeyEncrypted(privateKey); - if (!encrypted) { - log("Found default key for fallback", { keyPath, keyName: name }); - return { privateKey, keyPath, keyName: name }; - } else { - log("Skipping encrypted key", { keyPath, keyName: name }); - return null; - } - } catch (e) { - log("Failed to read key", { keyPath, error: e.message }); - return null; - } - }); - - const results = await Promise.all(promises); - const keys = results.filter(Boolean); - log("Found default SSH keys", { count: keys.length, keyNames: keys.map(k => k.keyName) }); - return keys; -} - const WIN_SSH_AGENT_PIPE = "\\\\.\\pipe\\openssh-ssh-agent"; /** diff --git a/electron/bridges/sshBridge.connectionTimeout.test.cjs b/electron/bridges/sshBridge.connectionTimeout.test.cjs index bc48ba5ab..cb4bf4d62 100644 --- a/electron/bridges/sshBridge.connectionTimeout.test.cjs +++ b/electron/bridges/sshBridge.connectionTimeout.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from sshBridge.connectionTimeout.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const { EventEmitter } = require("node:events"); @@ -263,3 +267,43 @@ test("SSH authentication timeout starts only after TCP connects", async (t) => { assert.ok(Date.now() - startedAt >= 900); assert.equal(MockSSHClient.instances[0].connectOpts.timeout, 45_000); }); +} + +// --- merged from sshBridge.connectionTimeouts.test.cjs --- +{ +const assert = require("node:assert/strict"); +const test = require("node:test"); + +const { + SSH_AUTH_READY_TIMEOUT_MS, + SSH_TCP_CONNECT_TIMEOUT_MS, + resolveSshConnectionTimeouts, +} = require("./sshBridge/startSession.cjs"); + +test("SSH bridge uses default connection timeouts", () => { + assert.deepEqual(resolveSshConnectionTimeouts({}), { + tcpConnectTimeoutMs: SSH_TCP_CONNECT_TIMEOUT_MS, + authReadyTimeoutMs: SSH_AUTH_READY_TIMEOUT_MS, + }); +}); + +test("SSH bridge accepts valid custom connection timeouts", () => { + assert.deepEqual(resolveSshConnectionTimeouts({ + sshTcpConnectTimeoutMs: 45_000, + sshAuthReadyTimeoutMs: 300_000, + }), { + tcpConnectTimeoutMs: 45_000, + authReadyTimeoutMs: 300_000, + }); +}); + +test("SSH bridge rejects invalid custom connection timeouts", () => { + assert.deepEqual(resolveSshConnectionTimeouts({ + sshTcpConnectTimeoutMs: 0, + sshAuthReadyTimeoutMs: 3_600_001, + }), { + tcpConnectTimeoutMs: SSH_TCP_CONNECT_TIMEOUT_MS, + authReadyTimeoutMs: SSH_AUTH_READY_TIMEOUT_MS, + }); +}); +} diff --git a/electron/bridges/sshBridge.connectionTimeouts.test.cjs b/electron/bridges/sshBridge.connectionTimeouts.test.cjs deleted file mode 100644 index 2101fd14e..000000000 --- a/electron/bridges/sshBridge.connectionTimeouts.test.cjs +++ /dev/null @@ -1,35 +0,0 @@ -const assert = require("node:assert/strict"); -const test = require("node:test"); - -const { - SSH_AUTH_READY_TIMEOUT_MS, - SSH_TCP_CONNECT_TIMEOUT_MS, - resolveSshConnectionTimeouts, -} = require("./sshBridge/startSession.cjs"); - -test("SSH bridge uses default connection timeouts", () => { - assert.deepEqual(resolveSshConnectionTimeouts({}), { - tcpConnectTimeoutMs: SSH_TCP_CONNECT_TIMEOUT_MS, - authReadyTimeoutMs: SSH_AUTH_READY_TIMEOUT_MS, - }); -}); - -test("SSH bridge accepts valid custom connection timeouts", () => { - assert.deepEqual(resolveSshConnectionTimeouts({ - sshTcpConnectTimeoutMs: 45_000, - sshAuthReadyTimeoutMs: 300_000, - }), { - tcpConnectTimeoutMs: 45_000, - authReadyTimeoutMs: 300_000, - }); -}); - -test("SSH bridge rejects invalid custom connection timeouts", () => { - assert.deepEqual(resolveSshConnectionTimeouts({ - sshTcpConnectTimeoutMs: 0, - sshAuthReadyTimeoutMs: 3_600_001, - }), { - tcpConnectTimeoutMs: SSH_TCP_CONNECT_TIMEOUT_MS, - authReadyTimeoutMs: SSH_AUTH_READY_TIMEOUT_MS, - }); -}); diff --git a/electron/bridges/sshBridge.strictAgentRetry.test.cjs b/electron/bridges/sshBridge.strictAgentRetry.test.cjs deleted file mode 100644 index e7d7b0e00..000000000 --- a/electron/bridges/sshBridge.strictAgentRetry.test.cjs +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { - _canFailedHopRetryWithEncryptedDefaultKeys, - _canRetryWithEncryptedDefaultKeys, - _isStrictAgentAuthFailure, -} = require("./sshBridge.cjs"); - -test("strict agent failures skip encrypted default-key prompts", () => { - const jumpHosts = [ - { hostname: "shared.example", useSshAgent: false }, - { hostname: "shared.example", useSshAgent: true, identitiesOnly: true }, - ]; - assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { - isJumpHostAuthError: true, - jumpHostIndex: 1, - jumpHostHostname: "shared.example", - }), true); - assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { - isJumpHostAuthError: true, - jumpHostIndex: 0, - jumpHostHostname: "shared.example", - }), false); - assert.equal(_isStrictAgentAuthFailure({ jumpHosts }, { - isJumpHostAuthError: true, - jumpHostHostname: "shared.example", - }), false, "ambiguous legacy errors must not guess the failed hop"); -}); - -test("encrypted default-key retry is limited to automatic or legacy hops", () => { - assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "password" }), false); - assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "key" }), false); - assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "certificate" }), false); - assert.equal(_canRetryWithEncryptedDefaultKeys({ authMethod: "auto" }), true); - assert.equal(_canRetryWithEncryptedDefaultKeys({ - authMethod: "password", - jumpHosts: [{ authMethod: "auto" }], - }), true); - assert.equal(_canRetryWithEncryptedDefaultKeys({ - authMethod: "password", - jumpHosts: [{ authMethod: "password" }, { authMethod: "key" }], - }), false); - assert.equal(_canRetryWithEncryptedDefaultKeys({ - authMethod: "auto", - _unlockedEncryptedKeys: [{ keyName: "id_work" }], - }), false); -}); - -test("encrypted default-key prompts follow the hop that actually failed", () => { - const automaticJumpExplicitTarget = { - authMethod: "password", - jumpHosts: [{ authMethod: "auto", hostname: "jump.example" }], - }; - assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( - automaticJumpExplicitTarget, - { level: "client-authentication" }, - ), false); - assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( - automaticJumpExplicitTarget, - { isJumpHostAuthError: true, jumpHostIndex: 0 }, - ), true); - - const automaticTargetExplicitJump = { - authMethod: "auto", - jumpHosts: [{ authMethod: "key", hostname: "jump.example" }], - }; - assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( - automaticTargetExplicitJump, - { level: "client-authentication" }, - ), true); - assert.equal(_canFailedHopRetryWithEncryptedDefaultKeys( - automaticTargetExplicitJump, - { isJumpHostAuthError: true, jumpHostIndex: 0 }, - ), false); -}); diff --git a/electron/bridges/sshBridge.zmodemBackpressure.test.cjs b/electron/bridges/sshBridge.zmodemBackpressure.test.cjs deleted file mode 100644 index 44eceb025..000000000 --- a/electron/bridges/sshBridge.zmodemBackpressure.test.cjs +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; - -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const test = require("node:test"); - -test("SSH ZMODEM uploads wire stream backpressure to a real drain wait", () => { - const bridgeSource = fs.readFileSync(require.resolve("./sshBridge.cjs"), "utf8"); - const zmodemSource = fs.readFileSync(require.resolve("./zmodemHelper.cjs"), "utf8"); - const startSessionSource = fs.readFileSync( - require.resolve("./sshBridge/startSession.cjs"), - "utf8", - ); - - assert.match( - bridgeSource, - /createZmodemSentry,\s*waitForWritableDrain/, - "sshBridge must pass the shared drain helper into the SSH session factory", - ); - assert.match( - startSessionSource, - /waitForTransportDrain\(drainOpts = {}\)[\s\S]*?waitForWritableDrain\(stream, {[\s\S]*?progressIntervalMs: 1000[\s\S]*?stream\._chunk\?\.length/, - "SSH ZMODEM must count partial ssh2 channel-window delivery as progress", - ); - assert.match( - zmodemSource, - /For all other errors[\s\S]*?transferAbortController\?\.abort\(\)[\s\S]*?currentZSession = null/, - "a sentry protocol error must wake an upload blocked on SSH drain", - ); -}); diff --git a/electron/bridges/systemManagerBridge.cjs b/electron/bridges/systemManagerBridge.cjs index 3ab9cf9e5..bb7de0654 100644 --- a/electron/bridges/systemManagerBridge.cjs +++ b/electron/bridges/systemManagerBridge.cjs @@ -8,6 +8,7 @@ const { parseRuntimeProbe } = require("../../domain/systemManager/containerRunti const { createGpuOpsApi } = require("./systemManager/gpuOps.cjs"); const { createPortOpsApi } = require("./systemManager/portOps.cjs"); const { createServiceOpsApi } = require("./systemManager/serviceOps.cjs"); +const { registerWorkerHandle } = require("./workerIpcProxy.cjs"); function nerdctlUsableClause(markCommand) { // Offer nerdctl only when `nerdctl info` works. A socket permission error @@ -531,12 +532,6 @@ function createSystemManagerBridge(deps) { return serviceOps.serviceAction(event, payload); } - function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { - ipcMain.handle(channel, (event, payload) => terminalWorkerManager.request(channel, payload, { - webContentsId: event?.sender?.id, - })); - } - function registerHandlers(ipcMain, options = {}) { const terminalWorkerManager = options.terminalWorkerManager || null; if (terminalWorkerManager) { diff --git a/electron/bridges/terminalBridge.binaryInput.test.cjs b/electron/bridges/terminalBridge.binaryInput.test.cjs deleted file mode 100644 index 78c5bdbd6..000000000 --- a/electron/bridges/terminalBridge.binaryInput.test.cjs +++ /dev/null @@ -1,72 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { createPreloadApi } = require("../preload/api.cjs"); -const terminalBridge = require("./terminalBridge.cjs"); - -function setup(session) { - terminalBridge.init({ sessions: new Map([["session", session]]) }); - const sent = []; - const api = createPreloadApi({ - ipcRenderer: { - send(channel, payload) { - sent.push({ channel, payload }); - // Model Electron structured-clone IPC, including the binary flag. - terminalBridge.writeToSession({}, structuredClone(payload)); - }, - }, - webUtils: {}, - }); - return { api, sent }; -} - -for (const transport of ["stream", "proc", "socket", "serialPort"]) { - for (const encoding of ["utf-8", "gb18030"]) { - test(`binary input preserves all byte values through preload to ${transport} (${encoding})`, () => { - const writes = []; - const { api, sent } = setup({ - type: transport === "serialPort" ? "serial" : "ssh", - encoding, - [transport]: { write: (data) => writes.push(data) }, - }); - const bytes = Array.from({ length: 256 }, (_, i) => i); - const data = String.fromCharCode(...bytes); - api.writeToSession("session", data, { binary: true }); - - assert.equal(sent[0].channel, "netcatty:write"); - assert.equal(sent[0].payload.binary, true); - assert.equal(sent[0].payload.data, data); - assert.equal(writes.length, 1); - assert.ok(Buffer.isBuffer(writes[0])); - assert.deepEqual([...writes[0]], bytes); - }); - } -} - -test("binary Telnet input preserves bytes and still doubles IAC", () => { - const writes = []; - const { api } = setup({ - type: "telnet-native", - encoding: "gb18030", - telnetProtocolActive: true, - socket: { write: (data) => writes.push(data) }, - }); - const bytes = [0x1b, 0x5b, 0x4d, 0x20, 0xc0, 0xff, 0x0d, 0x21, 0x0a]; - api.writeToSession("session", String.fromCharCode(...bytes), { binary: true }); - assert.equal(writes.length, 1); - assert.ok(Buffer.isBuffer(writes[0])); - assert.deepEqual([...writes[0]], [0x1b, 0x5b, 0x4d, 0x20, 0xc0, 0xff, 0xff, 0x0d, 0x21, 0x0a]); -}); - -test("ordinary CJK text retains the default UTF-8 string path", () => { - const writes = []; - const { api, sent } = setup({ - type: "ssh", - encoding: "utf-8", - stream: { write: (data) => writes.push(data) }, - }); - const text = "\u4e2d\u6587"; - api.writeToSession("session", text); - assert.equal(sent[0].payload.binary, false); - assert.deepEqual(writes, [text]); - assert.deepEqual([...Buffer.from(writes[0], "utf8")], [0xe4, 0xb8, 0xad, 0xe6, 0x96, 0x87]); -}); diff --git a/electron/bridges/terminalBridge.bundledMosh.test.cjs b/electron/bridges/terminalBridge.bundledClients.test.cjs similarity index 53% rename from electron/bridges/terminalBridge.bundledMosh.test.cjs rename to electron/bridges/terminalBridge.bundledClients.test.cjs index 2daf15e78..3deb1bf4a 100644 --- a/electron/bridges/terminalBridge.bundledMosh.test.cjs +++ b/electron/bridges/terminalBridge.bundledClients.test.cjs @@ -1,3 +1,96 @@ +"use strict"; + +// --- merged from terminalBridge.bundledEt.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); + +const { bundledEtClient } = require("./terminalBridge.cjs"); + +function makeTmp() { + return fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-et-")); +} + +function writeExecutable(filePath, contents = "#!/bin/sh\nexit 0\n") { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, contents); + fs.chmodSync(filePath, 0o755); +} + +test("bundledEtClient returns null when no binary is present", () => { + const projectRoot = makeTmp(); + const result = bundledEtClient({ + platform: "linux", + arch: "x64", + projectRoot, + resourcesPath: path.join(projectRoot, "missing-resources"), + }); + assert.equal(result, null); +}); + +test("bundledEtClient prefers the packaged Resources path", () => { + const projectRoot = makeTmp(); + const resourcesPath = makeTmp(); + const packagedBin = path.join(resourcesPath, "et", "et"); + writeExecutable(packagedBin); + + const devBin = path.join(projectRoot, "resources", "et", "linux-x64", "et"); + writeExecutable(devBin); + + const result = bundledEtClient({ platform: "linux", arch: "x64", projectRoot, resourcesPath }); + assert.equal(result, packagedBin); +}); + +test("bundledEtClient falls back to the project-root dev path", () => { + const projectRoot = makeTmp(); + const devBin = path.join(projectRoot, "resources", "et", "linux-x64", "et"); + writeExecutable(devBin); + + const result = bundledEtClient({ + platform: "linux", + arch: "x64", + projectRoot, + resourcesPath: path.join(projectRoot, "missing"), + }); + assert.equal(result, devBin); +}); + +test("bundledEtClient looks under darwin-universal regardless of arch on macOS", () => { + const projectRoot = makeTmp(); + const universalBin = path.join(projectRoot, "resources", "et", "darwin-universal", "et"); + writeExecutable(universalBin); + + for (const arch of ["arm64", "x64"]) { + const result = bundledEtClient({ + platform: "darwin", + arch, + projectRoot, + resourcesPath: path.join(projectRoot, "missing"), + }); + assert.equal(result, universalBin, `arch=${arch}`); + } +}); + +test("bundledEtClient uses .exe basename on win32 (when running on a POSIX host)", { skip: process.platform === "win32" }, () => { + const projectRoot = makeTmp(); + const winBin = path.join(projectRoot, "resources", "et", "win32-x64", "et.exe"); + writeExecutable(winBin); + + const result = bundledEtClient({ + platform: "win32", + arch: "x64", + projectRoot, + resourcesPath: path.join(projectRoot, "missing"), + }); + assert.equal(result, winBin); +}); +} + +// --- merged from terminalBridge.bundledMosh.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); @@ -99,3 +192,4 @@ test("bundledMoshClient ignores non-executable matches", { skip: process.platfor }); assert.equal(result, null); }); +} diff --git a/electron/bridges/terminalBridge.bundledEt.test.cjs b/electron/bridges/terminalBridge.bundledEt.test.cjs deleted file mode 100644 index 08c13bb38..000000000 --- a/electron/bridges/terminalBridge.bundledEt.test.cjs +++ /dev/null @@ -1,85 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); - -const { bundledEtClient } = require("./terminalBridge.cjs"); - -function makeTmp() { - return fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-et-")); -} - -function writeExecutable(filePath, contents = "#!/bin/sh\nexit 0\n") { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, contents); - fs.chmodSync(filePath, 0o755); -} - -test("bundledEtClient returns null when no binary is present", () => { - const projectRoot = makeTmp(); - const result = bundledEtClient({ - platform: "linux", - arch: "x64", - projectRoot, - resourcesPath: path.join(projectRoot, "missing-resources"), - }); - assert.equal(result, null); -}); - -test("bundledEtClient prefers the packaged Resources path", () => { - const projectRoot = makeTmp(); - const resourcesPath = makeTmp(); - const packagedBin = path.join(resourcesPath, "et", "et"); - writeExecutable(packagedBin); - - const devBin = path.join(projectRoot, "resources", "et", "linux-x64", "et"); - writeExecutable(devBin); - - const result = bundledEtClient({ platform: "linux", arch: "x64", projectRoot, resourcesPath }); - assert.equal(result, packagedBin); -}); - -test("bundledEtClient falls back to the project-root dev path", () => { - const projectRoot = makeTmp(); - const devBin = path.join(projectRoot, "resources", "et", "linux-x64", "et"); - writeExecutable(devBin); - - const result = bundledEtClient({ - platform: "linux", - arch: "x64", - projectRoot, - resourcesPath: path.join(projectRoot, "missing"), - }); - assert.equal(result, devBin); -}); - -test("bundledEtClient looks under darwin-universal regardless of arch on macOS", () => { - const projectRoot = makeTmp(); - const universalBin = path.join(projectRoot, "resources", "et", "darwin-universal", "et"); - writeExecutable(universalBin); - - for (const arch of ["arm64", "x64"]) { - const result = bundledEtClient({ - platform: "darwin", - arch, - projectRoot, - resourcesPath: path.join(projectRoot, "missing"), - }); - assert.equal(result, universalBin, `arch=${arch}`); - } -}); - -test("bundledEtClient uses .exe basename on win32 (when running on a POSIX host)", { skip: process.platform === "win32" }, () => { - const projectRoot = makeTmp(); - const winBin = path.join(projectRoot, "resources", "et", "win32-x64", "et.exe"); - writeExecutable(winBin); - - const result = bundledEtClient({ - platform: "win32", - arch: "x64", - projectRoot, - resourcesPath: path.join(projectRoot, "missing"), - }); - assert.equal(result, winBin); -}); diff --git a/electron/bridges/terminalBridge.cjs b/electron/bridges/terminalBridge.cjs index 40b7917fa..b49c24aae 100644 --- a/electron/bridges/terminalBridge.cjs +++ b/electron/bridges/terminalBridge.cjs @@ -13,6 +13,7 @@ const { promisify } = require("node:util"); const { StringDecoder } = require("node:string_decoder"); const { ensureNodePtySpawnHelperExecutable } = require("./nodePtySpawnHelperPermissions.cjs"); const { createTerminalFlowPauseArbiter } = require("./terminalFlowPauseArbiter.cjs"); +const { registerWorkerHandle } = require("./workerIpcProxy.cjs"); ensureNodePtySpawnHelperExecutable(); @@ -2458,14 +2459,6 @@ function getTelnetEchoMode(_event, { sessionId }) { /** * Register IPC handlers for terminal operations */ -function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { - ipcMain.handle(channel, (event, payload) => { - return terminalWorkerManager.request(channel, payload, { - webContentsId: event?.sender?.id, - }); - }); -} - function registerWorkerSend(ipcMain, terminalWorkerManager, channel) { ipcMain.on(channel, (event, payload) => { terminalWorkerManager.send(channel, payload, { diff --git a/electron/bridges/terminalBridge.clearPty.test.cjs b/electron/bridges/terminalBridge.clearPty.test.cjs deleted file mode 100644 index 9dd9c4bdd..000000000 --- a/electron/bridges/terminalBridge.clearPty.test.cjs +++ /dev/null @@ -1,56 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const terminalBridge = require("./terminalBridge.cjs"); - -function initBridge(sessions) { - terminalBridge.init({ - sessions, - electronModule: { - webContents: { - fromId: () => ({ send() {} }), - }, - }, - }); -} - -test("clearSessionPtyBuffer calls node-pty clear for ConPTY sync after frontend clear", () => { - const calls = []; - const sessions = new Map(); - sessions.set("local-ps-1", { - proc: { - clear() { - calls.push("clear"); - }, - write() { - calls.push("write"); - }, - }, - }); - initBridge(sessions); - - terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "local-ps-1" }); - - assert.deepEqual(calls, ["clear"]); -}); - -test("clearSessionPtyBuffer is a no-op when the session has no pty process", () => { - const sessions = new Map(); - sessions.set("ssh-1", { - stream: { - write() {}, - }, - }); - initBridge(sessions); - - assert.doesNotThrow(() => { - terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "ssh-1" }); - }); -}); - -test("clearSessionPtyBuffer ignores missing sessions", () => { - initBridge(new Map()); - assert.doesNotThrow(() => { - terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "missing" }); - }); -}); diff --git a/electron/bridges/terminalBridge.composeMultiline.test.cjs b/electron/bridges/terminalBridge.composeMultiline.test.cjs deleted file mode 100644 index 17025666f..000000000 --- a/electron/bridges/terminalBridge.composeMultiline.test.cjs +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Repro: multi-line compose bar input only sent the first line. - * - * Path: compose bar textarea -> executeSnippetCommand(text, false) -> - * multi-line autoRun -> lineDelayMs=250 -> backend writeToSession sends the - * first line immediately and queues the remaining lines in - * session.pendingAutomatedWriteTimers. - * - * Root cause: terminal-originated automatic replies used the same netcatty:write - * path without the automated flag. Treating those replies as user input cleared - * queued lines, so only the first line was sent. - */ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const terminalBridge = require("./terminalBridge.cjs"); - -function initBridge(sessions) { - terminalBridge.init({ - sessions, - electronModule: { - webContents: { fromId: () => ({ send() {} }) }, - }, - }); -} - -function delay(ms) { - return new Promise((resolve) => setTimeout(resolve, ms)); -} - -// Expected behavior: harmless terminal auto-replies must not cancel queued lines. -test("[REPRO] terminal auto-reply between automated lines must NOT cancel pending lines", async () => { - const calls = []; - const sessions = new Map(); - sessions.set("ssh-1", { - stream: { signal() {}, write(data) { calls.push(data); } }, - }); - initBridge(sessions); - - terminalBridge.writeToSession( - { sender: {} }, - { - sessionId: "ssh-1", - data: "echo one\necho two\necho three\r", - automated: true, - lineDelayMs: 20, - }, - ); - assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); - - terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[2;1R" }); - - await delay(80); - - assert.deepEqual( - calls, - ["echo one\r", "\x1b[2;1R", "echo two\r", "echo three\r"], - "terminal auto-replies should not clear queued line writes", - ); -}); - -test("[REPRO] Kitty keyboard query reply must NOT cancel pending lines", async () => { - const calls = []; - const sessions = new Map(); - sessions.set("ssh-1", { - stream: { signal() {}, write(data) { calls.push(data); } }, - }); - initBridge(sessions); - - terminalBridge.writeToSession( - { sender: {} }, - { - sessionId: "ssh-1", - data: "echo one\necho two\necho three\r", - automated: true, - lineDelayMs: 20, - }, - ); - assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); - - terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[?0u" }); - - await delay(80); - - assert.deepEqual( - calls, - ["echo one\r", "\x1b[?0u", "echo two\r", "echo three\r"], - "Kitty query replies should not clear queued line writes", - ); -}); - -// Guardrail: real user interruption must still cancel queued automated writes. -test("[GUARD] Ctrl+C between automated lines SHOULD cancel pending lines", async () => { - const calls = []; - const sessions = new Map(); - sessions.set("ssh-1", { - stream: { signal() {}, write(data) { calls.push(data); } }, - }); - initBridge(sessions); - - terminalBridge.writeToSession( - { sender: {} }, - { sessionId: "ssh-1", data: "echo one\necho two\r", automated: true, lineDelayMs: 20 }, - ); - assert.deepEqual(calls, ["echo one\r"]); - - terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x03" }); // Ctrl+C - await delay(60); - - assert.deepEqual(calls, ["echo one\r", "\x03"], "Ctrl+C should cancel queued line writes"); -}); diff --git a/electron/bridges/terminalBridge.inputEncoding.test.cjs b/electron/bridges/terminalBridge.inputEncoding.test.cjs index d684c5b21..723c8d87b 100644 --- a/electron/bridges/terminalBridge.inputEncoding.test.cjs +++ b/electron/bridges/terminalBridge.inputEncoding.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from terminalBridge.inputEncoding.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const net = require("node:net"); @@ -272,3 +276,195 @@ test("setSessionEncoding switches the Telnet input charset at runtime", async () await new Promise((resolve) => server.close(resolve)); } }); +} + +// --- merged from terminalBridge.binaryInput.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { createPreloadApi } = require("../preload/api.cjs"); +const terminalBridge = require("./terminalBridge.cjs"); + +function setup(session) { + terminalBridge.init({ sessions: new Map([["session", session]]) }); + const sent = []; + const api = createPreloadApi({ + ipcRenderer: { + send(channel, payload) { + sent.push({ channel, payload }); + // Model Electron structured-clone IPC, including the binary flag. + terminalBridge.writeToSession({}, structuredClone(payload)); + }, + }, + webUtils: {}, + }); + return { api, sent }; +} + +for (const transport of ["stream", "proc", "socket", "serialPort"]) { + for (const encoding of ["utf-8", "gb18030"]) { + test(`binary input preserves all byte values through preload to ${transport} (${encoding})`, () => { + const writes = []; + const { api, sent } = setup({ + type: transport === "serialPort" ? "serial" : "ssh", + encoding, + [transport]: { write: (data) => writes.push(data) }, + }); + const bytes = Array.from({ length: 256 }, (_, i) => i); + const data = String.fromCharCode(...bytes); + api.writeToSession("session", data, { binary: true }); + + assert.equal(sent[0].channel, "netcatty:write"); + assert.equal(sent[0].payload.binary, true); + assert.equal(sent[0].payload.data, data); + assert.equal(writes.length, 1); + assert.ok(Buffer.isBuffer(writes[0])); + assert.deepEqual([...writes[0]], bytes); + }); + } +} + +test("binary Telnet input preserves bytes and still doubles IAC", () => { + const writes = []; + const { api } = setup({ + type: "telnet-native", + encoding: "gb18030", + telnetProtocolActive: true, + socket: { write: (data) => writes.push(data) }, + }); + const bytes = [0x1b, 0x5b, 0x4d, 0x20, 0xc0, 0xff, 0x0d, 0x21, 0x0a]; + api.writeToSession("session", String.fromCharCode(...bytes), { binary: true }); + assert.equal(writes.length, 1); + assert.ok(Buffer.isBuffer(writes[0])); + assert.deepEqual([...writes[0]], [0x1b, 0x5b, 0x4d, 0x20, 0xc0, 0xff, 0xff, 0x0d, 0x21, 0x0a]); +}); + +test("ordinary CJK text retains the default UTF-8 string path", () => { + const writes = []; + const { api, sent } = setup({ + type: "ssh", + encoding: "utf-8", + stream: { write: (data) => writes.push(data) }, + }); + const text = "\u4e2d\u6587"; + api.writeToSession("session", text); + assert.equal(sent[0].payload.binary, false); + assert.deepEqual(writes, [text]); + assert.deepEqual([...Buffer.from(writes[0], "utf8")], [0xe4, 0xb8, 0xad, 0xe6, 0x96, 0x87]); +}); +} + +// --- merged from terminalBridge.composeMultiline.test.cjs --- +{ +/** + * Repro: multi-line compose bar input only sent the first line. + * + * Path: compose bar textarea -> executeSnippetCommand(text, false) -> + * multi-line autoRun -> lineDelayMs=250 -> backend writeToSession sends the + * first line immediately and queues the remaining lines in + * session.pendingAutomatedWriteTimers. + * + * Root cause: terminal-originated automatic replies used the same netcatty:write + * path without the automated flag. Treating those replies as user input cleared + * queued lines, so only the first line was sent. + */ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const terminalBridge = require("./terminalBridge.cjs"); + +function initBridge(sessions) { + terminalBridge.init({ + sessions, + electronModule: { + webContents: { fromId: () => ({ send() {} }) }, + }, + }); +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// Expected behavior: harmless terminal auto-replies must not cancel queued lines. +test("[REPRO] terminal auto-reply between automated lines must NOT cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + terminalBridge.writeToSession( + { sender: {} }, + { + sessionId: "ssh-1", + data: "echo one\necho two\necho three\r", + automated: true, + lineDelayMs: 20, + }, + ); + assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); + + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[2;1R" }); + + await delay(80); + + assert.deepEqual( + calls, + ["echo one\r", "\x1b[2;1R", "echo two\r", "echo three\r"], + "terminal auto-replies should not clear queued line writes", + ); +}); + +test("[REPRO] Kitty keyboard query reply must NOT cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + terminalBridge.writeToSession( + { sender: {} }, + { + sessionId: "ssh-1", + data: "echo one\necho two\necho three\r", + automated: true, + lineDelayMs: 20, + }, + ); + assert.deepEqual(calls, ["echo one\r"], "the first line is sent immediately"); + + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x1b[?0u" }); + + await delay(80); + + assert.deepEqual( + calls, + ["echo one\r", "\x1b[?0u", "echo two\r", "echo three\r"], + "Kitty query replies should not clear queued line writes", + ); +}); + +// Guardrail: real user interruption must still cancel queued automated writes. +test("[GUARD] Ctrl+C between automated lines SHOULD cancel pending lines", async () => { + const calls = []; + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { signal() {}, write(data) { calls.push(data); } }, + }); + initBridge(sessions); + + terminalBridge.writeToSession( + { sender: {} }, + { sessionId: "ssh-1", data: "echo one\necho two\r", automated: true, lineDelayMs: 20 }, + ); + assert.deepEqual(calls, ["echo one\r"]); + + terminalBridge.writeToSession({ sender: {} }, { sessionId: "ssh-1", data: "\x03" }); // Ctrl+C + await delay(60); + + assert.deepEqual(calls, ["echo one\r", "\x03"], "Ctrl+C should cancel queued line writes"); +}); +} diff --git a/electron/bridges/terminalBridge.localSessionEnv.test.cjs b/electron/bridges/terminalBridge.localPty.test.cjs similarity index 74% rename from electron/bridges/terminalBridge.localSessionEnv.test.cjs rename to electron/bridges/terminalBridge.localPty.test.cjs index 915aa249a..f13bb481a 100644 --- a/electron/bridges/terminalBridge.localSessionEnv.test.cjs +++ b/electron/bridges/terminalBridge.localPty.test.cjs @@ -1,3 +1,67 @@ +"use strict"; + +// --- merged from terminalBridge.clearPty.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const terminalBridge = require("./terminalBridge.cjs"); + +function initBridge(sessions) { + terminalBridge.init({ + sessions, + electronModule: { + webContents: { + fromId: () => ({ send() {} }), + }, + }, + }); +} + +test("clearSessionPtyBuffer calls node-pty clear for ConPTY sync after frontend clear", () => { + const calls = []; + const sessions = new Map(); + sessions.set("local-ps-1", { + proc: { + clear() { + calls.push("clear"); + }, + write() { + calls.push("write"); + }, + }, + }); + initBridge(sessions); + + terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "local-ps-1" }); + + assert.deepEqual(calls, ["clear"]); +}); + +test("clearSessionPtyBuffer is a no-op when the session has no pty process", () => { + const sessions = new Map(); + sessions.set("ssh-1", { + stream: { + write() {}, + }, + }); + initBridge(sessions); + + assert.doesNotThrow(() => { + terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "ssh-1" }); + }); +}); + +test("clearSessionPtyBuffer ignores missing sessions", () => { + initBridge(new Map()); + assert.doesNotThrow(() => { + terminalBridge.clearSessionPtyBuffer({ sender: {} }, { sessionId: "missing" }); + }); +}); +} + +// --- merged from terminalBridge.localSessionEnv.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const Module = require("node:module"); @@ -133,3 +197,4 @@ for (const pathKey of ["Path", "PATH", "path"]) { assert.deepEqual(Object.keys(env).filter((key) => key.toLowerCase() === "path"), [pathKey]); }); } +} diff --git a/electron/bridges/terminalBridge.serialAutoLogin.test.cjs b/electron/bridges/terminalBridge.serialAutoLogin.test.cjs index ff687a605..274c36b9e 100644 --- a/electron/bridges/terminalBridge.serialAutoLogin.test.cjs +++ b/electron/bridges/terminalBridge.serialAutoLogin.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from terminalBridge.serialAutoLogin.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const terminalBridge = require("./terminalBridge.cjs"); @@ -362,3 +366,53 @@ test("serial auto-login cancels at input ingress before a slow interceptor resol terminalBridge.cleanupAllSessions(); } }); +} + +// --- merged from terminalBridge.serialBackspace.test.cjs --- +{ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const terminalBridge = require('./terminalBridge.cjs'); +const { encodeTerminalInput, normalizeTerminalEncoding } = require('./terminalEncoding.cjs'); + +for (const charset of ['utf-8', 'GBK', 'Shift_JIS', 'Big5', 'EUC-JP', 'latin1', 'utf-16', 'unknown']) { + test(`serial byte deletion matches actual ${charset} input and preserves preceding text`, () => { + const encoding = normalizeTerminalEncoding(charset); + let wire = Buffer.alloc(0); + const serialPort = { write(data) { + for (const byte of Buffer.from(data)) { + wire = byte === 127 || byte === 8 ? wire.subarray(0, Math.max(0, wire.length - 1)) : Buffer.concat([wire, Buffer.from([byte])]); + } + } }; + terminalBridge.init({ sessions: new Map([['serial', {type: 'serial', protocol: 'serial', encoding, serialPort}]]), electronModule: {} }); + for (const char of ['你', 'é', 'ü', 'α', '〿', 'ア', '龘', '❤️', '𠀀']) { + wire = Buffer.alloc(0); + terminalBridge.writeToSession({}, {sessionId: 'serial', data: 'abc' + char}); + assert.equal(wire.length, 3 + Buffer.byteLength(encodeTerminalInput(char, encoding))); + terminalBridge.writeToSession({}, {sessionId: 'serial', data: '\x7f', serialEraseChar: char}); + assert.equal(wire.toString(), 'abc', char); + } + }); +} + +test('ordinary serial and non-serial input retain one Backspace', () => { + for (const serial of [true, false]) { + const writes = []; + const session = serial ? {serialPort: {write: data => writes.push(data)}} : {stream: {write: data => writes.push(data)}}; + terminalBridge.init({sessions: new Map([['s', session]]), electronModule: {}}); + terminalBridge.writeToSession({}, {sessionId: 's', data: '\x7f', ...(!serial ? {serialEraseChar: '你'} : {})}); + assert.deepEqual(writes, ['\x7f']); + } +}); + +test('serial byte deletion uses the current backend encoding and preserves other keys', () => { + const writes = []; + const session = {serialPort: {write: data => writes.push(Buffer.from(data))}, encoding: 'gb18030'}; + terminalBridge.init({sessions: new Map([['s', session]]), electronModule: {}}); + terminalBridge.writeToSession({}, {sessionId: 's', data: '\b', serialEraseChar: '你'}); + session.encoding = 'utf-8'; + terminalBridge.writeToSession({}, {sessionId: 's', data: '\b', serialEraseChar: '你'}); + terminalBridge.writeToSession({}, {sessionId: 's', data: '\x03', serialEraseChar: '你'}); + assert.deepEqual(writes.map(b => [...b]), [[8, 8], [8, 8, 8], [3]]); +}); +} diff --git a/electron/bridges/terminalBridge.serialBackspace.test.cjs b/electron/bridges/terminalBridge.serialBackspace.test.cjs deleted file mode 100644 index c59533ad0..000000000 --- a/electron/bridges/terminalBridge.serialBackspace.test.cjs +++ /dev/null @@ -1,45 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const terminalBridge = require('./terminalBridge.cjs'); -const { encodeTerminalInput, normalizeTerminalEncoding } = require('./terminalEncoding.cjs'); - -for (const charset of ['utf-8', 'GBK', 'Shift_JIS', 'Big5', 'EUC-JP', 'latin1', 'utf-16', 'unknown']) { - test(`serial byte deletion matches actual ${charset} input and preserves preceding text`, () => { - const encoding = normalizeTerminalEncoding(charset); - let wire = Buffer.alloc(0); - const serialPort = { write(data) { - for (const byte of Buffer.from(data)) { - wire = byte === 127 || byte === 8 ? wire.subarray(0, Math.max(0, wire.length - 1)) : Buffer.concat([wire, Buffer.from([byte])]); - } - } }; - terminalBridge.init({ sessions: new Map([['serial', {type: 'serial', protocol: 'serial', encoding, serialPort}]]), electronModule: {} }); - for (const char of ['你', 'é', 'ü', 'α', '〿', 'ア', '龘', '❤️', '𠀀']) { - wire = Buffer.alloc(0); - terminalBridge.writeToSession({}, {sessionId: 'serial', data: 'abc' + char}); - assert.equal(wire.length, 3 + Buffer.byteLength(encodeTerminalInput(char, encoding))); - terminalBridge.writeToSession({}, {sessionId: 'serial', data: '\x7f', serialEraseChar: char}); - assert.equal(wire.toString(), 'abc', char); - } - }); -} - -test('ordinary serial and non-serial input retain one Backspace', () => { - for (const serial of [true, false]) { - const writes = []; - const session = serial ? {serialPort: {write: data => writes.push(data)}} : {stream: {write: data => writes.push(data)}}; - terminalBridge.init({sessions: new Map([['s', session]]), electronModule: {}}); - terminalBridge.writeToSession({}, {sessionId: 's', data: '\x7f', ...(!serial ? {serialEraseChar: '你'} : {})}); - assert.deepEqual(writes, ['\x7f']); - } -}); - -test('serial byte deletion uses the current backend encoding and preserves other keys', () => { - const writes = []; - const session = {serialPort: {write: data => writes.push(Buffer.from(data))}, encoding: 'gb18030'}; - terminalBridge.init({sessions: new Map([['s', session]]), electronModule: {}}); - terminalBridge.writeToSession({}, {sessionId: 's', data: '\b', serialEraseChar: '你'}); - session.encoding = 'utf-8'; - terminalBridge.writeToSession({}, {sessionId: 's', data: '\b', serialEraseChar: '你'}); - terminalBridge.writeToSession({}, {sessionId: 's', data: '\x03', serialEraseChar: '你'}); - assert.deepEqual(writes.map(b => [...b]), [[8, 8], [8, 8, 8], [3]]); -}); diff --git a/electron/bridges/terminalBridge.telnetEcho.test.cjs b/electron/bridges/terminalBridge.telnetEcho.test.cjs index b56d4d067..4e54b891a 100644 --- a/electron/bridges/terminalBridge.telnetEcho.test.cjs +++ b/electron/bridges/terminalBridge.telnetEcho.test.cjs @@ -1,3 +1,7 @@ +"use strict"; + +// --- merged from terminalBridge.telnetEcho.test.cjs --- +{ const test = require("node:test"); const assert = require("node:assert/strict"); const net = require("node:net"); @@ -413,3 +417,57 @@ test("replacing a Telnet session cancels delayed automated writes from the old s await new Promise((resolve) => newServer.close(resolve)); } }); +} + +// --- merged from terminalBridge.telnetResize.test.cjs --- +{ +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const terminalBridge = require("./terminalBridge.cjs"); + +test("Telnet resize does not write NAWS bytes before the peer enables NAWS", () => { + const sessionId = "telnet-resize-naws-disabled"; + const writes = []; + let windowSizeRequests = 0; + const sessions = new Map(); + + sessions.set(sessionId, { + type: "telnet-native", + socket: { + write(buf) { + writes.push(Buffer.from(buf)); + }, + destroy() {}, + }, + telnetProtocolActive: true, + sendTelnetWindowSize() { + windowSizeRequests++; + return false; + }, + }); + + terminalBridge.init({ + sessions, + electronModule: { + webContents: { + fromId: () => ({ send() {} }), + }, + }, + }); + + try { + terminalBridge.resizeSession( + { sender: { id: 1 } }, + { sessionId, cols: 94, rows: 55 }, + ); + + assert.equal(windowSizeRequests, 1); + assert.equal(writes.length, 0); + assert.equal(sessions.get(sessionId).cols, 94); + assert.equal(sessions.get(sessionId).rows, 55); + } finally { + terminalBridge.cleanupAllSessions(); + } +}); +} diff --git a/electron/bridges/terminalBridge.telnetResize.test.cjs b/electron/bridges/terminalBridge.telnetResize.test.cjs deleted file mode 100644 index b0eb57120..000000000 --- a/electron/bridges/terminalBridge.telnetResize.test.cjs +++ /dev/null @@ -1,49 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const terminalBridge = require("./terminalBridge.cjs"); - -test("Telnet resize does not write NAWS bytes before the peer enables NAWS", () => { - const sessionId = "telnet-resize-naws-disabled"; - const writes = []; - let windowSizeRequests = 0; - const sessions = new Map(); - - sessions.set(sessionId, { - type: "telnet-native", - socket: { - write(buf) { - writes.push(Buffer.from(buf)); - }, - destroy() {}, - }, - telnetProtocolActive: true, - sendTelnetWindowSize() { - windowSizeRequests++; - return false; - }, - }); - - terminalBridge.init({ - sessions, - electronModule: { - webContents: { - fromId: () => ({ send() {} }), - }, - }, - }); - - try { - terminalBridge.resizeSession( - { sender: { id: 1 } }, - { sessionId, cols: 94, rows: 55 }, - ); - - assert.equal(windowSizeRequests, 1); - assert.equal(writes.length, 0); - assert.equal(sessions.get(sessionId).cols, 94); - assert.equal(sessions.get(sessionId).rows, 55); - } finally { - terminalBridge.cleanupAllSessions(); - } -}); diff --git a/electron/bridges/testSupport/bridgeHarness.cjs b/electron/bridges/testSupport/bridgeHarness.cjs new file mode 100644 index 000000000..c1ac2f842 --- /dev/null +++ b/electron/bridges/testSupport/bridgeHarness.cjs @@ -0,0 +1,106 @@ +"use strict"; + +const { EventEmitter } = require("node:events"); +const Module = require("node:module"); + +/** + * Create a lightweight fake Electron WebContents/sender that records IPC sends. + */ +function createMockWebContents(overrides = {}) { + const emitter = new EventEmitter(); + const sent = []; + let destroyed = false; + + const sender = Object.assign(emitter, { + id: overrides.id ?? 1, + sent, + isDestroyed: () => destroyed, + destroy: () => { + destroyed = true; + emitter.emit("destroyed"); + }, + send: (channel, payload) => { + sent.push({ channel, payload }); + }, + ...overrides, + }); + + return sender; +} + +/** + * Create a fake ipcMain registry supporting handle / removeHandler / on / invoke. + */ +function createMockIpcMain() { + const handlers = new Map(); + const listeners = new Map(); + + return { + handlers, + listeners, + handle: (channel, handler) => { + handlers.set(channel, handler); + }, + removeHandler: (channel) => { + handlers.delete(channel); + }, + on: (channel, listener) => { + if (!listeners.has(channel)) listeners.set(channel, new Set()); + listeners.get(channel).add(listener); + }, + removeListener: (channel, listener) => { + listeners.get(channel)?.delete(listener); + }, + invoke: async (channel, event, ...args) => { + const handler = handlers.get(channel); + if (!handler) throw new Error(`No IPC handler registered for ${channel}`); + return handler(event ?? { sender: createMockWebContents() }, ...args); + }, + }; +} + +/** + * Load a CJS module freshly with temporary Module._load overrides and guaranteed restoration. + */ +function loadWithMockedModules(modulePath, mocks) { + const resolved = require.resolve(modulePath); + const originalLoad = Module._load; + const previousCache = require.cache[resolved]; + delete require.cache[resolved]; + + Module._load = function patchedLoad(request, parent, isMain) { + if (Object.prototype.hasOwnProperty.call(mocks, request)) { + return mocks[request]; + } + return originalLoad.call(this, request, parent, isMain); + }; + + try { + const loaded = require(resolved); + return { + exports: loaded, + restore: () => { + Module._load = originalLoad; + if (previousCache) { + require.cache[resolved] = previousCache; + } else { + delete require.cache[resolved]; + } + }, + }; + } catch (err) { + Module._load = originalLoad; + if (previousCache) { + require.cache[resolved] = previousCache; + } else { + delete require.cache[resolved]; + } + throw err; + } +} + +module.exports = { + createMockWebContents, + createMockIpcMain, + loadWithMockedModules, +}; diff --git a/electron/bridges/transferBridge.cjs b/electron/bridges/transferBridge.cjs index 0210184a4..64d8636ab 100644 --- a/electron/bridges/transferBridge.cjs +++ b/electron/bridges/transferBridge.cjs @@ -8,6 +8,7 @@ const path = require("node:path"); const crypto = require("node:crypto"); const { Readable } = require("node:stream"); const tempDirBridge = require("./tempDirBridge.cjs"); +const { registerWorkerHandle } = require("./workerIpcProxy.cjs"); const { encodePathForSession, ensureRemoteDirForSession, @@ -8318,12 +8319,6 @@ async function sameHostCopyDirectory(event, payload) { } } -function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { - ipcMain.handle(channel, (event, payload) => terminalWorkerManager.request(channel, payload, { - webContentsId: event?.sender?.id, - })); -} - /** * Register IPC handlers for transfer operations */ diff --git a/electron/bridges/workerIpcProxy.cjs b/electron/bridges/workerIpcProxy.cjs new file mode 100644 index 000000000..410579fb7 --- /dev/null +++ b/electron/bridges/workerIpcProxy.cjs @@ -0,0 +1,11 @@ +"use strict"; + +function registerWorkerHandle(ipcMain, terminalWorkerManager, channel) { + ipcMain.handle(channel, (event, payload) => terminalWorkerManager.request(channel, payload, { + webContentsId: event?.sender?.id, + })); +} + +module.exports = { + registerWorkerHandle, +}; diff --git a/electron/capabilities/adapters/index.cjs b/electron/capabilities/adapters/index.cjs deleted file mode 100644 index c7fd0137b..000000000 --- a/electron/capabilities/adapters/index.cjs +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; - -const cliAdapter = require("./cliAdapter.cjs"); -const mcpAdapter = require("./mcpAdapter.cjs"); - -module.exports = { - ...cliAdapter, - ...mcpAdapter, -}; diff --git a/electron/capabilities/catalog/integrity.test.cjs b/electron/capabilities/catalog/integrity.test.cjs index 064544260..661cf9987 100644 --- a/electron/capabilities/catalog/integrity.test.cjs +++ b/electron/capabilities/catalog/integrity.test.cjs @@ -3,7 +3,7 @@ const test = require("node:test"); const assert = require("node:assert/strict"); -const { ALL_CAPABILITIES } = require("../index.cjs"); +const { ALL_CAPABILITIES } = require("./index.cjs"); const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("../constants.cjs"); const { getCliRpcMethod } = require("../adapters/cliAdapter.cjs"); diff --git a/electron/capabilities/dispatch.cjs b/electron/capabilities/dispatch.cjs deleted file mode 100644 index 8cfcc6b33..000000000 --- a/electron/capabilities/dispatch.cjs +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; - -const { CAPABILITY_STATUS, CAPABILITY_SURFACES } = require("./constants.cjs"); -const { getCapabilityByRpcMethod } = require("./registry.cjs"); - -function createRegistryDispatcher({ - surface = CAPABILITY_SURFACES.BUILTIN, - handlers = {}, - fallback, -}) { - if (typeof fallback !== "function") { - throw new Error("fallback handler is required"); - } - - return async function dispatchRpc(rpcMethod, params = {}) { - const capability = getCapabilityByRpcMethod(rpcMethod, surface); - if (!capability) { - return fallback(rpcMethod, params); - } - if (capability.status !== CAPABILITY_STATUS.IMPLEMENTED) { - return { - ok: false, - error: `Capability "${capability.id}" is not implemented yet.`, - code: "CAPABILITY_NOT_IMPLEMENTED", - }; - } - - const handler = handlers[capability.id]; - if (typeof handler !== "function") { - return fallback(rpcMethod, params, capability); - } - - return await handler(params, capability); - }; -} - -module.exports = { - createRegistryDispatcher, -}; diff --git a/electron/capabilities/dispatch.test.cjs b/electron/capabilities/dispatch.test.cjs deleted file mode 100644 index b56d2d17d..000000000 --- a/electron/capabilities/dispatch.test.cjs +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { createRegistryDispatcher } = require("./dispatch.cjs"); -const { CAPABILITY_SURFACES } = require("./constants.cjs"); - -test("createRegistryDispatcher routes implemented capabilities to handlers", async () => { - const calls = []; - const dispatch = createRegistryDispatcher({ - surface: CAPABILITY_SURFACES.BUILTIN, - handlers: { - "meta.status": async (params) => ({ ok: true, params }), - }, - fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), - }); - - const result = await dispatch("netcatty/getStatus", { chatSessionId: "chat-1" }); - assert.equal(result.ok, true); - assert.equal(result.params.chatSessionId, "chat-1"); - assert.equal(calls.length, 0); -}); - -test("createRegistryDispatcher falls back for implemented capabilities without handlers", async () => { - const dispatch = createRegistryDispatcher({ - surface: CAPABILITY_SURFACES.GLOBAL, - handlers: {}, - fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), - }); - - const result = await dispatch("vault/host/notes/get", { hostId: "host-1" }); - assert.equal(result.ok, false); - assert.equal(result.error, "unknown:vault/host/notes/get"); -}); - -test("createRegistryDispatcher falls back for unknown rpc methods", async () => { - const dispatch = createRegistryDispatcher({ - surface: CAPABILITY_SURFACES.BUILTIN, - handlers: {}, - fallback: async (method) => ({ ok: false, error: `unknown:${method}` }), - }); - - const result = await dispatch("auth/verify", { token: "abc" }); - assert.equal(result.error, "unknown:auth/verify"); -}); diff --git a/electron/capabilities/index.cjs b/electron/capabilities/index.cjs deleted file mode 100644 index 2b6b1329a..000000000 --- a/electron/capabilities/index.cjs +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; - -const constants = require("./constants.cjs"); -const catalog = require("./catalog/index.cjs"); -const registry = require("./registry.cjs"); -const policy = require("./policy.cjs"); -const rpcTimeouts = require("./rpcTimeouts.cjs"); -const rpcTransport = require("./rpcTransport.cjs"); -const dispatch = require("./dispatch.cjs"); -const scope = require("./scope.cjs"); -const adapters = require("./adapters/index.cjs"); -const services = require("./services/index.cjs"); - -module.exports = { - ...constants, - ...catalog, - ...registry, - ...policy, - ...rpcTimeouts, - ...rpcTransport, - ...dispatch, - ...scope, - ...adapters, - ...services, -}; diff --git a/electron/capabilities/scope.cjs b/electron/capabilities/scope.cjs deleted file mode 100644 index 8d607bad9..000000000 --- a/electron/capabilities/scope.cjs +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; - -/** - * Scope helpers for capability execution boundaries. - * - * Concrete scope implementations (chat-scoped, public-exposure, global) will - * live with their bridges. This module defines shared validation helpers. - */ - -function createScopeError(code, message) { - return { ok: false, code, error: message }; -} - -function validateSessionInList(sessionId, allowedSessionIds) { - if (!sessionId) { - return createScopeError("SESSION_REQUIRED", "sessionId is required."); - } - if (!Array.isArray(allowedSessionIds)) { - return createScopeError("SCOPE_UNAVAILABLE", "Session scope is unavailable."); - } - if (allowedSessionIds.length === 0) { - return createScopeError("SESSION_NOT_IN_SCOPE", "No sessions are available in the current scope."); - } - if (!allowedSessionIds.includes(sessionId)) { - return createScopeError("SESSION_NOT_IN_SCOPE", `Session "${sessionId}" is not in the current scope.`); - } - return { ok: true }; -} - -function intersectSessionIds(primaryIds, secondaryIds) { - if (!Array.isArray(primaryIds)) return Array.isArray(secondaryIds) ? [...secondaryIds] : null; - if (!Array.isArray(secondaryIds)) return [...primaryIds]; - const secondary = new Set(secondaryIds); - return primaryIds.filter((sessionId) => secondary.has(sessionId)); -} - -module.exports = { - createScopeError, - validateSessionInList, - intersectSessionIds, -}; diff --git a/electron/capabilities/scope.test.cjs b/electron/capabilities/scope.test.cjs deleted file mode 100644 index 6d977a6f5..000000000 --- a/electron/capabilities/scope.test.cjs +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; - -const test = require("node:test"); -const assert = require("node:assert/strict"); - -const { validateSessionInList, intersectSessionIds } = require("./scope.cjs"); - -test("validateSessionInList rejects unknown sessions", () => { - const result = validateSessionInList("sess-2", ["sess-1"]); - assert.equal(result.ok, false); - assert.equal(result.code, "SESSION_NOT_IN_SCOPE"); -}); - -test("intersectSessionIds narrows explicit scope", () => { - assert.deepEqual( - intersectSessionIds(["a", "b", "c"], ["b", "c", "d"]), - ["b", "c"], - ); -}); diff --git a/electron/capabilities/services/index.cjs b/electron/capabilities/services/index.cjs deleted file mode 100644 index 225f5b5fa..000000000 --- a/electron/capabilities/services/index.cjs +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -const notImplemented = require("./notImplemented.cjs"); -const vaultService = require("./vaultService.cjs"); -const portforwardService = require("./portforwardService.cjs"); - -module.exports = { - ...notImplemented, - ...vaultService, - ...portforwardService, -}; diff --git a/electron/capabilities/services/notImplemented.cjs b/electron/capabilities/services/notImplemented.cjs deleted file mode 100644 index ce4e301fd..000000000 --- a/electron/capabilities/services/notImplemented.cjs +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; - -function createNotImplementedResult(capabilityId) { - return { - ok: false, - code: "CAPABILITY_NOT_IMPLEMENTED", - error: `Capability "${capabilityId}" is not implemented yet.`, - }; -} - -function createNotImplementedHandler(capabilityId) { - return async () => createNotImplementedResult(capabilityId); -} - -module.exports = { - createNotImplementedResult, - createNotImplementedHandler, -}; diff --git a/electron/cli/netcatty-tool-cli.capabilities.test.cjs b/electron/cli/netcatty-tool-cli.capabilities.test.cjs index 8d9d804fe..c53098480 100644 --- a/electron/cli/netcatty-tool-cli.capabilities.test.cjs +++ b/electron/cli/netcatty-tool-cli.capabilities.test.cjs @@ -30,7 +30,6 @@ test("netcatty-tool-cli capabilities runs from unpacked CLI runtime without app fs.mkdirSync(electronDir, { recursive: true }); fs.cpSync(path.join(__dirname), cliDir, { recursive: true }); fs.cpSync(path.join(__dirname, "..", "capabilities"), capabilitiesDir, { recursive: true }); - fs.rmSync(path.join(capabilitiesDir, "index.cjs")); fs.rmSync(path.join(capabilitiesDir, "services"), { recursive: true }); const result = spawnSync(process.execPath, [ diff --git a/electron/main.cjs b/electron/main.cjs index 2d0c10628..7d4fc9261 100644 --- a/electron/main.cjs +++ b/electron/main.cjs @@ -498,9 +498,7 @@ function getAppLockReopenWindows() { // Shared state const sessions = new Map(); const sftpClients = new Map(); -const keyRoot = path.join(os.homedir(), ".netcatty", "keys"); const APP_LOCK_SETTINGS_FILE = "app-lock-settings.json"; -let cloudSyncSessionPassword = null; const CLOUD_SYNC_PASSWORD_FILE = "netcatty_cloud_sync_master_password_v1"; let appLockSettingsStore = null; const appLockRuntimeBridge = createAppLockRuntimeBridge(); @@ -527,31 +525,6 @@ function getAppLockNativeWindowHandle() { return win ? win.getNativeWindowHandle() : null; } -// Key management helpers -const ensureKeyDir = async () => { - try { - await fs.promises.mkdir(keyRoot, { recursive: true, mode: 0o700 }); - } catch (err) { - console.warn("Unable to ensure key cache dir", err); - } -}; - -const writeKeyToDisk = async (keyId, privateKey) => { - if (!privateKey) return null; - await ensureKeyDir(); - const safeId = String(keyId || "temp").replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 120); - const filename = `${safeId}.pem`; - const target = path.join(keyRoot, filename); - const normalized = privateKey.endsWith("\n") ? privateKey : `${privateKey}\n`; - try { - await fs.promises.writeFile(target, normalized, { mode: 0o600 }); - return target; - } catch (err) { - console.error("Failed to persist private key", err); - return null; - } -}; - const { createBridgeRegistrar } = require("./main/registerBridges.cjs"); const registerBridges = createBridgeRegistrar({ @@ -1775,6 +1748,4 @@ for (const sig of ['SIGTERM', 'SIGINT']) { module.exports = { sessions, sftpClients, - ensureKeyDir, - writeKeyToDisk, }; diff --git a/electron/main/registerBridges.cjs b/electron/main/registerBridges.cjs index 6fc26b384..beb74873c 100644 --- a/electron/main/registerBridges.cjs +++ b/electron/main/registerBridges.cjs @@ -1,6 +1,5 @@ "use strict"; -let bridgesRegistered = false; let cloudSyncSessionPassword = null; const perfTrace = require("../perfTrace.cjs"); const { readClipboardFiles, readClipboardImage, hasClipboardImage } = require("../bridges/clipboardFiles.cjs"); diff --git a/electron/mainAppLockLaunchIntent.test.cjs b/electron/mainAppLockLaunchIntent.test.cjs deleted file mode 100644 index d94ace429..000000000 --- a/electron/mainAppLockLaunchIntent.test.cjs +++ /dev/null @@ -1,47 +0,0 @@ -const assert = require("node:assert/strict"); -const { readFileSync } = require("node:fs"); -const test = require("node:test"); - -const source = readFileSync(require.resolve("./main.cjs"), "utf8"); - -function readFunction(name, nextName) { - const start = source.indexOf(`async function ${name}`); - const end = source.indexOf(`function ${nextName}`, start + 1); - assert.notEqual(start, -1, `${name} must exist`); - assert.notEqual(end, -1, `${nextName} must exist after ${name}`); - return source.slice(start, end); -} - -test("locked startup launch intents wait for unlock instead of expiring", () => { - for (const [name, nextName] of [ - ["deliverJmsDeepLink", "flushPendingJmsDeepLinks"], - ["deliverTelnetDeepLink", "flushPendingSshDeepLinks"], - ["deliverOpenTerminalPath", "flushPendingOpenTerminalPaths"], - ]) { - const functionSource = readFunction(name, nextName); - assert.match(functionSource, /timeoutMs: 0/); - assert.doesNotMatch(functionSource, /15000|30000/); - } -}); - -test("failed locked launch-intent deliveries return to their queues", () => { - const jmsFlush = readFunction("flushPendingJmsDeepLinks", "deliverSshDeepLink"); - const telnetFlush = readFunction("flushPendingTelnetDeepLinks", "deliverOpenTerminalPath"); - const terminalFlush = readFunction("flushPendingOpenTerminalPaths", "hasPendingColdStartLaunchIntents"); - - assert.match(jmsFlush, /pendingJmsDeepLinkUrls\.unshift\(rawUrl\)/); - assert.match(telnetFlush, /pendingTelnetDeepLinkUrls\.unshift\(item\)/); - assert.match(terminalFlush, /pendingOpenTerminalPaths\.unshift\(targetPath\)/); -}); - -test("cold-start completion waits until the locked renderer is really ready", () => { - const start = source.indexOf("void createAndShowMainWindow().then(async (win) =>"); - const end = source.indexOf("// Trigger auto-update check", start); - const startupSettleSource = source.slice(start, end); - - assert.notEqual(start, -1); - assert.notEqual(end, -1); - assert.match(startupSettleSource, /waitForRendererReady\(win, \{\s*timeoutMs: 0/); - assert.match(startupSettleSource, /notifyColdStartIntentsSettled\(win\)/); - assert.doesNotMatch(startupSettleSource, /15000|30000/); -}); diff --git a/electron/mainQuitGuardSource.test.cjs b/electron/mainQuitGuardSource.test.cjs deleted file mode 100644 index a2162a693..000000000 --- a/electron/mainQuitGuardSource.test.cjs +++ /dev/null @@ -1,118 +0,0 @@ -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { readFileSync } = require("node:fs"); -const path = require("node:path"); - -test("before-quit dirty editor guard queries only registered editor-owner windows", () => { - const source = readFileSync(path.join(__dirname, "main.cjs"), "utf8"); - const lifecycleSource = readFileSync(path.join(__dirname, "main", "appLockLifecycle.cjs"), "utf8"); - const beforeQuitIndex = source.indexOf('app.on("before-quit"'); - const dirtyEditorWindowsIndex = source.indexOf("getDirtyEditorWindows", beforeQuitIndex); - const handleBeforeQuitIndex = source.indexOf("handleBeforeQuit", beforeQuitIndex); - const handleBeforeQuitEndIndex = source.indexOf("}).catch", handleBeforeQuitIndex); - const queryableIndex = lifecycleSource.indexOf("const queryableWebContents"); - const queryCallIndex = lifecycleSource.indexOf("queryDirtyEditors", queryableIndex); - const lifecycleBeforeQuitIndex = lifecycleSource.indexOf("async function handleBeforeQuit"); - const lifecycleGuardSetup = lifecycleSource.slice(lifecycleBeforeQuitIndex, queryCallIndex); - - assert.notEqual(beforeQuitIndex, -1); - assert.notEqual(dirtyEditorWindowsIndex, -1); - assert.notEqual(handleBeforeQuitIndex, -1); - assert.notEqual(handleBeforeQuitEndIndex, -1); - assert.notEqual(lifecycleBeforeQuitIndex, -1); - assert.notEqual(queryableIndex, -1); - assert.ok(dirtyEditorWindowsIndex < handleBeforeQuitIndex); - assert.match(source.slice(beforeQuitIndex, handleBeforeQuitIndex), /const dirtyEditorWindows = typeof getWindowManager\(\)\.getDirtyEditorWindows === "function"/); - assert.match(source.slice(handleBeforeQuitIndex, handleBeforeQuitEndIndex), /mainWindows,\s*\n\s*queryDirtyEditors/); - assert.match(lifecycleGuardSetup, /const reachableMainWindows = \(Array\.isArray\(mainWindows\) \? mainWindows : \[\]\)\.filter/); - // Prefer queryableWindows (reachable + non-crashed webContents) over a raw - // reachableMainWindows map so dirty checks and focus targets stay aligned. - assert.match( - lifecycleSource.slice(queryableIndex, queryCallIndex), - /queryableWindows\s*\n?\s*\.map\(\(candidate\) => candidate\.webContents\)/, - ); - assert.doesNotMatch(lifecycleGuardSetup, /isVisible|isMinimized/); -}); - -test("macOS reopen after last window re-applies app lock for a fresh session", () => { - const source = readFileSync(path.join(__dirname, "main.cjs"), "utf8"); - const lifecycleSource = readFileSync(path.join(__dirname, "main", "appLockLifecycle.cjs"), "utf8"); - - assert.match(lifecycleSource, /function ensureAppLockForFreshSession/); - assert.match(lifecycleSource, /function hasNoUsableAppContentWindows/); - assert.match(source, /ensureAppLockForFreshSession/); - assert.match(source, /hasNoUsableAppContentWindows/); - - const createIndex = source.indexOf("async function createAndShowMainWindow"); - const createBodyEnd = source.indexOf("async function deliverSshDeepLink", createIndex); - assert.notEqual(createIndex, -1); - assert.notEqual(createBodyEnd, -1); - const createBody = source.slice(createIndex, createBodyEnd); - assert.match(createBody, /hasNoUsableAppContentWindows\(getAppLockReopenWindows\(\)\)/); - assert.match(createBody, /ensureAppLockForFreshSession\(appLockController,\s*"startup"\)/); - - const allClosedIndex = source.indexOf('app.on("window-all-closed"'); - assert.notEqual(allClosedIndex, -1); - const allClosedBody = source.slice(allClosedIndex, allClosedIndex + 350); - assert.match(allClosedBody, /process\.platform !== "darwin"/); - assert.match(allClosedBody, /ensureAppLockForFreshSession\(appLockController,\s*"startup"\)/); -}); - -test("before-quit dirty editor guard foregrounds dirty windows through the focus recovery helper", () => { - const lifecycleSource = readFileSync(path.join(__dirname, "main", "appLockLifecycle.cjs"), "utf8"); - const beforeQuitIndex = lifecycleSource.indexOf("async function handleBeforeQuit"); - const loopIndex = lifecycleSource.indexOf("for (const win of dirtyWindows)", beforeQuitIndex); - const dialogIndex = lifecycleSource.indexOf("// App Lock overlay sits above renderer toasts", loopIndex); - const foregroundBlock = lifecycleSource.slice(loopIndex, dialogIndex); - - assert.notEqual(beforeQuitIndex, -1); - assert.notEqual(loopIndex, -1); - assert.notEqual(dialogIndex, -1); - assert.match(foregroundBlock, /windowManager\.showAndFocusMainWindow\(win\)/); - assert.doesNotMatch(foregroundBlock, /commitQuit\(\)/); -}); - -test("before-quit keeps the original event cancelled while plugin shutdown runs without a renderer", () => { - const lifecycleSource = readFileSync(path.join(__dirname, "main", "appLockLifecycle.cjs"), "utf8"); - const commitIndex = lifecycleSource.indexOf("const commit = () => {"); - const commitEnd = lifecycleSource.indexOf("};", commitIndex); - const commitBlock = lifecycleSource.slice(commitIndex, commitEnd); - - assert.notEqual(commitIndex, -1); - assert.match(commitBlock, /event\?\.preventDefault\?\.\(\)/); - assert.match(commitBlock, /commitQuit\(\)/); - assert.ok( - commitBlock.indexOf("event?.preventDefault?.()") < commitBlock.indexOf("commitQuit()"), - "the original quit must be cancelled before asynchronous plugin shutdown starts", - ); - - const source = readFileSync(path.join(__dirname, "main.cjs"), "utf8"); - const beforeQuitIndex = source.indexOf('app.on("before-quit"'); - const handleIndex = source.indexOf("handleBeforeQuit", beforeQuitIndex); - const handleEnd = source.indexOf("}).catch", handleIndex); - assert.notEqual(handleIndex, -1); - assert.match(source.slice(handleIndex, handleEnd), /commitQuit,/); -}); - -test("all app content windows use the WindowManager-level last-window close handler", () => { - const mainSource = readFileSync(path.join(__dirname, "main.cjs"), "utf8"); - const windowSource = readFileSync(path.join( - __dirname, - "bridges", - "windowManager", - "mainWindow.cjs", - ), "utf8"); - const createWindowIndex = mainSource.indexOf("async function createWindow()"); - const setHandlerIndex = mainSource.indexOf("setAppContentWindowClosedHandler", createWindowIndex); - const managerCreateIndex = mainSource.indexOf("windowManager.createWindow", createWindowIndex); - - assert.notEqual(setHandlerIndex, -1); - assert.notEqual(managerCreateIndex, -1); - assert.ok(setHandlerIndex < managerCreateIndex); - const closedIndex = windowSource.indexOf("win.on('closed'"); - const appContentBranchIndex = windowSource.indexOf("if (registerAsAppContentWindow)", closedIndex); - const notifyIndex = windowSource.indexOf("notifyAppContentWindowClosed(win)", appContentBranchIndex); - assert.notEqual(closedIndex, -1); - assert.notEqual(appContentBranchIndex, -1); - assert.notEqual(notifyIndex, -1); -}); diff --git a/electron/plugins/contributionService.cjs b/electron/plugins/contributionService.cjs index 7196ddfea..d570b6eda 100644 --- a/electron/plugins/contributionService.cjs +++ b/electron/plugins/contributionService.cjs @@ -6,6 +6,7 @@ const { assertPluginContextKey, evaluateContextKeyExpression } = require("./cont const { assertPluginJsonValue } = require("./jsonBoundary.cjs"); const { compileRestrictedJsonSchema } = require("./restrictedJsonSchema.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { invalidArgument, freezeJson } = require("./validationUtils.cjs"); const { InteractiveCommandFeature, InteractiveCommandLimits } = require("./generated/plugin-contract.schema.json").$defs; const MAX_SETTING_BYTES = 128 * 1024; @@ -14,24 +15,10 @@ const MAX_PATTERN_VALUE_LENGTH = 4_096; const MAX_SCOPE_ID_LENGTH = 256; const SETTINGS_SCOPES = new Set(["application", "workspace", "host", "session", "device"]); -function invalidArgument(message) { - return new PluginRpcError(RPC_ERRORS.invalidArgument, message); -} - function notFound(message) { return new PluginRpcError(RPC_ERRORS.notFound, message); } -function freezeJson(value) { - const clone = structuredClone(value); - const freeze = (item) => { - if (!item || typeof item !== "object" || Object.isFrozen(item)) return item; - for (const child of Array.isArray(item) ? item : Object.values(item)) freeze(child); - return Object.freeze(item); - }; - return freeze(clone); -} - function assertJsonValue(value, label = "value") { try { assertPluginJsonValue(value, { maxBytes: MAX_SETTING_BYTES }); } catch (error) { diff --git a/electron/plugins/extensionProviderService.cjs b/electron/plugins/extensionProviderService.cjs index 8b3374df1..5aa594410 100644 --- a/electron/plugins/extensionProviderService.cjs +++ b/electron/plugins/extensionProviderService.cjs @@ -11,6 +11,7 @@ const { } = require("./contractValidator.cjs"); const { assertPluginJsonValue } = require("./jsonBoundary.cjs"); const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs"); +const { invalidArgument, freezeJson } = require("./validationUtils.cjs"); const { compileRestrictedJsonSchema } = require("./restrictedJsonSchema.cjs"); const pluginContractSchema = require("./generated/plugin-contract.schema.json"); @@ -87,20 +88,6 @@ const definitionValidators = Object.freeze({ SyncDeleteObjectResult: createDefinitionValidator("SyncDeleteObjectResult"), }); -function invalidArgument(message) { - return new PluginRpcError(RPC_ERRORS.invalidArgument, message); -} - -function freezeJson(value) { - const clone = structuredClone(value); - const freeze = (item) => { - if (!item || typeof item !== "object" || Object.isFrozen(item)) return item; - for (const child of Array.isArray(item) ? item : Object.values(item)) freeze(child); - return Object.freeze(item); - }; - return freeze(clone); -} - function assertBoundedJson(value, label, maxBytes = MAX_PROVIDER_JSON_BYTES) { try { assertPluginJsonValue(value, { maxBytes }); } catch (error) { throw invalidArgument(`${label} must be bounded JSON: ${error?.message ?? error}`); } diff --git a/electron/plugins/filesystemBroker.cjs b/electron/plugins/filesystemBroker.cjs index 62e74e7fd..e529c1f67 100644 --- a/electron/plugins/filesystemBroker.cjs +++ b/electron/plugins/filesystemBroker.cjs @@ -6,15 +6,12 @@ const path = require("node:path"); const { PLUGIN_RPC_MAX_RAW_BYTES } = require("./constants.cjs"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { invalidArgument } = require("./validationUtils.cjs"); const MAX_FILESYSTEM_BYTES = PLUGIN_RPC_MAX_RAW_BYTES; const MAX_DIRECTORY_ENTRIES = 1_000; const NOFOLLOW = fs.constants.O_NOFOLLOW ?? 0; -function invalidArgument(message) { - return new PluginRpcError(RPC_ERRORS.invalidArgument, message); -} - function assertAbsolutePath(value) { if ( typeof value !== "string" diff --git a/electron/plugins/networkBroker.cjs b/electron/plugins/networkBroker.cjs index 0491e5c11..231f7940f 100644 --- a/electron/plugins/networkBroker.cjs +++ b/electron/plugins/networkBroker.cjs @@ -5,6 +5,7 @@ const validateLease = createDefinitionValidator("SecretLeaseRef"); const validateAuthorization = createDefinitionValidator("PluginNetworkAuthorization"); const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); +const { invalidArgument } = require("./validationUtils.cjs"); const { PLUGIN_RPC_MAX_RAW_BYTES } = require("./constants.cjs"); const { canonicalizeNetworkOrigin } = require("./permissionResources.cjs"); @@ -23,10 +24,6 @@ const FORBIDDEN_REQUEST_HEADERS = new Set([ const SENSITIVE_REDIRECT_HEADERS = new Set(["authorization", "cookie", "proxy-authorization"]); const ENTITY_REDIRECT_HEADERS = new Set(["content-encoding", "content-language", "content-type"]); -function invalidArgument(message) { - return new PluginRpcError(RPC_ERRORS.invalidArgument, message); -} - async function cancelResponseBody(response, reason) { try { await response.body?.cancel?.(reason); } catch {} diff --git a/electron/plugins/terminalProviderService.cjs b/electron/plugins/terminalProviderService.cjs index fb80cab00..0384cb788 100644 --- a/electron/plugins/terminalProviderService.cjs +++ b/electron/plugins/terminalProviderService.cjs @@ -8,6 +8,7 @@ const { } = require("./contractValidator.cjs"); const { assertPluginJsonValue } = require("./jsonBoundary.cjs"); const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs"); +const { invalidArgument, freezeJson } = require("./validationUtils.cjs"); const MAX_PROVIDER_JSON_BYTES = 128 * 1024; const MAX_TERMINAL_PROVIDERS_PER_REQUEST = 32; @@ -70,20 +71,6 @@ const TERMINAL_EVENT_TYPES = new Set([ const TERMINAL_STATUSES = new Set(["connecting", "connected", "disconnected"]); const TERMINAL_SHELL_TYPES = new Set(["posix", "fish", "powershell", "cmd", "unknown"]); -function invalidArgument(message) { - return new PluginRpcError(RPC_ERRORS.invalidArgument, message); -} - -function freezeJson(value) { - const clone = structuredClone(value); - const freeze = (item) => { - if (!item || typeof item !== "object" || Object.isFrozen(item)) return item; - for (const child of Array.isArray(item) ? item : Object.values(item)) freeze(child); - return Object.freeze(item); - }; - return freeze(clone); -} - function assertBoundedJson(value, label) { try { assertPluginJsonValue(value, { maxBytes: MAX_PROVIDER_JSON_BYTES }); diff --git a/electron/plugins/validationUtils.cjs b/electron/plugins/validationUtils.cjs new file mode 100644 index 000000000..fe3f60d7a --- /dev/null +++ b/electron/plugins/validationUtils.cjs @@ -0,0 +1,22 @@ +"use strict"; + +const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs"); + +function invalidArgument(message) { + return new PluginRpcError(RPC_ERRORS.invalidArgument, message); +} + +function freezeJson(value) { + const clone = structuredClone(value); + const freeze = (item) => { + if (!item || typeof item !== "object" || Object.isFrozen(item)) return item; + for (const child of Array.isArray(item) ? item : Object.values(item)) freeze(child); + return Object.freeze(item); + }; + return freeze(clone); +} + +module.exports = { + invalidArgument, + freezeJson, +}; diff --git a/electron/preload/api.aiSessionsBackup.test.cjs b/electron/preload/api.aiSessionsBackup.test.cjs deleted file mode 100644 index 437dbc8cf..000000000 --- a/electron/preload/api.aiSessionsBackup.test.cjs +++ /dev/null @@ -1,19 +0,0 @@ -const assert = require('node:assert/strict'); -const test = require('node:test'); -const { createPreloadApi } = require('./api.cjs'); - -test('backup write and export forward the serialized JSON payload unchanged', async () => { - const calls = []; - const api = createPreloadApi({ - ipcRenderer: { invoke: async (...args) => { calls.push(args); } }, - webUtils: {}, - }); - const payload = { json: '[]' }; - await api.aiSessionsBackupWrite(payload); - await api.aiSessionsBackupExport(payload); - assert.deepEqual(calls, [ - ['netcatty:aiSessionsBackup:write', payload], - ['netcatty:aiSessionsBackup:export', payload], - ]); - for (const [, argument] of calls) assert.equal(typeof argument.json, 'string'); -}); diff --git a/electron/preload/api.cjs b/electron/preload/api.cjs index 8878495a4..af2d1349e 100644 --- a/electron/preload/api.cjs +++ b/electron/preload/api.cjs @@ -2320,27 +2320,6 @@ function createPreloadApi(ctx) { ipcRenderer.on("netcatty:ai:stream:error", handler); return () => ipcRenderer.removeListener("netcatty:ai:stream:error", handler); }, - onAiAgentStdout: (agentId, cb) => { - const handler = (_event, payload) => { - if (payload.agentId === agentId) cb(payload.data); - }; - ipcRenderer.on("netcatty:ai:agent:stdout", handler); - return () => ipcRenderer.removeListener("netcatty:ai:agent:stdout", handler); - }, - onAiAgentStderr: (agentId, cb) => { - const handler = (_event, payload) => { - if (payload.agentId === agentId) cb(payload.data); - }; - ipcRenderer.on("netcatty:ai:agent:stderr", handler); - return () => ipcRenderer.removeListener("netcatty:ai:agent:stderr", handler); - }, - onAiAgentExit: (agentId, cb) => { - const handler = (_event, payload) => { - if (payload.agentId === agentId) cb(payload.code); - }; - ipcRenderer.on("netcatty:ai:agent:exit", handler); - return () => ipcRenderer.removeListener("netcatty:ai:agent:exit", handler); - }, scriptRun: async (params) => ipcRenderer.invoke("netcatty:script:run", params), scriptStop: async (runId) => ipcRenderer.invoke("netcatty:script:stop", { runId }), scriptPause: async (runId) => ipcRenderer.invoke("netcatty:script:pause", { runId }), diff --git a/electron/preload/api.cloudSyncPassword.test.cjs b/electron/preload/api.cloudSyncPassword.test.cjs deleted file mode 100644 index ce81be824..000000000 --- a/electron/preload/api.cloudSyncPassword.test.cjs +++ /dev/null @@ -1,17 +0,0 @@ -const assert = require('node:assert/strict'); -const test = require('node:test'); -const { EventEmitter } = require('node:events'); -const { createPreloadApi } = require('./api.cjs'); - -test('password-availability subscription exposes no IPC payload and unsubscribes', () => { - const ipcRenderer = new EventEmitter(); - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - const calls = []; - const unsubscribe = api.onCloudSyncSessionPasswordAvailable((...args) => calls.push(args)); - ipcRenderer.emit('netcatty:cloudSync:session:passwordAvailable', { sender: 'private' }, 'must-not-forward'); - assert.deepEqual(calls, [[]]); - unsubscribe(); - ipcRenderer.emit('netcatty:cloudSync:session:passwordAvailable', {}); - assert.equal(calls.length, 1); - assert.equal(ipcRenderer.listenerCount('netcatty:cloudSync:session:passwordAvailable'), 0); -}); diff --git a/electron/preload/api.editorWindow.test.cjs b/electron/preload/api.editorWindow.test.cjs deleted file mode 100644 index 79c8a0ae9..000000000 --- a/electron/preload/api.editorWindow.test.cjs +++ /dev/null @@ -1,43 +0,0 @@ -const assert = require("node:assert/strict"); -const test = require("node:test"); -const { createPreloadApi } = require("./api.cjs"); - -function harness(pending = []) { - const sent = []; - const editorOpenTabState = { pending, listeners: new Set() }; - const api = createPreloadApi({ editorOpenTabState, ipcRenderer: { send: (...args) => sent.push(args) }, webUtils: {} }); - return { api, sent, editorOpenTabState }; -} - -test("editor receiver announces readiness after subscribing and acknowledges installed contents", () => { - const h = harness(); - const received = []; - const off = h.api.onEditorWindowOpenTab((payload) => { - assert.equal(h.sent.length, 1, "receipt must follow installation"); - received.push(payload.content); - }); - assert.deepEqual(h.sent, [["netcatty:window:editorReady"]]); - const message = { requestId: "open-1", content: "unsaved" }; - for (const receive of h.editorOpenTabState.listeners) receive(message); - assert.deepEqual(received, ["unsaved"]); - assert.deepEqual(h.sent[1], ["netcatty:window:editorOpenTabResult", { requestId: "open-1", ok: true }]); - off(); - assert.equal(h.editorOpenTabState.listeners.size, 0); -}); - -test("failed renderer installation sends a negative receipt", () => { - const h = harness(); - h.api.onEditorWindowOpenTab(() => { throw new Error("cannot install"); }); - for (const receive of h.editorOpenTabState.listeners) receive({ requestId: "open-2" }); - assert.deepEqual(h.sent.at(-1), ["netcatty:window:editorOpenTabResult", { requestId: "open-2", ok: false, error: "cannot install" }]); -}); - -test("queued tabs are installed by the mounted receiver before cleanup", () => { - const h = harness([{ requestId: "queued", content: "unsaved" }]); - let installed = 0; - const off = h.api.onEditorWindowOpenTab(() => { installed++; }); - off(); - h.api.onEditorWindowOpenTab(() => { installed++; }); - assert.equal(installed, 1); - assert.equal(h.editorOpenTabState.pending.length, 0); -}); diff --git a/electron/preload/api.hostBrowser.test.cjs b/electron/preload/api.hostBrowser.test.cjs deleted file mode 100644 index f55dd1241..000000000 --- a/electron/preload/api.hostBrowser.test.cjs +++ /dev/null @@ -1,24 +0,0 @@ -const assert = require('node:assert/strict'); -const test = require('node:test'); -const { EventEmitter } = require('node:events'); -const { createPreloadApi } = require('./api.cjs'); - -test('browser requests survive before the lazy terminal receiver subscribes', () => { - const ipcRenderer = new EventEmitter(); - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - const first = { host: { id: 'first' } }; - const second = { host: { id: 'second' }, url: 'http://localhost:3000/' }; - const delivered = []; - ipcRenderer.emit('netcatty:host-browser:request-panel', {}, first); - ipcRenderer.emit('netcatty:host-browser:request-panel', {}, second); - const off = api.onHostBrowserPanelRequest((request) => delivered.push(request)); - assert.deepEqual(delivered, [first, second]); - off(); - const third = { host: { id: 'third' } }; - ipcRenderer.emit('netcatty:host-browser:request-panel', {}, third); - const offAgain = api.onHostBrowserPanelRequest((request) => delivered.push(request)); - assert.deepEqual(delivered, [first, second, third], 'queued requests must be consumed once'); - ipcRenderer.emit('netcatty:host-browser:request-panel', {}, first); - assert.deepEqual(delivered, [first, second, third, first]); - offAgain(); -}); diff --git a/electron/preload/api.localFileDrag.test.cjs b/electron/preload/api.localFileDrag.test.cjs deleted file mode 100644 index 98351e8fb..000000000 --- a/electron/preload/api.localFileDrag.test.cjs +++ /dev/null @@ -1,15 +0,0 @@ -const assert = require("node:assert/strict"); -const test = require("node:test"); -const { createPreloadApi } = require("./api.cjs"); - -test("local file drag exposes only the dedicated start and cancellation channels", async () => { - const calls = []; - const api = createPreloadApi({ ipcRenderer: { - invoke: async (...args) => { calls.push(args); return { started: true }; }, - send: (...args) => calls.push(args), - }, webUtils: {} }); - const payload = { requestId: "one", paths: ["/file"] }; - assert.deepEqual(await api.startLocalFileDrag(payload), { started: true }); - api.cancelLocalFileDrag("one"); - assert.deepEqual(calls, [["netcatty:local:drag-start", payload], ["netcatty:local:drag-cancel", { requestId: "one" }]]); -}); diff --git a/electron/preload/api.pasteWriteReceipt.test.cjs b/electron/preload/api.pasteWriteReceipt.test.cjs deleted file mode 100644 index 6aca721c3..000000000 --- a/electron/preload/api.pasteWriteReceipt.test.cjs +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -const test = require("node:test"); -const assert = require("node:assert/strict"); -const { EventEmitter } = require("node:events"); -const { createPreloadApi } = require("./api.cjs"); - -test("paste ID is opt-in and receipts use direct IPC with removable subscription", () => { - const ipcRenderer = new EventEmitter(); - const sent = []; - ipcRenderer.send = (...args) => sent.push(args); - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - api.writeToSession("s", "secret", { automated: true, lineDelayMs: 100, pasteRequestId: "uuid" }); - assert.equal(sent[0][0], "netcatty:write"); - assert.equal(sent[0][1].pasteRequestId, "uuid"); - api.writeToSession("s", "x"); - api.writeToSession("s", "x", { pasteRequestId: 17 }); - assert.equal(sent[1][1].pasteRequestId, undefined); - assert.equal(sent[2][1].pasteRequestId, undefined); - const calls = []; - const unsubscribe = api.onTerminalPasteWrite((...args) => calls.push(args)); - const receipt = { sessionId: "s", requestId: "uuid", index: 0, done: true }; - ipcRenderer.emit("netcatty:paste-write", { sender: "private" }, receipt); - assert.deepEqual(calls, [[receipt]]); - unsubscribe(); - ipcRenderer.emit("netcatty:paste-write", {}, receipt); - assert.equal(calls.length, 1); - assert.equal(ipcRenderer.listenerCount("netcatty:paste-write"), 0); -}); - -test("cancel-only bypasses urgent raw-interrupt port while ordinary interrupt preserves it", () => { - const ipcRenderer = new EventEmitter(); - const sent = []; - const urgent = []; - ipcRenderer.send = (...args) => sent.push(args); - const api = createPreloadApi({ ipcRenderer, webUtils: {}, terminalUrgentInputPorts: { - postInterrupt(...args) { urgent.push(args); return true; }, - } }); - api.interruptSession("s", undefined, { cancelPendingWritesOnly: true }); - assert.deepEqual(sent, [["netcatty:interrupt", { sessionId: "s", trace: undefined, cancelPendingWritesOnly: true }]]); - assert.deepEqual(urgent, []); - api.interruptSession("s"); - assert.equal(urgent.length, 1); - assert.equal(sent.length, 1); -}); diff --git a/electron/preload/api.pluginAIHost.test.cjs b/electron/preload/api.pluginAIHost.test.cjs deleted file mode 100644 index 9ca3a4efb..000000000 --- a/electron/preload/api.pluginAIHost.test.cjs +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -const test = require("node:test"); -const assert = require("node:assert/strict"); -const fs = require("node:fs"); -const path = require("node:path"); -const { EventEmitter } = require("node:events"); -const { createPreloadApi } = require("./api.cjs"); - -test("trusted AI preload uses dedicated typed channels and disposes subscriptions", async () => { - const calls = []; const ipcRenderer = new EventEmitter(); - ipcRenderer.invoke = async (...args) => { calls.push(args); return true; }; - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - await api.setPluginAIHostReady(true); - const reply = { requestId: "request", actionToken: "token", error: true }; - await api.respondPluginAIHost(reply); - assert.deepEqual(calls, [["netcatty:plugins:ai-host-ready", true], ["netcatty:plugins:ai-host-response", reply]]); - const received = []; const off = api.onPluginAIHostRequest((request) => received.push(request)); - const request = { kind: "model.select" }; - ipcRenderer.emit("netcatty:plugins:ai-host-request", {}, request); off(); - ipcRenderer.emit("netcatty:plugins:ai-host-request", {}, { kind: "context.select" }); - assert.deepEqual(received, [request]); - assert.doesNotMatch(fs.readFileSync(path.join(__dirname, "../plugins/runtime/browserPreload.cjs"), "utf8"), /ai-host-|PluginAIHost/); -}); diff --git a/electron/preload/api.systemTheme.test.cjs b/electron/preload/api.systemTheme.test.cjs deleted file mode 100644 index 877dd4642..000000000 --- a/electron/preload/api.systemTheme.test.cjs +++ /dev/null @@ -1,32 +0,0 @@ -const assert = require('node:assert/strict'); -const test = require('node:test'); -const { EventEmitter } = require('node:events'); -const { createPreloadApi } = require('./api.cjs'); - -const channel = 'netcatty:system-theme-changed'; - -test('system theme subscription forwards light/dark without exposing the IPC event and unsubscribes', () => { - const ipcRenderer = new EventEmitter(); - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - const calls = []; - const unsubscribe = api.onSystemThemeChanged((...args) => calls.push(args)); - ipcRenderer.emit(channel, { sender: 'private' }, { isDark: true }); - ipcRenderer.emit(channel, { sender: 'private' }, { isDark: false }); - assert.deepEqual(calls, [[{ isDark: true }], [{ isDark: false }]]); - unsubscribe(); - ipcRenderer.emit(channel, {}, { isDark: true }); - assert.equal(calls.length, 2); - assert.equal(ipcRenderer.listenerCount(channel), 0); -}); - -test('system theme subscription ignores malformed payloads', () => { - const ipcRenderer = new EventEmitter(); - const api = createPreloadApi({ ipcRenderer, webUtils: {} }); - const calls = []; - const unsubscribe = api.onSystemThemeChanged((payload) => calls.push(payload)); - for (const payload of [undefined, null, {}, { isDark: 'false' }, { isDark: 0 }]) { - ipcRenderer.emit(channel, {}, payload); - } - unsubscribe(); - assert.deepEqual(calls, []); -}); diff --git a/electron/preload/api.test.cjs b/electron/preload/api.test.cjs new file mode 100644 index 000000000..d64abddb1 --- /dev/null +++ b/electron/preload/api.test.cjs @@ -0,0 +1,217 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { EventEmitter } = require("node:events"); +const fs = require("node:fs"); +const path = require("node:path"); +const test = require("node:test"); +const { createPreloadApi } = require("./api.cjs"); + +function createMockIpc(overrides = {}) { + const ipcRenderer = new EventEmitter(); + const invoked = []; + const sent = []; + ipcRenderer.invoke = overrides.invoke ?? (async (...args) => { invoked.push(args); }); + ipcRenderer.send = overrides.send ?? ((...args) => { sent.push(args); }); + return { ipcRenderer, invoked, sent }; +} + +test("backup write and export forward the serialized JSON payload unchanged", async () => { + const { ipcRenderer, invoked } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + const payload = { json: "[]" }; + await api.aiSessionsBackupWrite(payload); + await api.aiSessionsBackupExport(payload); + assert.deepEqual(invoked, [ + ["netcatty:aiSessionsBackup:write", payload], + ["netcatty:aiSessionsBackup:export", payload], + ]); + for (const [, argument] of invoked) assert.equal(typeof argument.json, "string"); +}); + +test("password-availability subscription exposes no IPC payload and unsubscribes", () => { + const { ipcRenderer } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + const calls = []; + const unsubscribe = api.onCloudSyncSessionPasswordAvailable((...args) => calls.push(args)); + ipcRenderer.emit("netcatty:cloudSync:session:passwordAvailable", { sender: "private" }, "must-not-forward"); + assert.deepEqual(calls, [[]]); + unsubscribe(); + ipcRenderer.emit("netcatty:cloudSync:session:passwordAvailable", {}); + assert.equal(calls.length, 1); + assert.equal(ipcRenderer.listenerCount("netcatty:cloudSync:session:passwordAvailable"), 0); +}); + +function createEditorHarness(pending = []) { + const { ipcRenderer, sent } = createMockIpc(); + const editorOpenTabState = { pending, listeners: new Set() }; + const api = createPreloadApi({ editorOpenTabState, ipcRenderer, webUtils: {} }); + return { api, sent, editorOpenTabState }; +} + +test("editor receiver announces readiness after subscribing and acknowledges installed contents", () => { + const h = createEditorHarness(); + const received = []; + const off = h.api.onEditorWindowOpenTab((payload) => { + assert.equal(h.sent.length, 1, "receipt must follow installation"); + received.push(payload.content); + }); + assert.deepEqual(h.sent, [["netcatty:window:editorReady"]]); + const message = { requestId: "open-1", content: "unsaved" }; + for (const receive of h.editorOpenTabState.listeners) receive(message); + assert.deepEqual(received, ["unsaved"]); + assert.deepEqual(h.sent[1], ["netcatty:window:editorOpenTabResult", { requestId: "open-1", ok: true }]); + off(); + assert.equal(h.editorOpenTabState.listeners.size, 0); +}); + +test("failed renderer installation sends a negative receipt", () => { + const h = createEditorHarness(); + h.api.onEditorWindowOpenTab(() => { throw new Error("cannot install"); }); + for (const receive of h.editorOpenTabState.listeners) receive({ requestId: "open-2" }); + assert.deepEqual(h.sent.at(-1), [ + "netcatty:window:editorOpenTabResult", + { requestId: "open-2", ok: false, error: "cannot install" }, + ]); +}); + +test("queued tabs are installed by the mounted receiver before cleanup", () => { + const h = createEditorHarness([{ requestId: "queued", content: "unsaved" }]); + let installed = 0; + const off = h.api.onEditorWindowOpenTab(() => { installed += 1; }); + off(); + h.api.onEditorWindowOpenTab(() => { installed += 1; }); + assert.equal(installed, 1); + assert.equal(h.editorOpenTabState.pending.length, 0); +}); + +test("browser requests survive before the lazy terminal receiver subscribes", () => { + const { ipcRenderer } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + const first = { host: { id: "first" } }; + const second = { host: { id: "second" }, url: "http://localhost:3000/" }; + const delivered = []; + ipcRenderer.emit("netcatty:host-browser:request-panel", {}, first); + ipcRenderer.emit("netcatty:host-browser:request-panel", {}, second); + const off = api.onHostBrowserPanelRequest((request) => delivered.push(request)); + assert.deepEqual(delivered, [first, second]); + off(); + const third = { host: { id: "third" } }; + ipcRenderer.emit("netcatty:host-browser:request-panel", {}, third); + const offAgain = api.onHostBrowserPanelRequest((request) => delivered.push(request)); + assert.deepEqual(delivered, [first, second, third], "queued requests must be consumed once"); + ipcRenderer.emit("netcatty:host-browser:request-panel", {}, first); + assert.deepEqual(delivered, [first, second, third, first]); + offAgain(); +}); + +test("local file drag exposes only the dedicated start and cancellation channels", async () => { + const calls = []; + const api = createPreloadApi({ + ipcRenderer: { + invoke: async (...args) => { calls.push(args); return { started: true }; }, + send: (...args) => calls.push(args), + }, + webUtils: {}, + }); + const payload = { requestId: "one", paths: ["/file"] }; + assert.deepEqual(await api.startLocalFileDrag(payload), { started: true }); + api.cancelLocalFileDrag("one"); + assert.deepEqual(calls, [ + ["netcatty:local:drag-start", payload], + ["netcatty:local:drag-cancel", { requestId: "one" }], + ]); +}); + +test("paste ID is opt-in and receipts use direct IPC with removable subscription", () => { + const { ipcRenderer, sent } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + api.writeToSession("s", "secret", { automated: true, lineDelayMs: 100, pasteRequestId: "uuid" }); + assert.equal(sent[0][0], "netcatty:write"); + assert.equal(sent[0][1].pasteRequestId, "uuid"); + api.writeToSession("s", "x"); + api.writeToSession("s", "x", { pasteRequestId: 17 }); + assert.equal(sent[1][1].pasteRequestId, undefined); + assert.equal(sent[2][1].pasteRequestId, undefined); + const calls = []; + const unsubscribe = api.onTerminalPasteWrite((...args) => calls.push(args)); + const receipt = { sessionId: "s", requestId: "uuid", index: 0, done: true }; + ipcRenderer.emit("netcatty:paste-write", { sender: "private" }, receipt); + assert.deepEqual(calls, [[receipt]]); + unsubscribe(); + ipcRenderer.emit("netcatty:paste-write", {}, receipt); + assert.equal(calls.length, 1); + assert.equal(ipcRenderer.listenerCount("netcatty:paste-write"), 0); +}); + +test("cancel-only bypasses urgent raw-interrupt port while ordinary interrupt preserves it", () => { + const { ipcRenderer, sent } = createMockIpc(); + const urgent = []; + const api = createPreloadApi({ + ipcRenderer, + webUtils: {}, + terminalUrgentInputPorts: { + postInterrupt(...args) { urgent.push(args); return true; }, + }, + }); + api.interruptSession("s", undefined, { cancelPendingWritesOnly: true }); + assert.deepEqual(sent, [["netcatty:interrupt", { sessionId: "s", trace: undefined, cancelPendingWritesOnly: true }]]); + assert.deepEqual(urgent, []); + api.interruptSession("s"); + assert.equal(urgent.length, 1); + assert.equal(sent.length, 1); +}); + +test("trusted AI preload uses dedicated typed channels and disposes subscriptions", async () => { + const calls = []; + const { ipcRenderer } = createMockIpc({ + invoke: async (...args) => { calls.push(args); return true; }, + }); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + await api.setPluginAIHostReady(true); + const reply = { requestId: "request", actionToken: "token", error: true }; + await api.respondPluginAIHost(reply); + assert.deepEqual(calls, [ + ["netcatty:plugins:ai-host-ready", true], + ["netcatty:plugins:ai-host-response", reply], + ]); + const received = []; + const off = api.onPluginAIHostRequest((request) => received.push(request)); + const request = { kind: "model.select" }; + ipcRenderer.emit("netcatty:plugins:ai-host-request", {}, request); + off(); + ipcRenderer.emit("netcatty:plugins:ai-host-request", {}, { kind: "context.select" }); + assert.deepEqual(received, [request]); + assert.doesNotMatch( + fs.readFileSync(path.join(__dirname, "../plugins/runtime/browserPreload.cjs"), "utf8"), + /ai-host-|PluginAIHost/, + ); +}); + +test("system theme subscription forwards light/dark without exposing the IPC event and unsubscribes", () => { + const channel = "netcatty:system-theme-changed"; + const { ipcRenderer } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + const calls = []; + const unsubscribe = api.onSystemThemeChanged((...args) => calls.push(args)); + ipcRenderer.emit(channel, { sender: "private" }, { isDark: true }); + ipcRenderer.emit(channel, { sender: "private" }, { isDark: false }); + assert.deepEqual(calls, [[{ isDark: true }], [{ isDark: false }]]); + unsubscribe(); + ipcRenderer.emit(channel, {}, { isDark: true }); + assert.equal(calls.length, 2); + assert.equal(ipcRenderer.listenerCount(channel), 0); +}); + +test("system theme subscription ignores malformed payloads", () => { + const channel = "netcatty:system-theme-changed"; + const { ipcRenderer } = createMockIpc(); + const api = createPreloadApi({ ipcRenderer, webUtils: {} }); + const calls = []; + const unsubscribe = api.onSystemThemeChanged((payload) => calls.push(payload)); + for (const payload of [undefined, null, {}, { isDark: "false" }, { isDark: 0 }]) { + ipcRenderer.emit(channel, {}, payload); + } + unsubscribe(); + assert.deepEqual(calls, []); +}); diff --git a/global.d.ts b/global.d.ts index f3c476211..b8ef7df2f 100644 --- a/global.d.ts +++ b/global.d.ts @@ -6,6 +6,8 @@ /// /// /// +/// +/// declare module "*.cjs" { const value: Record; export = value; @@ -89,16 +91,6 @@ declare global { algorithmOverrides?: import("./domain/models").HostAlgorithmOverrides; } - // Host key information for verification - // Reserved for future host key verification UI feature - interface _NetcattyHostKeyInfo { - hostname: string; - port: number; - keyType: string; - fingerprint: string; - publicKey?: string; - } - interface NetcattySSHOptions { keyLabel?: string; sessionId?: string; @@ -214,650 +206,11 @@ declare global { ino?: number; } - interface SftpTransferProgress { - transferId: string; - bytesTransferred: number; - totalBytes: number; - speed: number; // bytes per second - } - - // Port Forwarding Types - interface PortForwardOptions { - ruleId?: string; - tunnelId: string; - type: 'local' | 'remote' | 'dynamic'; - localPort: number; - bindAddress?: string; - remoteHost?: string; - remotePort?: number; - // SSH connection details - hostname: string; - hostId?: string; - port?: number; - username: string; - authMethod?: import("./domain/models").HostAuthMethod; - requiresMfa?: boolean; - password?: string; - totp?: NetcattyTotpConfig; - privateKey?: string; - certificate?: string; - keyId?: string; - passphrase?: string; - knownHosts?: import("./domain/models").KnownHost[]; - verifyHostKeys?: boolean; - proxy?: NetcattyProxyConfig; - jumpHosts?: NetcattyJumpHost[]; - identityFilePaths?: string[]; - useSshAgent?: boolean; - agentPublicKeys?: string[]; - identityAgent?: string; - identitiesOnly?: boolean; - addKeysToAgent?: string; - useKeychain?: boolean; - legacyAlgorithms?: boolean; - skipEcdsaHostKey?: boolean; - algorithmOverrides?: import("./domain/models").HostAlgorithmOverrides; - // Resolved keepalive for the target connection (caller has already - // applied host override / global fallback). interval in seconds. - keepaliveInterval?: number; - keepaliveCountMax?: number; - sshTcpConnectTimeoutMs?: number; - sshAuthReadyTimeoutMs?: number; - reuseTransport?: boolean; - } - - interface PortForwardResult { - tunnelId: string; - success: boolean; - localPort?: number; - cancelled?: boolean; - blockedByCleanup?: boolean; - reused?: boolean; - status?: 'inactive' | 'connecting' | 'active' | 'error'; - error?: string; - } - - interface PortForwardStatusResult { - tunnelId: string; - status: 'inactive' | 'connecting' | 'active' | 'error'; - type?: 'local' | 'remote' | 'dynamic'; - error?: string; - } - - type PortForwardRuntimePhase = - | 'connecting' - | 'active' - | 'stopping' - | 'error' - | 'inactive'; - - interface PortForwardRuntimeRecord { - ruleId?: string; - tunnelId: string; - phase: PortForwardRuntimePhase | string; - error?: string; - cleanupRequired?: boolean; - revision: number; - updatedAt: number; - } - - interface PortForwardRuntimeSnapshot { - epoch: string; - revision: number; - records: PortForwardRuntimeRecord[]; - } - - type PortForwardRuntimeEvent = - | { - epoch: string; - revision: number; - kind: 'upsert'; - record: PortForwardRuntimeRecord; - } - | { - epoch: string; - revision: number; - kind: 'remove'; - tunnelId: string; - ruleId?: string; - }; - interface NetcattyWindowsPtyInfo { backend: 'conpty' | 'winpty'; buildNumber?: number; } - type PortForwardStatusCallback = (status: 'inactive' | 'connecting' | 'active' | 'error', error?: string) => void; - type PortForwardRuntimeEventCallback = (event: PortForwardRuntimeEvent) => void; - - interface NetcattyPluginRuntimeStatus { - available: boolean; - experimental: true; - credentialStorageAvailable?: boolean; - } - - interface NetcattyPluginCatalogSnapshot { - entries: NetcattyPluginCatalogEntry[]; - source: "registry" | "cached" | "builtin"; - error: string | null; - } - - interface NetcattyPluginCatalogEntry { - selectionToken?: string; - id: string; - version: string; - name: string; - description: string; - author: string; - repository: string; - commit: string; - license: string; - readme: string; - manifest: import("@netcatty/plugin-contract").PluginManifest; - artifact?: { url: string; sha256: string }; - } - - type NetcattyPluginAuthorRequest = - | { kind: 'catalog'; pluginId: string; selectionToken: string; sourceId: string } - | { kind: 'installed'; pluginId: string }; - interface NetcattyPluginAuthorPresentation { - author: string; - avatar: string | null; - officialMaintained: boolean; - sourceId: string; - version: string; - archiveSha256: string | null; - } - - type PluginPermissionMode = 'allow' | 'ask' | 'deny'; - type NetcattyPluginPermissionPrompt = import('@netcatty/plugin-contract').PermissionRequest & { - actionToken: string; resources: string[]; - }; - interface NetcattyPluginPermissionSnapshot { - policyRevision?: string; - policies?: Array<{ permission: string; resources: string[]; mode: PluginPermissionMode }>; - grants: Array<{ - permission: string; resource: string; resourceKind: string; - scope: 'always' | 'application' | 'session'; sessionId: string | null; grantedAt: number; - matchesCurrentActivation: boolean; - }>; - audit: Array<{ event: string; createdAt: number; permission?: string; scope?: string; mode?: PluginPermissionMode; action?: string }>; - } - - interface NetcattyPluginSource { - id: string; - kind: 'official' | 'third-party' | 'local' | 'github'; - name: string; - origin: string | null; - enabled?: boolean; - tag?: string; - commit?: string; - assetId?: number; - } - interface NetcattyGitHubPluginPreview { - token: string; - source: NetcattyPluginSource; - manifest: import("@netcatty/plugin-contract").PluginManifest; - archiveSha256: string; - assetName: string; - size: number; - } - interface NetcattyInstalledPlugin { - source?: NetcattyPluginSource; - id: string; - enabled: boolean; - activeVersion: string | null; - manifest: import("@netcatty/plugin-contract").PluginManifest | null; - archiveSha256?: string | null; - runtime: { - status: string; - kind: 'browser' | 'utility' | null; - lastError: string | null; - quarantinedAt: number | null; - }; - } - - interface NetcattyExtensionProviderContribution { - pluginId: string; - pluginVersion: string; - pluginDisplayName?: string; - provider: import("@netcatty/plugin-contract").ProviderContribution; - } - - interface NetcattyExtensionProviderRequest { - providerId: string; - kind: 'connection' | 'authentication' | 'importer'; - operation: string; - requestId?: string; - payload?: import("@netcatty/plugin-contract").JsonValue; - deadlineMs?: number; - } - - interface NetcattyPluginConnectionStartRequest { - requestId?: string; - sessionId: string; - protocol?: string; - hostLabel?: string; - hostname?: string; - providerId: string; - configuration: import("@netcatty/plugin-contract").JsonValue; - columns: number; - rows: number; - credential?: import("@netcatty/plugin-contract").CredentialRef | import("@netcatty/plugin-contract").SecretRef; - authenticationProviderId?: string; - sessionLog?: { enabled: boolean; directory: string; format: string; timestampsEnabled?: boolean }; - deadlineMs?: number; - } - - interface NetcattyPluginImporterPreview { - providerId: string; - result: import("@netcatty/plugin-contract").ImporterParseResult; - records: ReadonlyArray; - } - - interface NetcattyPluginImporterProgressEvent { - requestId: string; - providerId: string; - progress: Extract; - } - - interface NetcattyPluginAuthenticationChallengeOpenEvent { - requestId: string; - challengeRequestId: string; - challenge: import("@netcatty/plugin-contract").AuthenticationChallenge; - } - - interface NetcattyPluginAuthenticationChallengeCancelEvent { - requestId: string; - challengeRequestId: string; - challengeId?: string; - cancelled: true; - } - - type NetcattyPluginAuthenticationChallengeEvent = - | NetcattyPluginAuthenticationChallengeOpenEvent - | NetcattyPluginAuthenticationChallengeCancelEvent; - - interface NetcattyPluginLogStatus { - saveToDisk: boolean; - verbose: boolean; - droppedRecords: number; - writeErrors: number; - pendingBytes: number; - maxBytes: number; - retentionDays: number; - } - - interface NetcattyBridge { - getPluginLogStatus?(): Promise; - configurePluginLogs?(settings: { saveToDisk: boolean; verbose: boolean }): Promise; - openPluginLogFolder?(): Promise; - exportPluginLogs?(): Promise; - clearPluginLogs?(): Promise; - getPluginRuntimeStatus?(): Promise; - getPluginSourceBinding?(pluginId: string): Promise; - resetPluginSource?(pluginId: string, expectedSourceId: string): Promise; - listPluginSources?(): Promise; - addPluginSource?(source: { name: string; address: string }): Promise; - updatePluginSource?(source: { id: string; name: string; enabled: boolean }): Promise; - removePluginSource?(id: string, disablePlugins: boolean): Promise; - listPluginCatalog?(sourceId?: string): Promise; - getPluginAuthorPresentation?(request: NetcattyPluginAuthorRequest): Promise; - onPluginCatalogChanged?(callback: (event: { sourceId: string }) => void): () => void; - getPluginCatalogReadme?(id: string, selectionToken?: string, sourceId?: string): Promise; - getPluginCatalogReadmeImages?(id: string, selectionToken?: string, sourceId?: string): Promise>; - installCatalogPlugin?(id: string, selectionToken?: string, sourceId?: string, acceptedSourceId?: string): Promise; - setPluginAIHostReady?(ready: boolean): Promise; - setPluginAgentHostReady?(ready: boolean): Promise; - respondPluginAgentHost?(response: import("@netcatty/plugin-contract").PluginAgentHostResponse): Promise; - onPluginAgentHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAgentHostRequest) => void): () => void; - respondPluginAIHost?(response: import("@netcatty/plugin-contract").PluginAIHostResponse): Promise; - onPluginAIHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAIHostRequest) => void): () => void; - setPluginInteractionReady?(ready: boolean): Promise; - respondPluginInteraction?(response: import("@netcatty/plugin-contract").HostInteractionResponse): Promise; - onPluginInteraction?(callback: (event: import("@netcatty/plugin-contract").HostInteractionEvent) => void): () => void; - listPlugins?(): Promise; - setPluginPermissionMode?(pluginId: string, permission: string, mode: PluginPermissionMode, policyRevision: string): Promise; - setPluginPermissionReady?(ready: boolean): Promise; - respondPluginPermission?(response: { requestId: string; actionToken: string; decision: 'allow' | 'deny' | 'cancel' }): Promise; - onPluginPermission?(callback: (event: NetcattyPluginPermissionPrompt | { requestId: string; closed: true }) => void): () => void; - getPluginPermissions?(pluginId: string): Promise; - revokePluginPermissions?(pluginId: string): Promise; - installPluginPackage?(archivePath: string, options?: { enable?: boolean }): Promise; - prepareGitHubPlugin?(repository: string): Promise; - installGitHubPlugin?(token: string): Promise; - discardGitHubPlugin?(token: string): Promise; - setPluginEnabled?(pluginId: string, enabled: boolean): Promise; - restartPlugin?(pluginId: string): Promise; - uninstallPlugin?(pluginId: string): Promise; - setPluginTerminalTarget?(target: import("@netcatty/plugin-contract").HostTerminalTarget): Promise; - getPluginThemes?(): Promise; - applyPluginTheme?(request: import("@netcatty/plugin-contract").ThemePackApplyRequest): Promise; - onPluginThemesChanged?(callback: () => void): () => void; - getPluginContributions?(options?: NetcattyPluginContributionQuery): Promise; - getPluginBrandIcon?(pluginId: string): Promise<{ light: string; dark?: string } | null>; - getPluginContributionIcon?(pluginId: string, icon: Extract): Promise<{ light: string; dark?: string }>; - executePluginCommand?(command: string, args?: unknown, context?: Record): Promise; - updatePluginSetting?(pluginId: string, settingId: string, value: unknown, scopeId?: string): Promise<{ restartRequired: boolean }>; - resetPluginSetting?(pluginId: string, settingId: string, scopeId?: string): Promise<{ restartRequired: boolean }>; - setPluginEnvironment?(environment: NetcattyPluginEnvironment): Promise; - listPluginTerminalProviders?(options: NetcattyTerminalProviderQuery): Promise>; - providePluginTerminal?(request: NetcattyTerminalProviderRequest): Promise>; - cancelPluginTerminalRequest?(requestId: string): Promise; - publishPluginTerminalSessionEvent?(event: NetcattyTerminalSessionEvent): Promise>; - listPluginExtensionProviders?(options: { kind: 'connection' | 'authentication' | 'importer' | 'sync'; locale?: string }): Promise>; - updatePluginCredentialCatalog?(entries: ReadonlyArray<{ id: string; ciphertext: string }>): Promise; - invokePluginExtensionProvider?(request: NetcattyExtensionProviderRequest): Promise; - cancelPluginExtensionRequest?(requestId: string): Promise; - pluginSyncConnect?(request: { - requestId?: string; - providerId: string; - configuration?: unknown; - credential?: unknown; - deadlineMs?: number; - }): Promise<{ account: { id: string; email?: string; name?: string; avatarUrl?: string } }>; - pluginSyncDisconnect?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise; - pluginSyncGetAccount?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise<{ - account: { id: string; email?: string; name?: string; avatarUrl?: string } | null; - }>; - pluginSyncGetCapabilities?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise<{ - revisions: boolean; - conditionalWrites: boolean; - atomicReplacement: boolean; - maxObjectBytes?: number; - maxObjects?: number; - }>; - pluginSyncReadObject?(request: { - requestId?: string; - providerId: string; - key: string; - preferStream?: boolean; - deadlineMs?: number; - }): Promise<{ - found: boolean; - key: string; - data?: Uint8Array | null; - streamed?: boolean; - transferId?: string; - byteLength?: number; - revision?: string; - contentType?: string; - }>; - pluginSyncReadChunk?(request: { - requestId: string; - transferId: string; - maxBytes?: number; - }): Promise<{ chunk: Uint8Array; done: boolean }>; - pluginSyncWriteObject?(request: { - requestId?: string; - providerId: string; - key: string; - data: Uint8Array; - expectedRevision?: string | null; - preferStream?: boolean; - deadlineMs?: number; - }): Promise<{ created: boolean; revision?: string }>; - pluginSyncWriteBegin?(request: { - requestId?: string; - providerId: string; - key: string; - byteLength: number; - expectedRevision?: string | null; - deadlineMs?: number; - }): Promise<{ transferId: string; windowBytes: number }>; - pluginSyncWriteChunk?(request: { - requestId: string; - transferId: string; - sequence: number; - chunk: Uint8Array; - }): Promise<{ accepted: number }>; - pluginSyncWriteCommit?(request: { - requestId: string; - transferId: string; - }): Promise<{ created: boolean; revision?: string }>; - pluginSyncDeleteObject?(request: { - requestId?: string; - providerId: string; - key: string; - expectedRevision?: string; - deadlineMs?: number; - }): Promise<{ deleted: boolean }>; - pluginSyncPutSecret?(request: { - providerId: string; - key: string; - value: string; - }): Promise<{ kind: 'secret'; id: string; key: string; created?: boolean }>; - pluginSyncDeleteSecrets?(request: { - providerId: string; - keys?: string[]; - }): Promise<{ deleted: number }>; - pluginSyncRestoreSecrets?(request: { - providerId: string; - keys: string[]; - discard?: boolean; - }): Promise<{ restored: number; discarded?: number }>; - collectPluginSyncSidecars?(): Promise; - applyPluginSyncSidecars?(bundle: unknown): Promise<{ applied: boolean; count?: number; entries?: unknown }>; - pluginHostReady?(): boolean; - startPluginConnection?(request: NetcattyPluginConnectionStartRequest): Promise<{ sessionId: string; providerId: string; status: 'connecting' | 'connected'; diagnostics: ReadonlyArray }>; - writePluginConnection?(sessionId: string, data: Uint8Array): Promise; - controlPluginConnection?(sessionId: string, operation: 'resize' | 'signal' | 'reconnect' | 'close' | 'getStatus', payload?: Record): Promise; - detectPluginImporter?(request: { providerId: string; sample: Uint8Array; fileName?: string; mediaType?: string; deadlineMs?: number }): Promise; - selectPluginImporterFile?(): Promise<{ selectionToken: string; fileName: string; sample: Uint8Array } | null>; - releasePluginImporterFile?(selectionToken: string): Promise; - parsePluginImporterFile?(request: { requestId?: string; providerId: string; selectionToken: string; mediaType?: string; options?: import("@netcatty/plugin-contract").JsonValue; deadlineMs?: number }): Promise; - onPluginImporterProgress?(callback: (event: NetcattyPluginImporterProgressEvent) => void): () => void; - respondPluginAuthenticationChallenge?(response: { - requestId: string; - challengeRequestId: string; - challengeId: string; - response?: string | boolean | ReadonlyArray; - cancelled?: boolean; - }): Promise; - onPluginAuthenticationChallenge?(callback: (event: NetcattyPluginAuthenticationChallengeEvent) => void): () => void; - onPluginConnectionData?(callback: (event: { sessionId: string; data: Uint8Array }) => void): () => void; - onPluginConnectionClosed?(callback: (event: { sessionId: string; reason: string }) => void): () => void; - getPluginViewResource?(payload: import('@netcatty/plugin-contract').PluginViewResourceRequest): Promise; - openHostDrawnPluginView?(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; - closeHostDrawnPluginView?(instanceId: string): Promise; - sendHostDrawnPluginViewEvent?(instanceId: string, event: import('@netcatty/plugin-contract').HostDrawnViewEvent): Promise; - onHostDrawnPluginViewUpdate?(callback: (event: import('@netcatty/plugin-contract').HostDrawnViewMessage & { viewId: string }) => void): () => void; - onPluginContributionsChanged?(callback: (event: { reason: string; pluginId: string | null; revision: number }) => void): () => void; - onPluginViewClosed?(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; - getPluginScopeCatalog?(): Promise; - setPluginScopeCatalog?(catalog: NetcattyPluginScopeCatalog): Promise; - onPluginScopeCatalogChanged?(callback: (catalog: NetcattyPluginScopeCatalog) => void): () => void; - } - - interface NetcattyPluginContributionQuery { - locale?: string; - context?: Record; - menuContexts?: Partial>>; - scopeIds?: Partial>; - } - - interface NetcattyPluginSettingContribution { - group?: string; - id: string; - label: string; - description?: string; - placeholder?: string; - control: string; - scope: string; - scopeId: string | null; - value?: unknown; - secret?: boolean; - configured: boolean; - visible: boolean; - restartRequired?: boolean; - required?: boolean; - options?: ReadonlyArray<{ value: string; label: string; description?: string }>; - minimum?: number; - maximum?: number; - step?: number; - sortable?: boolean; - valueSchema?: unknown; - } - - type NetcattyPluginIconReference = - | { kind: 'theme'; name: string } - | { kind: 'package'; light: string; dark?: string }; - - interface NetcattyPluginContributionSnapshot { - locale: string; - plugins: ReadonlyArray<{ - id: string; - version: string; - displayName: string; - description: string; - commands: ReadonlyArray<{ id: string; title: string; category?: string; description?: string; icon?: NetcattyPluginIconReference; enabled: boolean }>; - keybindings: ReadonlyArray<{ command: string; key: string; mac?: string; linux?: string; windows?: string; args?: unknown; enabled: boolean }>; - menus: ReadonlyArray<{ - id: string; - command: string; - alt?: string; - location: string; - title: string; - visible: boolean; - enabled: boolean; - checked?: boolean; - order?: number; - group?: string; - shortcut?: string; - showKeybinding?: boolean; - icon?: NetcattyPluginIconReference; - }>; - settings: ReadonlyArray; - views: ReadonlyArray<{ id: string; title: string; location: string; icon?: NetcattyPluginIconReference; order?: number; visible: boolean }>; - }>; - } - - interface NetcattyPluginEnvironment { - locale: string; - theme: string; - reducedMotion: boolean; - highContrast: boolean; - themeTokens?: Record; - } - - type NetcattyTerminalProviderKind = - | 'terminal.completion' - | 'terminal.decoration' - | 'terminal.link' - | 'terminal.hover' - | 'terminal.matcher' - | 'terminal.semantic' - | 'terminal.prompt' - | 'terminal.background' - | 'terminal.theme'; - - interface NetcattyTerminalProviderContribution { - pluginId: string; - pluginVersion: string; - runtimeId?: string; - pluginDisplayName: string; - provider: { - id: string; - label: string; - description?: string; - kind: NetcattyTerminalProviderKind; - capabilities?: ReadonlyArray; - configurationSchema?: unknown; - }; - } - - interface NetcattyTerminalProviderQuery { - kind: NetcattyTerminalProviderKind; - locale?: string; - preferredProviderIds?: ReadonlyArray; - } - - interface NetcattyTerminalSessionSnapshot { - sessionId: string; - hostId?: string; - workspaceId?: string; - protocol: string; - status: 'connecting' | 'connected' | 'disconnected'; - cwd?: string; - title?: string; - shellType?: 'posix' | 'fish' | 'powershell' | 'cmd' | 'unknown'; - cols?: number; - rows?: number; - alternateScreen?: boolean; - } - - interface NetcattyTerminalSessionEvent { - type: - | 'snapshot' - | 'created' - | 'connected' - | 'reconnected' - | 'cwdChanged' - | 'titleChanged' - | 'resized' - | 'alternateScreenChanged' - | 'commandSubmitted' - | 'commandCompleted' - | 'disconnected' - | 'disposed'; - session: NetcattyTerminalSessionSnapshot; - exitCode?: number; - } - - interface NetcattyTerminalProviderRequest { - requestId: string; - kind: NetcattyTerminalProviderKind; - operation: string; - session: NetcattyTerminalSessionSnapshot; - payload?: unknown; - locale?: string; - preferredProviderIds?: ReadonlyArray; - deadlineMs?: number; - } - - type NetcattyTerminalProviderResult = { - pluginId: string; - pluginVersion: string; - runtimeId?: string; - providerId: string; - kind: NetcattyTerminalProviderKind; - requestId: string; - status: 'ok'; - result: unknown; - } | { - pluginId: string; - pluginVersion: string; - runtimeId?: string; - providerId: string; - kind: NetcattyTerminalProviderKind; - requestId: string; - status: 'cancelled'; - } | { - pluginId: string; - pluginVersion: string; - providerId: string; - kind: NetcattyTerminalProviderKind; - requestId: string; - status: 'failed'; - error: { code: number; message: string; data?: unknown }; - }; - - type NetcattyPluginViewOpenRequest = import('@netcatty/plugin-contract').HostDrawnViewOpenRequest; - - interface NetcattyPluginViewClosedEvent { - instanceId: string; - pluginId: string; - viewId: string; - reason: string; - } - - type NetcattyPluginSettingScopeKind = 'workspace' | 'host' | 'session' | 'device'; - - type NetcattyPluginScopeCatalog = Record< - NetcattyPluginSettingScopeKind, - ReadonlyArray<{ id: string; label: string }> - >; - interface Window { netcatty?: NetcattyBridge; } diff --git a/index.css b/index.css index ba491e89f..652dfc50c 100644 --- a/index.css +++ b/index.css @@ -1,6 +1,5 @@ @import "tailwindcss"; @import "./components/settings/tabs/plugin-marketplace.css"; -@import "@mdxeditor/editor/style.css"; /* Bundled icon-only fallback so terminals show Nerd Font glyphs (powerline, devicons, etc.) regardless of which base font the user picks. The font is @@ -105,30 +104,8 @@ --font-mono: "JetBrains Mono", monospace; /* Animations */ - --animate-accordion-down: accordion-down 0.2s ease-out; - --animate-accordion-up: accordion-up 0.2s ease-out; --animate-fade-in: fade-in 0.2s ease-out; - @keyframes accordion-down { - from { - height: 0; - } - - to { - height: var(--radix-collapsible-content-height); - } - } - - @keyframes accordion-up { - from { - height: var(--radix-collapsible-content-height); - } - - to { - height: 0; - } - } - @keyframes fade-in { from { opacity: 0; @@ -669,12 +646,6 @@ html[data-theme-transition] *::after { } } -.glass-panel { - background: hsl(var(--secondary) / 0.95); - border: 1px solid hsl(var(--border) / 0.8); - box-shadow: 0 14px 40px hsl(var(--foreground) / 0.12); -} - .soft-card { background: hsl(var(--card)); border: 1px solid hsl(var(--border) / 0.8); @@ -718,24 +689,6 @@ html[data-theme-transition] *::after { animation: coding-cli-icon-pulse 1.6s ease-in-out infinite; } -.card-highlight { - position: relative; - overflow: hidden; -} - -.card-highlight::before { - content: ""; - position: absolute; - inset: -40%; - background: radial-gradient(500px circle at 20% 20%, hsl(var(--primary) / 0.18), transparent 55%); - opacity: 0; - transition: opacity 180ms ease; -} - -.card-highlight:hover::before { - opacity: 1; -} - .elevate { transition: transform 140ms ease, border-color 140ms ease; } @@ -749,55 +702,6 @@ html[data-theme-transition] *::after { color: hsl(var(--foreground)); } -/* Port Forwarding Traffic Animation */ -@keyframes traffic-flow { - 0% { - stroke-dashoffset: 24; - } - - 100% { - stroke-dashoffset: 0; - } -} - -@keyframes traffic-flow-reverse { - 0% { - stroke-dashoffset: 0; - } - - 100% { - stroke-dashoffset: 24; - } -} - -@keyframes pulse-glow { - - 0%, - 100% { - opacity: 0.6; - } - - 50% { - opacity: 1; - } -} - - - -.traffic-line { - stroke-dasharray: 8 4; - animation: traffic-flow 0.8s linear infinite; -} - -.traffic-line-reverse { - stroke-dasharray: 8 4; - animation: traffic-flow-reverse 0.8s linear infinite; -} - -.traffic-glow { - animation: pulse-glow 1.5s ease-in-out infinite; -} - /* Custom titlebar drag regions for Electron */ .app-drag { -webkit-app-region: drag; @@ -873,15 +777,6 @@ html[data-theme-transition] *::after { color: var(--top-tabs-muted, hsl(var(--muted-foreground))); } -.no-scrollbar { - scrollbar-width: none; - -ms-overflow-style: none; -} - -.no-scrollbar::-webkit-scrollbar { - display: none; -} - .workspace-pane { outline: none; overflow: visible; @@ -1014,1164 +909,6 @@ html[data-theme-transition] *::after { padding: 3px !important; } -.netcatty-mdx-editor { - container-type: inline-size; - /* MDX linkDialog uses position:fixed anchors with coords adjusted whenever - * getFixedContainingBlock sees container-type. Browsers do not treat - * container-type alone as a fixed CB, so unadjusted viewport coords + those - * offsets park the preview toolbar over the notes tree. A zero transform - * makes the fixed CB real so the adjustment matches. */ - transform: translateZ(0); - min-width: 0; - --basePageBg: hsl(var(--background)); - --baseBase: hsl(var(--background)); - --baseBgSubtle: hsl(var(--secondary) / 0.45); - --baseBg: hsl(var(--secondary) / 0.7); - --baseBgHover: hsl(var(--secondary)); - --baseBgActive: hsl(var(--secondary)); - --baseLine: hsl(var(--border) / 0.45); - --baseBorder: hsl(var(--border) / 0.6); - --baseBorderHover: hsl(var(--border)); - --baseSolid: hsl(var(--muted-foreground)); - --baseText: hsl(var(--muted-foreground)); - --baseTextContrast: hsl(var(--foreground)); - --accentText: hsl(var(--primary)); - --accentSolid: hsl(var(--primary)); - --accentSolidHover: hsl(var(--primary) / 0.9); - background: transparent; - color: hsl(var(--foreground)); -} - -.netcatty-note-preview-empty { - min-height: calc(100vh - 15rem); - color: hsl(var(--muted-foreground)); - font-size: 14px; - line-height: 1.75; -} - -.netcatty-mdx-editor, -.netcatty-mdx-editor .mdxeditor-root-contenteditable { - min-height: 100%; - overflow: visible; -} - -.mdxeditor-popup-container.netcatty-mdx-editor { - position: fixed; - inset: 0; - z-index: 200000; - min-height: 0; - overflow: visible; - pointer-events: none; -} - -.mdxeditor-popup-container.netcatty-mdx-editor [data-radix-popper-content-wrapper], -.mdxeditor-popup-container.netcatty-mdx-editor [role="dialog"], -.mdxeditor-popup-container.netcatty-mdx-editor [class*="_tableColumnEditorPopoverContent_"] { - pointer-events: auto; -} - -/* - * Image edit / insert dialog (MDX ImageDialog via Radix). - * Match Netcatty popover / form tokens instead of stock MDX chrome. - */ -.netcatty-mdx-editor [class*="_dialogOverlay_"] { - background: hsl(var(--background) / 0.55) !important; - backdrop-filter: blur(2px); - opacity: 1 !important; - z-index: 200100 !important; -} - -.netcatty-mdx-editor [class*="_dialogContent_"], -.netcatty-mdx-editor [class*="_largeDialogContent_"] { - min-width: min(22rem, calc(100vw - 2rem)); - max-width: min(26rem, calc(100vw - 2rem)); - padding: 1rem 1.1rem 0.9rem !important; - gap: 0.65rem !important; - align-items: stretch !important; - flex-direction: column !important; - border: 1px solid hsl(var(--border) / 0.7) !important; - border-radius: 0.75rem !important; - background: hsl(var(--popover)) !important; - color: hsl(var(--popover-foreground)) !important; - box-shadow: - 0 0 0 1px hsl(var(--border) / 0.35), - 0 12px 40px hsl(0 0% 0% / 0.28) !important; - filter: none !important; - z-index: 200110 !important; - font-size: 13px !important; -} - -.netcatty-mdx-editor [class*="_dialogContent_"] > h2, -.netcatty-mdx-editor [class*="_largeDialogContent_"] > h2 { - margin: 0 0 0.15rem !important; - padding: 0 !important; - font-size: 0.9375rem !important; - font-weight: 600 !important; - letter-spacing: -0.01em; - color: hsl(var(--foreground)) !important; - line-height: 1.3 !important; -} - -.netcatty-mdx-editor form[class*="_multiFieldForm_"] { - padding: 0.15rem 0 0 !important; - gap: 0.75rem !important; -} - -.netcatty-mdx-editor form[class*="_multiFieldForm_"] [class*="_formField_"] { - gap: 0.35rem !important; -} - -.netcatty-mdx-editor form[class*="_multiFieldForm_"] [class*="_formField_"] > label { - font-size: 11px !important; - font-weight: 500 !important; - letter-spacing: 0.01em; - color: hsl(var(--muted-foreground)) !important; - line-height: 1.3 !important; -} - -.netcatty-mdx-editor [class*="_textInput_"], -.netcatty-mdx-editor [class*="_downshiftInput_"], -.netcatty-mdx-editor [class*="_dialogInput_"] { - width: 100% !important; - min-height: 2.1rem !important; - box-sizing: border-box !important; - padding: 0.4rem 0.65rem !important; - border-radius: 0.5rem !important; - border: 1px solid hsl(var(--border) / 0.75) !important; - background: hsl(var(--background)) !important; - color: hsl(var(--foreground)) !important; - font-size: 12.5px !important; - line-height: 1.35 !important; - box-shadow: none !important; - transition: border-color 120ms ease, box-shadow 120ms ease; -} - -.netcatty-mdx-editor [class*="_textInput_"]:focus, -.netcatty-mdx-editor [class*="_downshiftInput_"]:focus, -.netcatty-mdx-editor [class*="_dialogInput_"]:focus, -.netcatty-mdx-editor [class*="_downshiftInputWrapper_"]:focus-within { - outline: none !important; - border-color: hsl(var(--primary) / 0.65) !important; - box-shadow: 0 0 0 3px hsl(var(--primary) / 0.18) !important; -} - -.netcatty-mdx-editor [class*="_downshiftInputWrapper_"] { - width: 100% !important; - border-radius: 0.5rem !important; - border: 1px solid hsl(var(--border) / 0.75) !important; - background: hsl(var(--background)) !important; - overflow: hidden; -} - -.netcatty-mdx-editor [class*="_downshiftInputWrapper_"] [class*="_downshiftInput_"] { - border: 0 !important; - box-shadow: none !important; - border-radius: 0 !important; -} - -.netcatty-mdx-editor [class*="_downshiftInputWrapper_"]:focus-within { - border-color: hsl(var(--primary) / 0.65) !important; - box-shadow: 0 0 0 3px hsl(var(--primary) / 0.18) !important; -} - -.netcatty-mdx-editor [class*="_imageDimensionsContainer_"] { - display: grid !important; - grid-template-columns: 1fr 1fr; - gap: 0.65rem !important; -} - -.netcatty-mdx-editor [class*="_imageDimensionsContainer_"] [class*="_formField_"] { - min-width: 0; -} - -/* Action row at the bottom of the form */ -.netcatty-mdx-editor form[class*="_multiFieldForm_"] > div:last-child { - display: flex !important; - justify-content: flex-end !important; - align-items: center !important; - gap: 0.5rem !important; - margin-top: 0.35rem !important; - padding-top: 0.75rem !important; - border-top: 1px solid hsl(var(--border) / 0.55); -} - -.netcatty-mdx-editor [class*="_primaryButton_"], -.netcatty-mdx-editor [class*="_secondaryButton_"] { - display: inline-flex !important; - align-items: center !important; - justify-content: center !important; - min-height: 2rem !important; - padding: 0.35rem 0.85rem !important; - border-radius: 0.5rem !important; - font-size: 12px !important; - font-weight: 550 !important; - line-height: 1.2 !important; - cursor: pointer !important; - transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease, opacity 120ms ease; -} - -.netcatty-mdx-editor [class*="_primaryButton_"] { - border: 1px solid hsl(var(--primary) / 0.35) !important; - background: hsl(var(--primary)) !important; - color: hsl(var(--primary-foreground)) !important; -} - -.netcatty-mdx-editor [class*="_primaryButton_"]:hover { - background: hsl(var(--primary) / 0.9) !important; -} - -.netcatty-mdx-editor [class*="_secondaryButton_"] { - border: 1px solid hsl(var(--border) / 0.8) !important; - background: hsl(var(--secondary) / 0.55) !important; - color: hsl(var(--foreground)) !important; -} - -.netcatty-mdx-editor [class*="_secondaryButton_"]:hover { - background: hsl(var(--secondary)) !important; -} - -/* Hide empty "Upload an image" file field chrome when handler is null (hidden input only). */ -.netcatty-mdx-editor form[class*="_multiFieldForm_"] input[type="file"] { - font-size: 12px; - color: hsl(var(--muted-foreground)); -} - -.netcatty-mdx-content { - min-height: calc(100vh - 15rem); - padding: 0; - color: hsl(var(--foreground) / 0.9); - /* Note body follows the UI font (Settings > Appearance > Interface Font); - the note font tool only controls code block / inline code fonts. */ - font-family: var(--font-sans); - font-size: var(--note-font-size, 15px); - line-height: 1.75; - outline: none; -} - -.netcatty-mdx-content:focus { - outline: none; -} - -.netcatty-mdx-content p { - margin: 0.55rem 0; -} - -.netcatty-mdx-content[contenteditable="true"] > p:first-child { - min-height: 1.85em; -} - -.netcatty-mdx-editor .mdxeditor-root-contenteditable > .netcatty-mdx-content:not([contenteditable]) { - top: 0; - padding: 0 !important; - color: hsl(var(--muted-foreground)); - line-height: 1.75; -} - -.netcatty-mdx-editor .mdxeditor-root-contenteditable > .netcatty-mdx-content:not([contenteditable]) p { - margin: 0; -} - -.netcatty-mdx-content h1, -.netcatty-mdx-content h2, -.netcatty-mdx-content h3 { - color: hsl(var(--foreground)); - font-weight: 650; - letter-spacing: 0; -} - -.netcatty-mdx-content h1 { - margin: 1.1rem 0 0.7rem; - font-size: 1.7rem; - line-height: 1.2; -} - -.netcatty-mdx-content h2 { - margin: 1rem 0 0.6rem; - font-size: 1.3rem; - line-height: 1.25; -} - -.netcatty-mdx-content h3 { - margin: 0.85rem 0 0.5rem; - font-size: 1.05rem; - line-height: 1.35; -} - -.netcatty-mdx-content ul, -.netcatty-mdx-content ol { - margin: 0.55rem 0; - padding-left: 1.35rem; -} - -.netcatty-mdx-content ul { - list-style-type: disc; -} - -.netcatty-mdx-content ul ul { - list-style-type: circle; -} - -.netcatty-mdx-content ul ul ul { - list-style-type: square; -} - -.netcatty-mdx-content ol { - list-style-type: decimal; -} - -.netcatty-mdx-content ol ol { - list-style-type: lower-alpha; -} - -.netcatty-mdx-content ol ol ol { - list-style-type: lower-roman; -} - -.netcatty-mdx-content li { - margin: 0.25rem 0; -} - -/* - * GFM task lists (Lexical CheckListPlugin): default MDX styles pin the checkbox - * at top:0, which sits high against our 1.75 line-height. Re-center the box with - * the first text line, keep a solid hit target, and drop the hanging negative - * margin so label text lines up cleanly with the control. - */ -.netcatty-mdx-content ul:has(> li[role="checkbox"]), -.netcatty-mdx-content ul:has(> li[aria-checked]), -.netcatty-mdx-content ul:has(> li[class*="_listItemChecked_"]), -.netcatty-mdx-content ul:has(> li[class*="_listItemUnchecked_"]) { - list-style: none !important; - list-style-type: none !important; - padding-left: 0.15rem; - margin-left: 0; -} - -.netcatty-mdx-content li[role="checkbox"], -.netcatty-mdx-content li[aria-checked] { - position: relative; - list-style: none; - margin-left: 0 !important; - margin-inline-start: 0 !important; - padding-left: 1.75rem !important; - padding-right: 0 !important; - min-height: 1.75em; - line-height: 1.75; - cursor: default; -} - -.netcatty-mdx-content li[role="checkbox"]::before, -.netcatty-mdx-content li[aria-checked]::before { - content: "" !important; - box-sizing: border-box !important; - position: absolute !important; - /* Vertically center 1rem box in a 1.75em line: (1.75em - 1rem) / 2 */ - top: calc((1.75em - 1rem) / 2) !important; - left: 0 !important; - width: 1rem !important; - height: 1rem !important; - margin: 0 !important; - cursor: pointer !important; - pointer-events: auto !important; - display: block !important; - background-size: cover !important; - border-radius: 3px !important; -} - -.netcatty-mdx-content li[aria-checked="false"]::before, -.netcatty-mdx-content li[role="checkbox"][aria-checked="false"]::before { - border: 1px solid hsl(var(--border)) !important; - background-color: transparent !important; -} - -.netcatty-mdx-content li[aria-checked="true"]::before { - border: 1px solid hsl(var(--primary) / 0.7) !important; - background-color: hsl(var(--primary)) !important; -} - -/* Checkmark glyph (MDX draws this with ::after) */ -.netcatty-mdx-content li[aria-checked="true"]::after { - top: calc((1.75em - 1rem) / 2 + 0.1rem) !important; - left: 0.35rem !important; - width: 0.28rem !important; - height: 0.55rem !important; - cursor: pointer !important; -} - -/* Preview is readOnly — still show pointer on the control so it feels clickable. */ -.netcatty-mdx-editor--preview .netcatty-mdx-content li[role="checkbox"], -.netcatty-mdx-editor--preview .netcatty-mdx-content li[aria-checked] { - cursor: default; -} - -.netcatty-mdx-editor--preview .netcatty-mdx-content li[role="checkbox"]::before, -.netcatty-mdx-editor--preview .netcatty-mdx-content li[aria-checked]::before, -.netcatty-mdx-editor--preview .netcatty-mdx-content li[aria-checked="true"]::after { - cursor: pointer !important; -} - -.netcatty-mdx-content code { - border-radius: 4px; - background: hsl(var(--secondary) / 0.8); - padding: 0.12rem 0.3rem; - font-family: var(--note-font-family, var(--font-mono)); - font-size: var(--note-code-font-size, 0.88em); -} - -.netcatty-mdx-content pre { - border: 0; - border-radius: 0; - background: transparent; - padding: 0; -} - -.netcatty-mdx-editor [class*="_codeMirrorWrapper_"] { - position: relative !important; - min-height: 2rem !important; - margin: 0.35rem 0 0.65rem; - border: 0 !important; - border-radius: 0; - background: transparent !important; - padding: 0 !important; - overflow: visible !important; -} - -.netcatty-note-code-copy { - position: absolute !important; - top: 0.2rem !important; - right: 0.15rem !important; - z-index: 40 !important; - display: inline-flex !important; - align-items: center !important; - justify-content: center !important; - width: 1.45rem !important; - height: 1.45rem !important; - padding: 0 !important; - border: 0 !important; - border-radius: 4px !important; - background: transparent !important; - color: hsl(var(--muted-foreground)) !important; - box-shadow: none !important; - opacity: 0; - cursor: pointer !important; - transition: opacity 0.15s, color 0.15s, background-color 0.15s; -} - -.netcatty-mdx-editor [class*="_codeMirrorWrapper_"]:hover .netcatty-note-code-copy, -.netcatty-mdx-editor .cm-editor:hover ~ .netcatty-note-code-copy, -.netcatty-mdx-editor pre:hover .netcatty-note-code-copy, -.netcatty-mdx-content pre:hover .netcatty-note-code-copy, -.netcatty-mdx-editor--preview .netcatty-note-code-copy, -.netcatty-note-code-copy[data-copied="true"], -.netcatty-note-code-copy:focus-visible { - opacity: 0.85 !important; - pointer-events: auto !important; -} - -.netcatty-note-code-copy:hover, -.netcatty-mdx-editor--preview .netcatty-note-code-copy:hover { - opacity: 1 !important; - background: hsl(var(--secondary)) !important; - color: hsl(var(--foreground)) !important; -} - -.netcatty-note-code-copy[data-copied="true"] { - color: hsl(var(--foreground)) !important; -} - -.netcatty-mdx-editor .cm-editor, -.netcatty-mdx-editor .cm-content, -.netcatty-mdx-editor [class*="_codeMirrorWrapper_"], -.netcatty-mdx-editor pre, -.netcatty-mdx-editor code, -.netcatty-mdx-editor [class*="_code_"], -.netcatty-mdx-editor [class*="code_"], -.netcatty-mdx-editor kbd, -.netcatty-mdx-editor samp, -.netcatty-mdx-content pre, -.netcatty-mdx-content code, -.netcatty-mdx-content [class*="_code_"], -.netcatty-mdx-content [class*="code_"], -.netcatty-mdx-content kbd, -.netcatty-mdx-content samp, -.netcatty-source-editor, -.netcatty-source-editor textarea { - font-family: var(--note-font-family, var(--font-mono)) !important; -} - -.netcatty-mdx-editor .cm-editor, -.netcatty-mdx-editor .cm-content, -.netcatty-mdx-editor pre, -.netcatty-mdx-content pre, -.netcatty-source-editor textarea { - font-size: var(--note-code-font-size, 13px) !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorWrapper_"]:has([data-language="latex"]), -.netcatty-mdx-editor [class*="_codeMirrorWrapper_"]:has([data-language="tex"]) { - border: 0 !important; - background: transparent !important; - padding: 0 !important; -} - -.netcatty-math-formula-preview { - display: flex; - align-items: center; - justify-content: safe center; - padding: 0.55rem 0; - margin: 0.4rem 0; - border-radius: 0; - background: transparent; - border: 0; - font-size: 1.45em; - color: hsl(var(--foreground)); - overflow-x: auto; - max-width: 100%; - user-select: text; - min-height: 2.25rem; -} - -.netcatty-math-formula-preview .katex-display { - flex: 0 0 auto; - margin: 0; -} - -.netcatty-math-formula-preview .katex { - font-size: 1em; - color: inherit; -} - -.netcatty-math-formula-preview .katex-mathml math { - flex: 0 0 auto; -} - -.netcatty-math-reading-mode .cm-editor { - display: none !important; -} - -.netcatty-math-reading-mode { - background: transparent !important; - border: none !important; - padding: 0 !important; - margin: 0.4rem 0 !important; -} - -.netcatty-math-reading-mode .netcatty-math-formula-preview { - margin: 0; - background: transparent; -} - -.netcatty-math-reading-mode > .netcatty-note-code-copy { - display: none !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"] { - display: flex; - flex-direction: column; - align-items: stretch; - gap: 0; - margin: 0.25rem 0 0.55rem; - border-radius: 0; - background: transparent !important; - overflow: visible !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) .netcatty-mdx-content p:has(+ [class*="_codeMirrorWrapper_"]) { - margin-bottom: 0.2rem; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"] .cm-editor { - min-height: 2rem !important; - background: transparent !important; - border-radius: 0 !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"] .cm-content { - padding: 0 !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"] .cm-scroller { - padding-right: 4.8rem !important; - min-height: 2.2rem !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorToolbar_"] { - position: absolute !important; - top: 0.35rem !important; - right: 0.35rem !important; - z-index: 30 !important; - display: inline-flex !important; - align-items: center !important; - justify-content: flex-end; - gap: 0.25rem !important; - padding: 0.2rem 0.25rem !important; - margin: 0 !important; - width: auto !important; - border-radius: 6px !important; - background: hsl(var(--background) / 0.94) !important; - border: 1px solid hsl(var(--border) / 0.65) !important; - backdrop-filter: blur(8px) !important; - box-shadow: 0 2px 8px rgb(0 0 0 / 0.18) !important; - opacity: 0 !important; - pointer-events: none !important; - transition: opacity 0.15s ease !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"]:hover [class*="_codeMirrorToolbar_"], -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"]:focus-within [class*="_codeMirrorToolbar_"], -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorToolbar_"]:has([data-state="open"]) { - opacity: 1 !important; - pointer-events: auto !important; -} - -/* Language selector trigger in toolbar */ -/* Align the TooltipWrap span wrapper so the language select sits level with action buttons */ -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_tooltipTrigger_"] { - display: inline-flex !important; - align-items: center !important; - align-self: center !important; - line-height: 1 !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_toolbarCodeBlockLanguageSelectTrigger_"], -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectTrigger_"] { - display: inline-flex !important; - align-items: center !important; - justify-content: flex-start !important; - height: 1.45rem !important; - min-height: 1.45rem !important; - width: auto !important; - min-width: 0 !important; - max-width: none !important; - padding: 0 0.45rem !important; - margin: 0 !important; - gap: 0.25rem !important; - font-size: 11px !important; - font-weight: 500 !important; - line-height: 1 !important; - white-space: nowrap !important; - border: 0 !important; - border-radius: 4px !important; - background: hsl(var(--muted) / 0.7) !important; - color: hsl(var(--foreground)) !important; - box-shadow: none !important; - cursor: pointer !important; - transition: background-color 0.15s ease, color 0.15s ease !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_toolbarCodeBlockLanguageSelectTrigger_"]:hover, -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectTrigger_"]:hover { - background: hsl(var(--secondary)) !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectTrigger_"] [data-radix-select-value], -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectTrigger_"] > span:first-child { - flex: 0 0 auto; - overflow: visible; - max-width: none; - font-size: 11px !important; - line-height: 1 !important; - white-space: nowrap; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectDropdownArrow_"] svg, -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_toolbarCodeBlockLanguageSelectTrigger_"] svg, -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectTrigger_"] svg { - width: 10px !important; - height: 10px !important; - flex-shrink: 0; - opacity: 0.75; -} - -/* Base style for all action buttons (Delete & Copy) in toolbar */ -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] button:not([class*="_selectTrigger_"]):not([class*="_toolbarCodeBlockLanguageSelectTrigger_"]) { - display: inline-flex !important; - align-items: center !important; - justify-content: center !important; - height: 1.4rem !important; - min-height: 1.4rem !important; - max-height: 1.4rem !important; - width: 1.4rem !important; - min-width: 1.4rem !important; - max-width: 1.4rem !important; - padding: 0 !important; - margin: 0 !important; - border: 0 !important; - border-radius: 4px !important; - background: transparent !important; - color: hsl(var(--muted-foreground)) !important; - box-shadow: none !important; - cursor: pointer !important; - transition: background-color 0.15s ease, color 0.15s ease !important; -} - -/* Delete Button specific hover */ -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] button:not([class*="_selectTrigger_"]):not([class*="_toolbarCodeBlockLanguageSelectTrigger_"]):not(.netcatty-note-code-copy):hover { - background: hsl(var(--destructive) / 0.15) !important; - color: hsl(var(--destructive)) !important; -} - -/* Copy Button inside toolbar */ -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] .netcatty-note-code-copy { - position: static !important; - opacity: 1 !important; - pointer-events: auto !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] .netcatty-note-code-copy:hover { - background: hsl(160 84% 39% / 0.15) !important; - color: hsl(160 84% 39%) !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] button svg { - width: 10px !important; - height: 10px !important; -} - -.netcatty-mdx-editor:not(.netcatty-mdx-editor--preview) [class*="_codeMirrorWrapper_"]:has([class*="_codeMirrorToolbar_"]) > .netcatty-note-code-copy { - display: none !important; -} - -.netcatty-mdx-editor--preview [class*="_codeMirrorToolbar_"] { - display: none !important; -} - -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_toolbarCodeBlockLanguageSelectTrigger_"] span { - font-size: inherit !important; - line-height: inherit !important; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"], -.netcatty-mdx-editor [class*="_codeMirrorToolbar_"] [class*="_selectContainer_"] { - width: auto !important; - min-width: max-content !important; - max-width: none !important; - max-height: 12rem; - overflow-x: visible !important; - overflow-y: auto; - font-size: 11px !important; - line-height: 1.25 !important; - margin: 0 !important; - padding: 0.15rem 0 !important; - border: 1px solid hsl(var(--border) / 0.7) !important; - border-radius: 6px !important; - background: hsl(var(--popover)) !important; - box-shadow: 0 8px 20px rgb(0 0 0 / 0.22) !important; - filter: none !important; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"] [data-radix-select-viewport] { - width: auto !important; - min-width: max-content !important; - max-width: none !important; - padding: 0 !important; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"] [class*="_selectItem_"] { - font-size: 11px !important; - line-height: 1.25 !important; - padding: 0.28rem 0.45rem !important; - min-height: 0 !important; - white-space: nowrap; - overflow: visible; - text-overflow: clip; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"] [class*="_selectItem_"] [data-radix-select-item-text] { - font-size: 11px !important; - line-height: 1.25 !important; - white-space: nowrap; - overflow: visible; - text-overflow: clip; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"] { - width: auto !important; - min-width: max-content !important; - max-width: none !important; - font-size: 11px !important; - max-height: 12rem; - overflow-y: auto; -} - -.netcatty-mdx-editor [class*="_toolbarCodeBlockLanguageSelectContent_"] [class*="_selectItem_"] { - font-size: 11px !important; - padding: 0.28rem 0.45rem !important; - min-height: 0 !important; -} - -.netcatty-mdx-editor .cm-editor { - --note-code-token-muted: hsl(var(--muted-foreground) / 0.9); - --note-code-token-keyword: color-mix(in oklab, hsl(var(--primary)) 82%, hsl(var(--foreground))); - --note-code-token-name: color-mix(in oklab, hsl(var(--primary)) 50%, hsl(var(--foreground))); - --note-code-token-value: color-mix(in oklab, hsl(var(--primary)) 38%, hsl(var(--foreground))); - --note-code-token-string: color-mix(in oklab, hsl(var(--primary)) 24%, hsl(var(--foreground))); - overflow: hidden; - border: 0 !important; - border-radius: 0; - background: transparent !important; - color: hsl(var(--foreground) / 0.9) !important; - font-family: var(--font-mono); - font-size: 13px !important; -} - -.netcatty-mdx-editor .cm-scroller { - background: transparent !important; - color: hsl(var(--foreground) / 0.9) !important; - font-family: var(--font-mono); -} - -.netcatty-mdx-editor .cm-content { - background: transparent !important; - color: hsl(var(--foreground) / 0.9) !important; - font-family: var(--font-mono); - padding: 0 !important; -} - -.netcatty-mdx-editor .cm-line { - color: inherit !important; - line-height: 1.45 !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-muted { - color: var(--note-code-token-muted) !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-keyword { - color: var(--note-code-token-keyword) !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-name, -.netcatty-mdx-editor .cm-content .netcatty-code-token-variable, -.netcatty-mdx-editor .cm-content .netcatty-code-token-type, -.netcatty-mdx-editor .cm-content .netcatty-code-token-property { - color: var(--note-code-token-name) !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-value { - color: var(--note-code-token-value) !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-string { - color: var(--note-code-token-string) !important; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-link { - color: hsl(var(--primary)) !important; - text-decoration: underline; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-heading, -.netcatty-mdx-editor .cm-content .netcatty-code-token-strong { - font-weight: 600; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-emphasis { - font-style: italic; -} - -.netcatty-mdx-editor .cm-content .netcatty-code-token-invalid { - color: hsl(var(--destructive)) !important; -} - -.netcatty-mdx-editor .cm-gutters { - border-right: 1px solid hsl(var(--border) / 0.35) !important; - background: transparent !important; - color: hsl(var(--muted-foreground) / 0.75) !important; - font-family: var(--font-mono); - font-size: 13px !important; - line-height: 1.45 !important; - padding: 0 !important; -} - -.netcatty-mdx-editor .cm-gutterElement { - font-size: 13px !important; - line-height: 1.45 !important; -} - -.netcatty-mdx-editor .cm-lineNumbers .cm-gutterElement { - padding: 0 0.45rem 0 0.55rem !important; -} - -.netcatty-mdx-editor .cm-activeLine, -.netcatty-mdx-editor .cm-activeLineGutter { - background: transparent !important; -} - -.netcatty-mdx-editor .cm-editor:focus-within .cm-activeLine, -.netcatty-mdx-editor .cm-editor:focus-within .cm-activeLineGutter { - background: hsl(var(--primary) / 0.08) !important; -} - -.netcatty-mdx-editor .cm-selectionBackground { - background: hsl(var(--primary) / 0.22) !important; -} - -.netcatty-mdx-editor .cm-cursor { - border-left-color: hsl(var(--foreground)) !important; -} - -.netcatty-mdx-content blockquote { - margin: 0.7rem 0; - border-left: 2px solid hsl(var(--border)); - padding-left: 0.85rem; - color: hsl(var(--muted-foreground)); -} - -.netcatty-mdx-content hr { - margin: 1.35rem 0; - border-color: hsl(var(--border) / 0.45); -} - -.netcatty-mdx-content table:not([class*="_tableEditor_"]) { - margin: 0.9rem 0; - width: max-content; - max-width: 100%; - border-collapse: collapse; - border: 1px solid hsl(var(--border)); -} - -.netcatty-mdx-content table:not([class*="_tableEditor_"]) th, -.netcatty-mdx-content table:not([class*="_tableEditor_"]) td { - border: 1px solid hsl(var(--border) / 0.45); - padding: 0.42rem 0.65rem; - text-align: left; - vertical-align: top; -} - -.netcatty-mdx-content table:not([class*="_tableEditor_"]) th { - font-weight: 650; -} - -/* - * Note images: source keeps width/height (HTML attrs for MDX / aspect ratio). - * Display: max-width caps screenshots to the pane; height:auto keeps ratio - * when width is known or unconstrained. Do NOT force height:auto on height-only - * images (e.g. ) — that would ignore the presentational size. - * Do NOT force width:auto — that would ignore a 128px logo preference. - */ -.netcatty-mdx-content img, -.netcatty-mdx-editor [class*="_imageWrapper_"] img, -.netcatty-mdx-editor img { - max-width: 100% !important; - object-fit: contain; - display: block; - margin-left: auto; - margin-right: auto; - border-radius: 0.375rem; -} - -/* Width-only (or no size): keep aspect ratio via height:auto. */ -.netcatty-mdx-content img:not([height]), -.netcatty-mdx-content img[width], -.netcatty-mdx-editor [class*="_imageWrapper_"] img:not([height]), -.netcatty-mdx-editor [class*="_imageWrapper_"] img[width], -.netcatty-mdx-editor img:not([height]), -.netcatty-mdx-editor img[width] { - height: auto !important; -} - -/* Height-only: keep aspect ratio via width:auto (do not force height:auto above). */ -.netcatty-mdx-content img[height]:not([width]), -.netcatty-mdx-editor [class*="_imageWrapper_"] img[height]:not([width]), -.netcatty-mdx-editor img[height]:not([width]) { - width: auto !important; - max-width: 100% !important; -} - -/* Cap MDX image chrome when ImageNode bakes large pixel widths into styles. */ -.netcatty-mdx-editor [class*="_imageWrapper_"], -.netcatty-mdx-editor [class*="_imageContainer_"], -.netcatty-mdx-editor [class*="_imageControlWrapper_"] { - max-width: 100% !important; - height: auto !important; - overflow: visible !important; - box-sizing: border-box; -} - -/* - * Small icon rows (README distro wall, width≤96): flow horizontally. - * JS sets data-note-img-size="sm" (see annotateNoteImageSizes) so we avoid a - * combinatorial :has(img[width="N"]) matrix that thrashes style recalc on - * badge walls. Large screenshots stay block + full-width capped above. - */ -.netcatty-mdx-content img[data-note-img-size="sm"], -.netcatty-mdx-editor img[data-note-img-size="sm"] { - display: inline-block !important; - margin: 0.35rem 0.4rem !important; - vertical-align: middle; - border-radius: 0.25rem; -} - -.netcatty-mdx-editor [data-editor-block-type="image"][data-note-img-size="sm"], -.netcatty-mdx-editor [class*="_imageWrapper_"][data-note-img-size="sm"] { - display: inline-block !important; - vertical-align: middle; - margin: 0.2rem 0.15rem !important; - max-width: none !important; - width: auto !important; -} - -/* Lone image paragraph marked sm by JS — keep it in the icon row. */ -.netcatty-mdx-content p[data-note-img-size="sm"], -.netcatty-mdx-editor p[data-note-img-size="sm"] { - display: inline !important; - margin: 0 !important; -} - -/* Image chrome stays out of the image until the image is hovered or focused. */ -.netcatty-mdx-editor [data-editor-block-type="image"] [class*="_editImageToolbar_"], -.netcatty-mdx-editor [class*="_imageWrapper_"] [class*="_editImageToolbar_"] { - top: 0.375rem; - right: 0.375rem; - gap: 0.0625rem; - padding: 0.125rem; - opacity: 0; - pointer-events: none; - border: 1px solid hsl(var(--border) / 0.8); - border-radius: 0.375rem; - background: hsl(var(--background) / 0.96); - box-shadow: 0 2px 8px hsl(var(--foreground) / 0.12); - transition: opacity 120ms ease; -} - -.netcatty-mdx-editor [data-editor-block-type="image"] [class*="_editImageToolbar_"] button, -.netcatty-mdx-editor [class*="_imageWrapper_"] [class*="_editImageToolbar_"] button { - display: inline-flex; - width: 1.375rem; - height: 1.375rem; - align-items: center; - justify-content: center; - border-radius: 0.25rem; -} - -.netcatty-mdx-editor [data-editor-block-type="image"] [class*="_editImageToolbar_"] button svg, -.netcatty-mdx-editor [class*="_imageWrapper_"] [class*="_editImageToolbar_"] button svg { - width: 0.875rem; - height: 0.875rem; -} - -.netcatty-mdx-editor [data-editor-block-type="image"] [class*="_editImageToolbar_"] button:hover, -.netcatty-mdx-editor [class*="_imageWrapper_"] [class*="_editImageToolbar_"] button:hover { - background: hsl(var(--secondary) / 0.75); -} - -.netcatty-mdx-editor [data-editor-block-type="image"]:hover [class*="_editImageToolbar_"], -.netcatty-mdx-editor [data-editor-block-type="image"]:focus-within [class*="_editImageToolbar_"], -.netcatty-mdx-editor [class*="_imageWrapper_"]:hover [class*="_editImageToolbar_"], -.netcatty-mdx-editor [class*="_imageWrapper_"]:focus-within [class*="_editImageToolbar_"] { - opacity: 1; - pointer-events: auto; -} - -/* - * Preserve README-style center alignment from paste (MDX edit path). - * (
/ align=center / text-align:center). - */ -.netcatty-mdx-content [align="center"], -.netcatty-mdx-editor [align="center"], -.netcatty-mdx-content [style*="text-align:center"], -.netcatty-mdx-content [style*="text-align: center"], -.netcatty-mdx-editor [style*="text-align:center"], -.netcatty-mdx-editor [style*="text-align: center"] { - text-align: center !important; -} - -.netcatty-mdx-content [align="center"] img, -.netcatty-mdx-editor [align="center"] img, -.netcatty-mdx-content [align="center"] [class*="_imageWrapper_"], -.netcatty-mdx-editor [align="center"] [class*="_imageWrapper_"], -.netcatty-mdx-content [align="center"] [data-editor-block-type="image"], -.netcatty-mdx-editor [align="center"] [data-editor-block-type="image"] { - margin-left: auto !important; - margin-right: auto !important; -} - -/* Badge / shield images inside links: keep inline so rows stay horizontal. */ -.netcatty-mdx-content a img, -.netcatty-mdx-editor a img, -.netcatty-mdx-content a [class*="_imageWrapper_"], -.netcatty-mdx-editor a [class*="_imageWrapper_"], -.netcatty-mdx-content a [data-editor-block-type="image"], -.netcatty-mdx-editor a [data-editor-block-type="image"] { - display: inline-block !important; - margin: 0.25rem 0.35rem !important; - vertical-align: middle; - max-width: 100% !important; - height: auto !important; -} - -.netcatty-mdx-content a:has(img), -.netcatty-mdx-editor a:has(img), -.netcatty-mdx-content a:has([data-editor-block-type="image"]), -.netcatty-mdx-editor a:has([data-editor-block-type="image"]) { - display: inline-block !important; - text-decoration: none !important; - vertical-align: middle; - margin: 0.15rem 0.25rem; -} - -.netcatty-mdx-content a { - color: hsl(var(--primary)); - text-decoration: underline; - text-underline-offset: 0.18em; -} - -.netcatty-mdx-content a[data-netcatty-host-link="true"] { - display: inline-flex; - align-items: baseline; - gap: 0.28em; -} - -.netcatty-mdx-content a[data-netcatty-host-link="true"]::before { - content: ""; - display: inline-block; - width: 0.92em; - height: 0.92em; - flex: 0 0 auto; - background-color: currentColor; - transform: translateY(0.12em); - -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect width='16' height='10' x='4' y='5' rx='2'/%3E%3Cpath d='M12 15v4'/%3E%3Cpath d='M8 19h8'/%3E%3C/svg%3E") center / contain no-repeat; - mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect width='16' height='10' x='4' y='5' rx='2'/%3E%3Cpath d='M12 15v4'/%3E%3Cpath d='M8 19h8'/%3E%3C/svg%3E") center / contain no-repeat; -} - -.dark .netcatty-mdx-content table:not([class*="_tableEditor_"]) { - border-color: hsl(var(--foreground) / 0.32); -} - -.dark .netcatty-mdx-content table:not([class*="_tableEditor_"]) th, -.dark .netcatty-mdx-content table:not([class*="_tableEditor_"]) td { - border-color: hsl(var(--foreground) / 0.18); -} - -.netcatty-mdx-editor [class*="_tableColumnEditorTrigger_"], -.netcatty-mdx-editor [class*="_tableRowEditorTrigger_"], -.netcatty-mdx-editor [class*="_addRowButton_"], -.netcatty-mdx-editor [class*="_addColumnButton_"], -.netcatty-mdx-editor [class*="_tableColumnEditorToolbar_"] button { - cursor: pointer !important; -} - -.netcatty-mdx-editor [class*="_tableColumnEditorPopoverContent_"] { - z-index: 80; - background: hsl(var(--popover)); - color: hsl(var(--popover-foreground)); -} - -.netcatty-mdx-editor [data-radix-popper-content-wrapper] { - z-index: 90 !important; -} - -.netcatty-mdx-editor [class*="_tableEditor_"] > tbody > tr > td:not([class*="_toolCell_"]), -.netcatty-mdx-editor [class*="_tableEditor_"] > tbody > tr > th:not([class*="_toolCell_"]):not([data-tool-cell="true"]) { - border-color: hsl(var(--border)) !important; -} - -.dark .netcatty-mdx-editor [class*="_tableEditor_"] > tbody > tr > td:not([class*="_toolCell_"]), -.dark .netcatty-mdx-editor [class*="_tableEditor_"] > tbody > tr > th:not([class*="_toolCell_"]):not([data-tool-cell="true"]) { - border-color: hsl(var(--foreground) / 0.3) !important; -} - /* Terminal appearance runtime (--nc-term-* injected by useThemeRuntime) */ [data-terminal-appearance-root] { --terminal-sidepanel-bg: var(--nc-term-panel-bg, var(--background)); diff --git a/infrastructure/ai/agentKinds.ts b/infrastructure/ai/agentKinds.ts index 9f2e0f4a1..906a9d730 100644 --- a/infrastructure/ai/agentKinds.ts +++ b/infrastructure/ai/agentKinds.ts @@ -7,6 +7,3 @@ export const AGENT_KINDS = { } as const; export type AgentKind = (typeof AGENT_KINDS)[keyof typeof AGENT_KINDS]; - -export const SIDEBAR_AGENT_KIND: AgentKind = AGENT_KINDS.SIDEBAR; -export const GLOBAL_AGENT_KIND: AgentKind = AGENT_KINDS.GLOBAL; diff --git a/infrastructure/ai/harness/agentEventAdapter.ts b/infrastructure/ai/harness/agentEventAdapter.ts index 8824ad29e..64e6cc137 100644 --- a/infrastructure/ai/harness/agentEventAdapter.ts +++ b/infrastructure/ai/harness/agentEventAdapter.ts @@ -1,4 +1,4 @@ -import type { AgentEvent, AgentEventListener } from './types'; +import type { AgentEvent } from './types'; import { resolveStreamChunkToolCallId, SHELL_READINESS_UNKNOWN_CODE } from '../aiChatStreamingSupport'; let eventCounter = 0; @@ -315,9 +315,3 @@ export function mapCattyStreamChunkToAgentEvents( } export { isStepHandleNoticeMessage }; - -export function createHarnessEventSink( - listener: AgentEventListener, -): AgentEventListener { - return (event) => listener(event); -} diff --git a/components/ai/cattyHistoryReplay.test.ts b/infrastructure/ai/harness/cattyHistoryReplay.test.ts similarity index 97% rename from components/ai/cattyHistoryReplay.test.ts rename to infrastructure/ai/harness/cattyHistoryReplay.test.ts index d6e24680c..82f93ac54 100644 --- a/components/ai/cattyHistoryReplay.test.ts +++ b/infrastructure/ai/harness/cattyHistoryReplay.test.ts @@ -1,19 +1,19 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { buildExternalBridgeContextMessages } from "../../infrastructure/ai/harness/externalBridgeContext.ts"; -import { ToolOutputStore } from "../../infrastructure/ai/harness/toolOutputStore.ts"; +import { buildExternalBridgeContextMessages } from "./externalBridgeContext.ts"; +import { ToolOutputStore } from "./toolOutputStore.ts"; import { buildCattySdkMessages, createContinuationContext, -} from "../../infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts"; +} from "./turnDrivers/cattyMessageBuilder.ts"; -import type { ChatMessageAttachment, ToolCall, ToolResult } from "../../infrastructure/ai/types.ts"; +import type { ChatMessageAttachment, ToolCall, ToolResult } from "../types.ts"; import { buildHistoricalToolReplayMaps, buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent, } from "./cattyHistoryReplay.ts"; -import type { ChatMessage } from "../../infrastructure/ai/types.ts"; +import type { ChatMessage } from "../types.ts"; test("buildHistoricalUserReplayContent replaces historical image data with a placeholder", () => { const attachment: ChatMessageAttachment = { diff --git a/components/ai/cattyHistoryReplay.ts b/infrastructure/ai/harness/cattyHistoryReplay.ts similarity index 95% rename from components/ai/cattyHistoryReplay.ts rename to infrastructure/ai/harness/cattyHistoryReplay.ts index ce8512d96..7ee386267 100644 --- a/components/ai/cattyHistoryReplay.ts +++ b/infrastructure/ai/harness/cattyHistoryReplay.ts @@ -1,8 +1,8 @@ -import type { ChatMessage, ChatMessageAttachment, ToolCall, ToolResult } from "../../infrastructure/ai/types"; -import { isTerminalSelectionAttachment } from "../../application/state/terminalSelectionAttachment"; -import { formatVaultNoteReferences, isVaultNoteAttachment } from "../../application/state/vaultNoteAttachment"; -import { redactSecretsForModel } from "../../infrastructure/ai/harness/modelSecretRedaction"; -import { sliceHead, sliceTail } from "../../infrastructure/ai/textBoundaries"; +import type { ChatMessage, ChatMessageAttachment, ToolCall, ToolResult } from "../types"; +import { isTerminalSelectionAttachment } from "../../../application/state/terminalSelectionAttachment"; +import { formatVaultNoteReferences, isVaultNoteAttachment } from "../../../application/state/vaultNoteAttachment"; +import { redactSecretsForModel } from "./modelSecretRedaction"; +import { sliceHead, sliceTail } from "../textBoundaries"; const MAX_ATTACHMENT_PLACEHOLDER_DETAIL_CHARS = 120; const MAX_TOOL_COMMAND_CHARS = 220; diff --git a/infrastructure/ai/harness/contextManager.ts b/infrastructure/ai/harness/contextManager.ts index 6a9b737c4..3f1e8f04a 100644 --- a/infrastructure/ai/harness/contextManager.ts +++ b/infrastructure/ai/harness/contextManager.ts @@ -26,9 +26,7 @@ import type { CompactionTrace, ContextPrepareResult, ContextPrepareTrigger, - ExternalBridgeHistoryMessage, } from './types'; -import { buildExternalBridgeContextMessages } from './externalBridgeContext'; import { repairToolMessageIntegrity } from './toolMessageIntegrity'; import { pruneFirstModelMessage } from './compactionPruner'; @@ -319,12 +317,6 @@ export async function prepareTurnContext( return { messages: working, didAdjust: false }; } -export function buildExternalBridgeContext( - messages: ChatMessage[], -): ExternalBridgeHistoryMessage[] { - return buildExternalBridgeContextMessages(messages); -} - export function extractLatestUserGoal(messages: ModelMessage[] | ChatMessage[]): string | undefined { for (let i = messages.length - 1; i >= 0; i -= 1) { const message = messages[i]; diff --git a/infrastructure/ai/harness/externalBridgeContext.ts b/infrastructure/ai/harness/externalBridgeContext.ts index 1f98ee266..257532a58 100644 --- a/infrastructure/ai/harness/externalBridgeContext.ts +++ b/infrastructure/ai/harness/externalBridgeContext.ts @@ -1,7 +1,7 @@ import type { ChatMessage } from '../types'; import type { ExternalBridgeHistoryMessage } from './types'; import { sliceHead } from '../textBoundaries'; -import { buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent } from '../../../components/ai/cattyHistoryReplay'; +import { buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent } from './cattyHistoryReplay'; import { formatVaultNoteReferences, isVaultNoteAttachment } from '../../../application/state/vaultNoteAttachment'; type ExternalAgentHistoryMessage = ExternalBridgeHistoryMessage; diff --git a/infrastructure/ai/harness/index.ts b/infrastructure/ai/harness/index.ts deleted file mode 100644 index 9304bfe81..000000000 --- a/infrastructure/ai/harness/index.ts +++ /dev/null @@ -1,147 +0,0 @@ -export type { - AgentBackend, - AgentEvent, - AgentEventListener, - AgentEventType, - ApprovalOutcome, - CompactionEvent, - CompactionTrace, - ContextPrepareResult, - ContextPrepareTrigger, - ExternalBridgeHistoryMessage, - TokenEstimatorKind, - UsageEvent, - PerformanceEvent, - ModelCallStartEvent, - StepEndEvent, -} from './types'; -export type { - TurnSteerFailureReason, - TurnSteerInput, - TurnSteerResult, -} from './turnDrivers/types'; - -export { TraceStore, globalTraceStore } from './traceStore'; -export type { TraceExport } from './traceStore'; - -export { stopAgentTurn, clearChatSessionCancelled } from './agentStop'; -export type { AgentStopBridge, StopAgentTurnParams, StopAgentTurnReason } from './agentStop'; - -export { AgentRuntime } from './agentRuntime'; -export { globalAgentRuntime, getAgentRuntime } from './globalAgentRuntime'; - -export { - estimateModelMessagesTokens, - estimateModelMessagesTokensWithKind, - estimateTextTokens, - estimateUnknownTokens, -} from './tokenEstimator'; -export type { EstimateModelMessagesTokensInput, EstimateModelMessagesTokensResult } from './tokenEstimator'; - -export { ToolOutputStore, globalToolOutputStore } from './toolOutputStore'; -export type { - ToolOutputHandle, - StoreToolOutputInput, - ReadToolOutputInput, - ToolOutputReadResult, - ToolOutputPersistence, - ToolOutputStoreOptions, -} from './toolOutputStore'; - -export { ToolResultDedup, hashScopeKey, previewToolResult } from './toolResultDedup'; -export type { ToolResultDedupEntry } from './toolResultDedup'; - -export { cattyTurnDriver } from './turnDrivers/cattyTurnDriver'; -export { externalSdkTurnDriver } from './turnDrivers/externalSdkTurnDriver'; -export type { - TurnInput, - TurnResult, - TurnDriver, - TurnDriverContext, - TurnUiCallbacks, - CattyTurnInput, - ExternalTurnInput, -} from './turnDrivers/types'; - -export { - prepareTurnContext, - prepareStepContext, - buildExternalBridgeContext, - extractLatestUserGoal, -} from './contextManager'; -export type { PrepareTurnContextInput, PostCompactReinjection } from './contextManager'; - -export { - computeCompactionThreshold, - computeTotalInputTokens, - shouldCompactByBudget, - DEFAULT_MAX_OUTPUT_TOKENS, -} from './contextBudget'; - -export { SessionStateStore, globalSessionStateStore } from './sessionState'; -export type { CattySessionState } from './sessionState'; - -export { repairToolMessageIntegrity } from './toolMessageIntegrity'; -export { redactSecretsForModel } from './modelSecretRedaction'; -export { buildPromptContextSnapshot } from './promptContextSnapshot'; -export type { PromptContextSnapshot } from './promptContextSnapshot'; - -export { pruneStaleToolContext } from './staleContextPruner'; -export { pruneUntilFitsCompaction } from './compactionPruner'; - -export { CATTY_COMPACTION_STATUS_KEYS } from './compactionStatusKeys'; - -export { buildExternalBridgeContextMessages } from './externalBridgeContext'; - -export { - fitTerminalExecuteResultForModel, - MAX_LIVE_TERMINAL_STDOUT_CHARS, - MAX_LIVE_TERMINAL_STDERR_CHARS, -} from './terminalCompression'; -export type { TerminalExecuteResult, TerminalOutputHandle } from './terminalCompression'; - -export { - encodeSdkSessionIdentity, - parseSdkSessionIdentity, - SDK_SESSION_ID_PREFIX, -} from './sdkSessionIdentity'; -export type { SdkSessionIdentityPayload } from './sdkSessionIdentity'; - -export { - mapCattyStreamChunkToAgentEvents, - mapSdkStreamEventToAgentEvents, - createHarnessEventSink, -} from './agentEventAdapter'; -export type { StreamEventContext } from './agentEventAdapter'; - -export { - compactCattyMessages, - prepareCattyMessagesForStream, -} from './cattyRuntime'; -export type { CompactCattyMessagesInput, CompactCattyMessagesResult } from './cattyRuntime'; - -export { createCattyToolsFromCatalog } from './capabilityTools'; -export type { CattyToolsBundle } from './capabilityTools'; - -export { - createInitialCattyRuntimeContext, - cattyRuntimeContextSchema, - cattyToolContextSchema, -} from './cattyRuntimeContext'; -export type { CattyRuntimeContext, CattyToolContext } from './cattyRuntimeContext'; - -export { buildCattyStreamTimeouts, buildCattyCompactionTimeout } from './streamTimeouts'; -export { buildCattyToolApproval } from './cattyToolApproval'; - -export { - PermissionGrantStore, - buildGrantFromApproval, - createPermissionGrantId, - getActivePermissionGrants, - matchPermissionGrant, - patternMatches, - resolveCapabilityId, - sanitizePermissionGrants, - setActivePermissionGrants, -} from './permissionGrants'; -export type { PermissionGrantMatchContext, PermissionGrantRule } from './permissionGrants'; diff --git a/infrastructure/ai/harness/permissionGrants.ts b/infrastructure/ai/harness/permissionGrants.ts index eac513501..b3f5b5c80 100644 --- a/infrastructure/ai/harness/permissionGrants.ts +++ b/infrastructure/ai/harness/permissionGrants.ts @@ -295,37 +295,3 @@ export function setActivePermissionGrants(rules: PermissionGrantRule[]): void { export function getActivePermissionGrants(): readonly PermissionGrantRule[] { return activeRules; } - -export class PermissionGrantStore { - private rules: PermissionGrantRule[]; - - constructor(rules: PermissionGrantRule[] = []) { - this.rules = [...rules]; - } - - getRules(): readonly PermissionGrantRule[] { - return this.rules; - } - - setRules(rules: PermissionGrantRule[]): void { - this.rules = [...rules]; - } - - addRule(rule: PermissionGrantRule): void { - this.rules = [...this.rules, rule]; - } - - updateRule(id: string, updates: Partial>): void { - this.rules = this.rules.map((rule) => ( - rule.id === id ? { ...rule, ...updates } : rule - )); - } - - removeRule(id: string): void { - this.rules = this.rules.filter((rule) => rule.id !== id); - } - - match(ctx: PermissionGrantMatchContext): PermissionGrantRule | null { - return matchPermissionGrant(this.rules, ctx); - } -} diff --git a/infrastructure/ai/harness/sessionState.ts b/infrastructure/ai/harness/sessionState.ts index 251a40387..040ac9b08 100644 --- a/infrastructure/ai/harness/sessionState.ts +++ b/infrastructure/ai/harness/sessionState.ts @@ -291,5 +291,3 @@ export class SessionStateStore { return lines.join('\n'); } } - -export const globalSessionStateStore = new SessionStateStore(); diff --git a/infrastructure/ai/harness/toolOutputStore.ts b/infrastructure/ai/harness/toolOutputStore.ts index aeb8f93e1..f0b802fad 100644 --- a/infrastructure/ai/harness/toolOutputStore.ts +++ b/infrastructure/ai/harness/toolOutputStore.ts @@ -848,5 +848,3 @@ function buildReadResult( hasMore: endOffset < content.length, }; } - -export const globalToolOutputStore = new ToolOutputStore(); diff --git a/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts b/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts index 63f136a03..19e82386b 100644 --- a/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts +++ b/infrastructure/ai/harness/turnDrivers/cattyMessageBuilder.ts @@ -10,7 +10,7 @@ import { buildHistoricalToolReplayMaps, buildHistoricalToolResultReplayText, buildHistoricalUserReplayContent, -} from '../../../../components/ai/cattyHistoryReplay'; +} from '../cattyHistoryReplay'; import { buildPromptWithTerminalSelectionAttachments, isInlineTextAttachment, diff --git a/infrastructure/ai/managedAgents.ts b/infrastructure/ai/managedAgents.ts index 16dc29b2c..3c93bba3b 100644 --- a/infrastructure/ai/managedAgents.ts +++ b/infrastructure/ai/managedAgents.ts @@ -16,11 +16,6 @@ const MANAGED_AGENT_META: Record, ): agent is Pick & { command: ManagedAgentKey } { @@ -60,30 +55,6 @@ export function getExternalAgentSdkBackend( return agent?.sdkBackend || agent?.acpCommand || undefined; } -export function getManagedAgentStoredPath( - agents: ExternalAgentConfig[], - agentKey: ManagedAgentKey, -): string | null { - const managedId = `discovered_${agentKey}`; - const preferredAgent = agents.find( - (agent) => - agent.id === managedId && - isPathLikeCommand(agent.command) && - matchesPrimaryCliBasename(agent.command, agentKey), - ); - if (preferredAgent) { - return preferredAgent.command; - } - - const fallbackAgent = agents.find( - (agent) => - matchesManagedAgentConfig(agent, agentKey) && - isPathLikeCommand(agent.command) && - matchesPrimaryCliBasename(agent.command, agentKey), - ); - return fallbackAgent?.command ?? null; -} - export function getManualAgentCommand( config: Pick | null | undefined, ): string | undefined { diff --git a/infrastructure/ai/quickMessages.ts b/infrastructure/ai/quickMessages.ts index a73cc0808..9879b7d54 100644 --- a/infrastructure/ai/quickMessages.ts +++ b/infrastructure/ai/quickMessages.ts @@ -196,11 +196,6 @@ export function createQuickMessageId(): string { return `qm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`; } -export function isSystemStopSlashCommand(input: string): boolean { - const trimmed = input.trim(); - return /^\/stop(?:\s|$)/i.test(trimmed) || trimmed.toLowerCase() === '/stop'; -} - export function getSystemSlashCommand(input: string): SystemSlashCommandSlug | null { const trimmed = input.trim().toLowerCase(); if (/^\/stop(?:\s|$)/.test(trimmed)) return 'stop'; diff --git a/infrastructure/ai/shared/approvalGate.ts b/infrastructure/ai/shared/approvalGate.ts index 999d3c1b6..a43572d31 100644 --- a/infrastructure/ai/shared/approvalGate.ts +++ b/infrastructure/ai/shared/approvalGate.ts @@ -73,14 +73,6 @@ function refreshPermissionGrantsFromStorage(): void { ); } -export function setGrantPersister(persister: GrantPersister | null): void { - grantPersisterStack.length = 0; - if (persister) { - grantPersisterStack.push(persister); - } - grantPersister = persister; -} - /** Register a grant persister; supports multiple mounted AI panels via a stack. */ export function registerGrantPersister(persister: GrantPersister): () => void { grantPersisterStack.push(persister); @@ -421,13 +413,6 @@ export function clearPendingApprovalIds(toolCallIds: string[]): void { } } -/** - * Check if a specific toolCallId has a pending approval. - */ -export function hasPendingApproval(toolCallId: string): boolean { - return pendingApprovals.has(toolCallId); -} - /** * Clear pending approvals, optionally scoped to a specific chatSessionId. * Resolves matching entries with `false` (denied) so execute functions don't hang. diff --git a/infrastructure/ai/types.ts b/infrastructure/ai/types.ts index 3b1d386e1..125bb0437 100644 --- a/infrastructure/ai/types.ts +++ b/infrastructure/ai/types.ts @@ -204,29 +204,6 @@ export interface ToolResult { isError?: boolean; } -export interface ChatParams { - model: string; - messages: ChatMessage[]; - tools?: ToolDefinition[]; - temperature?: number; - maxTokens?: number; - systemPrompt?: string; -} - -export interface ToolDefinition { - name: string; - description: string; - parameters: Record; // JSON Schema -} - -// Streaming events -export type ChatStreamEvent = - | { type: 'text'; content: string } - | { type: 'thinking'; content: string } - | { type: 'tool_call'; toolCall: ToolCall } - | { type: 'error'; error: string } - | { type: 'done'; usage?: { promptTokens: number; completionTokens: number } }; - // AI Session types export interface AISession { id: string; @@ -439,20 +416,6 @@ export function normalizeResponseIdleTimeoutSeconds(value: number): number { return Math.min(MAX_RESPONSE_IDLE_TIMEOUT_SECONDS, Math.max(1, value)); } -export const DEFAULT_AI_SETTINGS: AISettings = { - providers: [], - activeProviderId: '', - activeModelId: '', - globalPermissionMode: 'confirm', - toolIntegrationMode: 'mcp', - externalAgents: [], - defaultAgentId: 'catty', - commandBlocklist: [...DEFAULT_COMMAND_BLOCKLIST], - commandTimeout: DEFAULT_COMMAND_TIMEOUT_SECONDS, - responseIdleTimeout: DEFAULT_RESPONSE_IDLE_TIMEOUT_SECONDS, - maxIterations: 20, -}; - export interface ProviderPreset { name: string; defaultBaseURL: string; diff --git a/infrastructure/config/storageKeys.ts b/infrastructure/config/storageKeys.ts index b74c37706..bb7f3ea68 100644 --- a/infrastructure/config/storageKeys.ts +++ b/infrastructure/config/storageKeys.ts @@ -1,7 +1,6 @@ export const STORAGE_KEY_HOSTS = 'netcatty_hosts_v1'; export const STORAGE_KEY_KEYS = 'netcatty_keys_v1'; export const STORAGE_KEY_GROUPS = 'netcatty_groups_v1'; -export const STORAGE_KEY_CUSTOM_GROUPS = STORAGE_KEY_GROUPS; export const STORAGE_KEY_SNIPPETS = 'netcatty_snippets_v1'; export const STORAGE_KEY_SNIPPET_PACKAGES = 'netcatty_snippet_packages_v1'; export const STORAGE_KEY_NOTES = 'netcatty_notes_v1'; @@ -70,9 +69,7 @@ export const STORAGE_KEY_VAULT_SIDEBAR_WIDTH = 'netcatty_vault_sidebar_width_v1' export const STORAGE_KEY_VAULT_KEYS_VIEW_MODE = 'netcatty_vault_keys_view_mode_v1'; export const STORAGE_KEY_VAULT_PROXY_PROFILES_VIEW_MODE = 'netcatty_vault_proxy_profiles_view_mode_v1'; export const STORAGE_KEY_VAULT_SNIPPETS_VIEW_MODE = 'netcatty_vault_snippets_view_mode_v1'; -export const STORAGE_KEY_VAULT_NOTES_VIEW_MODE = 'netcatty_vault_notes_view_mode_v1'; export const STORAGE_KEY_VAULT_NOTES_EDITOR_MODE = 'netcatty_vault_notes_editor_mode_v1'; -export const STORAGE_KEY_VAULT_NOTES_SELECTED_GROUP = 'netcatty_vault_notes_selected_group_v1'; export const STORAGE_KEY_VAULT_NOTES_TREE_WIDTH = 'netcatty_vault_notes_tree_width_v1'; export const STORAGE_KEY_VAULT_NOTES_FONT_FAMILY = 'netcatty_vault_notes_font_family_v1'; export const STORAGE_KEY_VAULT_NOTES_FONT_SIZE = 'netcatty_vault_notes_font_size_v1'; @@ -270,11 +267,6 @@ export const STORAGE_KEY_AI_PANEL_DIAGNOSTIC_PROFILE = 'netcatty.aiDebug.profile // SFTP Transfer Concurrency export const STORAGE_KEY_SFTP_TRANSFER_CONCURRENCY = 'netcatty_sftp_transfer_concurrency_v1'; -/** - * Legacy key only. Folder full-tree pre-scan was removed; values are ignored - * so old localStorage / sync payloads do not resurrect a live setting. - */ -export const STORAGE_KEY_SFTP_FOLDER_PRESCAN = 'netcatty_sftp_folder_prescan_v1'; /** Skip files when target size + mtime already match the source (rsync-like). */ export const STORAGE_KEY_SFTP_SKIP_UNCHANGED = 'netcatty_sftp_skip_unchanged_v1'; /** diff --git a/infrastructure/config/uiFontBootstrap.test.ts b/infrastructure/config/uiFontBootstrap.test.ts deleted file mode 100644 index efa70eadf..000000000 --- a/infrastructure/config/uiFontBootstrap.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { describe, it } from 'node:test'; - -/** - * Regression for #2647: Windows boot CSS used a higher-specificity - * `html.platform-win32 body { font-family: ... }` rule that beat - * `body { font-family: var(--font-sans) }` from index.css. Popovers / - * context menus inherit from body, so transfer / sync / quick-control - * panels and menu items ignored the Appearance UI font setting. - */ -const indexHtml = readFileSync(new URL('../../index.html', import.meta.url), 'utf8'); - -describe('index.html UI font bootstrap', () => { - it('applies the runtime --font-sans variable on body', () => { - assert.match( - indexHtml, - /body\s*\{[^}]*font-family:\s*var\(--font-sans\)/s, - 'body must use var(--font-sans) so Appearance UI font updates reach portaled panels', - ); - }); - - it('does not hardcode a Windows body font stack that overrides --font-sans', () => { - assert.doesNotMatch( - indexHtml, - /html\.platform-win32\s+body\s*\{[^}]*font-family:/s, - 'platform-win32 must not set body font-family; emoji fallbacks belong on --font-sans', - ); - assert.doesNotMatch( - indexHtml, - /body\s*\{[^}]*font-family:\s*['"]Space Grotesk['"]/s, - 'body must not hardcode Space Grotesk ahead of the user UI font setting', - ); - }); -}); diff --git a/infrastructure/config/uiThemes.ts b/infrastructure/config/uiThemes.ts index 20709801e..474986534 100644 --- a/infrastructure/config/uiThemes.ts +++ b/infrastructure/config/uiThemes.ts @@ -28,1567 +28,836 @@ export type UiThemePreset = { tokens: UiThemeTokens; }; +type UiThemeBaseTokens = Pick< + UiThemeTokens, + | "background" + | "foreground" + | "card" + | "primary" + | "primaryForeground" + | "secondary" + | "muted" + | "mutedForeground" + | "destructive" + | "border" +> & + Partial< + Pick< + UiThemeTokens, + | "cardForeground" + | "popover" + | "popoverForeground" + | "secondaryForeground" + | "accent" + | "accentForeground" + | "destructiveForeground" + | "input" + | "ring" + > + >; + +function defineUiTheme( + id: string, + name: string, + t: UiThemeBaseTokens, + collection?: "core", +): UiThemePreset { + const preset: UiThemePreset = { + id, + name, + ...(collection ? { collection } : {}), + tokens: { + background: t.background, + foreground: t.foreground, + card: t.card, + cardForeground: t.cardForeground ?? t.foreground, + popover: t.popover ?? t.card, + popoverForeground: t.popoverForeground ?? t.foreground, + primary: t.primary, + primaryForeground: t.primaryForeground, + secondary: t.secondary, + secondaryForeground: t.secondaryForeground ?? t.foreground, + muted: t.muted, + mutedForeground: t.mutedForeground, + accent: t.accent ?? t.primary, + accentForeground: t.accentForeground ?? t.primaryForeground, + destructive: t.destructive, + destructiveForeground: t.destructiveForeground ?? t.primaryForeground, + border: t.border, + input: t.input ?? t.border, + ring: t.ring ?? t.primary, + }, + }; + return preset; +} + export const CORE_LIGHT_UI_THEMES: UiThemePreset[] = [ - { - id: "snow", - name: "Snow", - collection: "core", - tokens: { - background: "216 33% 96%", - foreground: "222 47% 12%", - card: "0 0% 100%", - cardForeground: "222 47% 12%", - popover: "0 0% 100%", - popoverForeground: "222 47% 12%", - primary: "208 100% 50%", - primaryForeground: "0 0% 100%", - secondary: "220 16% 90%", - secondaryForeground: "222 47% 12%", - muted: "220 16% 90%", - mutedForeground: "220 10% 45%", - accent: "208 100% 50%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "220 16% 82%", - input: "220 16% 82%", - ring: "208 100% 50%", - }, - }, - { - id: "pure-white", - name: "Pure White", - collection: "core", - tokens: { - background: "0 0% 100%", - foreground: "222 47% 12%", - card: "0 0% 100%", - cardForeground: "222 47% 12%", - popover: "0 0% 100%", - popoverForeground: "222 47% 12%", - primary: "210 90% 48%", - primaryForeground: "0 0% 100%", - secondary: "220 12% 95%", - secondaryForeground: "222 47% 12%", - muted: "220 12% 95%", - mutedForeground: "220 10% 45%", - accent: "210 90% 48%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "220 12% 88%", - input: "220 12% 88%", - ring: "210 90% 48%", - }, - }, - { - id: "ivory", - name: "Ivory", - collection: "core", - tokens: { - background: "38 40% 95%", - foreground: "222 47% 12%", - card: "40 45% 98%", - cardForeground: "222 47% 12%", - popover: "40 45% 98%", - popoverForeground: "222 47% 12%", - primary: "28 85% 50%", - primaryForeground: "0 0% 100%", - secondary: "36 28% 90%", - secondaryForeground: "222 47% 12%", - muted: "36 28% 90%", - mutedForeground: "220 10% 45%", - accent: "28 85% 50%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "34 24% 84%", - input: "34 24% 84%", - ring: "28 85% 50%", - }, - }, - { - id: "mist", - name: "Mist", - collection: "core", - tokens: { - background: "210 20% 97%", - foreground: "222 47% 12%", - card: "210 20% 99%", - cardForeground: "222 47% 12%", - popover: "210 20% 99%", - popoverForeground: "222 47% 12%", - primary: "195 90% 45%", - primaryForeground: "0 0% 100%", - secondary: "210 16% 92%", - secondaryForeground: "222 47% 12%", - muted: "210 16% 92%", - mutedForeground: "220 10% 45%", - accent: "195 90% 45%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "210 14% 84%", - input: "210 14% 84%", - ring: "195 90% 45%", - }, - }, - { - id: "mint", - name: "Mint", - collection: "core", - tokens: { - background: "150 30% 96%", - foreground: "222 47% 12%", - card: "150 30% 98%", - cardForeground: "222 47% 12%", - popover: "150 30% 98%", - popoverForeground: "222 47% 12%", - primary: "160 70% 40%", - primaryForeground: "0 0% 100%", - secondary: "150 18% 90%", - secondaryForeground: "222 47% 12%", - muted: "150 18% 90%", - mutedForeground: "220 10% 45%", - accent: "160 70% 40%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "150 16% 84%", - input: "150 16% 84%", - ring: "160 70% 40%", - }, - }, - { - id: "sand", - name: "Sand", - collection: "core", - tokens: { - background: "34 30% 94%", - foreground: "222 47% 12%", - card: "34 30% 97%", - cardForeground: "222 47% 12%", - popover: "34 30% 97%", - popoverForeground: "222 47% 12%", - primary: "24 80% 50%", - primaryForeground: "0 0% 100%", - secondary: "34 18% 88%", - secondaryForeground: "222 47% 12%", - muted: "34 18% 88%", - mutedForeground: "220 10% 45%", - accent: "24 80% 50%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "34 16% 82%", - input: "34 16% 82%", - ring: "24 80% 50%", - }, - }, - { - id: "lavender", - name: "Lavender", - collection: "core", - tokens: { - background: "270 30% 97%", - foreground: "222 47% 12%", - card: "270 30% 99%", - cardForeground: "222 47% 12%", - popover: "270 30% 99%", - popoverForeground: "222 47% 12%", - primary: "270 70% 55%", - primaryForeground: "0 0% 100%", - secondary: "270 20% 92%", - secondaryForeground: "222 47% 12%", - muted: "270 20% 92%", - mutedForeground: "220 10% 45%", - accent: "270 70% 55%", - accentForeground: "222 47% 12%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "270 18% 86%", - input: "270 18% 86%", - ring: "270 70% 55%", - }, - }, + defineUiTheme("snow", "Snow", { + background: "216 33% 96%", + foreground: "222 47% 12%", + card: "0 0% 100%", + primary: "208 100% 50%", + primaryForeground: "0 0% 100%", + secondary: "220 16% 90%", + muted: "220 16% 90%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "220 16% 82%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("pure-white", "Pure White", { + background: "0 0% 100%", + foreground: "222 47% 12%", + card: "0 0% 100%", + primary: "210 90% 48%", + primaryForeground: "0 0% 100%", + secondary: "220 12% 95%", + muted: "220 12% 95%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "220 12% 88%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("ivory", "Ivory", { + background: "38 40% 95%", + foreground: "222 47% 12%", + card: "40 45% 98%", + primary: "28 85% 50%", + primaryForeground: "0 0% 100%", + secondary: "36 28% 90%", + muted: "36 28% 90%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "34 24% 84%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("mist", "Mist", { + background: "210 20% 97%", + foreground: "222 47% 12%", + card: "210 20% 99%", + primary: "195 90% 45%", + primaryForeground: "0 0% 100%", + secondary: "210 16% 92%", + muted: "210 16% 92%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "210 14% 84%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("mint", "Mint", { + background: "150 30% 96%", + foreground: "222 47% 12%", + card: "150 30% 98%", + primary: "160 70% 40%", + primaryForeground: "0 0% 100%", + secondary: "150 18% 90%", + muted: "150 18% 90%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "150 16% 84%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("sand", "Sand", { + background: "34 30% 94%", + foreground: "222 47% 12%", + card: "34 30% 97%", + primary: "24 80% 50%", + primaryForeground: "0 0% 100%", + secondary: "34 18% 88%", + muted: "34 18% 88%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "34 16% 82%", + accentForeground: "222 47% 12%", + }, "core"), + defineUiTheme("lavender", "Lavender", { + background: "270 30% 97%", + foreground: "222 47% 12%", + card: "270 30% 99%", + primary: "270 70% 55%", + primaryForeground: "0 0% 100%", + secondary: "270 20% 92%", + muted: "270 20% 92%", + mutedForeground: "220 10% 45%", + destructive: "0 70% 50%", + border: "270 18% 86%", + accentForeground: "222 47% 12%", + }, "core"), ]; export const EXTENDED_LIGHT_UI_THEMES: UiThemePreset[] = [ - { - id: "a-cup-of-coffee", - name: "A cup of coffee", - tokens: { - background: "0 0% 98.4%", - foreground: "0 0% 0%", - card: "0 0% 99.2%", - cardForeground: "0 0% 0%", - popover: "0 0% 99.2%", - popoverForeground: "0 0% 0%", - primary: "211.3 95.3% 33.1%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 92.9%", - secondaryForeground: "0 0% 0%", - muted: "0 0% 90.2%", - mutedForeground: "0 0% 33.3%", - accent: "211.3 95.3% 33.1%", - accentForeground: "0 0% 100%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 83.5%", - input: "0 0% 83.5%", - ring: "211.3 95.3% 33.1%", - }, - }, - { - id: "abolkog", - name: "ABOLKOG", - tokens: { - background: "0 0% 100%", - foreground: "210 12.2% 16.1%", - card: "0 0% 100%", - cardForeground: "210 12.2% 16.1%", - popover: "0 0% 100%", - popoverForeground: "210 12.2% 16.1%", - primary: "40 70.6% 73.3%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "210 12.2% 16.1%", - muted: "0 0% 91.4%", - mutedForeground: "205.7 3.1% 44.5%", - accent: "40 70.6% 73.3%", - accentForeground: "0 0% 0%", - destructive: "354.3 42.3% 56.5%", - destructiveForeground: "0 0% 0%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "40 70.6% 73.3%", - }, - }, - { - id: "aurora", - name: "Aurora", - tokens: { - background: "44.5 88.6% 93.1%", - foreground: "40.5 100% 14.5%", - card: "47.1 87.5% 96.9%", - cardForeground: "40.5 100% 14.5%", - popover: "47.1 87.5% 96.9%", - popoverForeground: "40.5 100% 14.5%", - primary: "171.4 100% 22%", - primaryForeground: "0 0% 100%", - secondary: "45.5 47.5% 88%", - secondaryForeground: "40.5 100% 14.5%", - muted: "45 36.8% 85.1%", - mutedForeground: "41 28.6% 41.2%", - accent: "171.4 100% 22%", - accentForeground: "0 0% 100%", - destructive: "341.7 100% 36.1%", - destructiveForeground: "0 0% 100%", - border: "43.8 24.5% 79.2%", - input: "43.8 24.5% 79.2%", - ring: "171.4 100% 22%", - }, - }, - { - id: "ayu", - name: "Ayu", - tokens: { - background: "210 16.7% 97.6%", - foreground: "210 5.2% 38%", - card: "240 20% 99%", - cardForeground: "210 5.2% 38%", - popover: "240 20% 99%", - popoverForeground: "210 5.2% 38%", - primary: "75.1 100% 35.1%", - primaryForeground: "0 0% 0%", - secondary: "210 5% 92.2%", - secondaryForeground: "210 5.2% 38%", - muted: "210 3.7% 89.4%", - mutedForeground: "205.7 3.3% 58.2%", - accent: "75.1 100% 35.1%", - accentForeground: "0 0% 0%", - destructive: "0 80.9% 69.2%", - destructiveForeground: "0 0% 0%", - border: "210 2.3% 83.1%", - input: "210 2.3% 83.1%", - ring: "75.1 100% 35.1%", - }, - }, - { - id: "base16-flat", - name: "Base16 Flat", - tokens: { - background: "192 15.2% 93.5%", - foreground: "184.3 5.8% 52.5%", - card: "200 20% 97.1%", - cardForeground: "184.3 5.8% 52.5%", - popover: "200 20% 97.1%", - popoverForeground: "184.3 5.8% 52.5%", - primary: "204.1 69.9% 53.1%", - primaryForeground: "0 0% 0%", - secondary: "192 8.5% 88.4%", - secondaryForeground: "184.3 5.8% 52.5%", - muted: "192 6.8% 85.7%", - mutedForeground: "185.5 6.4% 66.5%", - accent: "204.1 69.9% 53.1%", - accentForeground: "0 0% 0%", - destructive: "5.6 78.1% 57.1%", - destructiveForeground: "0 0% 0%", - border: "195 3.8% 79.6%", - input: "195 3.8% 79.6%", - ring: "204.1 69.9% 53.1%", - }, - }, - { - id: "base16-mocha", - name: "Base16 Mocha", - tokens: { - background: "18 33.3% 94.1%", - foreground: "30 22% 32.2%", - card: "12 38.5% 97.5%", - cardForeground: "30 22% 32.2%", - popover: "12 38.5% 97.5%", - popoverForeground: "30 22% 32.2%", - primary: "16.1 51.9% 63.3%", - primaryForeground: "0 0% 0%", - secondary: "18 17.9% 89%", - secondaryForeground: "30 22% 32.2%", - muted: "20 12.7% 86.1%", - mutedForeground: "28.9 11.3% 53.1%", - accent: "16.1 51.9% 63.3%", - accentForeground: "0 0% 0%", - destructive: "347.1 50.7% 58.6%", - destructiveForeground: "0 0% 0%", - border: "15 7.8% 80%", - input: "15 7.8% 80%", - ring: "16.1 51.9% 63.3%", - }, - }, - { - id: "blue-dolphin", - name: "Blue Dolphin", - tokens: { - background: "195 40% 94.1%", - foreground: "193.2 65.8% 14.9%", - card: "192 38.5% 97.5%", - cardForeground: "193.2 65.8% 14.9%", - popover: "192 38.5% 97.5%", - popoverForeground: "193.2 65.8% 14.9%", - primary: "195 100% 25.1%", - primaryForeground: "0 0% 100%", - secondary: "190.9 19.3% 88.8%", - secondaryForeground: "193.2 65.8% 14.9%", - muted: "196.4 15.5% 86.1%", - mutedForeground: "193 17.4% 41.8%", - accent: "195 100% 25.1%", - accentForeground: "0 0% 100%", - destructive: "353.3 64.3% 43.9%", - destructiveForeground: "0 0% 100%", - border: "192 9.8% 80%", - input: "192 9.8% 80%", - ring: "195 100% 25.1%", - }, - }, - { - id: "calm-days-sober-nights-sky", - name: "Calm Days, Sober Nights Sky", - tokens: { - background: "0 0% 100%", - foreground: "221.5 11.1% 45.9%", - card: "0 0% 100%", - cardForeground: "221.5 11.1% 45.9%", - popover: "0 0% 100%", - popoverForeground: "221.5 11.1% 45.9%", - primary: "142.1 100% 35.1%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "221.5 11.1% 45.9%", - muted: "0 0% 91.4%", - mutedForeground: "220 9.9% 64.3%", - accent: "142.1 100% 35.1%", - accentForeground: "0 0% 0%", - destructive: "350.1 76% 67.3%", - destructiveForeground: "0 0% 0%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "142.1 100% 35.1%", - }, - }, - { - id: "catppuccin", - name: "Catppuccin", - tokens: { - background: "220 23.1% 94.9%", - foreground: "233.8 16% 35.5%", - card: "220 27.3% 97.8%", - cardForeground: "233.8 16% 35.5%", - popover: "220 27.3% 97.8%", - popoverForeground: "233.8 16% 35.5%", - primary: "219.9 91.5% 53.9%", - primaryForeground: "0 0% 100%", - secondary: "220 11.5% 89.8%", - secondaryForeground: "233.8 16% 35.5%", - muted: "216 7.5% 86.9%", - mutedForeground: "231.8 9.7% 55.7%", - accent: "219.9 91.5% 53.9%", - accentForeground: "0 0% 100%", - destructive: "347.1 86.7% 44.1%", - destructiveForeground: "0 0% 100%", - border: "216 5.1% 80.6%", - input: "216 5.1% 80.6%", - ring: "219.9 91.5% 53.9%", - }, - }, - { - id: "chai", - name: "Chai", - tokens: { - background: "0 0% 96.9%", - foreground: "228 8.2% 23.9%", - card: "0 0% 98.4%", - cardForeground: "228 8.2% 23.9%", - popover: "0 0% 98.4%", - popoverForeground: "228 8.2% 23.9%", - primary: "262.9 85.6% 59.2%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 91.4%", - secondaryForeground: "228 8.2% 23.9%", - muted: "0 0% 88.6%", - mutedForeground: "231.4 2.8% 48.8%", - accent: "262.9 85.6% 59.2%", - accentForeground: "0 0% 100%", - destructive: "344.9 69.7% 49.2%", - destructiveForeground: "0 0% 100%", - border: "0 0% 82.4%", - input: "0 0% 82.4%", - ring: "262.9 85.6% 59.2%", - }, - }, - { - id: "chinolor", - name: "Chinolor", - tokens: { - background: "38.2 44% 95.1%", - foreground: "130 6.5% 18%", - card: "36 45.5% 97.8%", - cardForeground: "130 6.5% 18%", - popover: "36 45.5% 97.8%", - popoverForeground: "130 6.5% 18%", - primary: "48.2 100% 23.9%", - primaryForeground: "0 0% 100%", - secondary: "42 19.2% 89.8%", - secondaryForeground: "130 6.5% 18%", - muted: "36 15.2% 87.1%", - mutedForeground: "84 2.2% 44.1%", - accent: "48.2 100% 23.9%", - accentForeground: "0 0% 100%", - destructive: "355.2 83.7% 59%", - destructiveForeground: "0 0% 0%", - border: "36 10.2% 80.8%", - input: "36 10.2% 80.8%", - ring: "48.2 100% 23.9%", - }, - }, - { - id: "cyberdyne", - name: "Cyberdyne", - tokens: { - background: "248.6 22.6% 93.9%", - foreground: "153.9 69.7% 12.9%", - card: "255 28.6% 97.3%", - cardForeground: "153.9 69.7% 12.9%", - popover: "255 28.6% 97.3%", - popoverForeground: "153.9 69.7% 12.9%", - primary: "213 100% 31.4%", - primaryForeground: "0 0% 100%", - secondary: "248.6 12.3% 88.8%", - secondaryForeground: "153.9 69.7% 12.9%", - muted: "250 8.3% 85.9%", - mutedForeground: "158 14.7% 40%", - accent: "213 100% 31.4%", - accentForeground: "0 0% 100%", - destructive: "9 76.9% 40.8%", - destructiveForeground: "0 0% 100%", - border: "240 5.9% 80%", - input: "240 5.9% 80%", - ring: "213 100% 31.4%", - }, - }, - { - id: "desert", - name: "Desert", - tokens: { - background: "34.3 22.6% 93.9%", - foreground: "27.6 74.5% 20%", - card: "30 28.6% 97.3%", - cardForeground: "27.6 74.5% 20%", - popover: "30 28.6% 97.3%", - popoverForeground: "27.6 74.5% 20%", - primary: "147.7 100% 20.4%", - primaryForeground: "0 0% 100%", - secondary: "34.3 12.3% 88.8%", - secondaryForeground: "27.6 74.5% 20%", - muted: "40 8.3% 85.9%", - mutedForeground: "27.7 22.6% 45.1%", - accent: "147.7 100% 20.4%", - accentForeground: "0 0% 100%", - destructive: "0 100% 36.1%", - destructiveForeground: "0 0% 100%", - border: "30 5.9% 80%", - input: "30 5.9% 80%", - ring: "147.7 100% 20.4%", - }, - }, - { - id: "django-reborn-again", - name: "Django Reborn Again", - tokens: { - background: "150 26.7% 94.1%", - foreground: "155 47.4% 14.9%", - card: "150 28.6% 97.3%", - cardForeground: "155 47.4% 14.9%", - popover: "150 28.6% 97.3%", - popoverForeground: "155 47.4% 14.9%", - primary: "51.1 100% 23.9%", - primaryForeground: "0 0% 100%", - secondary: "150 14.3% 89%", - secondaryForeground: "155 47.4% 14.9%", - muted: "154.3 9.9% 86.1%", - mutedForeground: "155.6 12.7% 41.8%", - accent: "51.1 100% 23.9%", - accentForeground: "0 0% 100%", - destructive: "20.9 100% 36.1%", - destructiveForeground: "0 0% 100%", - border: "150 5.9% 80%", - input: "150 5.9% 80%", - ring: "51.1 100% 23.9%", - }, - }, - { - id: "espresso", - name: "Espresso", - tokens: { - background: "46.7 23.1% 92.4%", - foreground: "180 37.9% 17.1%", - card: "45 22.2% 96.5%", - cardForeground: "180 37.9% 17.1%", - popover: "45 22.2% 96.5%", - popoverForeground: "180 37.9% 17.1%", - primary: "195.8 20.4% 36.5%", - primaryForeground: "0 0% 100%", - secondary: "46.7 13.8% 87.3%", - secondaryForeground: "180 37.9% 17.1%", - muted: "46.7 11.4% 84.5%", - mutedForeground: "171.8 10% 43.1%", - accent: "195.8 20.4% 36.5%", - accentForeground: "0 0% 100%", - destructive: "0 27.4% 48.6%", - destructiveForeground: "0 0% 100%", - border: "45 7.3% 78.4%", - input: "45 7.3% 78.4%", - ring: "195.8 20.4% 36.5%", - }, - }, - { - id: "eyehealth", - name: "EyeHealth", - tokens: { - background: "47 100% 95.5%", - foreground: "22.4 31.2% 42.2%", - card: "48 100% 98%", - cardForeground: "22.4 31.2% 42.2%", - popover: "48 100% 98%", - popoverForeground: "22.4 31.2% 42.2%", - primary: "35.8 100% 50%", - primaryForeground: "0 0% 0%", - secondary: "46.4 44% 90.2%", - secondaryForeground: "22.4 31.2% 42.2%", - muted: "48.6 32.3% 87.3%", - mutedForeground: "25.4 25.7% 60.4%", - accent: "35.8 100% 50%", - accentForeground: "0 0% 0%", - destructive: "354 67% 56.1%", - destructiveForeground: "0 0% 0%", - border: "48 20.8% 81.2%", - input: "48 20.8% 81.2%", - ring: "35.8 100% 50%", - }, - }, - { - id: "flexoki", - name: "Flexoki", - tokens: { - background: "48 100% 97.1%", - foreground: "0 3.2% 6.1%", - card: "51.4 100% 98.6%", - cardForeground: "0 3.2% 6.1%", - popover: "51.4 100% 98.6%", - popoverForeground: "0 3.2% 6.1%", - primary: "45.3 98.9% 34.1%", - primaryForeground: "0 0% 0%", - secondary: "47.1 33.3% 91.8%", - secondaryForeground: "0 3.2% 6.1%", - muted: "50.8 22.8% 88.8%", - mutedForeground: "48 2.6% 37.1%", - accent: "45.3 98.9% 34.1%", - accentForeground: "0 0% 0%", - destructive: "3.1 62% 42.4%", - destructiveForeground: "0 0% 100%", - border: "46.2 14.6% 82.5%", - input: "46.2 14.6% 82.5%", - ring: "45.3 98.9% 34.1%", - }, - }, - { - id: "fox", - name: "Fox", - tokens: { - background: "30 30.8% 94.9%", - foreground: "263 35.3% 26.1%", - card: "30 33.3% 97.6%", - cardForeground: "263 35.3% 26.1%", - popover: "30 33.3% 97.6%", - popoverForeground: "263 35.3% 26.1%", - primary: "28.9 97.7% 34.1%", - primaryForeground: "0 0% 100%", - secondary: "34.3 13.2% 89.6%", - secondaryForeground: "263 35.3% 26.1%", - muted: "25.7 10.4% 86.9%", - mutedForeground: "266.9 11.6% 49.2%", - accent: "28.9 97.7% 34.1%", - accentForeground: "0 0% 100%", - destructive: "354 65.8% 39%", - destructiveForeground: "0 0% 100%", - border: "34.3 7.1% 80.6%", - input: "34.3 7.1% 80.6%", - ring: "28.9 97.7% 34.1%", - }, - }, - { - id: "garbage-oracle", - name: "Garbage Oracle", - tokens: { - background: "303.8 38.1% 91.8%", - foreground: "320.9 100% 26.5%", - card: "300 36.8% 96.3%", - cardForeground: "320.9 100% 26.5%", - popover: "300 36.8% 96.3%", - popoverForeground: "320.9 100% 26.5%", - primary: "22.7 66.2% 29%", - primaryForeground: "0 0% 100%", - secondary: "304 22.4% 86.9%", - secondaryForeground: "320.9 100% 26.5%", - muted: "300 17.1% 83.9%", - mutedForeground: "319.8 37.9% 48.6%", - accent: "22.7 66.2% 29%", - accentForeground: "0 0% 100%", - destructive: "352.2 54.7% 41.6%", - destructiveForeground: "0 0% 100%", - border: "304.3 12.5% 78%", - input: "304.3 12.5% 78%", - ring: "22.7 66.2% 29%", - }, - }, - { - id: "github", - name: "GitHub", - tokens: { - background: "0 0% 100%", - foreground: "213.3 12.7% 13.9%", - card: "0 0% 100%", - cardForeground: "213.3 12.7% 13.9%", - popover: "0 0% 100%", - popoverForeground: "213.3 12.7% 13.9%", - primary: "212.4 92.1% 44.5%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 94.5%", - secondaryForeground: "213.3 12.7% 13.9%", - muted: "0 0% 91.4%", - mutedForeground: "210 2.7% 43.1%", - accent: "212.4 92.1% 44.5%", - accentForeground: "0 0% 100%", - destructive: "355.8 71.8% 47.3%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "212.4 92.1% 44.5%", - }, - }, - { - id: "gruvbox-material", - name: "Gruvbox Material", - tokens: { - background: "48.5 86.7% 88.2%", - foreground: "22.5 31.2% 30.2%", - card: "49.6 85.2% 94.7%", - cardForeground: "22.5 31.2% 30.2%", - popover: "49.6 85.2% 94.7%", - popoverForeground: "22.5 31.2% 30.2%", - primary: "36.5 90.5% 37.1%", - primaryForeground: "0 0% 0%", - secondary: "49 57.6% 83.3%", - secondaryForeground: "22.5 31.2% 30.2%", - muted: "48.8 49% 80.8%", - mutedForeground: "31.8 19.2% 50%", - accent: "36.5 90.5% 37.1%", - accentForeground: "0 0% 0%", - destructive: "0 49% 52.4%", - destructiveForeground: "0 0% 100%", - border: "49.1 34.4% 74.9%", - input: "49.1 34.4% 74.9%", - ring: "36.5 90.5% 37.1%", - }, - }, - { - id: "homebrew", - name: "Homebrew", - tokens: { - background: "120 40% 94.1%", - foreground: "120 65.8% 14.9%", - card: "120 38.5% 97.5%", - cardForeground: "120 65.8% 14.9%", - popover: "120 38.5% 97.5%", - popoverForeground: "120 65.8% 14.9%", - primary: "300 100% 23.5%", - primaryForeground: "0 0% 100%", - secondary: "120 19.3% 88.8%", - secondaryForeground: "120 65.8% 14.9%", - muted: "120 15.5% 86.1%", - mutedForeground: "120 17.4% 41.8%", - accent: "300 100% 23.5%", - accentForeground: "0 0% 100%", - destructive: "0 100% 23.9%", - destructiveForeground: "0 0% 100%", - border: "120 9.8% 80%", - input: "120 9.8% 80%", - ring: "300 100% 23.5%", - }, - }, - { - id: "ic-orange-ppl", - name: "IC Orange PPL", - tokens: { - background: "35 40% 94.1%", - foreground: "34.8 65.8% 14.9%", - card: "36 38.5% 97.5%", - cardForeground: "34.8 65.8% 14.9%", - popover: "36 38.5% 97.5%", - popoverForeground: "34.8 65.8% 14.9%", - primary: "24 100% 23.5%", - primaryForeground: "0 0% 100%", - secondary: "38.2 19.3% 88.8%", - secondaryForeground: "34.8 65.8% 14.9%", - muted: "38.2 15.5% 86.1%", - mutedForeground: "35.7 17.4% 41.8%", - accent: "24 100% 23.5%", - accentForeground: "0 0% 100%", - destructive: "14.1 100% 26.7%", - destructiveForeground: "0 0% 100%", - border: "36 9.8% 80%", - input: "36 9.8% 80%", - ring: "24 100% 23.5%", - }, - }, - { - id: "ikki", - name: "IKKI", - tokens: { - background: "43.6 100% 97.8%", - foreground: "22.4 31.2% 42.2%", - card: "48 100% 99%", - cardForeground: "22.4 31.2% 42.2%", - popover: "48 100% 99%", - popoverForeground: "22.4 31.2% 42.2%", - primary: "35.8 100% 50%", - primaryForeground: "0 0% 0%", - secondary: "42 26.3% 92.5%", - secondaryForeground: "22.4 31.2% 42.2%", - muted: "48 18.5% 89.4%", - mutedForeground: "23.7 24.2% 61.2%", - accent: "35.8 100% 50%", - accentForeground: "0 0% 0%", - destructive: "354 67% 56.1%", - destructiveForeground: "0 0% 0%", - border: "42 11.6% 83.1%", - input: "42 11.6% 83.1%", - ring: "35.8 100% 50%", - }, - }, - { - id: "kanso-ink", - name: "Kanso Ink", - tokens: { - background: "40 10.3% 94.3%", - foreground: "218.2 13.9% 15.5%", - card: "60 7.7% 97.5%", - cardForeground: "218.2 13.9% 15.5%", - popover: "60 7.7% 97.5%", - popoverForeground: "218.2 13.9% 15.5%", - primary: "351.6 55.3% 51.8%", - primaryForeground: "0 0% 100%", - secondary: "40 5.5% 89.2%", - secondaryForeground: "218.2 13.9% 15.5%", - muted: "60 2.9% 86.3%", - mutedForeground: "220 2.8% 42.4%", - accent: "351.6 55.3% 51.8%", - accentForeground: "0 0% 100%", - destructive: "351.6 55.3% 51.8%", - destructiveForeground: "0 0% 100%", - border: "40 3% 80.2%", - input: "40 3% 80.2%", - ring: "351.6 55.3% 51.8%", - }, - }, - { - id: "kary-pro-colors", - name: "Kary Pro Colors", - tokens: { - background: "207.3 57.9% 96.3%", - foreground: "209.5 53.8% 46.7%", - card: "204 55.6% 98.2%", - cardForeground: "209.5 53.8% 46.7%", - popover: "204 55.6% 98.2%", - popoverForeground: "209.5 53.8% 46.7%", - primary: "32.7 76.5% 36.7%", - primaryForeground: "0 0% 100%", - secondary: "210 21.7% 91%", - secondaryForeground: "209.5 53.8% 46.7%", - muted: "210 16.7% 88.2%", - mutedForeground: "209.3 47.3% 63.5%", - accent: "32.7 76.5% 36.7%", - accentForeground: "0 0% 100%", - destructive: "13.1 69.6% 46.5%", - destructiveForeground: "0 0% 100%", - border: "206.7 9.7% 81.8%", - input: "206.7 9.7% 81.8%", - ring: "32.7 76.5% 36.7%", - }, - }, - { - id: "light-purple", - name: "Light purple", - tokens: { - background: "10 15.8% 92.5%", - foreground: "274.8 33.8% 29%", - card: "20 17.6% 96.7%", - cardForeground: "274.8 33.8% 29%", - popover: "20 17.6% 96.7%", - popoverForeground: "274.8 33.8% 29%", - primary: "46.8 98.2% 44.3%", - primaryForeground: "0 0% 0%", - secondary: "10 9.4% 87.5%", - secondaryForeground: "274.8 33.8% 29%", - muted: "10 7.7% 84.7%", - mutedForeground: "278.2 13% 50.4%", - accent: "46.8 98.2% 44.3%", - accentForeground: "0 0% 0%", - destructive: "0.7 71.2% 55.1%", - destructiveForeground: "0 0% 0%", - border: "12 4.6% 78.6%", - input: "12 4.6% 78.6%", - ring: "46.8 98.2% 44.3%", - }, - }, - { - id: "mondrian", - name: "Mondrian", - tokens: { - background: "0 0% 100%", - foreground: "0 0% 0%", - card: "0 0% 100%", - cardForeground: "0 0% 0%", - popover: "0 0% 100%", - popoverForeground: "0 0% 0%", - primary: "217.4 89% 60.8%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "0 0% 0%", - muted: "0 0% 91.4%", - mutedForeground: "0 0% 34.1%", - accent: "217.4 89% 60.8%", - accentForeground: "0 0% 0%", - destructive: "4.8 69.5% 53.7%", - destructiveForeground: "0 0% 0%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "217.4 89% 60.8%", - }, - }, - { - id: "monochrome", - name: "Monochrome", - tokens: { - background: "210 40% 96.1%", - foreground: "222.2 47.4% 11.2%", - card: "200 33.3% 98.2%", - cardForeground: "222.2 47.4% 11.2%", - popover: "200 33.3% 98.2%", - popoverForeground: "222.2 47.4% 11.2%", - primary: "222.2 47.4% 11.2%", - primaryForeground: "0 0% 100%", - secondary: "205.7 14.9% 90.8%", - secondaryForeground: "222.2 47.4% 11.2%", - muted: "214.3 11.5% 88%", - mutedForeground: "222 9.8% 40%", - accent: "222.2 47.4% 11.2%", - accentForeground: "0 0% 100%", - destructive: "222.2 47.4% 11.2%", - destructiveForeground: "0 0% 100%", - border: "214.3 7.5% 81.8%", - input: "214.3 7.5% 81.8%", - ring: "222.2 47.4% 11.2%", - }, - }, - { - id: "monochrome-stone", - name: "Monochrome Stone", - tokens: { - background: "60 4.8% 95.9%", - foreground: "24 9.8% 10%", - card: "60 11.1% 98.2%", - cardForeground: "24 9.8% 10%", - popover: "60 11.1% 98.2%", - popoverForeground: "24 9.8% 10%", - primary: "24 9.8% 10%", - primaryForeground: "0 0% 100%", - secondary: "60 2.1% 90.8%", - secondaryForeground: "24 9.8% 10%", - muted: "60 1.6% 87.6%", - mutedForeground: "30 2% 39.2%", - accent: "24 9.8% 10%", - accentForeground: "0 0% 100%", - destructive: "24 9.8% 10%", - destructiveForeground: "0 0% 100%", - border: "60 1.1% 81.4%", - input: "60 1.1% 81.4%", - ring: "24 9.8% 10%", - }, - }, - { - id: "monokai-pro-spectrum", - name: "Monokai Pro Spectrum", - tokens: { - background: "28.2 54.8% 93.9%", - foreground: "289.1 13.6% 15.9%", - card: "30 57.1% 97.3%", - cardForeground: "289.1 13.6% 15.9%", - popover: "30 57.1% 97.3%", - popoverForeground: "289.1 13.6% 15.9%", - primary: "34.8 96.7% 35.3%", - primaryForeground: "0 0% 0%", - secondary: "30 27.6% 88.6%", - secondaryForeground: "289.1 13.6% 15.9%", - muted: "30 22.2% 85.9%", - mutedForeground: "326.7 4.1% 42.5%", - accent: "34.8 96.7% 35.3%", - accentForeground: "0 0% 0%", - destructive: "341.8 57.9% 54.3%", - destructiveForeground: "0 0% 0%", - border: "28 14.6% 79.8%", - input: "28 14.6% 79.8%", - ring: "34.8 96.7% 35.3%", - }, - }, - { - id: "monospace", - name: "Monospace", - tokens: { - background: "0 0% 100%", - foreground: "216.9 29.5% 17.3%", - card: "0 0% 100%", - cardForeground: "216.9 29.5% 17.3%", - popover: "0 0% 100%", - popoverForeground: "216.9 29.5% 17.3%", - primary: "196.7 100% 31.8%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 94.5%", - secondaryForeground: "216.9 29.5% 17.3%", - muted: "0 0% 91.4%", - mutedForeground: "215.3 7.4% 45.3%", - accent: "196.7 100% 31.8%", - accentForeground: "0 0% 100%", - destructive: "356.8 61.6% 52%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "196.7 100% 31.8%", - }, - }, - { - id: "noctis-azureus", - name: "Noctis Azureus", - tokens: { - background: "40 90% 96.1%", - foreground: "186.8 100% 19%", - card: "40 100% 98.2%", - cardForeground: "186.8 100% 19%", - popover: "40 100% 98.2%", - popoverForeground: "186.8 100% 19%", - primary: "203 100% 47.1%", - primaryForeground: "0 0% 0%", - secondary: "38.8 36.2% 90.8%", - secondaryForeground: "186.8 100% 19%", - muted: "41.2 25.8% 87.8%", - mutedForeground: "183.1 25.2% 45.1%", - accent: "203 100% 47.1%", - accentForeground: "0 0% 0%", - destructive: "15.1 78% 50%", - destructiveForeground: "0 0% 0%", - border: "40 16.1% 81.8%", - input: "40 16.1% 81.8%", - ring: "203 100% 47.1%", - }, - }, - { - id: "noctis-hibernus", - name: "Noctis Hibernus", - tokens: { - background: "180 10% 96.1%", - foreground: "186.8 100% 19%", - card: "180 11.1% 98.2%", - cardForeground: "186.8 100% 19%", - popover: "180 11.1% 98.2%", - popoverForeground: "186.8 100% 19%", - primary: "203 100% 47.1%", - primaryForeground: "0 0% 0%", - secondary: "180 2.1% 90.8%", - secondaryForeground: "186.8 100% 19%", - muted: "180 3.2% 87.8%", - mutedForeground: "187.4 28.1% 45.3%", - accent: "203 100% 47.1%", - accentForeground: "0 0% 0%", - destructive: "15.1 78% 50%", - destructiveForeground: "0 0% 0%", - border: "180 2.1% 81.6%", - input: "180 2.1% 81.6%", - ring: "203 100% 47.1%", - }, - }, - { - id: "noir-essence", - name: "Noir Essence", - tokens: { - background: "41.5 44.8% 94.3%", - foreground: "0 0% 0%", - card: "48 38.5% 97.5%", - cardForeground: "0 0% 0%", - popover: "48 38.5% 97.5%", - popoverForeground: "0 0% 0%", - primary: "54.1 100% 23.9%", - primaryForeground: "0 0% 100%", - secondary: "45 21.4% 89%", - secondaryForeground: "0 0% 0%", - muted: "40 17.1% 86.3%", - mutedForeground: "45 2.4% 32.2%", - accent: "54.1 100% 23.9%", - accentForeground: "0 0% 100%", - destructive: "3 56.6% 58.4%", - destructiveForeground: "0 0% 0%", - border: "43.6 10.9% 80.2%", - input: "43.6 10.9% 80.2%", - ring: "54.1 100% 23.9%", - }, - }, - { - id: "nord-midnight", - name: "Nord Midnight", - tokens: { - background: "217.5 26.7% 94.1%", - foreground: "220 16.4% 21.6%", - card: "210 28.6% 97.3%", - cardForeground: "220 16.4% 21.6%", - popover: "210 28.6% 97.3%", - popoverForeground: "220 16.4% 21.6%", - primary: "187.1 83% 30%", - primaryForeground: "0 0% 100%", - secondary: "217.5 14.3% 89%", - secondaryForeground: "220 16.4% 21.6%", - muted: "214.3 9.9% 86.1%", - mutedForeground: "218.6 5.9% 46.3%", - accent: "187.1 83% 30%", - accentForeground: "0 0% 100%", - destructive: "354.3 42.3% 56.5%", - destructiveForeground: "0 0% 0%", - border: "220 5.9% 80%", - input: "220 5.9% 80%", - ring: "187.1 83% 30%", - }, - }, - { - id: "notionish", - name: "Notionish", - tokens: { - background: "0 0% 100%", - foreground: "60 2% 9.6%", - card: "0 0% 100%", - cardForeground: "60 2% 9.6%", - popover: "0 0% 100%", - popoverForeground: "60 2% 9.6%", - primary: "208.4 100% 43.5%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "60 2% 9.6%", - muted: "0 0% 91.4%", - mutedForeground: "0 0% 40.4%", - accent: "208.4 100% 43.5%", - accentForeground: "0 0% 0%", - destructive: "7.2 83.8% 48.4%", - destructiveForeground: "0 0% 0%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "208.4 100% 43.5%", - }, - }, - { - id: "phonebook", - name: "Phonebook", - tokens: { - background: "35.6 37.2% 83.1%", - foreground: "31.3 45.1% 20%", - card: "36 38.5% 92.4%", - cardForeground: "31.3 45.1% 20%", - popover: "36 38.5% 92.4%", - popoverForeground: "31.3 45.1% 20%", - primary: "186.5 100% 37.8%", - primaryForeground: "0 0% 0%", - secondary: "36 27.3% 78.4%", - secondaryForeground: "31.3 45.1% 20%", - muted: "36 24.6% 76.1%", - mutedForeground: "32.2 19.4% 41.4%", - accent: "186.5 100% 37.8%", - accentForeground: "0 0% 0%", - destructive: "4 89.9% 61%", - destructiveForeground: "0 0% 0%", - border: "35.6 18.1% 70.8%", - input: "35.6 18.1% 70.8%", - ring: "186.5 100% 37.8%", - }, - }, - { - id: "polychrome", - name: "Polychrome", - tokens: { - background: "30 20% 98%", - foreground: "255.6 60% 44.1%", - card: "60 20% 99%", - cardForeground: "255.6 60% 44.1%", - popover: "60 20% 99%", - popoverForeground: "255.6 60% 44.1%", - primary: "255.3 86.5% 59.2%", - primaryForeground: "0 0% 100%", - secondary: "30 5.3% 92.5%", - secondaryForeground: "255.6 60% 44.1%", - muted: "30 3.8% 89.8%", - mutedForeground: "255.7 45.8% 62.4%", - accent: "255.3 86.5% 59.2%", - accentForeground: "0 0% 100%", - destructive: "0 90.2% 56.1%", - destructiveForeground: "0 0% 0%", - border: "60 1.2% 83.3%", - input: "60 1.2% 83.3%", - ring: "255.3 86.5% 59.2%", - }, - }, - { - id: "purplepeter", - name: "Purplepeter", - tokens: { - background: "261.8 40.7% 94.7%", - foreground: "258.6 55.3% 14.9%", - card: "264 38.5% 97.5%", - cardForeground: "258.6 55.3% 14.9%", - popover: "264 38.5% 97.5%", - popoverForeground: "258.6 55.3% 14.9%", - primary: "190.2 83.9% 31.6%", - primaryForeground: "0 0% 100%", - secondary: "264 18.5% 89.4%", - secondaryForeground: "258.6 55.3% 14.9%", - muted: "264 14.7% 86.7%", - mutedForeground: "258.8 15% 42%", - accent: "190.2 83.9% 31.6%", - accentForeground: "0 0% 100%", - destructive: "0 41.9% 48.6%", - destructiveForeground: "0 0% 100%", - border: "260 9.1% 80.6%", - input: "260 9.1% 80.6%", - ring: "190.2 83.9% 31.6%", - }, - }, - { - id: "rainglow-codecourse", - name: "Rainglow Codecourse", - tokens: { - background: "0 0% 100%", - foreground: "197.7 26.6% 44.9%", - card: "0 0% 100%", - cardForeground: "197.7 26.6% 44.9%", - popover: "0 0% 100%", - popoverForeground: "197.7 26.6% 44.9%", - primary: "202.7 97.4% 55.3%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "197.7 26.6% 44.9%", - muted: "0 0% 91.4%", - mutedForeground: "196.5 21.5% 63.5%", - accent: "202.7 97.4% 55.3%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "202.7 97.4% 55.3%", - }, - }, - { - id: "rainglow-crisp", - name: "Rainglow Crisp", - tokens: { - background: "0 0% 100%", - foreground: "300 13.3% 11.8%", - card: "0 0% 100%", - cardForeground: "300 13.3% 11.8%", - popover: "0 0% 100%", - popoverForeground: "300 13.3% 11.8%", - primary: "23 97.5% 52.4%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "300 13.3% 11.8%", - muted: "0 0% 91.4%", - mutedForeground: "300 2.3% 41.8%", - accent: "23 97.5% 52.4%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "23 97.5% 52.4%", - }, - }, - { - id: "rainglow-lavender", - name: "Rainglow Lavender", - tokens: { - background: "0 0% 100%", - foreground: "275 15% 15.7%", - card: "0 0% 100%", - cardForeground: "275 15% 15.7%", - popover: "0 0% 100%", - popoverForeground: "275 15% 15.7%", - primary: "273.9 100% 67.1%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "275 15% 15.7%", - muted: "0 0% 91.4%", - mutedForeground: "277.5 3.5% 44.3%", - accent: "273.9 100% 67.1%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "273.9 100% 67.1%", - }, - }, - { - id: "remedy-tilted", - name: "Remedy Tilted", - tokens: { - background: "41.1 90.5% 95.9%", - foreground: "39.2 72% 19.6%", - card: "40 100% 98.2%", - cardForeground: "39.2 72% 19.6%", - popover: "40 100% 98.2%", - popoverForeground: "39.2 72% 19.6%", - primary: "24.6 65.8% 62.2%", - primaryForeground: "0 0% 0%", - secondary: "40 37.5% 90.6%", - secondaryForeground: "39.2 72% 19.6%", - muted: "42.4 27% 87.6%", - mutedForeground: "40 23.3% 45.5%", - accent: "24.6 65.8% 62.2%", - accentForeground: "0 0% 0%", - destructive: "0 42.9% 45.3%", - destructiveForeground: "0 0% 100%", - border: "41.2 17% 81.6%", - input: "41.2 17% 81.6%", - ring: "24.6 65.8% 62.2%", - }, - }, - { - id: "rose-pine", - name: "Rosé Pine", - tokens: { - background: "32.3 56.5% 95.5%", - foreground: "247.7 19.2% 39.8%", - card: "30 60% 98%", - cardForeground: "247.7 19.2% 39.8%", - popover: "30 60% 98%", - popoverForeground: "247.7 19.2% 39.8%", - primary: "34.6 81.2% 56.1%", - primaryForeground: "0 0% 0%", - secondary: "35 24% 90.2%", - secondaryForeground: "247.7 19.2% 39.8%", - muted: "30 18.8% 87.5%", - mutedForeground: "253 10.8% 58.2%", - accent: "34.6 81.2% 56.1%", - accentForeground: "0 0% 0%", - destructive: "343 35.1% 54.7%", - destructiveForeground: "0 0% 0%", - border: "30 12.5% 81.2%", - input: "30 12.5% 81.2%", - ring: "34.6 81.2% 56.1%", - }, - }, - { - id: "selene-selenized", - name: "Selene Selenized", - tokens: { - background: "41.7 94.7% 92.5%", - foreground: "193.8 18.8% 27.1%", - card: "42.4 100% 96.7%", - cardForeground: "193.8 18.8% 27.1%", - popover: "42.4 100% 96.7%", - popoverForeground: "193.8 18.8% 27.1%", - primary: "207.1 100% 41.2%", - primaryForeground: "0 0% 100%", - secondary: "42.4 53.1% 87.5%", - secondaryForeground: "193.8 18.8% 27.1%", - muted: "41.8 41.8% 84.5%", - mutedForeground: "150 3.9% 50.2%", - accent: "207.1 100% 41.2%", - accentForeground: "0 0% 100%", - destructive: "356.6 73.1% 48%", - destructiveForeground: "0 0% 100%", - border: "42.6 28.4% 78.6%", - input: "42.6 28.4% 78.6%", - ring: "207.1 100% 41.2%", - }, - }, - { - id: "soft-color", - name: "Soft Color", - tokens: { - background: "95 100% 97.6%", - foreground: "0 0% 35.3%", - card: "96 100% 99%", - cardForeground: "0 0% 35.3%", - popover: "96 100% 99%", - popoverForeground: "0 0% 35.3%", - primary: "211.3 95.3% 33.1%", - primaryForeground: "0 0% 100%", - secondary: "98.2 28.2% 92.4%", - secondaryForeground: "0 0% 35.3%", - muted: "92.7 20% 89.2%", - mutedForeground: "90 1.8% 56.5%", - accent: "211.3 95.3% 33.1%", - accentForeground: "0 0% 100%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "96 11.6% 83.1%", - input: "96 11.6% 83.1%", - ring: "211.3 95.3% 33.1%", - }, - }, - { - id: "tearout", - name: "Tearout", - tokens: { - background: "96.9 26.5% 90.4%", - foreground: "90 7.9% 14.9%", - card: "100 27.3% 95.7%", - cardForeground: "90 7.9% 14.9%", - popover: "100 27.3% 95.7%", - popoverForeground: "90 7.9% 14.9%", - primary: "22.5 36.4% 34.5%", - primaryForeground: "0 0% 100%", - secondary: "100 16.2% 85.5%", - secondaryForeground: "90 7.9% 14.9%", - muted: "95 13.6% 82.7%", - mutedForeground: "93.3 4.3% 40.6%", - accent: "22.5 36.4% 34.5%", - accentForeground: "0 0% 100%", - destructive: "6.7 33.3% 42.4%", - destructiveForeground: "0 0% 100%", - border: "92.7 9.2% 76.7%", - input: "92.7 9.2% 76.7%", - ring: "22.5 36.4% 34.5%", - }, - }, - { - id: "tokyo-night", - name: "Tokyo Night", - tokens: { - background: "230 11.1% 89.4%", - foreground: "221.9 55.3% 48.2%", - card: "240 8.3% 95.3%", - cardForeground: "221.9 55.3% 48.2%", - popover: "240 8.3% 95.3%", - popoverForeground: "221.9 55.3% 48.2%", - primary: "195.1 100% 29.6%", - primaryForeground: "0 0% 100%", - secondary: "228 6.3% 84.5%", - secondaryForeground: "221.9 55.3% 48.2%", - muted: "228 5.4% 81.8%", - mutedForeground: "222.4 47.9% 62.4%", - accent: "195.1 100% 29.6%", - accentForeground: "0 0% 100%", - destructive: "342.6 91% 56.3%", - destructiveForeground: "0 0% 0%", - border: "228 4.1% 75.9%", - input: "228 4.1% 75.9%", - ring: "195.1 100% 29.6%", - }, - }, - { - id: "tomorrow-night-eighties", - name: "Tomorrow Night Eighties", - tokens: { - background: "0 0% 100%", - foreground: "60 0.7% 30%", - card: "0 0% 100%", - cardForeground: "60 0.7% 30%", - popover: "0 0% 100%", - popoverForeground: "60 0.7% 30%", - primary: "71.6 100% 27.5%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 94.5%", - secondaryForeground: "60 0.7% 30%", - muted: "0 0% 91.4%", - mutedForeground: "60 0.4% 53.9%", - accent: "71.6 100% 27.5%", - accentForeground: "0 0% 0%", - destructive: "359.6 66.7% 47.1%", - destructiveForeground: "0 0% 100%", - border: "0 0% 85.1%", - input: "0 0% 85.1%", - ring: "71.6 100% 27.5%", - }, - }, - { - id: "vaporizer-turquoise", - name: "Vaporizer Turquoise", - tokens: { - background: "0 0% 95.3%", - foreground: "117.5 50% 18.8%", - card: "0 0% 98%", - cardForeground: "117.5 50% 18.8%", - popover: "0 0% 98%", - popoverForeground: "117.5 50% 18.8%", - primary: "300 94.8% 37.8%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 90.2%", - secondaryForeground: "117.5 50% 18.8%", - muted: "0 0% 87.1%", - mutedForeground: "116.3 14% 44.7%", - accent: "300 94.8% 37.8%", - accentForeground: "0 0% 100%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 81.2%", - input: "0 0% 81.2%", - ring: "300 94.8% 37.8%", - }, - }, - { - id: "xotopio", - name: "Xotopio", - tokens: { - background: "20 15.8% 96.3%", - foreground: "0 0% 12.9%", - card: "60 11.1% 98.2%", - cardForeground: "0 0% 12.9%", - popover: "60 11.1% 98.2%", - popoverForeground: "0 0% 12.9%", - primary: "331 64.2% 55.1%", - primaryForeground: "0 0% 0%", - secondary: "30 4.3% 91%", - secondaryForeground: "0 0% 12.9%", - muted: "20 4.9% 88%", - mutedForeground: "0 0.5% 41.4%", - accent: "331 64.2% 55.1%", - accentForeground: "0 0% 0%", - destructive: "0.7 71.2% 55.1%", - destructiveForeground: "0 0% 0%", - border: "20 3.2% 81.8%", - input: "20 3.2% 81.8%", - ring: "331 64.2% 55.1%", - }, - }, - { - id: "yuttari", - name: "Yuttari", - tokens: { - background: "336.7 100% 96.5%", - foreground: "334.3 10.4% 26.3%", - card: "337.5 100% 98.4%", - cardForeground: "334.3 10.4% 26.3%", - popover: "337.5 100% 98.4%", - popoverForeground: "334.3 10.4% 26.3%", - primary: "223.5 30.4% 60%", - primaryForeground: "0 0% 0%", - secondary: "335.3 37.8% 91.2%", - secondaryForeground: "334.3 10.4% 26.3%", - muted: "337.5 26.7% 88.2%", - mutedForeground: "333.8 6.3% 50.2%", - accent: "223.5 30.4% 60%", - accentForeground: "0 0% 0%", - destructive: "0 38.8% 54.5%", - destructiveForeground: "0 0% 0%", - border: "337.5 17.4% 82%", - input: "337.5 17.4% 82%", - ring: "223.5 30.4% 60%", - }, - }, - { - id: "zenbones-rosebones", - name: "Zenbones Rosebones", - tokens: { - background: "32.7 57.9% 96.3%", - foreground: "2.4 27.4% 35.1%", - card: "36 55.6% 98.2%", - cardForeground: "2.4 27.4% 35.1%", - popover: "36 55.6% 98.2%", - popoverForeground: "2.4 27.4% 35.1%", - primary: "34.4 83% 56.3%", - primaryForeground: "0 0% 0%", - secondary: "30 21.7% 91%", - secondaryForeground: "2.4 27.4% 35.1%", - muted: "30 16.7% 88.2%", - mutedForeground: "5 16.1% 56.1%", - accent: "34.4 83% 56.3%", - accentForeground: "0 0% 0%", - destructive: "343.2 35.7% 54.9%", - destructiveForeground: "0 0% 0%", - border: "33.3 9.7% 81.8%", - input: "33.3 9.7% 81.8%", - ring: "34.4 83% 56.3%", - }, - }, - { - id: "zhxo-red", - name: "Zhxo'red", - tokens: { - background: "24 100% 97.1%", - foreground: "240 10.1% 51.6%", - card: "25.7 100% 98.6%", - cardForeground: "240 10.1% 51.6%", - popover: "25.7 100% 98.6%", - popoverForeground: "240 10.1% 51.6%", - primary: "284.1 83.8% 45.9%", - primaryForeground: "0 0% 100%", - secondary: "21.4 33.3% 91.8%", - secondaryForeground: "240 10.1% 51.6%", - muted: "23.1 22.8% 88.8%", - mutedForeground: "252 8.8% 66.5%", - accent: "284.1 83.8% 45.9%", - accentForeground: "0 0% 100%", - destructive: "0 53.4% 50.4%", - destructiveForeground: "0 0% 100%", - border: "23.1 14.6% 82.5%", - input: "23.1 14.6% 82.5%", - ring: "284.1 83.8% 45.9%", - }, - } + defineUiTheme("a-cup-of-coffee", "A cup of coffee", { + background: "0 0% 98.4%", + foreground: "0 0% 0%", + card: "0 0% 99.2%", + primary: "211.3 95.3% 33.1%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 92.9%", + muted: "0 0% 90.2%", + mutedForeground: "0 0% 33.3%", + destructive: "0 61.4% 49.8%", + border: "0 0% 83.5%", + }), + defineUiTheme("abolkog", "ABOLKOG", { + background: "0 0% 100%", + foreground: "210 12.2% 16.1%", + card: "0 0% 100%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "205.7 3.1% 44.5%", + destructive: "354.3 42.3% 56.5%", + border: "0 0% 85.1%", + }), + defineUiTheme("aurora", "Aurora", { + background: "44.5 88.6% 93.1%", + foreground: "40.5 100% 14.5%", + card: "47.1 87.5% 96.9%", + primary: "171.4 100% 22%", + primaryForeground: "0 0% 100%", + secondary: "45.5 47.5% 88%", + muted: "45 36.8% 85.1%", + mutedForeground: "41 28.6% 41.2%", + destructive: "341.7 100% 36.1%", + border: "43.8 24.5% 79.2%", + }), + defineUiTheme("ayu", "Ayu", { + background: "210 16.7% 97.6%", + foreground: "210 5.2% 38%", + card: "240 20% 99%", + primary: "75.1 100% 35.1%", + primaryForeground: "0 0% 0%", + secondary: "210 5% 92.2%", + muted: "210 3.7% 89.4%", + mutedForeground: "205.7 3.3% 58.2%", + destructive: "0 80.9% 69.2%", + border: "210 2.3% 83.1%", + }), + defineUiTheme("base16-flat", "Base16 Flat", { + background: "192 15.2% 93.5%", + foreground: "184.3 5.8% 52.5%", + card: "200 20% 97.1%", + primary: "204.1 69.9% 53.1%", + primaryForeground: "0 0% 0%", + secondary: "192 8.5% 88.4%", + muted: "192 6.8% 85.7%", + mutedForeground: "185.5 6.4% 66.5%", + destructive: "5.6 78.1% 57.1%", + border: "195 3.8% 79.6%", + }), + defineUiTheme("base16-mocha", "Base16 Mocha", { + background: "18 33.3% 94.1%", + foreground: "30 22% 32.2%", + card: "12 38.5% 97.5%", + primary: "16.1 51.9% 63.3%", + primaryForeground: "0 0% 0%", + secondary: "18 17.9% 89%", + muted: "20 12.7% 86.1%", + mutedForeground: "28.9 11.3% 53.1%", + destructive: "347.1 50.7% 58.6%", + border: "15 7.8% 80%", + }), + defineUiTheme("blue-dolphin", "Blue Dolphin", { + background: "195 40% 94.1%", + foreground: "193.2 65.8% 14.9%", + card: "192 38.5% 97.5%", + primary: "195 100% 25.1%", + primaryForeground: "0 0% 100%", + secondary: "190.9 19.3% 88.8%", + muted: "196.4 15.5% 86.1%", + mutedForeground: "193 17.4% 41.8%", + destructive: "353.3 64.3% 43.9%", + border: "192 9.8% 80%", + }), + defineUiTheme("calm-days-sober-nights-sky", "Calm Days, Sober Nights Sky", { + background: "0 0% 100%", + foreground: "221.5 11.1% 45.9%", + card: "0 0% 100%", + primary: "142.1 100% 35.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "220 9.9% 64.3%", + destructive: "350.1 76% 67.3%", + border: "0 0% 85.1%", + }), + defineUiTheme("catppuccin", "Catppuccin", { + background: "220 23.1% 94.9%", + foreground: "233.8 16% 35.5%", + card: "220 27.3% 97.8%", + primary: "219.9 91.5% 53.9%", + primaryForeground: "0 0% 100%", + secondary: "220 11.5% 89.8%", + muted: "216 7.5% 86.9%", + mutedForeground: "231.8 9.7% 55.7%", + destructive: "347.1 86.7% 44.1%", + border: "216 5.1% 80.6%", + }), + defineUiTheme("chai", "Chai", { + background: "0 0% 96.9%", + foreground: "228 8.2% 23.9%", + card: "0 0% 98.4%", + primary: "262.9 85.6% 59.2%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 91.4%", + muted: "0 0% 88.6%", + mutedForeground: "231.4 2.8% 48.8%", + destructive: "344.9 69.7% 49.2%", + border: "0 0% 82.4%", + }), + defineUiTheme("chinolor", "Chinolor", { + background: "38.2 44% 95.1%", + foreground: "130 6.5% 18%", + card: "36 45.5% 97.8%", + primary: "48.2 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "42 19.2% 89.8%", + muted: "36 15.2% 87.1%", + mutedForeground: "84 2.2% 44.1%", + destructive: "355.2 83.7% 59%", + border: "36 10.2% 80.8%", + destructiveForeground: "0 0% 0%", + }), + defineUiTheme("cyberdyne", "Cyberdyne", { + background: "248.6 22.6% 93.9%", + foreground: "153.9 69.7% 12.9%", + card: "255 28.6% 97.3%", + primary: "213 100% 31.4%", + primaryForeground: "0 0% 100%", + secondary: "248.6 12.3% 88.8%", + muted: "250 8.3% 85.9%", + mutedForeground: "158 14.7% 40%", + destructive: "9 76.9% 40.8%", + border: "240 5.9% 80%", + }), + defineUiTheme("desert", "Desert", { + background: "34.3 22.6% 93.9%", + foreground: "27.6 74.5% 20%", + card: "30 28.6% 97.3%", + primary: "147.7 100% 20.4%", + primaryForeground: "0 0% 100%", + secondary: "34.3 12.3% 88.8%", + muted: "40 8.3% 85.9%", + mutedForeground: "27.7 22.6% 45.1%", + destructive: "0 100% 36.1%", + border: "30 5.9% 80%", + }), + defineUiTheme("django-reborn-again", "Django Reborn Again", { + background: "150 26.7% 94.1%", + foreground: "155 47.4% 14.9%", + card: "150 28.6% 97.3%", + primary: "51.1 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "150 14.3% 89%", + muted: "154.3 9.9% 86.1%", + mutedForeground: "155.6 12.7% 41.8%", + destructive: "20.9 100% 36.1%", + border: "150 5.9% 80%", + }), + defineUiTheme("espresso", "Espresso", { + background: "46.7 23.1% 92.4%", + foreground: "180 37.9% 17.1%", + card: "45 22.2% 96.5%", + primary: "195.8 20.4% 36.5%", + primaryForeground: "0 0% 100%", + secondary: "46.7 13.8% 87.3%", + muted: "46.7 11.4% 84.5%", + mutedForeground: "171.8 10% 43.1%", + destructive: "0 27.4% 48.6%", + border: "45 7.3% 78.4%", + }), + defineUiTheme("eyehealth", "EyeHealth", { + background: "47 100% 95.5%", + foreground: "22.4 31.2% 42.2%", + card: "48 100% 98%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "46.4 44% 90.2%", + muted: "48.6 32.3% 87.3%", + mutedForeground: "25.4 25.7% 60.4%", + destructive: "354 67% 56.1%", + border: "48 20.8% 81.2%", + }), + defineUiTheme("flexoki", "Flexoki", { + background: "48 100% 97.1%", + foreground: "0 3.2% 6.1%", + card: "51.4 100% 98.6%", + primary: "45.3 98.9% 34.1%", + primaryForeground: "0 0% 0%", + secondary: "47.1 33.3% 91.8%", + muted: "50.8 22.8% 88.8%", + mutedForeground: "48 2.6% 37.1%", + destructive: "3.1 62% 42.4%", + border: "46.2 14.6% 82.5%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("fox", "Fox", { + background: "30 30.8% 94.9%", + foreground: "263 35.3% 26.1%", + card: "30 33.3% 97.6%", + primary: "28.9 97.7% 34.1%", + primaryForeground: "0 0% 100%", + secondary: "34.3 13.2% 89.6%", + muted: "25.7 10.4% 86.9%", + mutedForeground: "266.9 11.6% 49.2%", + destructive: "354 65.8% 39%", + border: "34.3 7.1% 80.6%", + }), + defineUiTheme("garbage-oracle", "Garbage Oracle", { + background: "303.8 38.1% 91.8%", + foreground: "320.9 100% 26.5%", + card: "300 36.8% 96.3%", + primary: "22.7 66.2% 29%", + primaryForeground: "0 0% 100%", + secondary: "304 22.4% 86.9%", + muted: "300 17.1% 83.9%", + mutedForeground: "319.8 37.9% 48.6%", + destructive: "352.2 54.7% 41.6%", + border: "304.3 12.5% 78%", + }), + defineUiTheme("github", "GitHub", { + background: "0 0% 100%", + foreground: "213.3 12.7% 13.9%", + card: "0 0% 100%", + primary: "212.4 92.1% 44.5%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "210 2.7% 43.1%", + destructive: "355.8 71.8% 47.3%", + border: "0 0% 85.1%", + }), + defineUiTheme("gruvbox-material", "Gruvbox Material", { + background: "48.5 86.7% 88.2%", + foreground: "22.5 31.2% 30.2%", + card: "49.6 85.2% 94.7%", + primary: "36.5 90.5% 37.1%", + primaryForeground: "0 0% 0%", + secondary: "49 57.6% 83.3%", + muted: "48.8 49% 80.8%", + mutedForeground: "31.8 19.2% 50%", + destructive: "0 49% 52.4%", + border: "49.1 34.4% 74.9%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("homebrew", "Homebrew", { + background: "120 40% 94.1%", + foreground: "120 65.8% 14.9%", + card: "120 38.5% 97.5%", + primary: "300 100% 23.5%", + primaryForeground: "0 0% 100%", + secondary: "120 19.3% 88.8%", + muted: "120 15.5% 86.1%", + mutedForeground: "120 17.4% 41.8%", + destructive: "0 100% 23.9%", + border: "120 9.8% 80%", + }), + defineUiTheme("ic-orange-ppl", "IC Orange PPL", { + background: "35 40% 94.1%", + foreground: "34.8 65.8% 14.9%", + card: "36 38.5% 97.5%", + primary: "24 100% 23.5%", + primaryForeground: "0 0% 100%", + secondary: "38.2 19.3% 88.8%", + muted: "38.2 15.5% 86.1%", + mutedForeground: "35.7 17.4% 41.8%", + destructive: "14.1 100% 26.7%", + border: "36 9.8% 80%", + }), + defineUiTheme("ikki", "IKKI", { + background: "43.6 100% 97.8%", + foreground: "22.4 31.2% 42.2%", + card: "48 100% 99%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "42 26.3% 92.5%", + muted: "48 18.5% 89.4%", + mutedForeground: "23.7 24.2% 61.2%", + destructive: "354 67% 56.1%", + border: "42 11.6% 83.1%", + }), + defineUiTheme("kanso-ink", "Kanso Ink", { + background: "40 10.3% 94.3%", + foreground: "218.2 13.9% 15.5%", + card: "60 7.7% 97.5%", + primary: "351.6 55.3% 51.8%", + primaryForeground: "0 0% 100%", + secondary: "40 5.5% 89.2%", + muted: "60 2.9% 86.3%", + mutedForeground: "220 2.8% 42.4%", + destructive: "351.6 55.3% 51.8%", + border: "40 3% 80.2%", + }), + defineUiTheme("kary-pro-colors", "Kary Pro Colors", { + background: "207.3 57.9% 96.3%", + foreground: "209.5 53.8% 46.7%", + card: "204 55.6% 98.2%", + primary: "32.7 76.5% 36.7%", + primaryForeground: "0 0% 100%", + secondary: "210 21.7% 91%", + muted: "210 16.7% 88.2%", + mutedForeground: "209.3 47.3% 63.5%", + destructive: "13.1 69.6% 46.5%", + border: "206.7 9.7% 81.8%", + }), + defineUiTheme("light-purple", "Light purple", { + background: "10 15.8% 92.5%", + foreground: "274.8 33.8% 29%", + card: "20 17.6% 96.7%", + primary: "46.8 98.2% 44.3%", + primaryForeground: "0 0% 0%", + secondary: "10 9.4% 87.5%", + muted: "10 7.7% 84.7%", + mutedForeground: "278.2 13% 50.4%", + destructive: "0.7 71.2% 55.1%", + border: "12 4.6% 78.6%", + }), + defineUiTheme("mondrian", "Mondrian", { + background: "0 0% 100%", + foreground: "0 0% 0%", + card: "0 0% 100%", + primary: "217.4 89% 60.8%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "0 0% 34.1%", + destructive: "4.8 69.5% 53.7%", + border: "0 0% 85.1%", + }), + defineUiTheme("monochrome", "Monochrome", { + background: "210 40% 96.1%", + foreground: "222.2 47.4% 11.2%", + card: "200 33.3% 98.2%", + primary: "222.2 47.4% 11.2%", + primaryForeground: "0 0% 100%", + secondary: "205.7 14.9% 90.8%", + muted: "214.3 11.5% 88%", + mutedForeground: "222 9.8% 40%", + destructive: "222.2 47.4% 11.2%", + border: "214.3 7.5% 81.8%", + }), + defineUiTheme("monochrome-stone", "Monochrome Stone", { + background: "60 4.8% 95.9%", + foreground: "24 9.8% 10%", + card: "60 11.1% 98.2%", + primary: "24 9.8% 10%", + primaryForeground: "0 0% 100%", + secondary: "60 2.1% 90.8%", + muted: "60 1.6% 87.6%", + mutedForeground: "30 2% 39.2%", + destructive: "24 9.8% 10%", + border: "60 1.1% 81.4%", + }), + defineUiTheme("monokai-pro-spectrum", "Monokai Pro Spectrum", { + background: "28.2 54.8% 93.9%", + foreground: "289.1 13.6% 15.9%", + card: "30 57.1% 97.3%", + primary: "34.8 96.7% 35.3%", + primaryForeground: "0 0% 0%", + secondary: "30 27.6% 88.6%", + muted: "30 22.2% 85.9%", + mutedForeground: "326.7 4.1% 42.5%", + destructive: "341.8 57.9% 54.3%", + border: "28 14.6% 79.8%", + }), + defineUiTheme("monospace", "Monospace", { + background: "0 0% 100%", + foreground: "216.9 29.5% 17.3%", + card: "0 0% 100%", + primary: "196.7 100% 31.8%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "215.3 7.4% 45.3%", + destructive: "356.8 61.6% 52%", + border: "0 0% 85.1%", + }), + defineUiTheme("noctis-azureus", "Noctis Azureus", { + background: "40 90% 96.1%", + foreground: "186.8 100% 19%", + card: "40 100% 98.2%", + primary: "203 100% 47.1%", + primaryForeground: "0 0% 0%", + secondary: "38.8 36.2% 90.8%", + muted: "41.2 25.8% 87.8%", + mutedForeground: "183.1 25.2% 45.1%", + destructive: "15.1 78% 50%", + border: "40 16.1% 81.8%", + }), + defineUiTheme("noctis-hibernus", "Noctis Hibernus", { + background: "180 10% 96.1%", + foreground: "186.8 100% 19%", + card: "180 11.1% 98.2%", + primary: "203 100% 47.1%", + primaryForeground: "0 0% 0%", + secondary: "180 2.1% 90.8%", + muted: "180 3.2% 87.8%", + mutedForeground: "187.4 28.1% 45.3%", + destructive: "15.1 78% 50%", + border: "180 2.1% 81.6%", + }), + defineUiTheme("noir-essence", "Noir Essence", { + background: "41.5 44.8% 94.3%", + foreground: "0 0% 0%", + card: "48 38.5% 97.5%", + primary: "54.1 100% 23.9%", + primaryForeground: "0 0% 100%", + secondary: "45 21.4% 89%", + muted: "40 17.1% 86.3%", + mutedForeground: "45 2.4% 32.2%", + destructive: "3 56.6% 58.4%", + border: "43.6 10.9% 80.2%", + destructiveForeground: "0 0% 0%", + }), + defineUiTheme("nord-midnight", "Nord Midnight", { + background: "217.5 26.7% 94.1%", + foreground: "220 16.4% 21.6%", + card: "210 28.6% 97.3%", + primary: "187.1 83% 30%", + primaryForeground: "0 0% 100%", + secondary: "217.5 14.3% 89%", + muted: "214.3 9.9% 86.1%", + mutedForeground: "218.6 5.9% 46.3%", + destructive: "354.3 42.3% 56.5%", + border: "220 5.9% 80%", + destructiveForeground: "0 0% 0%", + }), + defineUiTheme("notionish", "Notionish", { + background: "0 0% 100%", + foreground: "60 2% 9.6%", + card: "0 0% 100%", + primary: "208.4 100% 43.5%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "0 0% 40.4%", + destructive: "7.2 83.8% 48.4%", + border: "0 0% 85.1%", + }), + defineUiTheme("phonebook", "Phonebook", { + background: "35.6 37.2% 83.1%", + foreground: "31.3 45.1% 20%", + card: "36 38.5% 92.4%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "36 27.3% 78.4%", + muted: "36 24.6% 76.1%", + mutedForeground: "32.2 19.4% 41.4%", + destructive: "4 89.9% 61%", + border: "35.6 18.1% 70.8%", + }), + defineUiTheme("polychrome", "Polychrome", { + background: "30 20% 98%", + foreground: "255.6 60% 44.1%", + card: "60 20% 99%", + primary: "255.3 86.5% 59.2%", + primaryForeground: "0 0% 100%", + secondary: "30 5.3% 92.5%", + muted: "30 3.8% 89.8%", + mutedForeground: "255.7 45.8% 62.4%", + destructive: "0 90.2% 56.1%", + border: "60 1.2% 83.3%", + destructiveForeground: "0 0% 0%", + }), + defineUiTheme("purplepeter", "Purplepeter", { + background: "261.8 40.7% 94.7%", + foreground: "258.6 55.3% 14.9%", + card: "264 38.5% 97.5%", + primary: "190.2 83.9% 31.6%", + primaryForeground: "0 0% 100%", + secondary: "264 18.5% 89.4%", + muted: "264 14.7% 86.7%", + mutedForeground: "258.8 15% 42%", + destructive: "0 41.9% 48.6%", + border: "260 9.1% 80.6%", + }), + defineUiTheme("rainglow-codecourse", "Rainglow Codecourse", { + background: "0 0% 100%", + foreground: "197.7 26.6% 44.9%", + card: "0 0% 100%", + primary: "202.7 97.4% 55.3%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "196.5 21.5% 63.5%", + destructive: "348.8 86% 39.2%", + border: "0 0% 85.1%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rainglow-crisp", "Rainglow Crisp", { + background: "0 0% 100%", + foreground: "300 13.3% 11.8%", + card: "0 0% 100%", + primary: "23 97.5% 52.4%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "300 2.3% 41.8%", + destructive: "348.8 86% 39.2%", + border: "0 0% 85.1%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rainglow-lavender", "Rainglow Lavender", { + background: "0 0% 100%", + foreground: "275 15% 15.7%", + card: "0 0% 100%", + primary: "273.9 100% 67.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "277.5 3.5% 44.3%", + destructive: "348.8 86% 39.2%", + border: "0 0% 85.1%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("remedy-tilted", "Remedy Tilted", { + background: "41.1 90.5% 95.9%", + foreground: "39.2 72% 19.6%", + card: "40 100% 98.2%", + primary: "24.6 65.8% 62.2%", + primaryForeground: "0 0% 0%", + secondary: "40 37.5% 90.6%", + muted: "42.4 27% 87.6%", + mutedForeground: "40 23.3% 45.5%", + destructive: "0 42.9% 45.3%", + border: "41.2 17% 81.6%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rose-pine", "Rosé Pine", { + background: "32.3 56.5% 95.5%", + foreground: "247.7 19.2% 39.8%", + card: "30 60% 98%", + primary: "34.6 81.2% 56.1%", + primaryForeground: "0 0% 0%", + secondary: "35 24% 90.2%", + muted: "30 18.8% 87.5%", + mutedForeground: "253 10.8% 58.2%", + destructive: "343 35.1% 54.7%", + border: "30 12.5% 81.2%", + }), + defineUiTheme("selene-selenized", "Selene Selenized", { + background: "41.7 94.7% 92.5%", + foreground: "193.8 18.8% 27.1%", + card: "42.4 100% 96.7%", + primary: "207.1 100% 41.2%", + primaryForeground: "0 0% 100%", + secondary: "42.4 53.1% 87.5%", + muted: "41.8 41.8% 84.5%", + mutedForeground: "150 3.9% 50.2%", + destructive: "356.6 73.1% 48%", + border: "42.6 28.4% 78.6%", + }), + defineUiTheme("soft-color", "Soft Color", { + background: "95 100% 97.6%", + foreground: "0 0% 35.3%", + card: "96 100% 99%", + primary: "211.3 95.3% 33.1%", + primaryForeground: "0 0% 100%", + secondary: "98.2 28.2% 92.4%", + muted: "92.7 20% 89.2%", + mutedForeground: "90 1.8% 56.5%", + destructive: "0 61.4% 49.8%", + border: "96 11.6% 83.1%", + }), + defineUiTheme("tearout", "Tearout", { + background: "96.9 26.5% 90.4%", + foreground: "90 7.9% 14.9%", + card: "100 27.3% 95.7%", + primary: "22.5 36.4% 34.5%", + primaryForeground: "0 0% 100%", + secondary: "100 16.2% 85.5%", + muted: "95 13.6% 82.7%", + mutedForeground: "93.3 4.3% 40.6%", + destructive: "6.7 33.3% 42.4%", + border: "92.7 9.2% 76.7%", + }), + defineUiTheme("tokyo-night", "Tokyo Night", { + background: "230 11.1% 89.4%", + foreground: "221.9 55.3% 48.2%", + card: "240 8.3% 95.3%", + primary: "195.1 100% 29.6%", + primaryForeground: "0 0% 100%", + secondary: "228 6.3% 84.5%", + muted: "228 5.4% 81.8%", + mutedForeground: "222.4 47.9% 62.4%", + destructive: "342.6 91% 56.3%", + border: "228 4.1% 75.9%", + destructiveForeground: "0 0% 0%", + }), + defineUiTheme("tomorrow-night-eighties", "Tomorrow Night Eighties", { + background: "0 0% 100%", + foreground: "60 0.7% 30%", + card: "0 0% 100%", + primary: "71.6 100% 27.5%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 94.5%", + muted: "0 0% 91.4%", + mutedForeground: "60 0.4% 53.9%", + destructive: "359.6 66.7% 47.1%", + border: "0 0% 85.1%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("vaporizer-turquoise", "Vaporizer Turquoise", { + background: "0 0% 95.3%", + foreground: "117.5 50% 18.8%", + card: "0 0% 98%", + primary: "300 94.8% 37.8%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 90.2%", + muted: "0 0% 87.1%", + mutedForeground: "116.3 14% 44.7%", + destructive: "0 61.4% 49.8%", + border: "0 0% 81.2%", + }), + defineUiTheme("xotopio", "Xotopio", { + background: "20 15.8% 96.3%", + foreground: "0 0% 12.9%", + card: "60 11.1% 98.2%", + primary: "331 64.2% 55.1%", + primaryForeground: "0 0% 0%", + secondary: "30 4.3% 91%", + muted: "20 4.9% 88%", + mutedForeground: "0 0.5% 41.4%", + destructive: "0.7 71.2% 55.1%", + border: "20 3.2% 81.8%", + }), + defineUiTheme("yuttari", "Yuttari", { + background: "336.7 100% 96.5%", + foreground: "334.3 10.4% 26.3%", + card: "337.5 100% 98.4%", + primary: "223.5 30.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "335.3 37.8% 91.2%", + muted: "337.5 26.7% 88.2%", + mutedForeground: "333.8 6.3% 50.2%", + destructive: "0 38.8% 54.5%", + border: "337.5 17.4% 82%", + }), + defineUiTheme("zenbones-rosebones", "Zenbones Rosebones", { + background: "32.7 57.9% 96.3%", + foreground: "2.4 27.4% 35.1%", + card: "36 55.6% 98.2%", + primary: "34.4 83% 56.3%", + primaryForeground: "0 0% 0%", + secondary: "30 21.7% 91%", + muted: "30 16.7% 88.2%", + mutedForeground: "5 16.1% 56.1%", + destructive: "343.2 35.7% 54.9%", + border: "33.3 9.7% 81.8%", + }), + defineUiTheme("zhxo-red", "Zhxo'red", { + background: "24 100% 97.1%", + foreground: "240 10.1% 51.6%", + card: "25.7 100% 98.6%", + primary: "284.1 83.8% 45.9%", + primaryForeground: "0 0% 100%", + secondary: "21.4 33.3% 91.8%", + muted: "23.1 22.8% 88.8%", + mutedForeground: "252 8.8% 66.5%", + destructive: "0 53.4% 50.4%", + border: "23.1 14.6% 82.5%", + }), ]; export const LIGHT_UI_THEMES: UiThemePreset[] = [ @@ -1596,1560 +865,771 @@ export const LIGHT_UI_THEMES: UiThemePreset[] = [ ...EXTENDED_LIGHT_UI_THEMES, ]; -export const EXTENDED_DARK_UI_THEMES: UiThemePreset[] = [ - { - id: "a-cup-of-coffee", - name: "A cup of coffee", - tokens: { - background: "0 0% 11.8%", - foreground: "0 0% 74.5%", - card: "0 0% 15.7%", - cardForeground: "0 0% 74.5%", - popover: "0 0% 15.7%", - popoverForeground: "0 0% 74.5%", - primary: "60 86.9% 48%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 19.2%", - secondaryForeground: "0 0% 74.5%", - muted: "0 0% 24.3%", - mutedForeground: "0 0% 56.9%", - accent: "60 86.9% 48%", - accentForeground: "0 0% 0%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 29.4%", - input: "0 0% 29.4%", - ring: "60 86.9% 48%", - }, - }, - { - id: "abolkog", - name: "ABOLKOG", - tokens: { - background: "220 13% 18%", - foreground: "218.8 27.9% 88%", - card: "223.6 9.9% 21.8%", - cardForeground: "218.8 27.9% 88%", - popover: "223.6 9.9% 21.8%", - popoverForeground: "218.8 27.9% 88%", - primary: "40 70.6% 73.3%", - primaryForeground: "0 0% 0%", - secondary: "218.2 8.7% 24.9%", - secondaryForeground: "218.8 27.9% 88%", - muted: "216 6.7% 29.4%", - mutedForeground: "220 9.3% 68.4%", - accent: "40 70.6% 73.3%", - accentForeground: "0 0% 0%", - destructive: "354.3 42.3% 56.5%", - destructiveForeground: "0 0% 0%", - border: "222 5.7% 34.5%", - input: "222 5.7% 34.5%", - ring: "40 70.6% 73.3%", - }, - }, - { - id: "aurora", - name: "Aurora", - tokens: { - background: "223.6 13.6% 15.9%", - foreground: "45.2 100% 57.8%", - card: "222 10% 19.6%", - cardForeground: "45.2 100% 57.8%", - popover: "222 10% 19.6%", - popoverForeground: "45.2 100% 57.8%", - primary: "171.5 97.2% 42.5%", - primaryForeground: "0 0% 0%", - secondary: "228 8.5% 23.1%", - secondaryForeground: "45.2 100% 57.8%", - muted: "226.7 6.4% 27.6%", - mutedForeground: "45.3 64.3% 46.1%", - accent: "171.5 97.2% 42.5%", - accentForeground: "0 0% 0%", - destructive: "338.3 87.1% 54.5%", - destructiveForeground: "0 0% 0%", - border: "226.7 5.4% 32.7%", - input: "226.7 5.4% 32.7%", - ring: "171.5 97.2% 42.5%", - }, - }, - { - id: "ayu", - name: "Ayu", - tokens: { - background: "222.4 21.5% 15.5%", - foreground: "48 8.9% 78%", - card: "221.3 16.3% 19.2%", - cardForeground: "48 8.9% 78%", - popover: "221.3 16.3% 19.2%", - popoverForeground: "48 8.9% 78%", - primary: "271.3 95.9% 80.8%", - primaryForeground: "0 0% 0%", - secondary: "221.3 13.8% 22.7%", - secondaryForeground: "48 8.9% 78%", - muted: "220 10.8% 27.3%", - mutedForeground: "60 1.5% 60.6%", - accent: "271.3 95.9% 80.8%", - accentForeground: "0 0% 0%", - destructive: "6.1 83.1% 65.1%", - destructiveForeground: "0 0% 0%", - border: "221.5 7.9% 32.4%", - input: "221.5 7.9% 32.4%", - ring: "271.3 95.9% 80.8%", - }, - }, - { - id: "base16-flat", - name: "Base16 Flat", - tokens: { - background: "210 29% 24.3%", - foreground: "0 0% 87.8%", - card: "209.1 24.8% 27.6%", - cardForeground: "0 0% 87.8%", - popover: "209.1 24.8% 27.6%", - popoverForeground: "0 0% 87.8%", - primary: "168.1 75.7% 42%", - primaryForeground: "0 0% 0%", - secondary: "210.9 21% 30.8%", - secondaryForeground: "0 0% 87.8%", - muted: "211 17.3% 35.1%", - mutedForeground: "210 6.6% 70.2%", - accent: "168.1 75.7% 42%", - accentForeground: "0 0% 0%", - destructive: "5.6 78.1% 57.1%", - destructiveForeground: "0 0% 0%", - border: "209 14.4% 39.4%", - input: "209 14.4% 39.4%", - ring: "168.1 75.7% 42%", - }, - }, - { - id: "base16-mocha", - name: "Base16 Mocha", - tokens: { - background: "31.6 19.2% 19.4%", - foreground: "12 9.6% 79.6%", - card: "30 15.3% 23.1%", - cardForeground: "12 9.6% 79.6%", - popover: "30 15.3% 23.1%", - popoverForeground: "12 9.6% 79.6%", - primary: "16.1 51.9% 63.3%", - primaryForeground: "0 0% 0%", - secondary: "30 13.4% 26.3%", - secondaryForeground: "12 9.6% 79.6%", - muted: "33.7 10.3% 30.6%", - mutedForeground: "20 6.3% 62.7%", - accent: "16.1 51.9% 63.3%", - accentForeground: "0 0% 0%", - destructive: "347.1 50.7% 58.6%", - destructiveForeground: "0 0% 0%", - border: "32 8.3% 35.5%", - input: "32 8.3% 35.5%", - ring: "16.1 51.9% 63.3%", - }, - }, - { - id: "blue-dolphin", - name: "Blue Dolphin", - tokens: { - background: "192.3 100% 25.9%", - foreground: "193.4 100% 88.6%", - card: "192.3 85.2% 29.2%", - cardForeground: "193.4 100% 88.6%", - popover: "192.3 85.2% 29.2%", - popoverForeground: "193.4 100% 88.6%", - primary: "218.8 100% 83.3%", - primaryForeground: "0 0% 0%", - secondary: "192 73.2% 32.2%", - secondaryForeground: "193.4 100% 88.6%", - muted: "192.2 61.1% 36.3%", - mutedForeground: "192.9 53.7% 71.2%", - accent: "218.8 100% 83.3%", - accentForeground: "0 0% 0%", - destructive: "357.1 100% 75.5%", - destructiveForeground: "0 0% 0%", - border: "192.5 51% 40.8%", - input: "192.5 51% 40.8%", - ring: "218.8 100% 83.3%", - }, - }, - { - id: "calm-days-sober-nights-sky", - name: "Calm Days, Sober Nights Sky", - tokens: { - background: "221.7 31.5% 14.3%", - foreground: "220 31.3% 86.9%", - card: "220.9 23.9% 18%", - cardForeground: "220 31.3% 86.9%", - popover: "220.9 23.9% 18%", - popoverForeground: "220 31.3% 86.9%", - primary: "198 93.3% 70.6%", - primaryForeground: "0 0% 0%", - secondary: "222.9 18.9% 21.8%", - secondaryForeground: "220 31.3% 86.9%", - muted: "222 14.9% 26.3%", - mutedForeground: "220 12.3% 66.5%", - accent: "198 93.3% 70.6%", - accentForeground: "0 0% 0%", - destructive: "354 77.1% 69.2%", - destructiveForeground: "0 0% 0%", - border: "220 11.2% 31.4%", - input: "220 11.2% 31.4%", - ring: "198 93.3% 70.6%", - }, - }, - { - id: "catppuccin", - name: "Catppuccin", - tokens: { - background: "229.1 18.6% 23.1%", - foreground: "227.2 70.1% 86.9%", - card: "228.6 15.6% 26.5%", - cardForeground: "227.2 70.1% 86.9%", - popover: "228.6 15.6% 26.5%", - popoverForeground: "227.2 70.1% 86.9%", - primary: "316 73.2% 83.9%", - primaryForeground: "0 0% 0%", - secondary: "231 13.2% 29.8%", - secondaryForeground: "227.2 70.1% 86.9%", - muted: "230.5 11% 33.9%", - mutedForeground: "228 25.3% 69%", - accent: "316 73.2% 83.9%", - accentForeground: "0 0% 0%", - destructive: "358.8 67.8% 70.8%", - destructiveForeground: "0 0% 0%", - border: "226.7 9.2% 38.4%", - input: "226.7 9.2% 38.4%", - ring: "316 73.2% 83.9%", - }, - }, - { - id: "chai", - name: "Chai", - tokens: { - background: "240 75% 1.6%", - foreground: "203.6 27.5% 80%", - card: "240 20% 5.9%", - cardForeground: "203.6 27.5% 80%", - popover: "240 20% 5.9%", - popoverForeground: "203.6 27.5% 80%", - primary: "202.9 78.4% 60%", - primaryForeground: "0 0% 0%", - secondary: "240 9.8% 10%", - secondaryForeground: "203.6 27.5% 80%", - muted: "240 6.3% 15.5%", - mutedForeground: "207.3 10.3% 58%", - accent: "202.9 78.4% 60%", - accentForeground: "0 0% 0%", - destructive: "16.8 78.2% 55.1%", - destructiveForeground: "0 0% 0%", - border: "240 4.6% 21.4%", - input: "240 4.6% 21.4%", - ring: "202.9 78.4% 60%", - }, - }, - { - id: "chinolor", - name: "Chinolor", - tokens: { - background: "130 6.5% 18%", - foreground: "36.9 19.4% 86.9%", - card: "120 4.5% 21.8%", - cardForeground: "36.9 19.4% 86.9%", - popover: "120 4.5% 21.8%", - popoverForeground: "36.9 19.4% 86.9%", - primary: "44.4 92.4% 69%", - primaryForeground: "0 0% 0%", - secondary: "130 4.7% 25.1%", - secondaryForeground: "36.9 19.4% 86.9%", - muted: "132 3.3% 29.6%", - mutedForeground: "46.7 5.4% 67.3%", - accent: "44.4 92.4% 69%", - accentForeground: "0 0% 0%", - destructive: "355.2 83.7% 59%", - destructiveForeground: "0 0% 0%", - border: "132 2.9% 34.3%", - input: "132 2.9% 34.3%", - ring: "44.4 92.4% 69%", - }, - }, - { - id: "cyberdyne", - name: "Cyberdyne", - tokens: { - background: "244.7 60% 16.7%", - foreground: "154.4 100% 50%", - card: "245 46.2% 20.4%", - cardForeground: "154.4 100% 50%", - popover: "245 46.2% 20.4%", - popoverForeground: "154.4 100% 50%", - primary: "300.5 100% 78.2%", - primaryForeground: "0 0% 0%", - secondary: "245.1 38.8% 23.7%", - secondaryForeground: "154.4 100% 50%", - muted: "245.5 30.6% 28.2%", - mutedForeground: "158.9 93.8% 38%", - accent: "300.5 100% 78.2%", - accentForeground: "0 0% 0%", - destructive: "6.9 100% 72.5%", - destructiveForeground: "0 0% 0%", - border: "244.5 23.5% 33.3%", - input: "244.5 23.5% 33.3%", - ring: "300.5 100% 78.2%", - }, - }, - { - id: "desert", - name: "Desert", - tokens: { - background: "0 0% 20%", - foreground: "0 0% 100%", - card: "0 0% 23.5%", - cardForeground: "0 0% 100%", - popover: "0 0% 23.5%", - popoverForeground: "0 0% 100%", - primary: "35.9 100% 83.9%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 26.7%", - secondaryForeground: "0 0% 100%", - muted: "0 0% 31.4%", - mutedForeground: "0 0% 77.6%", - accent: "35.9 100% 83.9%", - accentForeground: "0 0% 0%", - destructive: "0 100% 58.4%", - destructiveForeground: "0 0% 0%", - border: "0 0% 36.1%", - input: "0 0% 36.1%", - ring: "35.9 100% 83.9%", - }, - }, - { - id: "django-reborn-again", - name: "Django Reborn Again", - tokens: { - background: "154.6 72.2% 7.1%", - foreground: "150 5.7% 86.3%", - card: "156 43.9% 11.2%", - cardForeground: "150 5.7% 86.3%", - popover: "156 43.9% 11.2%", - popoverForeground: "150 5.7% 86.3%", - primary: "51.2 100% 69.2%", - primaryForeground: "0 0% 0%", - secondary: "155 31.6% 14.9%", - secondaryForeground: "150 5.7% 86.3%", - muted: "155.5 21.6% 20%", - mutedForeground: "152.7 6% 64.1%", - accent: "51.2 100% 69.2%", - accentForeground: "0 0% 0%", - destructive: "21.9 98.4% 51.4%", - destructiveForeground: "0 0% 0%", - border: "154.3 16% 25.7%", - input: "154.3 16% 25.7%", - ring: "51.2 100% 69.2%", - }, - }, - { - id: "espresso", - name: "Espresso", - tokens: { - background: "18 20% 9.8%", - foreground: "33.3 29.5% 76.1%", - card: "13.3 12.7% 13.9%", - cardForeground: "33.3 29.5% 76.1%", - popover: "13.3 12.7% 13.9%", - popoverForeground: "33.3 29.5% 76.1%", - primary: "42.9 70.9% 69%", - primaryForeground: "0 0% 0%", - secondary: "20 10.1% 17.5%", - secondaryForeground: "33.3 29.5% 76.1%", - muted: "13.3 7.8% 22.5%", - mutedForeground: "33.1 13.4% 57.5%", - accent: "42.9 70.9% 69%", - accentForeground: "0 0% 0%", - destructive: "8.6 70.9% 69%", - destructiveForeground: "0 0% 0%", - border: "15 5.6% 27.8%", - input: "15 5.6% 27.8%", - ring: "42.9 70.9% 69%", - }, - }, - { - id: "eyehealth", - name: "EyeHealth", - tokens: { - background: "0 0% 25.9%", - foreground: "0 0% 100%", - card: "0 0% 29.4%", - cardForeground: "0 0% 100%", - popover: "0 0% 29.4%", - popoverForeground: "0 0% 100%", - primary: "35.8 100% 50%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 32.2%", - secondaryForeground: "0 0% 100%", - muted: "0 0% 36.1%", - mutedForeground: "0 0% 79.2%", - accent: "35.8 100% 50%", - accentForeground: "0 0% 0%", - destructive: "354 67% 56.1%", - destructiveForeground: "0 0% 0%", - border: "0 0% 40.8%", - input: "0 0% 40.8%", - ring: "35.8 100% 50%", - }, - }, - { - id: "flexoki", - name: "Flexoki", - tokens: { - background: "0 3.2% 6.1%", - foreground: "54.5 10.1% 78.6%", - card: "0 1.9% 10.4%", - cardForeground: "54.5 10.1% 78.6%", - popover: "0 1.9% 10.4%", - popoverForeground: "54.5 10.1% 78.6%", - primary: "45.2 81.7% 44.9%", - primaryForeground: "0 0% 0%", - secondary: "0 1.4% 13.9%", - secondaryForeground: "54.5 10.1% 78.6%", - muted: "0 0% 19.2%", - mutedForeground: "52.5 3.8% 58.4%", - accent: "45.2 81.7% 44.9%", - accentForeground: "0 0% 0%", - destructive: "5 61% 53.7%", - destructiveForeground: "0 0% 0%", - border: "0 0.8% 24.9%", - input: "0 0.8% 24.9%", - ring: "45.2 81.7% 44.9%", - }, - }, - { - id: "fox", - name: "Fox", - tokens: { - background: "213.9 31.5% 14.3%", - foreground: "210 2% 80.8%", - card: "212.7 23.9% 18%", - cardForeground: "210 2% 80.8%", - popover: "212.7 23.9% 18%", - popoverForeground: "210 2% 80.8%", - primary: "181.1 52.9% 60%", - primaryForeground: "0 0% 0%", - secondary: "214.3 18.9% 21.8%", - secondaryForeground: "210 2% 80.8%", - muted: "213 14.9% 26.3%", - mutedForeground: "214.3 3.6% 62.2%", - accent: "181.1 52.9% 60%", - accentForeground: "0 0% 0%", - destructive: "345.2 53% 54.9%", - destructiveForeground: "0 0% 0%", - border: "213.3 11.2% 31.4%", - input: "213.3 11.2% 31.4%", - ring: "181.1 52.9% 60%", - }, - }, - { - id: "garbage-oracle", - name: "Garbage Oracle", - tokens: { - background: "311.5 31% 16.5%", - foreground: "303.8 38.1% 91.8%", - card: "312 24.3% 20.2%", - cardForeground: "303.8 38.1% 91.8%", - popover: "312 24.3% 20.2%", - popoverForeground: "303.8 38.1% 91.8%", - primary: "124.3 95.4% 82.9%", - primaryForeground: "0 0% 0%", - secondary: "312.5 20% 23.5%", - secondaryForeground: "303.8 38.1% 91.8%", - muted: "310.9 15.3% 28.2%", - mutedForeground: "306.3 12.8% 70.8%", - accent: "124.3 95.4% 82.9%", - accentForeground: "0 0% 0%", - destructive: "359.4 92.8% 78.2%", - destructiveForeground: "0 0% 0%", - border: "311.4 12.4% 33.1%", - input: "311.4 12.4% 33.1%", - ring: "124.3 95.4% 82.9%", - }, - }, - { - id: "github", - name: "GitHub", - tokens: { - background: "216 27.8% 7.1%", - foreground: "207.7 35.1% 92.7%", - card: "213.3 15.8% 11.2%", - cardForeground: "207.7 35.1% 92.7%", - popover: "213.3 15.8% 11.2%", - popoverForeground: "207.7 35.1% 92.7%", - primary: "212 100% 67.3%", - primaryForeground: "0 0% 0%", - secondary: "220 11.7% 15.1%", - secondaryForeground: "207.7 35.1% 92.7%", - muted: "217.5 7.8% 20%", - mutedForeground: "210 7.5% 68.6%", - accent: "212 100% 67.3%", - accentForeground: "0 0% 0%", - destructive: "3.8 100% 72.4%", - destructiveForeground: "0 0% 0%", - border: "210 6.2% 25.5%", - input: "210 6.2% 25.5%", - ring: "212 100% 67.3%", - }, - }, - { - id: "gruvbox-material", - name: "Gruvbox Material", - tokens: { - background: "0 1.2% 15.9%", - foreground: "38 41.1% 71.4%", - card: "0 1% 19.8%", - cardForeground: "38 41.1% 71.4%", - popover: "0 1% 19.8%", - popoverForeground: "38 41.1% 71.4%", - primary: "3.1 76.4% 65.1%", - primaryForeground: "0 0% 0%", - secondary: "0 0.9% 22.9%", - secondaryForeground: "38 41.1% 71.4%", - muted: "0 0.7% 27.6%", - mutedForeground: "37.7 19.1% 55.9%", - accent: "3.1 76.4% 65.1%", - accentForeground: "0 0% 0%", - destructive: "3.1 76.4% 65.1%", - destructiveForeground: "0 0% 0%", - border: "0 0.6% 32.7%", - input: "0 0.6% 32.7%", - ring: "3.1 76.4% 65.1%", - }, - }, - { - id: "homebrew", - name: "Homebrew", - tokens: { - background: "0 0% 0%", - foreground: "120 100% 50%", - card: "0 0% 4.3%", - cardForeground: "120 100% 50%", - popover: "0 0% 4.3%", - popoverForeground: "120 100% 50%", - primary: "184 100% 34.9%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 8.6%", - secondaryForeground: "120 100% 50%", - muted: "0 0% 14.1%", - mutedForeground: "120 100% 36.1%", - accent: "184 100% 34.9%", - accentForeground: "0 0% 0%", - destructive: "0 100% 30%", - destructiveForeground: "0 0% 100%", - border: "0 0% 20%", - input: "0 0% 20%", - ring: "184 100% 34.9%", - }, - }, - { - id: "ic-orange-ppl", - name: "IC Orange PPL", - tokens: { - background: "0 0% 14.9%", - foreground: "34.8 100% 75.7%", - card: "0 0% 18.8%", - cardForeground: "34.8 100% 75.7%", - popover: "0 0% 18.8%", - popoverForeground: "34.8 100% 75.7%", - primary: "36.2 100% 48.4%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 22%", - secondaryForeground: "34.8 100% 75.7%", - muted: "0 0% 26.7%", - mutedForeground: "35.1 42.2% 58.6%", - accent: "36.2 100% 48.4%", - accentForeground: "0 0% 0%", - destructive: "17.7 100% 37.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 31.8%", - input: "0 0% 31.8%", - ring: "36.2 100% 48.4%", - }, - }, - { - id: "ikki", - name: "IKKI", - tokens: { - background: "0 0% 32.5%", - foreground: "0 0% 83.9%", - card: "0 0% 35.7%", - cardForeground: "0 0% 83.9%", - popover: "0 0% 35.7%", - popoverForeground: "0 0% 83.9%", - primary: "35.8 100% 50%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 38.4%", - secondaryForeground: "0 0% 83.9%", - muted: "0 0% 42%", - mutedForeground: "0 0% 69.4%", - accent: "35.8 100% 50%", - accentForeground: "0 0% 0%", - destructive: "354 67% 56.1%", - destructiveForeground: "0 0% 0%", - border: "0 0% 45.9%", - input: "0 0% 45.9%", - ring: "35.8 100% 50%", - }, - }, - { - id: "kanso-ink", - name: "Kanso Ink", - tokens: { - background: "220 18.4% 9.6%", - foreground: "150 3.6% 78%", - card: "225 11.4% 13.7%", - cardForeground: "150 3.6% 78%", - popover: "225 11.4% 13.7%", - popoverForeground: "150 3.6% 78%", - primary: "41.4 33% 65.5%", - primaryForeground: "0 0% 0%", - secondary: "217.5 9.1% 17.3%", - secondaryForeground: "150 3.6% 78%", - muted: "225 7% 22.4%", - mutedForeground: "180 1.9% 58.4%", - accent: "41.4 33% 65.5%", - accentForeground: "0 0% 0%", - destructive: "4.2 42.2% 60%", - destructiveForeground: "0 0% 0%", - border: "222.9 5% 27.6%", - input: "222.9 5% 27.6%", - ring: "41.4 33% 65.5%", - }, - }, - { - id: "kary-pro-colors", - name: "Kary Pro Colors", - tokens: { - background: "0 0% 10.2%", - foreground: "0 0% 80%", - card: "0 0% 14.1%", - cardForeground: "0 0% 80%", - popover: "0 0% 14.1%", - popoverForeground: "0 0% 80%", - primary: "15.8 54.6% 62%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 17.6%", - secondaryForeground: "0 0% 80%", - muted: "0 0% 22.7%", - mutedForeground: "0 0% 60.4%", - accent: "15.8 54.6% 62%", - accentForeground: "0 0% 0%", - destructive: "15.8 54.6% 62%", - destructiveForeground: "0 0% 0%", - border: "0 0% 28.2%", - input: "0 0% 28.2%", - ring: "15.8 54.6% 62%", - }, - }, - { - id: "light-purple", - name: "Light purple", - tokens: { - background: "293.3 18% 19.6%", - foreground: "0 100% 94.5%", - card: "292.9 14.3% 23.3%", - cardForeground: "0 100% 94.5%", - popover: "292.9 14.3% 23.3%", - popoverForeground: "0 100% 94.5%", - primary: "191.2 74.1% 77.3%", - primaryForeground: "0 0% 0%", - secondary: "292.9 12.6% 26.5%", - secondaryForeground: "0 100% 94.5%", - muted: "296 9.6% 30.8%", - mutedForeground: "348 18.5% 73.5%", - accent: "191.2 74.1% 77.3%", - accentForeground: "0 0% 0%", - destructive: "348 69.3% 60.4%", - destructiveForeground: "0 0% 0%", - border: "295.7 7.7% 35.7%", - input: "295.7 7.7% 35.7%", - ring: "191.2 74.1% 77.3%", - }, - }, - { - id: "mondrian", - name: "Mondrian", - tokens: { - background: "240 27.8% 14.1%", - foreground: "0 0% 100%", - card: "240 20.9% 17.8%", - cardForeground: "0 0% 100%", - popover: "240 20.9% 17.8%", - popoverForeground: "0 0% 100%", - primary: "186.5 100% 37.8%", - primaryForeground: "0 0% 0%", - secondary: "240 17.4% 21.4%", - secondaryForeground: "0 0% 100%", - muted: "240 12.8% 26.1%", - mutedForeground: "240 4.1% 75.9%", - accent: "186.5 100% 37.8%", - accentForeground: "0 0% 0%", - destructive: "4.6 81.2% 56.3%", - destructiveForeground: "0 0% 0%", - border: "240 10% 31.4%", - input: "240 10% 31.4%", - ring: "186.5 100% 37.8%", - }, - }, - { - id: "monochrome", - name: "Monochrome", - tokens: { - background: "222.2 47.4% 11.2%", - foreground: "210 40% 96.1%", - card: "223.8 33.3% 15.3%", - cardForeground: "210 40% 96.1%", - popover: "223.8 33.3% 15.3%", - popoverForeground: "210 40% 96.1%", - primary: "210 40% 96.1%", - primaryForeground: "0 0% 0%", - secondary: "220.8 26.3% 18.6%", - secondaryForeground: "210 40% 96.1%", - muted: "224.3 19% 23.7%", - mutedForeground: "216.9 9.2% 72.4%", - accent: "210 40% 96.1%", - accentForeground: "0 0% 0%", - destructive: "210 40% 96.1%", - destructiveForeground: "0 0% 0%", - border: "223.6 14.9% 29%", - input: "223.6 14.9% 29%", - ring: "210 40% 96.1%", - }, - }, - { - id: "monochrome-stone", - name: "Monochrome Stone", - tokens: { - background: "24 9.8% 10%", - foreground: "60 4.8% 95.9%", - card: "24 7% 13.9%", - cardForeground: "60 4.8% 95.9%", - popover: "24 7% 13.9%", - popoverForeground: "60 4.8% 95.9%", - primary: "60 4.8% 95.9%", - primaryForeground: "0 0% 0%", - secondary: "30 4.4% 17.6%", - secondaryForeground: "60 4.8% 95.9%", - muted: "24 4.3% 22.5%", - mutedForeground: "30 1.4% 71.8%", - accent: "60 4.8% 95.9%", - accentForeground: "0 0% 0%", - destructive: "60 4.8% 95.9%", - destructiveForeground: "0 0% 0%", - border: "30 2.8% 27.8%", - input: "30 2.8% 27.8%", - ring: "60 4.8% 95.9%", - }, - }, - { - id: "monokai-pro-spectrum", - name: "Monokai Pro Spectrum", - tokens: { - background: "0 0% 13.3%", - foreground: "265.7 100% 97.3%", - card: "0 0% 17.3%", - cardForeground: "265.7 100% 97.3%", - popover: "0 0% 17.3%", - popoverForeground: "265.7 100% 97.3%", - primary: "22.6 97.7% 65.9%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 20.8%", - secondaryForeground: "265.7 100% 97.3%", - muted: "0 0% 25.5%", - mutedForeground: "264 7.5% 73.7%", - accent: "22.6 97.7% 65.9%", - accentForeground: "0 0% 0%", - destructive: "343 96.3% 68.4%", - destructiveForeground: "0 0% 0%", - border: "0 0% 30.6%", - input: "0 0% 30.6%", - ring: "22.6 97.7% 65.9%", - }, - }, - { - id: "monospace", - name: "Monospace", - tokens: { - background: "216 30.3% 12.9%", - foreground: "214.3 22.6% 87.8%", - card: "216 23.3% 16.9%", - cardForeground: "214.3 22.6% 87.8%", - popover: "216 23.3% 16.9%", - popoverForeground: "214.3 22.6% 87.8%", - primary: "227 100% 72%", - primaryForeground: "0 0% 0%", - secondary: "216.7 17.3% 20.4%", - secondaryForeground: "214.3 22.6% 87.8%", - muted: "216.7 14.1% 25.1%", - mutedForeground: "216 8.9% 66.9%", - accent: "227 100% 72%", - accentForeground: "0 0% 0%", - destructive: "359.2 90% 68.6%", - destructiveForeground: "0 0% 0%", - border: "213.8 10.4% 30.2%", - input: "213.8 10.4% 30.2%", - ring: "227 100% 72%", - }, - }, - { - id: "noctis-azureus", - name: "Noctis Azureus", - tokens: { - background: "203.1 78.8% 12.9%", - foreground: "203.6 27.5% 80%", - card: "202.8 58.1% 16.9%", - cardForeground: "203.6 27.5% 80%", - popover: "202.8 58.1% 16.9%", - popoverForeground: "203.6 27.5% 80%", - primary: "187.1 78.4% 60%", - primaryForeground: "0 0% 0%", - secondary: "203.7 46.2% 20.4%", - secondaryForeground: "203.6 27.5% 80%", - muted: "203.2 34.4% 25.1%", - mutedForeground: "202.9 17.2% 61.2%", - accent: "187.1 78.4% 60%", - accentForeground: "0 0% 0%", - destructive: "16.8 78.2% 55.1%", - destructiveForeground: "0 0% 0%", - border: "203.4 26.5% 30.4%", - input: "203.4 26.5% 30.4%", - ring: "187.1 78.4% 60%", - }, - }, - { - id: "noctis-hibernus", - name: "Noctis Hibernus", - tokens: { - background: "246.9 25.5% 20%", - foreground: "249 19.6% 80%", - card: "247.2 20.7% 23.7%", - cardForeground: "249 19.6% 80%", - popover: "247.2 20.7% 23.7%", - popoverForeground: "249 19.6% 80%", - primary: "187.1 78.4% 60%", - primaryForeground: "0 0% 0%", - secondary: "247.5 17.6% 26.7%", - secondaryForeground: "249 19.6% 80%", - muted: "247.8 14.5% 31.2%", - mutedForeground: "248.2 11.7% 63.1%", - accent: "187.1 78.4% 60%", - accentForeground: "0 0% 0%", - destructive: "16.8 78.2% 55.1%", - destructiveForeground: "0 0% 0%", - border: "248.6 11.5% 35.9%", - input: "248.6 11.5% 35.9%", - ring: "187.1 78.4% 60%", - }, - }, - { - id: "noir-essence", - name: "Noir Essence", - tokens: { - background: "200 8.1% 7.3%", - foreground: "41.5 44.8% 94.3%", - card: "200 5.1% 11.6%", - cardForeground: "41.5 44.8% 94.3%", - popover: "200 5.1% 11.6%", - popoverForeground: "41.5 44.8% 94.3%", - primary: "23.5 76.1% 60.6%", - primaryForeground: "0 0% 0%", - secondary: "200 3.9% 15.1%", - secondaryForeground: "41.5 44.8% 94.3%", - muted: "200 2.9% 20.2%", - mutedForeground: "40 5.9% 70%", - accent: "23.5 76.1% 60.6%", - accentForeground: "0 0% 0%", - destructive: "3.1 76.4% 65.1%", - destructiveForeground: "0 0% 0%", - border: "210 1.5% 25.9%", - input: "210 1.5% 25.9%", - ring: "23.5 76.1% 60.6%", - }, - }, - { - id: "nord-midnight", - name: "Nord Midnight", - tokens: { - background: "220 14.8% 12%", - foreground: "218.8 27.9% 88%", - card: "220 11.1% 15.9%", - cardForeground: "218.8 27.9% 88%", - popover: "220 11.1% 15.9%", - popoverForeground: "218.8 27.9% 88%", - primary: "40 70.6% 73.3%", - primaryForeground: "0 0% 0%", - secondary: "220 9.1% 19.4%", - secondaryForeground: "218.8 27.9% 88%", - muted: "217.5 6.5% 24.3%", - mutedForeground: "220 8.9% 66.9%", - accent: "40 70.6% 73.3%", - accentForeground: "0 0% 0%", - destructive: "354.3 42.3% 56.5%", - destructiveForeground: "0 0% 0%", - border: "222.9 4.6% 29.6%", - input: "222.9 4.6% 29.6%", - ring: "40 70.6% 73.3%", - }, - }, - { - id: "notionish", - name: "Notionish", - tokens: { - background: "60 2% 9.6%", - foreground: "30 10% 96.1%", - card: "60 1.4% 13.5%", - cardForeground: "30 10% 96.1%", - popover: "60 1.4% 13.5%", - popoverForeground: "30 10% 96.1%", - primary: "39.9 100% 68.4%", - primaryForeground: "0 0% 0%", - secondary: "60 1.1% 17.5%", - secondaryForeground: "30 10% 96.1%", - muted: "60 0.9% 22.2%", - mutedForeground: "30 1.4% 71.8%", - accent: "39.9 100% 68.4%", - accentForeground: "0 0% 0%", - destructive: "6.9 90.2% 67.8%", - destructiveForeground: "0 0% 0%", - border: "60 0.7% 27.6%", - input: "60 0.7% 27.6%", - ring: "39.9 100% 68.4%", - }, - }, - { - id: "phonebook", - name: "Phonebook", - tokens: { - background: "27.3 14.3% 15.1%", - foreground: "43 71.4% 67.1%", - card: "30 10.4% 18.8%", - cardForeground: "43 71.4% 67.1%", - popover: "30 10.4% 18.8%", - popoverForeground: "43 71.4% 67.1%", - primary: "186.5 100% 37.8%", - primaryForeground: "0 0% 0%", - secondary: "24 8.8% 22.4%", - secondaryForeground: "43 71.4% 67.1%", - muted: "24 7.2% 27.1%", - mutedForeground: "42 37.2% 52.5%", - accent: "186.5 100% 37.8%", - accentForeground: "0 0% 0%", - destructive: "4 89.9% 61%", - destructiveForeground: "0 0% 0%", - border: "26.7 5.5% 32%", - input: "26.7 5.5% 32%", - ring: "186.5 100% 37.8%", - }, - }, - { - id: "polychrome", - name: "Polychrome", - tokens: { - background: "250.9 12.1% 17.8%", - foreground: "251.7 31.6% 77.6%", - card: "252 9.1% 21.6%", - cardForeground: "251.7 31.6% 77.6%", - popover: "252 9.1% 21.6%", - popoverForeground: "251.7 31.6% 77.6%", - primary: "47.7 100% 76.1%", - primaryForeground: "0 0% 0%", - secondary: "252 7.9% 24.7%", - secondaryForeground: "251.7 31.6% 77.6%", - muted: "252 6.7% 29.4%", - mutedForeground: "250.3 14.6% 61%", - accent: "47.7 100% 76.1%", - accentForeground: "0 0% 0%", - destructive: "9.1 100% 63.9%", - destructiveForeground: "0 0% 0%", - border: "253.3 5.1% 34.3%", - input: "253.3 5.1% 34.3%", - ring: "47.7 100% 76.1%", - }, - }, - { - id: "purplepeter", - name: "Purplepeter", - tokens: { - background: "260 48% 19.6%", - foreground: "255.8 65.5% 94.3%", - card: "260.9 39% 23.1%", - cardForeground: "255.8 65.5% 94.3%", - popover: "260.9 39% 23.1%", - popoverForeground: "255.8 65.5% 94.3%", - primary: "264 100% 77.5%", - primaryForeground: "0 0% 0%", - secondary: "260.5 32.8% 26.3%", - secondaryForeground: "255.8 65.5% 94.3%", - muted: "260.5 26.1% 30.8%", - mutedForeground: "257.8 20% 73.5%", - accent: "264 100% 77.5%", - accentForeground: "0 0% 0%", - destructive: "4.9 100% 71.4%", - destructiveForeground: "0 0% 0%", - border: "260.5 20.9% 35.7%", - input: "260.5 20.9% 35.7%", - ring: "264 100% 77.5%", - }, - }, - { - id: "rainglow-codecourse", - name: "Rainglow Codecourse", - tokens: { - background: "204 33.3% 2.9%", - foreground: "197.6 30.4% 78%", - card: "204 13.5% 7.3%", - cardForeground: "197.6 30.4% 78%", - popover: "204 13.5% 7.3%", - popoverForeground: "197.6 30.4% 78%", - primary: "202.7 97.4% 55.3%", - primaryForeground: "0 0% 0%", - secondary: "204 8.8% 11.2%", - secondaryForeground: "197.6 30.4% 78%", - muted: "195 4.8% 16.5%", - mutedForeground: "196.2 11.8% 56.9%", - accent: "202.7 97.4% 55.3%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "210 3.5% 22.4%", - input: "210 3.5% 22.4%", - ring: "202.7 97.4% 55.3%", - }, - }, - { - id: "rainglow-crisp", - name: "Rainglow Crisp", - tokens: { - background: "300 14.3% 4.1%", - foreground: "0 0% 100%", - card: "300 7% 8.4%", - cardForeground: "0 0% 100%", - popover: "300 7% 8.4%", - popoverForeground: "0 0% 100%", - primary: "23 97.5% 52.4%", - primaryForeground: "0 0% 0%", - secondary: "300 4.8% 12.4%", - secondaryForeground: "0 0% 100%", - muted: "300 3.4% 17.5%", - mutedForeground: "300 0.7% 73.1%", - accent: "23 97.5% 52.4%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "300 2.5% 23.3%", - input: "300 2.5% 23.3%", - ring: "23 97.5% 52.4%", - }, - }, - { - id: "rainglow-lavender", - name: "Rainglow Lavender", - tokens: { - background: "270 12.5% 3.1%", - foreground: "274.8 46.3% 86.9%", - card: "270 5.3% 7.5%", - cardForeground: "274.8 46.3% 86.9%", - popover: "270 5.3% 7.5%", - popoverForeground: "274.8 46.3% 86.9%", - primary: "273.9 100% 67.1%", - primaryForeground: "0 0% 0%", - secondary: "270 3.4% 11.4%", - secondaryForeground: "274.8 46.3% 86.9%", - muted: "300 1.2% 16.7%", - mutedForeground: "276.5 12.3% 63.3%", - accent: "273.9 100% 67.1%", - accentForeground: "0 0% 0%", - destructive: "348.8 86% 39.2%", - destructiveForeground: "0 0% 100%", - border: "240 0.9% 22.5%", - input: "240 0.9% 22.5%", - ring: "273.9 100% 67.1%", - }, - }, - { - id: "remedy-tilted", - name: "Remedy Tilted", - tokens: { - background: "5 10.5% 22.4%", - foreground: "39.4 80.7% 83.7%", - card: "5 9.1% 25.9%", - cardForeground: "39.4 80.7% 83.7%", - popover: "5 9.1% 25.9%", - popoverForeground: "39.4 80.7% 83.7%", - primary: "24.6 65.8% 62.2%", - primaryForeground: "0 0% 0%", - secondary: "5.5 7.5% 28.8%", - secondaryForeground: "39.4 80.7% 83.7%", - muted: "0 5.9% 33.3%", - mutedForeground: "37.6 29.8% 66.5%", - accent: "24.6 65.8% 62.2%", - accentForeground: "0 0% 0%", - destructive: "0 42.9% 45.3%", - destructiveForeground: "0 0% 100%", - border: "6.7 4.7% 37.8%", - input: "6.7 4.7% 37.8%", - ring: "24.6 65.8% 62.2%", - }, - }, - { - id: "rose-pine", - name: "Rosé Pine", - tokens: { - background: "249.2 22% 11.6%", - foreground: "245.5 50% 91.4%", - card: "249.2 16.5% 15.5%", - cardForeground: "245.5 50% 91.4%", - popover: "249.2 16.5% 15.5%", - popoverForeground: "245.5 50% 91.4%", - primary: "35 87.6% 71.6%", - primaryForeground: "0 0% 0%", - secondary: "250 12.2% 19.2%", - secondaryForeground: "245.5 50% 91.4%", - muted: "250 9.8% 23.9%", - mutedForeground: "246 12.7% 69%", - accent: "35 87.6% 71.6%", - accentForeground: "0 0% 0%", - destructive: "343.1 75.6% 67.8%", - destructiveForeground: "0 0% 0%", - border: "250.9 7.4% 29.2%", - input: "250.9 7.4% 29.2%", - ring: "35 87.6% 71.6%", - }, - }, - { - id: "selene-selenized", - name: "Selene Selenized", - tokens: { - background: "189.9 87% 15.1%", - foreground: "183.8 17% 81.6%", - card: "189.4 66.7% 18.8%", - cardForeground: "183.8 17% 81.6%", - popover: "189.4 66.7% 18.8%", - popoverForeground: "183.8 17% 81.6%", - primary: "203.3 100% 48%", - primaryForeground: "0 0% 0%", - secondary: "190.6 54.4% 22.4%", - secondaryForeground: "183.8 17% 81.6%", - muted: "190.3 42% 27.1%", - mutedForeground: "187.7 16.4% 62.9%", - accent: "203.3 100% 48%", - accentForeground: "0 0% 0%", - destructive: "2.7 97.8% 64.9%", - destructiveForeground: "0 0% 0%", - border: "190 32.9% 32.2%", - input: "190 32.9% 32.2%", - ring: "203.3 100% 48%", - }, - }, - { - id: "soft-color", - name: "Soft Color", - tokens: { - background: "0 0% 14.5%", - foreground: "151.2 100% 95.1%", - card: "0 0% 18.4%", - cardForeground: "151.2 100% 95.1%", - popover: "0 0% 18.4%", - popoverForeground: "151.2 100% 95.1%", - primary: "60 86.9% 48%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 22%", - secondaryForeground: "151.2 100% 95.1%", - muted: "0 0% 26.7%", - mutedForeground: "150 12.9% 72.5%", - accent: "60 86.9% 48%", - accentForeground: "0 0% 0%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 31.8%", - input: "0 0% 31.8%", - ring: "60 86.9% 48%", - }, - }, - { - id: "tearout", - name: "Tearout", - tokens: { - background: "85 11.8% 20%", - foreground: "30.9 76.1% 82%", - card: "85 10% 23.5%", - cardForeground: "30.9 76.1% 82%", - popover: "85 10% 23.5%", - popoverForeground: "30.9 76.1% 82%", - primary: "46.4 51.2% 67.8%", - primaryForeground: "0 0% 0%", - secondary: "87.3 8% 26.9%", - secondaryForeground: "30.9 76.1% 82%", - muted: "87.3 6.9% 31.2%", - mutedForeground: "33.5 28.6% 64.3%", - accent: "46.4 51.2% 67.8%", - accentForeground: "0 0% 0%", - destructive: "20 44.3% 64.1%", - destructiveForeground: "0 0% 0%", - border: "84 5.4% 36.1%", - input: "84 5.4% 36.1%", - ring: "46.4 51.2% 67.8%", - }, - }, - { - id: "tokyo-night", - name: "Tokyo Night", - tokens: { - background: "235 18.8% 12.5%", - foreground: "228.7 72.6% 85.7%", - card: "235 14.3% 16.5%", - cardForeground: "228.7 72.6% 85.7%", - popover: "235 14.3% 16.5%", - popoverForeground: "228.7 72.6% 85.7%", - primary: "202.2 100% 74.5%", - primaryForeground: "0 0% 0%", - secondary: "234.5 10.9% 19.8%", - secondaryForeground: "228.7 72.6% 85.7%", - muted: "234 7.9% 24.7%", - mutedForeground: "229.8 23.2% 65.3%", - accent: "202.2 100% 74.5%", - accentForeground: "0 0% 0%", - destructive: "348.8 89% 71.6%", - destructiveForeground: "0 0% 0%", - border: "233.3 5.9% 30%", - input: "233.3 5.9% 30%", - ring: "202.2 100% 74.5%", - }, - }, - { - id: "tomorrow-night-eighties", - name: "Tomorrow Night Eighties", - tokens: { - background: "0 0% 17.6%", - foreground: "0 0% 80%", - card: "0 0% 21.2%", - cardForeground: "0 0% 80%", - popover: "0 0% 21.2%", - popoverForeground: "0 0% 80%", - primary: "40 100% 70%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 24.7%", - secondaryForeground: "0 0% 80%", - muted: "0 0% 29%", - mutedForeground: "0 0% 62.4%", - accent: "40 100% 70%", - accentForeground: "0 0% 0%", - destructive: "358.5 82.6% 70.8%", - destructiveForeground: "0 0% 0%", - border: "0 0% 34.1%", - input: "0 0% 34.1%", - ring: "40 100% 70%", - }, - }, - { - id: "vaporizer-turquoise", - name: "Vaporizer Turquoise", - tokens: { - background: "0 0% 9.8%", - foreground: "110.8 31.7% 67.8%", - card: "0 0% 13.7%", - cardForeground: "110.8 31.7% 67.8%", - popover: "0 0% 13.7%", - popoverForeground: "110.8 31.7% 67.8%", - primary: "151.9 100% 36.9%", - primaryForeground: "0 0% 0%", - secondary: "0 0% 17.6%", - secondaryForeground: "110.8 31.7% 67.8%", - muted: "0 0% 22.4%", - mutedForeground: "110.3 15% 51.6%", - accent: "151.9 100% 36.9%", - accentForeground: "0 0% 0%", - destructive: "0 61.4% 49.8%", - destructiveForeground: "0 0% 100%", - border: "0 0% 27.8%", - input: "0 0% 27.8%", - ring: "151.9 100% 36.9%", - }, - }, - { - id: "xotopio", - name: "Xotopio", - tokens: { - background: "233.3 69.2% 5.1%", - foreground: "0 0% 100%", - card: "232.9 36.2% 9.2%", - cardForeground: "0 0% 100%", - popover: "232.9 36.2% 9.2%", - popoverForeground: "0 0% 100%", - primary: "195.1 100% 66.5%", - primaryForeground: "0 0% 0%", - secondary: "232.9 25.4% 13.1%", - secondaryForeground: "0 0% 100%", - muted: "232.5 17% 18.4%", - mutedForeground: "240 3.7% 73.5%", - accent: "195.1 100% 66.5%", - accentForeground: "0 0% 0%", - destructive: "327.7 100% 48.8%", - destructiveForeground: "0 0% 0%", - border: "232 12.2% 24.1%", - input: "232 12.2% 24.1%", - ring: "195.1 100% 66.5%", - }, - }, - { - id: "yuttari", - name: "Yuttari", - tokens: { - background: "320 11.1% 10.6%", - foreground: "336.7 100% 96.5%", - card: "320 8.1% 14.5%", - cardForeground: "336.7 100% 96.5%", - popover: "320 8.1% 14.5%", - popoverForeground: "336.7 100% 96.5%", - primary: "38.5 43.3% 64.7%", - primaryForeground: "0 0% 0%", - secondary: "324 5.4% 18.2%", - secondaryForeground: "336.7 100% 96.5%", - muted: "320 5.1% 23.1%", - mutedForeground: "332 10.6% 72.4%", - accent: "38.5 43.3% 64.7%", - accentForeground: "0 0% 0%", - destructive: "0 41.1% 58%", - destructiveForeground: "0 0% 0%", - border: "324 3.4% 28.4%", - input: "324 3.4% 28.4%", - ring: "38.5 43.3% 64.7%", - }, - }, - { - id: "zenbones-rosebones", - name: "Zenbones Rosebones", - tokens: { - background: "249.2 21.3% 12%", - foreground: "0 17.8% 85.7%", - card: "249.2 16% 15.9%", - cardForeground: "0 17.8% 85.7%", - popover: "249.2 16% 15.9%", - popoverForeground: "0 17.8% 85.7%", - primary: "35.1 87.8% 71%", - primaryForeground: "0 0% 0%", - secondary: "245 12% 19.6%", - secondaryForeground: "0 17.8% 85.7%", - muted: "250 9.7% 24.3%", - mutedForeground: "336 5.5% 64.3%", - accent: "35.1 87.8% 71%", - accentForeground: "0 0% 0%", - destructive: "343.3 75.3% 68.2%", - destructiveForeground: "0 0% 0%", - border: "250.9 7.3% 29.6%", - input: "250.9 7.3% 29.6%", - ring: "35.1 87.8% 71%", - }, - }, - { - id: "zhxo-red", - name: "Zhxo'red", - tokens: { - background: "240 5.5% 10.8%", - foreground: "0 0% 67.1%", - card: "240 4% 14.7%", - cardForeground: "0 0% 67.1%", - popover: "240 4% 14.7%", - popoverForeground: "0 0% 67.1%", - primary: "182.7 86% 44.9%", - primaryForeground: "0 0% 0%", - secondary: "240 3.2% 18.2%", - secondaryForeground: "0 0% 67.1%", - muted: "240 2.5% 23.3%", - mutedForeground: "240 0.4% 51.2%", - accent: "182.7 86% 44.9%", - accentForeground: "0 0% 0%", - destructive: "0 72.6% 55.7%", - destructiveForeground: "0 0% 0%", - border: "240 1.4% 28.6%", - input: "240 1.4% 28.6%", - ring: "182.7 86% 44.9%", - }, - } +export const CORE_DARK_UI_THEMES: UiThemePreset[] = [ + defineUiTheme("pure-black", "Pure Black", { + background: "0 0% 0%", + foreground: "0 0% 95%", + card: "0 0% 5%", + primary: "210 90% 60%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 0%", + muted: "0 0% 15%", + mutedForeground: "0 0% 65%", + destructive: "0 70% 50%", + border: "0 0% 12%", + secondaryForeground: "0 0% 92%", + }), + defineUiTheme("midnight", "Midnight", { + background: "220 28% 10%", + foreground: "210 40% 95%", + card: "220 22% 12%", + primary: "200 100% 61%", + primaryForeground: "220 40% 96%", + secondary: "220 16% 16%", + muted: "220 16% 16%", + mutedForeground: "220 10% 70%", + destructive: "0 70% 50%", + border: "220 22% 18%", + secondaryForeground: "210 40% 90%", + destructiveForeground: "210 40% 96%", + }), + defineUiTheme("deep-blue", "Deep Blue", { + background: "220 35% 10%", + foreground: "210 40% 96%", + card: "220 28% 14%", + primary: "210 90% 60%", + primaryForeground: "220 40% 96%", + secondary: "220 20% 18%", + muted: "220 20% 18%", + mutedForeground: "220 10% 72%", + destructive: "0 70% 50%", + border: "220 20% 22%", + secondaryForeground: "210 40% 90%", + destructiveForeground: "210 40% 96%", + }), + defineUiTheme("vscode", "VS Code", { + background: "0 0% 12%", + foreground: "210 20% 92%", + card: "0 0% 16%", + primary: "210 90% 60%", + primaryForeground: "0 0% 100%", + secondary: "0 0% 18%", + muted: "0 0% 18%", + mutedForeground: "0 0% 65%", + destructive: "0 70% 50%", + border: "0 0% 22%", + }), + defineUiTheme("graphite", "Graphite", { + background: "220 8% 12%", + foreground: "210 20% 94%", + card: "220 8% 16%", + primary: "210 80% 60%", + primaryForeground: "0 0% 100%", + secondary: "220 6% 18%", + muted: "220 6% 18%", + mutedForeground: "0 0% 70%", + destructive: "0 70% 50%", + border: "220 6% 22%", + secondaryForeground: "210 20% 92%", + }), + defineUiTheme("obsidian", "Obsidian", { + background: "240 8% 8%", + foreground: "210 20% 94%", + card: "240 8% 12%", + primary: "265 80% 65%", + primaryForeground: "0 0% 100%", + secondary: "240 6% 16%", + muted: "240 6% 16%", + mutedForeground: "240 5% 70%", + destructive: "0 70% 50%", + border: "240 6% 20%", + secondaryForeground: "210 20% 92%", + }), + defineUiTheme("forest", "Forest", { + background: "150 12% 10%", + foreground: "150 20% 92%", + card: "150 12% 14%", + primary: "160 70% 50%", + primaryForeground: "0 0% 100%", + secondary: "150 10% 18%", + muted: "150 10% 18%", + mutedForeground: "150 8% 68%", + destructive: "0 70% 50%", + border: "150 8% 22%", + secondaryForeground: "150 20% 90%", + }), ]; -export const CORE_DARK_UI_THEMES: UiThemePreset[] = [ - { - id: "pure-black", - name: "Pure Black", - tokens: { - background: "0 0% 0%", - foreground: "0 0% 95%", - card: "0 0% 5%", - cardForeground: "0 0% 95%", - popover: "0 0% 5%", - popoverForeground: "0 0% 95%", - primary: "210 90% 60%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 0%", - secondaryForeground: "0 0% 92%", - muted: "0 0% 15%", - mutedForeground: "0 0% 65%", - accent: "210 90% 60%", - accentForeground: "0 0% 100%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "0 0% 12%", - input: "0 0% 12%", - ring: "210 90% 60%", - }, - }, - { - id: "midnight", - name: "Midnight", - tokens: { - background: "220 28% 10%", - foreground: "210 40% 95%", - card: "220 22% 12%", - cardForeground: "210 40% 95%", - popover: "220 22% 12%", - popoverForeground: "210 40% 95%", - primary: "200 100% 61%", - primaryForeground: "220 40% 96%", - secondary: "220 16% 16%", - secondaryForeground: "210 40% 90%", - muted: "220 16% 16%", - mutedForeground: "220 10% 70%", - accent: "200 100% 61%", - accentForeground: "220 40% 96%", - destructive: "0 70% 50%", - destructiveForeground: "210 40% 96%", - border: "220 22% 18%", - input: "220 22% 18%", - ring: "200 100% 61%", - }, - }, - { - id: "deep-blue", - name: "Deep Blue", - tokens: { - background: "220 35% 10%", - foreground: "210 40% 96%", - card: "220 28% 14%", - cardForeground: "210 40% 96%", - popover: "220 28% 14%", - popoverForeground: "210 40% 96%", - primary: "210 90% 60%", - primaryForeground: "220 40% 96%", - secondary: "220 20% 18%", - secondaryForeground: "210 40% 90%", - muted: "220 20% 18%", - mutedForeground: "220 10% 72%", - accent: "210 90% 60%", - accentForeground: "220 40% 96%", - destructive: "0 70% 50%", - destructiveForeground: "210 40% 96%", - border: "220 20% 22%", - input: "220 20% 22%", - ring: "210 90% 60%", - }, - }, - { - id: "vscode", - name: "VS Code", - tokens: { - background: "0 0% 12%", - foreground: "210 20% 92%", - card: "0 0% 16%", - cardForeground: "210 20% 92%", - popover: "0 0% 16%", - popoverForeground: "210 20% 92%", - primary: "210 90% 60%", - primaryForeground: "0 0% 100%", - secondary: "0 0% 18%", - secondaryForeground: "210 20% 92%", - muted: "0 0% 18%", - mutedForeground: "0 0% 65%", - accent: "210 90% 60%", - accentForeground: "0 0% 100%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "0 0% 22%", - input: "0 0% 22%", - ring: "210 90% 60%", - }, - }, - { - id: "graphite", - name: "Graphite", - tokens: { - background: "220 8% 12%", - foreground: "210 20% 94%", - card: "220 8% 16%", - cardForeground: "210 20% 94%", - popover: "220 8% 16%", - popoverForeground: "210 20% 94%", - primary: "210 80% 60%", - primaryForeground: "0 0% 100%", - secondary: "220 6% 18%", - secondaryForeground: "210 20% 92%", - muted: "220 6% 18%", - mutedForeground: "0 0% 70%", - accent: "210 80% 60%", - accentForeground: "0 0% 100%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "220 6% 22%", - input: "220 6% 22%", - ring: "210 80% 60%", - }, - }, - { - id: "obsidian", - name: "Obsidian", - tokens: { - background: "240 8% 8%", - foreground: "210 20% 94%", - card: "240 8% 12%", - cardForeground: "210 20% 94%", - popover: "240 8% 12%", - popoverForeground: "210 20% 94%", - primary: "265 80% 65%", - primaryForeground: "0 0% 100%", - secondary: "240 6% 16%", - secondaryForeground: "210 20% 92%", - muted: "240 6% 16%", - mutedForeground: "240 5% 70%", - accent: "265 80% 65%", - accentForeground: "0 0% 100%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "240 6% 20%", - input: "240 6% 20%", - ring: "265 80% 65%", - }, - }, - { - id: "forest", - name: "Forest", - tokens: { - background: "150 12% 10%", - foreground: "150 20% 92%", - card: "150 12% 14%", - cardForeground: "150 20% 92%", - popover: "150 12% 14%", - popoverForeground: "150 20% 92%", - primary: "160 70% 50%", - primaryForeground: "0 0% 100%", - secondary: "150 10% 18%", - secondaryForeground: "150 20% 90%", - muted: "150 10% 18%", - mutedForeground: "150 8% 68%", - accent: "160 70% 50%", - accentForeground: "0 0% 100%", - destructive: "0 70% 50%", - destructiveForeground: "0 0% 100%", - border: "150 8% 22%", - input: "150 8% 22%", - ring: "160 70% 50%", - }, - }, +export const EXTENDED_DARK_UI_THEMES: UiThemePreset[] = [ + defineUiTheme("a-cup-of-coffee", "A cup of coffee", { + background: "0 0% 11.8%", + foreground: "0 0% 74.5%", + card: "0 0% 15.7%", + primary: "60 86.9% 48%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 19.2%", + muted: "0 0% 24.3%", + mutedForeground: "0 0% 56.9%", + destructive: "0 61.4% 49.8%", + border: "0 0% 29.4%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("abolkog", "ABOLKOG", { + background: "220 13% 18%", + foreground: "218.8 27.9% 88%", + card: "223.6 9.9% 21.8%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "218.2 8.7% 24.9%", + muted: "216 6.7% 29.4%", + mutedForeground: "220 9.3% 68.4%", + destructive: "354.3 42.3% 56.5%", + border: "222 5.7% 34.5%", + }), + defineUiTheme("aurora", "Aurora", { + background: "223.6 13.6% 15.9%", + foreground: "45.2 100% 57.8%", + card: "222 10% 19.6%", + primary: "171.5 97.2% 42.5%", + primaryForeground: "0 0% 0%", + secondary: "228 8.5% 23.1%", + muted: "226.7 6.4% 27.6%", + mutedForeground: "45.3 64.3% 46.1%", + destructive: "338.3 87.1% 54.5%", + border: "226.7 5.4% 32.7%", + }), + defineUiTheme("ayu", "Ayu", { + background: "222.4 21.5% 15.5%", + foreground: "48 8.9% 78%", + card: "221.3 16.3% 19.2%", + primary: "271.3 95.9% 80.8%", + primaryForeground: "0 0% 0%", + secondary: "221.3 13.8% 22.7%", + muted: "220 10.8% 27.3%", + mutedForeground: "60 1.5% 60.6%", + destructive: "6.1 83.1% 65.1%", + border: "221.5 7.9% 32.4%", + }), + defineUiTheme("base16-flat", "Base16 Flat", { + background: "210 29% 24.3%", + foreground: "0 0% 87.8%", + card: "209.1 24.8% 27.6%", + primary: "168.1 75.7% 42%", + primaryForeground: "0 0% 0%", + secondary: "210.9 21% 30.8%", + muted: "211 17.3% 35.1%", + mutedForeground: "210 6.6% 70.2%", + destructive: "5.6 78.1% 57.1%", + border: "209 14.4% 39.4%", + }), + defineUiTheme("base16-mocha", "Base16 Mocha", { + background: "31.6 19.2% 19.4%", + foreground: "12 9.6% 79.6%", + card: "30 15.3% 23.1%", + primary: "16.1 51.9% 63.3%", + primaryForeground: "0 0% 0%", + secondary: "30 13.4% 26.3%", + muted: "33.7 10.3% 30.6%", + mutedForeground: "20 6.3% 62.7%", + destructive: "347.1 50.7% 58.6%", + border: "32 8.3% 35.5%", + }), + defineUiTheme("blue-dolphin", "Blue Dolphin", { + background: "192.3 100% 25.9%", + foreground: "193.4 100% 88.6%", + card: "192.3 85.2% 29.2%", + primary: "218.8 100% 83.3%", + primaryForeground: "0 0% 0%", + secondary: "192 73.2% 32.2%", + muted: "192.2 61.1% 36.3%", + mutedForeground: "192.9 53.7% 71.2%", + destructive: "357.1 100% 75.5%", + border: "192.5 51% 40.8%", + }), + defineUiTheme("calm-days-sober-nights-sky", "Calm Days, Sober Nights Sky", { + background: "221.7 31.5% 14.3%", + foreground: "220 31.3% 86.9%", + card: "220.9 23.9% 18%", + primary: "198 93.3% 70.6%", + primaryForeground: "0 0% 0%", + secondary: "222.9 18.9% 21.8%", + muted: "222 14.9% 26.3%", + mutedForeground: "220 12.3% 66.5%", + destructive: "354 77.1% 69.2%", + border: "220 11.2% 31.4%", + }), + defineUiTheme("catppuccin", "Catppuccin", { + background: "229.1 18.6% 23.1%", + foreground: "227.2 70.1% 86.9%", + card: "228.6 15.6% 26.5%", + primary: "316 73.2% 83.9%", + primaryForeground: "0 0% 0%", + secondary: "231 13.2% 29.8%", + muted: "230.5 11% 33.9%", + mutedForeground: "228 25.3% 69%", + destructive: "358.8 67.8% 70.8%", + border: "226.7 9.2% 38.4%", + }), + defineUiTheme("chai", "Chai", { + background: "240 75% 1.6%", + foreground: "203.6 27.5% 80%", + card: "240 20% 5.9%", + primary: "202.9 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "240 9.8% 10%", + muted: "240 6.3% 15.5%", + mutedForeground: "207.3 10.3% 58%", + destructive: "16.8 78.2% 55.1%", + border: "240 4.6% 21.4%", + }), + defineUiTheme("chinolor", "Chinolor", { + background: "130 6.5% 18%", + foreground: "36.9 19.4% 86.9%", + card: "120 4.5% 21.8%", + primary: "44.4 92.4% 69%", + primaryForeground: "0 0% 0%", + secondary: "130 4.7% 25.1%", + muted: "132 3.3% 29.6%", + mutedForeground: "46.7 5.4% 67.3%", + destructive: "355.2 83.7% 59%", + border: "132 2.9% 34.3%", + }), + defineUiTheme("cyberdyne", "Cyberdyne", { + background: "244.7 60% 16.7%", + foreground: "154.4 100% 50%", + card: "245 46.2% 20.4%", + primary: "300.5 100% 78.2%", + primaryForeground: "0 0% 0%", + secondary: "245.1 38.8% 23.7%", + muted: "245.5 30.6% 28.2%", + mutedForeground: "158.9 93.8% 38%", + destructive: "6.9 100% 72.5%", + border: "244.5 23.5% 33.3%", + }), + defineUiTheme("desert", "Desert", { + background: "0 0% 20%", + foreground: "0 0% 100%", + card: "0 0% 23.5%", + primary: "35.9 100% 83.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 26.7%", + muted: "0 0% 31.4%", + mutedForeground: "0 0% 77.6%", + destructive: "0 100% 58.4%", + border: "0 0% 36.1%", + }), + defineUiTheme("django-reborn-again", "Django Reborn Again", { + background: "154.6 72.2% 7.1%", + foreground: "150 5.7% 86.3%", + card: "156 43.9% 11.2%", + primary: "51.2 100% 69.2%", + primaryForeground: "0 0% 0%", + secondary: "155 31.6% 14.9%", + muted: "155.5 21.6% 20%", + mutedForeground: "152.7 6% 64.1%", + destructive: "21.9 98.4% 51.4%", + border: "154.3 16% 25.7%", + }), + defineUiTheme("espresso", "Espresso", { + background: "18 20% 9.8%", + foreground: "33.3 29.5% 76.1%", + card: "13.3 12.7% 13.9%", + primary: "42.9 70.9% 69%", + primaryForeground: "0 0% 0%", + secondary: "20 10.1% 17.5%", + muted: "13.3 7.8% 22.5%", + mutedForeground: "33.1 13.4% 57.5%", + destructive: "8.6 70.9% 69%", + border: "15 5.6% 27.8%", + }), + defineUiTheme("eyehealth", "EyeHealth", { + background: "0 0% 25.9%", + foreground: "0 0% 100%", + card: "0 0% 29.4%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 32.2%", + muted: "0 0% 36.1%", + mutedForeground: "0 0% 79.2%", + destructive: "354 67% 56.1%", + border: "0 0% 40.8%", + }), + defineUiTheme("flexoki", "Flexoki", { + background: "0 3.2% 6.1%", + foreground: "54.5 10.1% 78.6%", + card: "0 1.9% 10.4%", + primary: "45.2 81.7% 44.9%", + primaryForeground: "0 0% 0%", + secondary: "0 1.4% 13.9%", + muted: "0 0% 19.2%", + mutedForeground: "52.5 3.8% 58.4%", + destructive: "5 61% 53.7%", + border: "0 0.8% 24.9%", + }), + defineUiTheme("fox", "Fox", { + background: "213.9 31.5% 14.3%", + foreground: "210 2% 80.8%", + card: "212.7 23.9% 18%", + primary: "181.1 52.9% 60%", + primaryForeground: "0 0% 0%", + secondary: "214.3 18.9% 21.8%", + muted: "213 14.9% 26.3%", + mutedForeground: "214.3 3.6% 62.2%", + destructive: "345.2 53% 54.9%", + border: "213.3 11.2% 31.4%", + }), + defineUiTheme("garbage-oracle", "Garbage Oracle", { + background: "311.5 31% 16.5%", + foreground: "303.8 38.1% 91.8%", + card: "312 24.3% 20.2%", + primary: "124.3 95.4% 82.9%", + primaryForeground: "0 0% 0%", + secondary: "312.5 20% 23.5%", + muted: "310.9 15.3% 28.2%", + mutedForeground: "306.3 12.8% 70.8%", + destructive: "359.4 92.8% 78.2%", + border: "311.4 12.4% 33.1%", + }), + defineUiTheme("github", "GitHub", { + background: "216 27.8% 7.1%", + foreground: "207.7 35.1% 92.7%", + card: "213.3 15.8% 11.2%", + primary: "212 100% 67.3%", + primaryForeground: "0 0% 0%", + secondary: "220 11.7% 15.1%", + muted: "217.5 7.8% 20%", + mutedForeground: "210 7.5% 68.6%", + destructive: "3.8 100% 72.4%", + border: "210 6.2% 25.5%", + }), + defineUiTheme("gruvbox-material", "Gruvbox Material", { + background: "0 1.2% 15.9%", + foreground: "38 41.1% 71.4%", + card: "0 1% 19.8%", + primary: "3.1 76.4% 65.1%", + primaryForeground: "0 0% 0%", + secondary: "0 0.9% 22.9%", + muted: "0 0.7% 27.6%", + mutedForeground: "37.7 19.1% 55.9%", + destructive: "3.1 76.4% 65.1%", + border: "0 0.6% 32.7%", + }), + defineUiTheme("homebrew", "Homebrew", { + background: "0 0% 0%", + foreground: "120 100% 50%", + card: "0 0% 4.3%", + primary: "184 100% 34.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 8.6%", + muted: "0 0% 14.1%", + mutedForeground: "120 100% 36.1%", + destructive: "0 100% 30%", + border: "0 0% 20%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("ic-orange-ppl", "IC Orange PPL", { + background: "0 0% 14.9%", + foreground: "34.8 100% 75.7%", + card: "0 0% 18.8%", + primary: "36.2 100% 48.4%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 22%", + muted: "0 0% 26.7%", + mutedForeground: "35.1 42.2% 58.6%", + destructive: "17.7 100% 37.8%", + border: "0 0% 31.8%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("ikki", "IKKI", { + background: "0 0% 32.5%", + foreground: "0 0% 83.9%", + card: "0 0% 35.7%", + primary: "35.8 100% 50%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 38.4%", + muted: "0 0% 42%", + mutedForeground: "0 0% 69.4%", + destructive: "354 67% 56.1%", + border: "0 0% 45.9%", + }), + defineUiTheme("kanso-ink", "Kanso Ink", { + background: "220 18.4% 9.6%", + foreground: "150 3.6% 78%", + card: "225 11.4% 13.7%", + primary: "41.4 33% 65.5%", + primaryForeground: "0 0% 0%", + secondary: "217.5 9.1% 17.3%", + muted: "225 7% 22.4%", + mutedForeground: "180 1.9% 58.4%", + destructive: "4.2 42.2% 60%", + border: "222.9 5% 27.6%", + }), + defineUiTheme("kary-pro-colors", "Kary Pro Colors", { + background: "0 0% 10.2%", + foreground: "0 0% 80%", + card: "0 0% 14.1%", + primary: "15.8 54.6% 62%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 17.6%", + muted: "0 0% 22.7%", + mutedForeground: "0 0% 60.4%", + destructive: "15.8 54.6% 62%", + border: "0 0% 28.2%", + }), + defineUiTheme("light-purple", "Light purple", { + background: "293.3 18% 19.6%", + foreground: "0 100% 94.5%", + card: "292.9 14.3% 23.3%", + primary: "191.2 74.1% 77.3%", + primaryForeground: "0 0% 0%", + secondary: "292.9 12.6% 26.5%", + muted: "296 9.6% 30.8%", + mutedForeground: "348 18.5% 73.5%", + destructive: "348 69.3% 60.4%", + border: "295.7 7.7% 35.7%", + }), + defineUiTheme("mondrian", "Mondrian", { + background: "240 27.8% 14.1%", + foreground: "0 0% 100%", + card: "240 20.9% 17.8%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "240 17.4% 21.4%", + muted: "240 12.8% 26.1%", + mutedForeground: "240 4.1% 75.9%", + destructive: "4.6 81.2% 56.3%", + border: "240 10% 31.4%", + }), + defineUiTheme("monochrome", "Monochrome", { + background: "222.2 47.4% 11.2%", + foreground: "210 40% 96.1%", + card: "223.8 33.3% 15.3%", + primary: "210 40% 96.1%", + primaryForeground: "0 0% 0%", + secondary: "220.8 26.3% 18.6%", + muted: "224.3 19% 23.7%", + mutedForeground: "216.9 9.2% 72.4%", + destructive: "210 40% 96.1%", + border: "223.6 14.9% 29%", + }), + defineUiTheme("monochrome-stone", "Monochrome Stone", { + background: "24 9.8% 10%", + foreground: "60 4.8% 95.9%", + card: "24 7% 13.9%", + primary: "60 4.8% 95.9%", + primaryForeground: "0 0% 0%", + secondary: "30 4.4% 17.6%", + muted: "24 4.3% 22.5%", + mutedForeground: "30 1.4% 71.8%", + destructive: "60 4.8% 95.9%", + border: "30 2.8% 27.8%", + }), + defineUiTheme("monokai-pro-spectrum", "Monokai Pro Spectrum", { + background: "0 0% 13.3%", + foreground: "265.7 100% 97.3%", + card: "0 0% 17.3%", + primary: "22.6 97.7% 65.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 20.8%", + muted: "0 0% 25.5%", + mutedForeground: "264 7.5% 73.7%", + destructive: "343 96.3% 68.4%", + border: "0 0% 30.6%", + }), + defineUiTheme("monospace", "Monospace", { + background: "216 30.3% 12.9%", + foreground: "214.3 22.6% 87.8%", + card: "216 23.3% 16.9%", + primary: "227 100% 72%", + primaryForeground: "0 0% 0%", + secondary: "216.7 17.3% 20.4%", + muted: "216.7 14.1% 25.1%", + mutedForeground: "216 8.9% 66.9%", + destructive: "359.2 90% 68.6%", + border: "213.8 10.4% 30.2%", + }), + defineUiTheme("noctis-azureus", "Noctis Azureus", { + background: "203.1 78.8% 12.9%", + foreground: "203.6 27.5% 80%", + card: "202.8 58.1% 16.9%", + primary: "187.1 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "203.7 46.2% 20.4%", + muted: "203.2 34.4% 25.1%", + mutedForeground: "202.9 17.2% 61.2%", + destructive: "16.8 78.2% 55.1%", + border: "203.4 26.5% 30.4%", + }), + defineUiTheme("noctis-hibernus", "Noctis Hibernus", { + background: "246.9 25.5% 20%", + foreground: "249 19.6% 80%", + card: "247.2 20.7% 23.7%", + primary: "187.1 78.4% 60%", + primaryForeground: "0 0% 0%", + secondary: "247.5 17.6% 26.7%", + muted: "247.8 14.5% 31.2%", + mutedForeground: "248.2 11.7% 63.1%", + destructive: "16.8 78.2% 55.1%", + border: "248.6 11.5% 35.9%", + }), + defineUiTheme("noir-essence", "Noir Essence", { + background: "200 8.1% 7.3%", + foreground: "41.5 44.8% 94.3%", + card: "200 5.1% 11.6%", + primary: "23.5 76.1% 60.6%", + primaryForeground: "0 0% 0%", + secondary: "200 3.9% 15.1%", + muted: "200 2.9% 20.2%", + mutedForeground: "40 5.9% 70%", + destructive: "3.1 76.4% 65.1%", + border: "210 1.5% 25.9%", + }), + defineUiTheme("nord-midnight", "Nord Midnight", { + background: "220 14.8% 12%", + foreground: "218.8 27.9% 88%", + card: "220 11.1% 15.9%", + primary: "40 70.6% 73.3%", + primaryForeground: "0 0% 0%", + secondary: "220 9.1% 19.4%", + muted: "217.5 6.5% 24.3%", + mutedForeground: "220 8.9% 66.9%", + destructive: "354.3 42.3% 56.5%", + border: "222.9 4.6% 29.6%", + }), + defineUiTheme("notionish", "Notionish", { + background: "60 2% 9.6%", + foreground: "30 10% 96.1%", + card: "60 1.4% 13.5%", + primary: "39.9 100% 68.4%", + primaryForeground: "0 0% 0%", + secondary: "60 1.1% 17.5%", + muted: "60 0.9% 22.2%", + mutedForeground: "30 1.4% 71.8%", + destructive: "6.9 90.2% 67.8%", + border: "60 0.7% 27.6%", + }), + defineUiTheme("phonebook", "Phonebook", { + background: "27.3 14.3% 15.1%", + foreground: "43 71.4% 67.1%", + card: "30 10.4% 18.8%", + primary: "186.5 100% 37.8%", + primaryForeground: "0 0% 0%", + secondary: "24 8.8% 22.4%", + muted: "24 7.2% 27.1%", + mutedForeground: "42 37.2% 52.5%", + destructive: "4 89.9% 61%", + border: "26.7 5.5% 32%", + }), + defineUiTheme("polychrome", "Polychrome", { + background: "250.9 12.1% 17.8%", + foreground: "251.7 31.6% 77.6%", + card: "252 9.1% 21.6%", + primary: "47.7 100% 76.1%", + primaryForeground: "0 0% 0%", + secondary: "252 7.9% 24.7%", + muted: "252 6.7% 29.4%", + mutedForeground: "250.3 14.6% 61%", + destructive: "9.1 100% 63.9%", + border: "253.3 5.1% 34.3%", + }), + defineUiTheme("purplepeter", "Purplepeter", { + background: "260 48% 19.6%", + foreground: "255.8 65.5% 94.3%", + card: "260.9 39% 23.1%", + primary: "264 100% 77.5%", + primaryForeground: "0 0% 0%", + secondary: "260.5 32.8% 26.3%", + muted: "260.5 26.1% 30.8%", + mutedForeground: "257.8 20% 73.5%", + destructive: "4.9 100% 71.4%", + border: "260.5 20.9% 35.7%", + }), + defineUiTheme("rainglow-codecourse", "Rainglow Codecourse", { + background: "204 33.3% 2.9%", + foreground: "197.6 30.4% 78%", + card: "204 13.5% 7.3%", + primary: "202.7 97.4% 55.3%", + primaryForeground: "0 0% 0%", + secondary: "204 8.8% 11.2%", + muted: "195 4.8% 16.5%", + mutedForeground: "196.2 11.8% 56.9%", + destructive: "348.8 86% 39.2%", + border: "210 3.5% 22.4%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rainglow-crisp", "Rainglow Crisp", { + background: "300 14.3% 4.1%", + foreground: "0 0% 100%", + card: "300 7% 8.4%", + primary: "23 97.5% 52.4%", + primaryForeground: "0 0% 0%", + secondary: "300 4.8% 12.4%", + muted: "300 3.4% 17.5%", + mutedForeground: "300 0.7% 73.1%", + destructive: "348.8 86% 39.2%", + border: "300 2.5% 23.3%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rainglow-lavender", "Rainglow Lavender", { + background: "270 12.5% 3.1%", + foreground: "274.8 46.3% 86.9%", + card: "270 5.3% 7.5%", + primary: "273.9 100% 67.1%", + primaryForeground: "0 0% 0%", + secondary: "270 3.4% 11.4%", + muted: "300 1.2% 16.7%", + mutedForeground: "276.5 12.3% 63.3%", + destructive: "348.8 86% 39.2%", + border: "240 0.9% 22.5%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("remedy-tilted", "Remedy Tilted", { + background: "5 10.5% 22.4%", + foreground: "39.4 80.7% 83.7%", + card: "5 9.1% 25.9%", + primary: "24.6 65.8% 62.2%", + primaryForeground: "0 0% 0%", + secondary: "5.5 7.5% 28.8%", + muted: "0 5.9% 33.3%", + mutedForeground: "37.6 29.8% 66.5%", + destructive: "0 42.9% 45.3%", + border: "6.7 4.7% 37.8%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("rose-pine", "Rosé Pine", { + background: "249.2 22% 11.6%", + foreground: "245.5 50% 91.4%", + card: "249.2 16.5% 15.5%", + primary: "35 87.6% 71.6%", + primaryForeground: "0 0% 0%", + secondary: "250 12.2% 19.2%", + muted: "250 9.8% 23.9%", + mutedForeground: "246 12.7% 69%", + destructive: "343.1 75.6% 67.8%", + border: "250.9 7.4% 29.2%", + }), + defineUiTheme("selene-selenized", "Selene Selenized", { + background: "189.9 87% 15.1%", + foreground: "183.8 17% 81.6%", + card: "189.4 66.7% 18.8%", + primary: "203.3 100% 48%", + primaryForeground: "0 0% 0%", + secondary: "190.6 54.4% 22.4%", + muted: "190.3 42% 27.1%", + mutedForeground: "187.7 16.4% 62.9%", + destructive: "2.7 97.8% 64.9%", + border: "190 32.9% 32.2%", + }), + defineUiTheme("soft-color", "Soft Color", { + background: "0 0% 14.5%", + foreground: "151.2 100% 95.1%", + card: "0 0% 18.4%", + primary: "60 86.9% 48%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 22%", + muted: "0 0% 26.7%", + mutedForeground: "150 12.9% 72.5%", + destructive: "0 61.4% 49.8%", + border: "0 0% 31.8%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("tearout", "Tearout", { + background: "85 11.8% 20%", + foreground: "30.9 76.1% 82%", + card: "85 10% 23.5%", + primary: "46.4 51.2% 67.8%", + primaryForeground: "0 0% 0%", + secondary: "87.3 8% 26.9%", + muted: "87.3 6.9% 31.2%", + mutedForeground: "33.5 28.6% 64.3%", + destructive: "20 44.3% 64.1%", + border: "84 5.4% 36.1%", + }), + defineUiTheme("tokyo-night", "Tokyo Night", { + background: "235 18.8% 12.5%", + foreground: "228.7 72.6% 85.7%", + card: "235 14.3% 16.5%", + primary: "202.2 100% 74.5%", + primaryForeground: "0 0% 0%", + secondary: "234.5 10.9% 19.8%", + muted: "234 7.9% 24.7%", + mutedForeground: "229.8 23.2% 65.3%", + destructive: "348.8 89% 71.6%", + border: "233.3 5.9% 30%", + }), + defineUiTheme("tomorrow-night-eighties", "Tomorrow Night Eighties", { + background: "0 0% 17.6%", + foreground: "0 0% 80%", + card: "0 0% 21.2%", + primary: "40 100% 70%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 24.7%", + muted: "0 0% 29%", + mutedForeground: "0 0% 62.4%", + destructive: "358.5 82.6% 70.8%", + border: "0 0% 34.1%", + }), + defineUiTheme("vaporizer-turquoise", "Vaporizer Turquoise", { + background: "0 0% 9.8%", + foreground: "110.8 31.7% 67.8%", + card: "0 0% 13.7%", + primary: "151.9 100% 36.9%", + primaryForeground: "0 0% 0%", + secondary: "0 0% 17.6%", + muted: "0 0% 22.4%", + mutedForeground: "110.3 15% 51.6%", + destructive: "0 61.4% 49.8%", + border: "0 0% 27.8%", + destructiveForeground: "0 0% 100%", + }), + defineUiTheme("xotopio", "Xotopio", { + background: "233.3 69.2% 5.1%", + foreground: "0 0% 100%", + card: "232.9 36.2% 9.2%", + primary: "195.1 100% 66.5%", + primaryForeground: "0 0% 0%", + secondary: "232.9 25.4% 13.1%", + muted: "232.5 17% 18.4%", + mutedForeground: "240 3.7% 73.5%", + destructive: "327.7 100% 48.8%", + border: "232 12.2% 24.1%", + }), + defineUiTheme("yuttari", "Yuttari", { + background: "320 11.1% 10.6%", + foreground: "336.7 100% 96.5%", + card: "320 8.1% 14.5%", + primary: "38.5 43.3% 64.7%", + primaryForeground: "0 0% 0%", + secondary: "324 5.4% 18.2%", + muted: "320 5.1% 23.1%", + mutedForeground: "332 10.6% 72.4%", + destructive: "0 41.1% 58%", + border: "324 3.4% 28.4%", + }), + defineUiTheme("zenbones-rosebones", "Zenbones Rosebones", { + background: "249.2 21.3% 12%", + foreground: "0 17.8% 85.7%", + card: "249.2 16% 15.9%", + primary: "35.1 87.8% 71%", + primaryForeground: "0 0% 0%", + secondary: "245 12% 19.6%", + muted: "250 9.7% 24.3%", + mutedForeground: "336 5.5% 64.3%", + destructive: "343.3 75.3% 68.2%", + border: "250.9 7.3% 29.6%", + }), + defineUiTheme("zhxo-red", "Zhxo'red", { + background: "240 5.5% 10.8%", + foreground: "0 0% 67.1%", + card: "240 4% 14.7%", + primary: "182.7 86% 44.9%", + primaryForeground: "0 0% 0%", + secondary: "240 3.2% 18.2%", + muted: "240 2.5% 23.3%", + mutedForeground: "240 0.4% 51.2%", + destructive: "0 72.6% 55.7%", + border: "240 1.4% 28.6%", + }), ]; export const DARK_UI_THEMES: UiThemePreset[] = [ diff --git a/infrastructure/services/CloudSyncManager.ts b/infrastructure/services/CloudSyncManager.ts index 0a897dfff..4f2fdaa34 100644 --- a/infrastructure/services/CloudSyncManager.ts +++ b/infrastructure/services/CloudSyncManager.ts @@ -1072,11 +1072,4 @@ export const getCloudSyncManager = (): CloudSyncManager => { return syncManagerInstance; }; -export const resetCloudSyncManager = (): void => { - if (syncManagerInstance) { - syncManagerInstance.destroy(); - syncManagerInstance = null; - } -}; - export default CloudSyncManager; diff --git a/infrastructure/services/EncryptionService.ts b/infrastructure/services/EncryptionService.ts index 1efc71faa..f7735a1f4 100644 --- a/infrastructure/services/EncryptionService.ts +++ b/infrastructure/services/EncryptionService.ts @@ -332,22 +332,6 @@ export const decryptPayload = async ( return parsed; }; -/** - * Verify a SyncedFile can be decrypted with given password - * Does not return the payload, just validates the password - */ -export const verifySyncedFile = async ( - syncedFile: SyncedFile, - password: string -): Promise => { - try { - await decryptPayload(syncedFile, password); - return true; - } catch { - return false; - } -}; - // ============================================================================ // Master Key Management // ============================================================================ diff --git a/infrastructure/services/adapters/GoogleDriveAdapter.ts b/infrastructure/services/adapters/GoogleDriveAdapter.ts index 1b9fa03da..b08ecfac2 100644 --- a/infrastructure/services/adapters/GoogleDriveAdapter.ts +++ b/infrastructure/services/adapters/GoogleDriveAdapter.ts @@ -19,8 +19,13 @@ import { type SyncedFile, type PKCEChallenge, } from '../../../domain/sync'; -import { arrayBufferToBase64, generateRandomBytes } from '../EncryptionService'; import { netcattyBridge } from '../netcattyBridge'; +import { + OAuthPKCEAdapterBase, + generatePKCEChallenge, +} from './OAuthPKCEAdapterBase'; + +export { generatePKCEChallenge }; // ============================================================================ // Types @@ -40,54 +45,6 @@ export interface DriveFile { size?: string; } -// ============================================================================ -// PKCE Utilities -// ============================================================================ - -/** - * Generate a cryptographically random code verifier - */ -const generateCodeVerifier = (): string => { - const bytes = generateRandomBytes(32); - return base64UrlEncode(bytes); -}; - -/** - * Generate code challenge from verifier (S256) - */ -const generateCodeChallenge = async (verifier: string): Promise => { - const encoder = new TextEncoder(); - const data = encoder.encode(verifier); - const digest = await crypto.subtle.digest('SHA-256', data); - return base64UrlEncode(new Uint8Array(digest)); -}; - -/** - * Base64 URL encoding (no padding, URL-safe chars) - */ -const base64UrlEncode = (bytes: Uint8Array): string => { - const base64 = arrayBufferToBase64(bytes); - return base64 - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=+$/, ''); -}; - -/** - * Generate PKCE challenge - */ -export const generatePKCEChallenge = async (): Promise => { - const codeVerifier = generateCodeVerifier(); - const codeChallenge = await generateCodeChallenge(codeVerifier); - const state = base64UrlEncode(generateRandomBytes(16)); - - return { - codeVerifier, - codeChallenge, - state, - }; -}; - // ============================================================================ // OAuth Flow // ============================================================================ @@ -480,160 +437,42 @@ export const deleteSyncFile = async ( // Google Drive Adapter Class // ============================================================================ -export class GoogleDriveAdapter { - private tokens: OAuthTokens | null = null; - private fileId: string | null = null; - private account: ProviderAccount | null = null; - private pkceChallenge: PKCEChallenge | null = null; - /** - * Invoked whenever the access token is silently refreshed. Lets the owner - * (CloudSyncManager) persist the rotated tokens so the next launch doesn't - * load a stale access token and force a reconnect. Mirrors the OneDrive fix - * (#1189 / #1208); Google differs in that its refresh response usually omits a - * new refresh token, so refreshTokens() carries the previous one forward. - */ - private onTokensRefreshed: ((tokens: OAuthTokens) => void) | null = null; - - constructor(tokens?: OAuthTokens, fileId?: string) { - if (tokens) { - this.tokens = tokens; - } - this.fileId = fileId || null; +export class GoogleDriveAdapter extends OAuthPKCEAdapterBase { + protected buildProviderAuthUrl(redirectUri: string): Promise<{ url: string; pkce: PKCEChallenge }> { + return buildAuthUrl(redirectUri); } - /** - * Register a callback that receives refreshed tokens so the caller can - * persist them. Passing null removes the callback. - */ - setOnTokensRefreshed(callback: ((tokens: OAuthTokens) => void) | null): void { - this.onTokensRefreshed = callback; + protected exchangeProviderCode( + code: string, + codeVerifier: string, + redirectUri: string + ): Promise { + return exchangeCodeForTokens(code, codeVerifier, redirectUri); } - /** - * Refresh the access token using the supplied refresh token, store the - * rotated tokens in-memory, and notify the persistence callback. Google - * typically returns the same (or no) refresh token on refresh, so the prior - * refresh token is preserved when the response omits one — otherwise the - * persisted credentials would lose the ability to refresh again and force a - * reconnect on the next launch. - */ - private async refreshTokens(refreshToken: string): Promise { - const refreshed = await refreshAccessToken(refreshToken); + protected refreshProviderToken(refreshToken: string): Promise { + return refreshAccessToken(refreshToken); + } + + protected fetchProviderUserInfo(accessToken: string): Promise { + return getUserInfo(accessToken); + } + + protected validateProviderToken(accessToken: string): Promise { + return validateToken(accessToken); + } + + protected override mergeRefreshedTokens( + refreshed: OAuthTokens, + priorRefreshToken: string + ): OAuthTokens { // Google's refresh response frequently omits refresh_token (it does not // rotate on every refresh). Never let a missing value clobber the working // refresh token, or the persisted connection becomes unrefreshable. - const merged: OAuthTokens = { + return { ...refreshed, - refreshToken: refreshed.refreshToken || refreshToken, + refreshToken: refreshed.refreshToken || priorRefreshToken, }; - this.tokens = merged; - try { - this.onTokensRefreshed?.(merged); - } catch { - // Persistence is best-effort; a failed save must not abort the sync that - // triggered the refresh — the fresh tokens still work for this session. - } - return merged; - } - - get isAuthenticated(): boolean { - return !!this.tokens?.accessToken; - } - - get accountInfo(): ProviderAccount | null { - return this.account; - } - - get resourceId(): string | null { - return this.fileId; - } - - /** - * Start OAuth flow - returns URL to open in browser - */ - async startAuth(redirectUri: string): Promise { - const { url, pkce } = await buildAuthUrl(redirectUri); - this.pkceChallenge = pkce; - return url; - } - - /** - * Get PKCE state for verification - */ - getPKCEState(): string | null { - return this.pkceChallenge?.state || null; - } - - /** - * Complete authentication with authorization code - */ - async completeAuth(code: string, redirectUri: string): Promise { - if (!this.pkceChallenge) { - throw new Error('No PKCE challenge - start auth first'); - } - - this.tokens = await exchangeCodeForTokens( - code, - this.pkceChallenge.codeVerifier, - redirectUri - ); - this.pkceChallenge = null; - - this.account = await getUserInfo(this.tokens.accessToken); - - return this.tokens; - } - - /** - * Set tokens from storage - */ - async setTokens(tokens: OAuthTokens): Promise { - this.tokens = tokens; - - // Refresh if expired - if (tokens.expiresAt && Date.now() > tokens.expiresAt - 60000) { - if (tokens.refreshToken) { - this.tokens = await this.refreshTokens(tokens.refreshToken); - } else { - throw new Error('Token expired and no refresh token'); - } - } - - if (await validateToken(this.tokens.accessToken)) { - this.account = await getUserInfo(this.tokens.accessToken); - } else { - throw new Error('Token is invalid'); - } - } - - /** - * Ensure token is fresh - */ - private async ensureValidToken(): Promise { - if (!this.tokens) { - throw new Error('Not authenticated'); - } - - if (this.tokens.expiresAt && Date.now() > this.tokens.expiresAt - 60000) { - if (this.tokens.refreshToken) { - this.tokens = await this.refreshTokens(this.tokens.refreshToken); - } else { - throw new Error('Token expired'); - } - } - - return this.tokens.accessToken; - } - - /** - * Sign out - */ - signOut(): void { - this.tokens = null; - this.fileId = null; - this.account = null; - this.pkceChallenge = null; - this.onTokensRefreshed = null; } /** @@ -689,13 +528,6 @@ export class GoogleDriveAdapter { await deleteSyncFile(accessToken, this.fileId); this.fileId = null; } - - /** - * Get tokens for storage - */ - getTokens(): OAuthTokens | null { - return this.tokens; - } } export default GoogleDriveAdapter; diff --git a/infrastructure/services/adapters/OAuthPKCEAdapterBase.ts b/infrastructure/services/adapters/OAuthPKCEAdapterBase.ts new file mode 100644 index 000000000..5e5245a98 --- /dev/null +++ b/infrastructure/services/adapters/OAuthPKCEAdapterBase.ts @@ -0,0 +1,232 @@ +/** + * Shared PKCE + OAuth token lifecycle base for loopback OAuth CloudSync adapters + * (GoogleDriveAdapter and OneDriveAdapter). + */ + +import type { + OAuthTokens, + PKCEChallenge, + ProviderAccount, +} from '../../../domain/sync'; +import { arrayBufferToBase64, generateRandomBytes } from '../EncryptionService'; + +/** + * Base64 URL encoding (no padding, URL-safe chars) + */ +const base64UrlEncode = (bytes: Uint8Array): string => { + const base64 = arrayBufferToBase64(bytes); + return base64 + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); +}; + +/** + * Generate a cryptographically random code verifier + */ +const generateCodeVerifier = (): string => { + const bytes = generateRandomBytes(32); + return base64UrlEncode(bytes); +}; + +/** + * Generate code challenge from verifier (S256) + */ +const generateCodeChallenge = async (verifier: string): Promise => { + const encoder = new TextEncoder(); + const data = encoder.encode(verifier); + const digest = await crypto.subtle.digest('SHA-256', data); + return base64UrlEncode(new Uint8Array(digest)); +}; + +/** + * Generate PKCE challenge (RFC 7636 S256) + */ +export const generatePKCEChallenge = async (): Promise => { + const codeVerifier = generateCodeVerifier(); + const codeChallenge = await generateCodeChallenge(codeVerifier); + const state = base64UrlEncode(generateRandomBytes(16)); + + return { + codeVerifier, + codeChallenge, + state, + }; +}; + +export abstract class OAuthPKCEAdapterBase { + protected tokens: OAuthTokens | null = null; + protected fileId: string | null = null; + protected account: ProviderAccount | null = null; + protected pkceChallenge: PKCEChallenge | null = null; + protected onTokensRefreshed: ((tokens: OAuthTokens) => void) | null = null; + + constructor(tokens?: OAuthTokens, fileId?: string) { + if (tokens) { + this.tokens = tokens; + } + this.fileId = fileId || null; + } + + protected abstract buildProviderAuthUrl( + redirectUri: string + ): Promise<{ url: string; pkce: PKCEChallenge }>; + + protected abstract exchangeProviderCode( + code: string, + codeVerifier: string, + redirectUri: string + ): Promise; + + protected abstract refreshProviderToken(refreshToken: string): Promise; + + protected abstract fetchProviderUserInfo(accessToken: string): Promise; + + protected abstract validateProviderToken(accessToken: string): Promise; + + protected mergeRefreshedTokens(refreshed: OAuthTokens, _priorRefreshToken: string): OAuthTokens { + return refreshed; + } + + protected normalizeRefreshError(error: unknown): unknown { + return error; + } + + protected createExpiredTokenError(context: 'setTokens' | 'ensureValidToken'): Error { + return new Error( + context === 'setTokens' ? 'Token expired and no refresh token' : 'Token expired' + ); + } + + /** + * Register a callback that receives refreshed tokens so the caller can + * persist them. Passing null removes the callback. + */ + setOnTokensRefreshed(callback: ((tokens: OAuthTokens) => void) | null): void { + this.onTokensRefreshed = callback; + } + + protected async refreshTokens(refreshToken: string): Promise { + let refreshed: OAuthTokens; + try { + refreshed = await this.refreshProviderToken(refreshToken); + } catch (error) { + throw this.normalizeRefreshError(error); + } + const merged = this.mergeRefreshedTokens(refreshed, refreshToken); + this.tokens = merged; + try { + this.onTokensRefreshed?.(merged); + } catch { + // Persistence is best-effort; a failed save must not abort the sync that + // triggered the refresh — the fresh tokens still work for this session. + } + return merged; + } + + get isAuthenticated(): boolean { + return !!this.tokens?.accessToken; + } + + get accountInfo(): ProviderAccount | null { + return this.account; + } + + get resourceId(): string | null { + return this.fileId; + } + + /** + * Start OAuth flow - returns URL to open in browser + */ + async startAuth(redirectUri: string): Promise { + const { url, pkce } = await this.buildProviderAuthUrl(redirectUri); + this.pkceChallenge = pkce; + return url; + } + + /** + * Get PKCE state for verification + */ + getPKCEState(): string | null { + return this.pkceChallenge?.state || null; + } + + /** + * Complete authentication with authorization code + */ + async completeAuth(code: string, redirectUri: string): Promise { + if (!this.pkceChallenge) { + throw new Error('No PKCE challenge - start auth first'); + } + + this.tokens = await this.exchangeProviderCode( + code, + this.pkceChallenge.codeVerifier, + redirectUri + ); + this.pkceChallenge = null; + + this.account = await this.fetchProviderUserInfo(this.tokens.accessToken); + + return this.tokens; + } + + /** + * Set tokens from storage + */ + async setTokens(tokens: OAuthTokens): Promise { + this.tokens = tokens; + + if (tokens.expiresAt && Date.now() > tokens.expiresAt - 60000) { + if (tokens.refreshToken) { + this.tokens = await this.refreshTokens(tokens.refreshToken); + } else { + throw this.createExpiredTokenError('setTokens'); + } + } + + if (await this.validateProviderToken(this.tokens.accessToken)) { + this.account = await this.fetchProviderUserInfo(this.tokens.accessToken); + } else { + throw new Error('Token is invalid'); + } + } + + /** + * Ensure token is fresh + */ + protected async ensureValidToken(): Promise { + if (!this.tokens) { + throw new Error('Not authenticated'); + } + + if (this.tokens.expiresAt && Date.now() > this.tokens.expiresAt - 60000) { + if (this.tokens.refreshToken) { + this.tokens = await this.refreshTokens(this.tokens.refreshToken); + } else { + throw this.createExpiredTokenError('ensureValidToken'); + } + } + + return this.tokens.accessToken; + } + + /** + * Sign out + */ + signOut(): void { + this.tokens = null; + this.fileId = null; + this.account = null; + this.pkceChallenge = null; + this.onTokensRefreshed = null; + } + + /** + * Get tokens for storage + */ + getTokens(): OAuthTokens | null { + return this.tokens; + } +} diff --git a/infrastructure/services/adapters/OneDriveAdapter.ts b/infrastructure/services/adapters/OneDriveAdapter.ts index 3bad96935..3a44fa301 100644 --- a/infrastructure/services/adapters/OneDriveAdapter.ts +++ b/infrastructure/services/adapters/OneDriveAdapter.ts @@ -22,7 +22,12 @@ import { type PKCEChallenge, } from '../../../domain/sync'; import { netcattyBridge } from '../netcattyBridge'; -import { arrayBufferToBase64, generateRandomBytes } from '../EncryptionService'; +import { + OAuthPKCEAdapterBase, + generatePKCEChallenge, +} from './OAuthPKCEAdapterBase'; + +export { generatePKCEChallenge }; // ============================================================================ // Types @@ -89,54 +94,6 @@ const isUnauthorizedError = (error: unknown): boolean => { lower.includes('invalidauthenticationtoken'); }; -// ============================================================================ -// PKCE Utilities -// ============================================================================ - -/** - * Base64 URL encoding (no padding, URL-safe chars) - */ -const base64UrlEncode = (bytes: Uint8Array): string => { - const base64 = arrayBufferToBase64(bytes); - return base64 - .replace(/\+/g, '-') - .replace(/\//g, '_') - .replace(/=+$/, ''); -}; - -/** - * Generate a cryptographically random code verifier - */ -const generateCodeVerifier = (): string => { - const bytes = generateRandomBytes(32); - return base64UrlEncode(bytes); -}; - -/** - * Generate code challenge from verifier (S256) - */ -const generateCodeChallenge = async (verifier: string): Promise => { - const encoder = new TextEncoder(); - const data = encoder.encode(verifier); - const digest = await crypto.subtle.digest('SHA-256', data); - return base64UrlEncode(new Uint8Array(digest)); -}; - -/** - * Generate PKCE challenge - */ -export const generatePKCEChallenge = async (): Promise => { - const codeVerifier = generateCodeVerifier(); - const codeChallenge = await generateCodeChallenge(codeVerifier); - const state = base64UrlEncode(generateRandomBytes(16)); - - return { - codeVerifier, - codeChallenge, - state, - }; -}; - // ============================================================================ // OAuth Flow // ============================================================================ @@ -523,156 +480,46 @@ export const deleteSyncFile = async ( // OneDrive Adapter Class // ============================================================================ -export class OneDriveAdapter { - private tokens: OAuthTokens | null = null; - private fileId: string | null = null; - private account: ProviderAccount | null = null; - private pkceChallenge: PKCEChallenge | null = null; - /** - * Invoked whenever the access token is silently refreshed. Lets the owner - * (CloudSyncManager) persist the rotated tokens — Microsoft consumer refresh - * tokens rotate on every refresh and invalidate the previous one, so without - * persisting the new refresh token the stored one eventually goes stale and - * forces the user to reconnect (#1189). - */ - private onTokensRefreshed: ((tokens: OAuthTokens) => void) | null = null; +export class OneDriveAdapter extends OAuthPKCEAdapterBase { + protected buildProviderAuthUrl(redirectUri: string): Promise<{ url: string; pkce: PKCEChallenge }> { + return buildAuthUrl(redirectUri); + } - constructor(tokens?: OAuthTokens, fileId?: string) { - if (tokens) { - this.tokens = tokens; + protected exchangeProviderCode( + code: string, + codeVerifier: string, + redirectUri: string + ): Promise { + return exchangeCodeForTokens(code, codeVerifier, redirectUri); + } + + protected refreshProviderToken(refreshToken: string): Promise { + return refreshAccessToken(refreshToken); + } + + protected fetchProviderUserInfo(accessToken: string): Promise { + return getUserInfo(accessToken); + } + + protected validateProviderToken(accessToken: string): Promise { + return validateToken(accessToken); + } + + protected override normalizeRefreshError(error: unknown): unknown { + if (isOneDriveReauthRequiredError(error)) { + // Preserve the message (it carries the marker the bridge added) so + // downstream layers can still detect this after any re-wrapping. + return new OneDriveReauthRequiredError( + error instanceof Error ? error.message : String(error) + ); } - this.fileId = fileId || null; + return error; } - /** - * Register a callback that receives refreshed tokens so the caller can - * persist them. Passing null removes the callback. - */ - setOnTokensRefreshed(callback: ((tokens: OAuthTokens) => void) | null): void { - this.onTokensRefreshed = callback; - } - - /** - * Refresh the access token using the supplied refresh token, store the - * rotated tokens in-memory, and notify the persistence callback. Refresh - * failures caused by a dead refresh token are normalized to - * OneDriveReauthRequiredError so callers can prompt for reconnect. - */ - private async refreshTokens(refreshToken: string): Promise { - let refreshed: OAuthTokens; - try { - refreshed = await refreshAccessToken(refreshToken); - } catch (error) { - if (isOneDriveReauthRequiredError(error)) { - // Preserve the message (it carries the marker the bridge added) so - // downstream layers can still detect this after any re-wrapping. - throw new OneDriveReauthRequiredError( - error instanceof Error ? error.message : String(error) - ); - } - throw error; - } - this.tokens = refreshed; - try { - this.onTokensRefreshed?.(refreshed); - } catch { - // Persistence is best-effort; a failed save must not abort the sync that - // triggered the refresh — the fresh tokens still work for this session. - } - return refreshed; - } - - get isAuthenticated(): boolean { - return !!this.tokens?.accessToken; - } - - get accountInfo(): ProviderAccount | null { - return this.account; - } - - get resourceId(): string | null { - return this.fileId; - } - - /** - * Start OAuth flow - returns URL to open in browser - */ - async startAuth(redirectUri: string): Promise { - const { url, pkce } = await buildAuthUrl(redirectUri); - this.pkceChallenge = pkce; - return url; - } - - /** - * Get PKCE state for verification - */ - getPKCEState(): string | null { - return this.pkceChallenge?.state || null; - } - - /** - * Complete authentication with authorization code - */ - async completeAuth(code: string, redirectUri: string): Promise { - if (!this.pkceChallenge) { - throw new Error('No PKCE challenge - start auth first'); - } - - this.tokens = await exchangeCodeForTokens( - code, - this.pkceChallenge.codeVerifier, - redirectUri + protected override createExpiredTokenError(): Error { + return new OneDriveReauthRequiredError( + 'OneDrive session expired and no refresh token is available, please reconnect.' ); - this.pkceChallenge = null; - - this.account = await getUserInfo(this.tokens.accessToken); - - return this.tokens; - } - - /** - * Set tokens from storage - */ - async setTokens(tokens: OAuthTokens): Promise { - this.tokens = tokens; - - // Refresh if expired - if (tokens.expiresAt && Date.now() > tokens.expiresAt - 60000) { - if (tokens.refreshToken) { - this.tokens = await this.refreshTokens(tokens.refreshToken); - } else { - throw new OneDriveReauthRequiredError( - 'OneDrive session expired and no refresh token is available, please reconnect.' - ); - } - } - - if (await validateToken(this.tokens.accessToken)) { - this.account = await getUserInfo(this.tokens.accessToken); - } else { - throw new Error('Token is invalid'); - } - } - - /** - * Ensure token is fresh - */ - private async ensureValidToken(): Promise { - if (!this.tokens) { - throw new Error('Not authenticated'); - } - - if (this.tokens.expiresAt && Date.now() > this.tokens.expiresAt - 60000) { - if (this.tokens.refreshToken) { - this.tokens = await this.refreshTokens(this.tokens.refreshToken); - } else { - throw new OneDriveReauthRequiredError( - 'OneDrive session expired and no refresh token is available, please reconnect.' - ); - } - } - - return this.tokens.accessToken; } private async runWithAuthRetry( @@ -691,17 +538,6 @@ export class OneDriveAdapter { } } - /** - * Sign out - */ - signOut(): void { - this.tokens = null; - this.fileId = null; - this.account = null; - this.pkceChallenge = null; - this.onTokensRefreshed = null; - } - /** * Initialize or find sync file */ @@ -747,13 +583,6 @@ export class OneDriveAdapter { this.fileId = null; }); } - - /** - * Get tokens for storage - */ - getTokens(): OAuthTokens | null { - return this.tokens; - } } export default OneDriveAdapter; diff --git a/infrastructure/services/adapters/S3Adapter.ts b/infrastructure/services/adapters/S3Adapter.ts index 2fee0712b..a7ad220a0 100644 --- a/infrastructure/services/adapters/S3Adapter.ts +++ b/infrastructure/services/adapters/S3Adapter.ts @@ -1,14 +1,7 @@ /** - * S3 Compatible Adapter - AWS SDK v3 + * S3 Compatible Adapter - delegates to Electron main-process cloudSyncBridge. */ -import { - S3Client, - HeadObjectCommand, - PutObjectCommand, - GetObjectCommand, - DeleteObjectCommand, -} from '@aws-sdk/client-s3'; import { SYNC_CONSTANTS, type S3Config, @@ -26,29 +19,10 @@ const normalizeEndpoint = (endpoint: string): string => { return trimmed; }; -const toBodyString = async (body: unknown): Promise => { - if (!body) return ''; - if (typeof body === 'string') return body; - if (body instanceof Uint8Array) { - return new TextDecoder().decode(body); - } - if (body instanceof Blob) { - return await body.text(); - } - if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) { - return await new Response(body).text(); - } - if (typeof (body as { transformToString?: () => Promise }).transformToString === 'function') { - return await (body as { transformToString: () => Promise }).transformToString(); - } - throw new Error('Unsupported S3 response body'); -}; - export class S3Adapter { private config: S3Config | null; private resource: string | null; private account: ProviderAccount | null; - private client: S3Client | null; constructor(config?: S3Config, resourceId?: string) { this.config = config @@ -56,7 +30,6 @@ export class S3Adapter { : null; this.resource = resourceId || null; this.account = this.buildAccountInfo(this.config); - this.client = this.config ? this.createClient(this.config) : null; } get isAuthenticated(): boolean { @@ -75,7 +48,6 @@ export class S3Adapter { this.config = null; this.resource = null; this.account = null; - this.client = null; } async initializeSync(): Promise { @@ -83,27 +55,11 @@ export class S3Adapter { throw new Error('Missing S3 config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncS3Initialize) { - const result = await bridge.cloudSyncS3Initialize(this.config); - this.resource = result?.resourceId || this.getObjectKey(); - return this.resource; + if (!bridge?.cloudSyncS3Initialize) { + throw new Error('S3 sync requires the Netcatty desktop sync bridge'); } - const client = this.getClient(); - try { - await client.send(new HeadObjectCommand({ - Bucket: this.config.bucket, - Key: this.getObjectKey(), - })); - } catch (error) { - if (this.isNotFound(error)) { - // File doesn't exist yet. - } else if (this.isAccessDenied(error)) { - throw new Error('S3 access denied'); - } else { - throw error; - } - } - this.resource = this.getObjectKey(); + const result = await bridge.cloudSyncS3Initialize(this.config); + this.resource = result?.resourceId || this.getObjectKey(); return this.resource; } @@ -112,20 +68,11 @@ export class S3Adapter { throw new Error('Missing S3 config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncS3Upload) { - const result = await bridge.cloudSyncS3Upload(this.config, syncedFile); - this.resource = result?.resourceId || this.getObjectKey(); - return this.resource; + if (!bridge?.cloudSyncS3Upload) { + throw new Error('S3 sync requires the Netcatty desktop sync bridge'); } - const body = JSON.stringify(syncedFile); - const client = this.getClient(); - await client.send(new PutObjectCommand({ - Bucket: this.config.bucket, - Key: this.getObjectKey(), - Body: body, - ContentType: 'application/json', - })); - this.resource = this.getObjectKey(); + const result = await bridge.cloudSyncS3Upload(this.config, syncedFile); + this.resource = result?.resourceId || this.getObjectKey(); return this.resource; } @@ -134,25 +81,11 @@ export class S3Adapter { throw new Error('Missing S3 config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncS3Download) { - const result = await bridge.cloudSyncS3Download(this.config); - return (result?.syncedFile ?? null) as SyncedFile | null; - } - const client = this.getClient(); - try { - const response = await client.send(new GetObjectCommand({ - Bucket: this.config.bucket, - Key: this.getObjectKey(), - })); - const text = await toBodyString(response.Body); - if (!text) return null; - return JSON.parse(text) as SyncedFile; - } catch (error) { - if (this.isNotFound(error)) { - return null; - } - throw error; + if (!bridge?.cloudSyncS3Download) { + throw new Error('S3 sync requires the Netcatty desktop sync bridge'); } + const result = await bridge.cloudSyncS3Download(this.config); + return (result?.syncedFile ?? null) as SyncedFile | null; } async deleteSync(): Promise { @@ -160,77 +93,16 @@ export class S3Adapter { return; } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncS3Delete) { - await bridge.cloudSyncS3Delete(this.config); - return; - } - const client = this.getClient(); - try { - await client.send(new DeleteObjectCommand({ - Bucket: this.config.bucket, - Key: this.getObjectKey(), - })); - } catch (error) { - if (this.isNotFound(error)) { - return; - } - throw error; + if (!bridge?.cloudSyncS3Delete) { + throw new Error('S3 sync requires the Netcatty desktop sync bridge'); } + await bridge.cloudSyncS3Delete(this.config); } getTokens(): OAuthTokens | null { return null; } - private getClient(): S3Client { - if (!this.config || !this.client) { - if (this.config?.allowInsecure) { - throw new Error('S3 insecure connections require the Netcatty desktop sync bridge'); - } - throw new Error('Missing S3 config'); - } - return this.client; - } - - private createClient(config: S3Config): S3Client | null { - const clientConfig: ConstructorParameters[0] = { - region: config.region, - endpoint: config.endpoint, - forcePathStyle: config.forcePathStyle ?? true, - requestChecksumCalculation: 'WHEN_REQUIRED', - responseChecksumValidation: 'WHEN_REQUIRED', - credentials: { - accessKeyId: config.accessKeyId, - secretAccessKey: config.secretAccessKey, - sessionToken: config.sessionToken, - }, - }; - - if ( - config.allowInsecure - && typeof globalThis.process !== 'undefined' - && typeof require === 'function' - ) { - const https = require('https'); - const { NodeHttpHandler } = require('@smithy/node-http-handler'); - clientConfig.requestHandler = new NodeHttpHandler({ - httpsAgent: new https.Agent({ rejectUnauthorized: false }), - }); - } else if (config.allowInsecure) { - return null; - } - - return new S3Client(clientConfig); - } - - private isNotFound(error: unknown): boolean { - return Boolean((error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode === 404); - } - - private isAccessDenied(error: unknown): boolean { - return Boolean((error as { $metadata?: { httpStatusCode?: number } })?.$metadata?.httpStatusCode === 403); - } - private getObjectKey(): string { if (!this.config) { throw new Error('Missing S3 config'); diff --git a/infrastructure/services/adapters/WebDAVAdapter.ts b/infrastructure/services/adapters/WebDAVAdapter.ts index e939220a3..93795f2d7 100644 --- a/infrastructure/services/adapters/WebDAVAdapter.ts +++ b/infrastructure/services/adapters/WebDAVAdapter.ts @@ -1,8 +1,7 @@ /** - * WebDAV Adapter - webdav client library + * WebDAV Adapter - delegates to Electron main-process cloudSyncBridge. */ -import { AuthType, createClient } from 'webdav'; import { SYNC_CONSTANTS, type WebDAVConfig, @@ -12,8 +11,6 @@ import { } from '../../../domain/sync'; import { netcattyBridge } from '../netcattyBridge'; -type WebDAVClient = ReturnType; - const normalizeEndpoint = (endpoint: string): string => { const trimmed = endpoint.trim(); if (!/^https?:\/\//i.test(trimmed)) { @@ -25,135 +22,10 @@ const normalizeEndpoint = (endpoint: string): string => { const ensureLeadingSlash = (value: string): string => value.startsWith('/') ? value : `/${value}`; -/** - * Recover from trailing garbage left by non-truncating WebDAV PUT overwrites - * (#2223). Node/V8: "Unexpected non-whitespace character after JSON at position N". - */ -const parseSyncedFileJson = (raw: string): SyncedFile => { - try { - return JSON.parse(raw) as SyncedFile; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - const match = /Unexpected non-whitespace character after JSON at position (\d+)/i.exec( - message, - ); - if (match) { - const pos = Number(match[1]); - if (Number.isFinite(pos) && pos > 0 && pos <= raw.length) { - return JSON.parse(raw.slice(0, pos)) as SyncedFile; - } - } - throw error; - } -}; - -const utf8ByteLength = (value: string): number => - typeof Buffer !== 'undefined' - ? Buffer.byteLength(value, 'utf8') - : new TextEncoder().encode(value).length; - -/** Strict: intended body plus optional trailing whitespace only. */ -const remoteMatchesUploadedBody = (remoteText: string, body: string): boolean => { - if (!remoteText.startsWith(body)) return false; - return /^\s*$/.test(remoteText.slice(body.length)); -}; - -/** - * Prefer fixed-name temp PUT + MOVE (with pad + verify); else padded in-place - * PUT with strict body match so non-truncating servers cannot leave garbage. - */ -const putWebdavFileReplacing = async ( - client: WebDAVClient, - path: string, - body: string, -): Promise => { - const tmpPath = `${path}.tmp`; - const bodyLen = utf8ByteLength(body); - - const cleanupTemp = async () => { - try { - if (await client.exists(tmpPath)) { - await client.deleteFile(tmpPath); - } - } catch { - // best-effort - } - }; - - const readLen = async (target: string): Promise => { - let exists = false; - try { - exists = await client.exists(target); - } catch (error) { - throw new Error( - `WebDAV replace aborted: could not check existing file (${ - error instanceof Error ? error.message : String(error) - })`, - ); - } - if (!exists) return 0; - try { - const existing = await client.getFileContents(target, { format: 'text' }); - if (existing == null) return 0; - return utf8ByteLength(String(existing)); - } catch (error) { - throw new Error( - `WebDAV replace aborted: could not read existing file length (${ - error instanceof Error ? error.message : String(error) - })`, - ); - } - }; - - try { - let tmpMin = 0; - try { - tmpMin = await readLen(tmpPath); - } catch { - tmpMin = 0; - } - const tmpBody = tmpMin > bodyLen ? body + ' '.repeat(tmpMin - bodyLen) : body; - await client.putFileContents(tmpPath, tmpBody, { overwrite: true }); - await client.moveFile(tmpPath, path, { overwrite: true }); - const moved = String((await client.getFileContents(path, { format: 'text' })) ?? ''); - if (remoteMatchesUploadedBody(moved, body)) { - return; - } - } catch { - // fall through - } - await cleanupTemp(); - - let minLen = await readLen(path); - minLen = Math.max(minLen, bodyLen); - for (let attempt = 0; attempt < 3; attempt++) { - const payload = minLen > bodyLen ? body + ' '.repeat(minLen - bodyLen) : body; - await client.putFileContents(path, payload, { overwrite: true }); - let remoteText = ''; - try { - remoteText = String((await client.getFileContents(path, { format: 'text' })) ?? ''); - } catch (error) { - throw new Error( - `WebDAV upload verification failed: could not re-read file (${ - error instanceof Error ? error.message : String(error) - })`, - ); - } - if (remoteMatchesUploadedBody(remoteText, body)) { - return; - } - minLen = Math.max(minLen, utf8ByteLength(remoteText), bodyLen); - } - throw new Error( - 'WebDAV upload verification failed: remote file still does not match uploaded body after padded PUT', - ); -}; - export class WebDAVAdapter { private config: WebDAVConfig | null; private resource: string | null; private account: ProviderAccount | null; - private client: WebDAVClient | null; constructor(config?: WebDAVConfig, resourceId?: string) { this.config = config @@ -161,7 +33,6 @@ export class WebDAVAdapter { : null; this.resource = resourceId || null; this.account = this.buildAccountInfo(this.config); - this.client = this.config ? this.createClient(this.config) : null; } get isAuthenticated(): boolean { @@ -180,7 +51,6 @@ export class WebDAVAdapter { this.config = null; this.resource = null; this.account = null; - this.client = null; } async initializeSync(): Promise { @@ -189,15 +59,11 @@ export class WebDAVAdapter { throw new Error('Missing WebDAV config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncWebdavInitialize) { - const result = await bridge.cloudSyncWebdavInitialize(this.config); - this.resource = result?.resourceId || this.getSyncPath(); - return this.resource; + if (!bridge?.cloudSyncWebdavInitialize) { + throw new Error('WebDAV sync requires the Netcatty desktop sync bridge'); } - const client = this.getClient(); - const path = this.getSyncPath(); - await client.exists(path); - this.resource = path; + const result = await bridge.cloudSyncWebdavInitialize(this.config); + this.resource = result?.resourceId || this.getSyncPath(); return this.resource; }); } @@ -208,16 +74,12 @@ export class WebDAVAdapter { throw new Error('Missing WebDAV config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncWebdavUpload) { - const result = await bridge.cloudSyncWebdavUpload(this.config, syncedFile); - this.resource = result?.resourceId || this.getSyncPath(); - return this.resource; + if (!bridge?.cloudSyncWebdavUpload) { + throw new Error('WebDAV sync requires the Netcatty desktop sync bridge'); } - const client = this.getClient(); - const path = this.getSyncPath(); - await putWebdavFileReplacing(client, path, JSON.stringify(syncedFile)); - this.resource = path; - return path; + const result = await bridge.cloudSyncWebdavUpload(this.config, syncedFile); + this.resource = result?.resourceId || this.getSyncPath(); + return this.resource; }); } @@ -227,17 +89,11 @@ export class WebDAVAdapter { throw new Error('Missing WebDAV config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncWebdavDownload) { - const result = await bridge.cloudSyncWebdavDownload(this.config); - return (result?.syncedFile ?? null) as SyncedFile | null; + if (!bridge?.cloudSyncWebdavDownload) { + throw new Error('WebDAV sync requires the Netcatty desktop sync bridge'); } - const client = this.getClient(); - const path = this.getSyncPath(); - const exists = await client.exists(path); - if (!exists) return null; - const data = await client.getFileContents(path, { format: 'text' }); - if (!data) return null; - return parseSyncedFileJson(data as string); + const result = await bridge.cloudSyncWebdavDownload(this.config); + return (result?.syncedFile ?? null) as SyncedFile | null; }); } @@ -247,15 +103,10 @@ export class WebDAVAdapter { throw new Error('Missing WebDAV config'); } const bridge = netcattyBridge.get(); - if (bridge?.cloudSyncWebdavDelete) { - await bridge.cloudSyncWebdavDelete(this.config); - return; + if (!bridge?.cloudSyncWebdavDelete) { + throw new Error('WebDAV sync requires the Netcatty desktop sync bridge'); } - const client = this.getClient(); - const path = this.getSyncPath(); - const exists = await client.exists(path); - if (!exists) return; - await client.deleteFile(path); + await bridge.cloudSyncWebdavDelete(this.config); }); } @@ -263,48 +114,6 @@ export class WebDAVAdapter { return null; } - private getClient(): WebDAVClient { - if (!this.config || !this.client) { - throw new Error('Missing WebDAV config'); - } - return this.client; - } - - private createClient(config: WebDAVConfig): WebDAVClient { - const extraOpts: Record = {}; - if (config.allowInsecure && typeof globalThis.process !== 'undefined') { - const https = require('https'); - extraOpts.httpsAgent = new https.Agent({ rejectUnauthorized: false }); - } - - if (config.authType === 'token') { - return createClient(config.endpoint, { - authType: AuthType.Token, - token: { - access_token: config.token || '', - token_type: 'Bearer', - }, - ...extraOpts, - }); - } - - if (config.authType === 'digest') { - return createClient(config.endpoint, { - authType: AuthType.Digest, - username: config.username || '', - password: config.password || '', - ...extraOpts, - }); - } - - return createClient(config.endpoint, { - authType: AuthType.Password, - username: config.username || '', - password: config.password || '', - ...extraOpts, - }); - } - private async withWebdavErrorContext( operation: string, fn: () => Promise, diff --git a/infrastructure/services/adapters/encryptedObjectStorageBridge.ts b/infrastructure/services/adapters/encryptedObjectStorageBridge.ts index 6c6206f32..7d1f627b9 100644 --- a/infrastructure/services/adapters/encryptedObjectStorageBridge.ts +++ b/infrastructure/services/adapters/encryptedObjectStorageBridge.ts @@ -16,7 +16,6 @@ import { DEFAULT_ENCRYPTED_SYNC_OBJECT_KEY, } from '../../../domain/encryptedObjectStorage'; import type { - CloudProvider, OAuthTokens, ProviderAccount, SyncedFile, @@ -381,7 +380,3 @@ export function webdavEncryptedObjectCapabilities(): EncryptedObjectStorageCapab atomicReplacement: true, }; } - -export function isWebdavProvider(provider: CloudProvider): boolean { - return provider === 'webdav'; -} diff --git a/infrastructure/services/updateService.ts b/infrastructure/services/updateService.ts index 847248133..57805f00c 100644 --- a/infrastructure/services/updateService.ts +++ b/infrastructure/services/updateService.ts @@ -1,17 +1,9 @@ /** * Update Service * - * Combines two update mechanisms: - * 1. GitHub API-based version comparison (used by useUpdateCheck for notification banner) - * 2. electron-updater bridge (used by SettingsSystemTab for download/install) + * GitHub API-based version comparison used by useUpdateCheck for the notification banner. */ -import { netcattyBridge } from "./netcattyBridge"; - -// ================================ -// Part 1: GitHub API Version Check -// ================================ - const GITHUB_API_URL = 'https://api.github.com/repos/binaricat/Netcatty/releases/latest'; const RELEASES_PAGE_URL = 'https://github.com/binaricat/Netcatty/releases'; @@ -122,102 +114,3 @@ export function getReleaseUrl(version?: string): string { } return RELEASES_PAGE_URL; } - -/** - * Get download URL for current platform - */ -export function getDownloadUrlForPlatform( - release: ReleaseInfo, - platform: string -): string | null { - const assets = release.assets; - - // Platform-specific file patterns - const patterns: Record = { - win32: [/\.exe$/i, /win.*\.zip$/i, /windows/i], - darwin: [/\.dmg$/i, /mac.*\.zip$/i, /darwin/i], - linux: [/\.AppImage$/i, /\.deb$/i, /linux/i], - }; - - const platformPatterns = patterns[platform] || []; - - for (const pattern of platformPatterns) { - const asset = assets.find((a) => pattern.test(a.name)); - if (asset) { - return asset.browserDownloadUrl; - } - } - - // Fallback to release page - return null; -} - -// ============================================= -// Part 2: electron-updater Bridge (IPC-based) -// ============================================= - -export interface ElectronUpdateCheckResult { - available: boolean; - supported?: boolean; - version?: string; - releaseNotes?: string; - releaseDate?: string | null; - error?: string; -} - -export interface UpdateDownloadProgress { - percent: number; - bytesPerSecond: number; - transferred: number; - total: number; -} - -export async function checkForUpdate(): Promise { - const bridge = netcattyBridge.get(); - if (!bridge?.checkForUpdate) { - return { available: false, supported: false, error: "Bridge unavailable" }; - } - try { - return await bridge.checkForUpdate(); - } catch (err: unknown) { - const message = err instanceof Error ? err.message : "Unknown error"; - return { available: false, error: message }; - } -} - -export async function downloadUpdate(): Promise<{ success: boolean; error?: string }> { - const bridge = netcattyBridge.get(); - if (!bridge?.downloadUpdate) { - return { success: false, error: "Bridge unavailable" }; - } - return bridge.downloadUpdate(); -} - -export function installUpdate(): void { - const bridge = netcattyBridge.get(); - bridge?.installUpdate?.(); -} - -export function onDownloadProgress( - cb: (progress: UpdateDownloadProgress) => void, -): (() => void) | undefined { - return netcattyBridge.get()?.onUpdateDownloadProgress?.(cb); -} - -export function onDownloaded(cb: () => void): (() => void) | undefined { - return netcattyBridge.get()?.onUpdateDownloaded?.(cb); -} - -export function onError( - cb: (payload: { error: string }) => void, -): (() => void) | undefined { - return netcattyBridge.get()?.onUpdateError?.(cb); -} - -/** Returns the GitHub Releases page URL, optionally for a specific version tag. */ -export function getReleasesUrl(version?: string): string { - if (version) { - return `${RELEASES_PAGE_URL}/tag/v${version}`; - } - return `${RELEASES_PAGE_URL}/latest`; -} diff --git a/infrastructure/theme/terminalAppearanceTokens.ts b/infrastructure/theme/terminalAppearanceTokens.ts index 1329d31b4..8223dac60 100644 --- a/infrastructure/theme/terminalAppearanceTokens.ts +++ b/infrastructure/theme/terminalAppearanceTokens.ts @@ -338,12 +338,6 @@ export function buildHostTreeThemeFromTerminalTheme(theme: TerminalTheme): HostT }; } -export const terminalAppearancePanelStyle = { - backgroundColor: 'var(--nc-term-panel-bg, var(--background))', - color: 'var(--nc-term-panel-fg, var(--foreground))', - borderColor: 'var(--nc-term-panel-border, var(--border))', -} as const; - export const terminalAppearanceSidePanelStyle = { ['--terminal-sidepanel-bg' as const]: 'var(--nc-term-panel-bg, var(--background))', ['--terminal-sidepanel-fg' as const]: 'var(--nc-term-panel-fg, var(--foreground))', @@ -363,14 +357,3 @@ export const terminalAppearanceThemePanelVars = { ['--terminal-panel-hover' as const]: 'var(--nc-term-panel-hover, var(--accent))', ['--terminal-panel-active' as const]: 'var(--nc-term-panel-active, var(--accent))', } as const; - -export const terminalAppearanceHostTreeTheme = { - termBg: 'var(--nc-term-host-tree-bg, var(--nc-term-bg, var(--background)))', - termFg: 'var(--nc-term-host-tree-fg, var(--nc-term-fg, var(--foreground)))', - mutedFg: 'var(--nc-term-host-tree-muted, var(--nc-term-muted, var(--muted-foreground)))', - separator: 'var(--nc-term-host-tree-separator, var(--nc-term-border, var(--border)))', - rowHoverBg: 'var(--nc-term-host-tree-hover-bg, var(--nc-term-hover, transparent))', - rowActiveBg: 'var(--nc-term-host-tree-active-bg, var(--nc-term-active, transparent))', - rowDropBg: 'var(--nc-term-host-tree-drop-bg, var(--nc-term-active, transparent))', - folderFg: 'var(--nc-term-host-tree-folder-fg, var(--nc-term-fg, var(--foreground)))', -} as const; diff --git a/infrastructure/theme/terminalAppearanceVars.ts b/infrastructure/theme/terminalAppearanceVars.ts index b77aa303e..a69263356 100644 --- a/infrastructure/theme/terminalAppearanceVars.ts +++ b/infrastructure/theme/terminalAppearanceVars.ts @@ -55,10 +55,6 @@ function applyTerminalAppearanceVarsToTargets(targets: HTMLElement[], theme: Ter } } -export function injectTerminalChromeSurfaceVars(theme: TerminalTheme): void { - applyTerminalAppearanceVarsToTargets(collectTerminalChromeSurfaceElements(), theme); -} - export function injectTerminalLayerChromeSurfaceVars(theme: TerminalTheme): void { applyTerminalAppearanceVarsToTargets(collectTerminalLayerChromeSurfaceElements(), theme); } @@ -72,11 +68,6 @@ function clearTerminalAppearanceVarsOnTargets(targets: HTMLElement[]): void { } } -export function clearTerminalChromeSurfaceVars(): void { - if (typeof document === 'undefined') return; - clearTerminalAppearanceVarsOnTargets(collectTerminalChromeSurfaceElements()); -} - export function clearTerminalLayerChromeSurfaceVars(): void { if (typeof document === 'undefined') return; clearTerminalAppearanceVarsOnTargets(collectTerminalLayerChromeSurfaceElements()); @@ -109,21 +100,6 @@ export function injectTerminalAppearanceVars( applyTerminalAppearanceVarsToTargets(targets, theme); } -export function clearTerminalAppearanceVars(root?: HTMLElement | null): void { - if (typeof document === 'undefined') return; - const targets: HTMLElement[] = []; - const appearanceRoot = root ?? findTerminalAppearanceRoot(); - if (appearanceRoot) targets.push(appearanceRoot); - const tabsRoot = document.querySelector('[data-top-tabs-root]'); - if (tabsRoot && tabsRoot !== appearanceRoot) targets.push(tabsRoot); - for (const hostTreeRoot of document.querySelectorAll( - '[data-section="app-host-tree-layer"], [data-section="terminal-host-tree-sidebar"], [data-section="terminal-side-panel"]', - )) { - if (!targets.includes(hostTreeRoot)) targets.push(hostTreeRoot); - } - clearTerminalAppearanceVarsOnTargets(targets); -} - export function injectTerminalPaneAppearanceVars(sessionId: string, theme: TerminalTheme): void { if (typeof document === 'undefined') return; const pane = document.querySelector(`[data-session-id="${sessionId}"]`); @@ -143,18 +119,3 @@ export function injectTerminalPaneAppearanceVars(sessionId: string, theme: Termi setStylePropertyIfChanged(pane, '--terminal-preview-toolbar-btn-hover', vars['--nc-term-toolbar-btn-hover']); setStylePropertyIfChanged(pane, '--terminal-preview-toolbar-btn-active', vars['--nc-term-toolbar-btn-active']); } - -export function clearTerminalPaneAppearanceVars(sessionId: string): void { - if (typeof document === 'undefined') return; - const pane = document.querySelector(`[data-session-id="${sessionId}"]`); - if (!pane) return; - const keys = [ - '--nc-term-bg', '--nc-term-fg', '--nc-term-border', - '--nc-term-toolbar-btn', '--nc-term-toolbar-btn-hover', '--nc-term-toolbar-btn-active', - '--terminal-preview-bg', '--terminal-preview-fg', '--terminal-preview-border', - '--terminal-preview-toolbar-btn', '--terminal-preview-toolbar-btn-hover', '--terminal-preview-toolbar-btn-active', - ]; - for (const key of keys) { - removeStylePropertyIfSet(pane, key); - } -} diff --git a/lib/customCss.test.ts b/lib/customCss.test.ts deleted file mode 100644 index 6f05e4935..000000000 --- a/lib/customCss.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; -import test from 'node:test'; - -const root = new URL('..', import.meta.url); - -function readProjectFile(path: string): string { - return readFileSync(join(root.pathname, path), 'utf8'); -} - -test('custom CSS helper uses a single stable style element id', () => { - const source = readProjectFile('lib/customCss.ts'); - - assert.match(source, /netcatty-custom-css/); - assert.match(source, /styleEl\.textContent = css/); -}); - -test('settings state applies custom CSS through the shared helper', () => { - const source = readProjectFile('application/state/useSettingsState.ts'); - - assert.match(source, /applyCustomCssToDocument\(customCSS\)/); -}); diff --git a/lib/useDiscoveredShells.test.ts b/lib/useDiscoveredShells.test.ts index a9c015611..35e76891f 100644 --- a/lib/useDiscoveredShells.test.ts +++ b/lib/useDiscoveredShells.test.ts @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { matchesSearchQuery } from "./searchMatcher"; +import { matchesSearchQuery } from "../domain/searchMatcher"; import { buildQuickSwitcherShells, resolveShellSetting } from "./useDiscoveredShells"; const DISCOVERED: DiscoveredShell[] = [ diff --git a/metadata.json b/metadata.json deleted file mode 100755 index 7bb08e006..000000000 --- a/metadata.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "netcatty SSH", - "description": "A modern, AI-powered SSH server manager and terminal simulator. Manage your hosts and practice in a virtual Linux environment powered by Gemini.", - "requestFramePermissions": [] -} diff --git a/package.json b/package.json index b97ab9e36..41e4539a5 100644 --- a/package.json +++ b/package.json @@ -55,11 +55,11 @@ "lint": "eslint .", "lint:fix": "eslint . --fix", "pretest": "npm run build:plugin-runtime-deps && npm run check:codebuddy-sdk-contract", - "test": "node --test --import tsx electron/*.test.cjs electron/preload/*.test.cjs electron/mcp/*.test.cjs electron/shared/*Privacy*.test.cjs electron/scripts/*.test.cjs electron/terminalWorker/*.test.cjs electron/capabilities/*.test.cjs electron/capabilities/*/*.test.cjs electron/capabilities/*/*/*.test.cjs electron/cli/*.test.cjs electron/hostBrowser/*Store.test.cjs electron/hostBrowser/hostBrowserManager.test.cjs electron/bridges/*.test.cjs electron/bridges/*/*.test.cjs electron/bridges/aiBridge/codexAppServer/*.test.cjs electron/bridges/aiBridge/sdk/*.test.cjs scripts/*.test.cjs application/*.test.ts application/app/*.test.ts application/i18n/locales/*.test.ts application/state/*.test.ts application/state/*/*.test.ts components/*.test.ts components/*.test.tsx components/editor/*.test.ts components/editor/*.test.tsx components/notes/*.test.ts components/notes/*.test.tsx components/port-forwarding/*.test.ts components/scripts/*.test.tsx components/systemManager/*.test.ts components/terminalLayer/*.test.ts components/settings/*.test.tsx components/settings/tabs/*.test.ts components/settings/tabs/ai/*.test.ts components/settings/tabs/ai/*.test.tsx components/ai/*.test.ts components/ai/*.test.tsx components/ai/toolArtifacts/*.test.ts components/ai/toolArtifacts/*.test.tsx components/ai-elements/*.test.tsx components/sftp/*.test.ts components/terminal/*.test.ts components/terminal/*.test.tsx components/terminal/runtime/*.test.ts components/vault/*.test.ts components/vault/*.test.tsx domain/*.test.ts domain/*/*.test.ts domain/*/*.test.cjs infrastructure/ai/*.test.ts infrastructure/ai/*/*.test.ts infrastructure/ai/sdk/*.test.ts infrastructure/config/*.test.ts infrastructure/monaco/*.test.ts infrastructure/persistence/*.test.ts infrastructure/services/*.test.ts infrastructure/services/*/*.test.ts lib/*.test.ts packages/*/src/*.test.ts", + "test": "node scripts/run-tests.mjs", "test:plugin-contract": "node --test --import tsx packages/*/src/*.test.ts", "test:plugin-examples": "node --test examples/plugins/database-minimal/*.test.cjs examples/plugins/database-rfam-readonly/*.test.cjs examples/plugins/terminal-selection-draft/prepare.test.cjs examples/plugins/global-agent/*.test.cjs", "pretest:plugin-runtime": "npm run build:plugin-runtime-deps && npm run build:plugin-view-examples", - "test:plugin-runtime": "node --test electron/plugins/*.test.cjs domain/pluginRuntimePolicy.test.cjs domain/pluginPermissionDescriptions.test.cjs domain/pluginThemePack.test.cjs domain/pluginGitHubRepository.test.cjs", + "test:plugin-runtime": "node scripts/run-tests.mjs --suite plugin-runtime", "test:plugin-host-drawn": "node --test --import tsx domain/pluginRemoteTreePolicy.test.cjs domain/pluginViewStylePolicy.test.cjs electron/plugins/hostDrawnViewHost.test.cjs application/state/pluginRemoteTree.test.tsx components/plugins/PluginRemoteSurface.test.tsx packages/plugin-sdk/src/hostReact.test.tsx application/state/pluginViewSession.test.ts application/state/terminalSidePanelPluginTabs.test.tsx components/PluginVaultPages.test.tsx components/PluginTerminalSidebar.test.tsx electron/plugins/viewResourceService.test.cjs", "pretest:plugin-runtime:electron": "npm run build:plugin-runtime-deps", "test:plugin-runtime:electron": "electron electron/plugins/electronRuntime.live.test.cjs", @@ -97,7 +97,6 @@ "@withfig/autocomplete": "^2.692.3", "ajv": "8.18.0", "ajv-formats": "3.0.1", - "bidi-js": "1.0.3", "css-tree": "^3.2.1", "electron-updater": "^6.8.3", "http-proxy-agent": "^7.0.2", @@ -155,6 +154,7 @@ "@xterm/addon-webgl": "0.20.0-beta.291", "@xterm/xterm": "6.1.0-beta.292", "ai": "^7.0.2", + "bidi-js": "1.0.3", "clsx": "2.1.1", "concurrently": "^9.2.1", "cross-env": "^10.1.0", diff --git a/scripts/electron-builder-config.test.cjs b/scripts/electron-builder-config.test.cjs index f7465068e..bbc6d8a96 100644 --- a/scripts/electron-builder-config.test.cjs +++ b/scripts/electron-builder-config.test.cjs @@ -52,10 +52,6 @@ test("build.files includes the single-channel SSH banner matcher", () => { config.files.includes("domain/singleChannelSshBanner.shared.cjs"), "packaged SSH and SFTP bridges require the shared banner matcher", ); - assert.ok( - config.files.includes("domain/singleChannelSshBanner.shared.mjs"), - "the shared banner matcher requires its source module", - ); const banner = require("../domain/singleChannelSshBanner.shared.cjs"); assert.equal(banner.remoteSoftwareRequiresSingleChannel("BHostSSH_7.0"), true); assert.equal(banner.remoteSoftwareRequiresSingleChannel("JumpServer"), false); diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs new file mode 100644 index 000000000..709c278fe --- /dev/null +++ b/scripts/run-tests.mjs @@ -0,0 +1,184 @@ +#!/usr/bin/env node +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const TEST_FILE_RE = /\.test\.(?:ts|tsx|cjs|mjs|js)$/; +const EXCLUDED_FILE_RE = /\.(?:live|docker)\.test\.(?:ts|tsx|cjs|mjs|js)$/; +const IGNORED_DIRS = new Set(["node_modules", "dist", "release", ".git"]); + +const UNIT_ROOT_DIRS = [ + "application", + "components", + "domain", + "electron", + "infrastructure", + "lib", + "packages", + "scripts", +]; + +const UNIT_ROOT_FILES = ["vite.config.test.ts"]; + +const PLUGIN_RUNTIME_DOMAIN_TESTS = [ + "domain/pluginRuntimePolicy.test.cjs", + "domain/pluginPermissionDescriptions.test.cjs", + "domain/pluginThemePack.test.cjs", + "domain/pluginGitHubRepository.test.cjs", +]; + +function walkTests(dir, out, excludeDirs = new Set()) { + if (!fs.existsSync(dir)) return; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (IGNORED_DIRS.has(entry.name) || excludeDirs.has(full)) continue; + walkTests(full, out, excludeDirs); + } else if ( + entry.isFile() && + TEST_FILE_RE.test(entry.name) && + !EXCLUDED_FILE_RE.test(entry.name) + ) { + out.push(full); + } + } +} + +function parseArgs(argv) { + let suite = "unit"; + let listOnly = false; + const filters = []; + const extraNodeTestArgs = []; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--suite" && argv[i + 1]) { + suite = argv[i + 1]; + i += 1; + } else if (arg.startsWith("--suite=")) { + suite = arg.slice("--suite=".length); + } else if (arg === "--filter" && argv[i + 1]) { + filters.push(argv[i + 1]); + i += 1; + } else if (arg.startsWith("--filter=")) { + filters.push(arg.slice("--filter=".length)); + } else if (arg === "--list") { + listOnly = true; + } else { + extraNodeTestArgs.push(arg); + } + } + + return { suite, listOnly, filters, extraNodeTestArgs }; +} + +function discoverFiles(suite) { + const files = []; + if (suite === "unit") { + const excludeDirs = new Set([path.join("electron", "plugins")]); + for (const root of UNIT_ROOT_DIRS) { + walkTests(root, files, excludeDirs); + } + for (const file of UNIT_ROOT_FILES) { + if (fs.existsSync(file)) files.push(file); + } + } else if (suite === "plugin-runtime") { + walkTests(path.join("electron", "plugins"), files); + for (const file of PLUGIN_RUNTIME_DOMAIN_TESTS) { + if (fs.existsSync(file)) files.push(file); + } + } else { + console.error(`[run-tests] Unknown suite: ${suite}`); + process.exit(2); + } + + return Array.from(new Set(files)).sort(); +} + +const WINDOWS_MAX_CMD_CHARS = 20_000; +const POSIX_MAX_CMD_CHARS = 120_000; +// Conservative per-argument quoting + separator overhead for CreateProcessW. +const ARG_OVERHEAD_CHARS = 3; + +export function batchTestFiles( + files, + baseArgsLength = 0, + maxCmdChars = process.platform === "win32" ? WINDOWS_MAX_CMD_CHARS : POSIX_MAX_CMD_CHARS, +) { + const batches = []; + let current = []; + let currentLen = baseArgsLength; + + for (const file of files) { + const addition = file.length + ARG_OVERHEAD_CHARS; + if (current.length > 0 && currentLen + addition > maxCmdChars) { + batches.push(current); + current = [file]; + currentLen = baseArgsLength + addition; + } else { + current.push(file); + currentLen += addition; + } + } + + if (current.length > 0) { + batches.push(current); + } + return batches; +} + +function main() { + const { suite, listOnly, filters, extraNodeTestArgs } = parseArgs(process.argv.slice(2)); + let files = discoverFiles(suite); + + if (filters.length > 0) { + files = files.filter((file) => filters.some((f) => file.includes(f))); + } + + if (listOnly) { + for (const file of files) console.log(file); + process.exit(0); + } + + if (files.length === 0) { + console.error(`[run-tests] No test files matched suite="${suite}"`); + process.exit(1); + } + + const baseArgs = ["--test"]; + if (suite === "unit") { + baseArgs.push("--import", "tsx"); + } + baseArgs.push(...extraNodeTestArgs); + + const baseLength = + process.execPath.length + + ARG_OVERHEAD_CHARS + + baseArgs.reduce((sum, arg) => sum + arg.length + ARG_OVERHEAD_CHARS, 0); + + const batches = batchTestFiles(files, baseLength); + let exitCode = 0; + + for (const batch of batches) { + const result = spawnSync(process.execPath, [...baseArgs, ...batch], { stdio: "inherit" }); + if (result.error) { + console.error(`[run-tests] Failed to spawn test process: ${result.error.message}`); + process.exit(1); + } + if (result.signal) { + process.kill(process.pid, result.signal); + } + if ((result.status ?? 1) !== 0 && exitCode === 0) { + exitCode = result.status ?? 1; + } + } + + process.exit(exitCode); +} + +const isMain = + process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isMain) { + main(); +} diff --git a/scripts/run-tests.test.mjs b/scripts/run-tests.test.mjs new file mode 100644 index 000000000..1e1093e43 --- /dev/null +++ b/scripts/run-tests.test.mjs @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { batchTestFiles } from "./run-tests.mjs"; + +test("batchTestFiles splits large test suites safely under the Windows 32,767-char CreateProcessW limit", () => { + const files = Array.from( + { length: 1400 }, + (_, i) => `components/settings/tabs/ai/verySpecificFeatureModule${String(i).padStart(4, "0")}.test.tsx`, + ); + const baseArgsLength = 200; + const batches = batchTestFiles(files, baseArgsLength, 20_000); + + assert.ok(batches.length > 1, "expected multiple batches for 1,400 paths"); + assert.deepEqual(batches.flat(), files, "all files must be preserved in order"); + + for (const batch of batches) { + const estimatedCmdLen = + baseArgsLength + batch.reduce((sum, f) => sum + f.length + 3, 0); + assert.ok( + estimatedCmdLen <= 20_000, + `batch exceeded budget: ${estimatedCmdLen}`, + ); + } +}); + +test("batchTestFiles keeps a single batch when total command length fits within budget", () => { + const files = ["a.test.ts", "b.test.ts", "c.test.ts"]; + const batches = batchTestFiles(files, 100, 20_000); + assert.deepEqual(batches, [files]); +}); + +test("batchTestFiles never drops or loops on a single path longer than the remaining budget", () => { + const longFile = `${"a".repeat(200)}.test.ts`; + const batches = batchTestFiles([longFile, "short.test.ts"], 150, 200); + assert.deepEqual(batches, [[longFile], ["short.test.ts"]]); +}); diff --git a/scripts/terminal-snippet-completion-performance.live.test.cjs b/scripts/terminal-snippet-completion-performance.live.test.cjs index ef811fb77..85aaffea4 100644 --- a/scripts/terminal-snippet-completion-performance.live.test.cjs +++ b/scripts/terminal-snippet-completion-performance.live.test.cjs @@ -28,7 +28,7 @@ if (!process.versions.electron) { stdin: { contents: [ 'export { getCompletions } from "./components/terminal/autocomplete/completionEngine";', - 'export { resetPinyinCacheForTests, getPinyinCacheStatsForTests } from "./lib/searchMatcher";', + 'export { resetPinyinCacheForTests, getPinyinCacheStatsForTests } from "./domain/searchMatcher";', ].join("\n"), resolveDir: root, loader: "ts", diff --git a/types/global/netcatty-bridge-ai.d.ts b/types/global/netcatty-bridge-ai.d.ts index bbe8bb00b..38bc871a6 100644 --- a/types/global/netcatty-bridge-ai.d.ts +++ b/types/global/netcatty-bridge-ai.d.ts @@ -262,9 +262,6 @@ declare global { onAiStreamData?(requestId: string, cb: (data: string) => void): () => void; onAiStreamEnd?(requestId: string, cb: () => void): () => void; onAiStreamError?(requestId: string, cb: (error: string) => void): () => void; - onAiAgentStdout?(agentId: string, cb: (data: string) => void): () => void; - onAiAgentStderr?(agentId: string, cb: (data: string) => void): () => void; - onAiAgentExit?(agentId: string, cb: (code: number | null) => void): () => void; } } diff --git a/types/global/netcatty-bridge-plugin.d.ts b/types/global/netcatty-bridge-plugin.d.ts new file mode 100644 index 000000000..300ec04c1 --- /dev/null +++ b/types/global/netcatty-bridge-plugin.d.ts @@ -0,0 +1,532 @@ +declare global { + interface NetcattyPluginRuntimeStatus { + available: boolean; + experimental: true; + credentialStorageAvailable?: boolean; + } + + interface NetcattyPluginCatalogSnapshot { + entries: NetcattyPluginCatalogEntry[]; + source: "registry" | "cached" | "builtin"; + error: string | null; + } + + interface NetcattyPluginCatalogEntry { + selectionToken?: string; + id: string; + version: string; + name: string; + description: string; + author: string; + repository: string; + commit: string; + license: string; + readme: string; + manifest: import("@netcatty/plugin-contract").PluginManifest; + artifact?: { url: string; sha256: string }; + } + + type NetcattyPluginAuthorRequest = + | { kind: 'catalog'; pluginId: string; selectionToken: string; sourceId: string } + | { kind: 'installed'; pluginId: string }; + interface NetcattyPluginAuthorPresentation { + author: string; + avatar: string | null; + officialMaintained: boolean; + sourceId: string; + version: string; + archiveSha256: string | null; + } + + type PluginPermissionMode = 'allow' | 'ask' | 'deny'; + type NetcattyPluginPermissionPrompt = import('@netcatty/plugin-contract').PermissionRequest & { + actionToken: string; resources: string[]; + }; + interface NetcattyPluginPermissionSnapshot { + policyRevision?: string; + policies?: Array<{ permission: string; resources: string[]; mode: PluginPermissionMode }>; + grants: Array<{ + permission: string; resource: string; resourceKind: string; + scope: 'always' | 'application' | 'session'; sessionId: string | null; grantedAt: number; + matchesCurrentActivation: boolean; + }>; + audit: Array<{ event: string; createdAt: number; permission?: string; scope?: string; mode?: PluginPermissionMode; action?: string }>; + } + + interface NetcattyPluginSource { + id: string; + kind: 'official' | 'third-party' | 'local' | 'github'; + name: string; + origin: string | null; + enabled?: boolean; + tag?: string; + commit?: string; + assetId?: number; + } + interface NetcattyGitHubPluginPreview { + token: string; + source: NetcattyPluginSource; + manifest: import("@netcatty/plugin-contract").PluginManifest; + archiveSha256: string; + assetName: string; + size: number; + } + interface NetcattyInstalledPlugin { + source?: NetcattyPluginSource; + id: string; + enabled: boolean; + activeVersion: string | null; + manifest: import("@netcatty/plugin-contract").PluginManifest | null; + archiveSha256?: string | null; + runtime: { + status: string; + kind: 'browser' | 'utility' | null; + lastError: string | null; + quarantinedAt: number | null; + }; + } + + interface NetcattyExtensionProviderContribution { + pluginId: string; + pluginVersion: string; + pluginDisplayName?: string; + provider: import("@netcatty/plugin-contract").ProviderContribution; + } + + interface NetcattyExtensionProviderRequest { + providerId: string; + kind: 'connection' | 'authentication' | 'importer'; + operation: string; + requestId?: string; + payload?: import("@netcatty/plugin-contract").JsonValue; + deadlineMs?: number; + } + + interface NetcattyPluginConnectionStartRequest { + requestId?: string; + sessionId: string; + protocol?: string; + hostLabel?: string; + hostname?: string; + providerId: string; + configuration: import("@netcatty/plugin-contract").JsonValue; + columns: number; + rows: number; + credential?: import("@netcatty/plugin-contract").CredentialRef | import("@netcatty/plugin-contract").SecretRef; + authenticationProviderId?: string; + sessionLog?: { enabled: boolean; directory: string; format: string; timestampsEnabled?: boolean }; + deadlineMs?: number; + } + + interface NetcattyPluginImporterPreview { + providerId: string; + result: import("@netcatty/plugin-contract").ImporterParseResult; + records: ReadonlyArray; + } + + interface NetcattyPluginImporterProgressEvent { + requestId: string; + providerId: string; + progress: Extract; + } + + interface NetcattyPluginAuthenticationChallengeOpenEvent { + requestId: string; + challengeRequestId: string; + challenge: import("@netcatty/plugin-contract").AuthenticationChallenge; + } + + interface NetcattyPluginAuthenticationChallengeCancelEvent { + requestId: string; + challengeRequestId: string; + challengeId?: string; + cancelled: true; + } + + type NetcattyPluginAuthenticationChallengeEvent = + | NetcattyPluginAuthenticationChallengeOpenEvent + | NetcattyPluginAuthenticationChallengeCancelEvent; + + interface NetcattyPluginLogStatus { + saveToDisk: boolean; + verbose: boolean; + droppedRecords: number; + writeErrors: number; + pendingBytes: number; + maxBytes: number; + retentionDays: number; + } + + interface NetcattyBridge { + getPluginLogStatus?(): Promise; + configurePluginLogs?(settings: { saveToDisk: boolean; verbose: boolean }): Promise; + openPluginLogFolder?(): Promise; + exportPluginLogs?(): Promise; + clearPluginLogs?(): Promise; + getPluginRuntimeStatus?(): Promise; + getPluginSourceBinding?(pluginId: string): Promise; + resetPluginSource?(pluginId: string, expectedSourceId: string): Promise; + listPluginSources?(): Promise; + addPluginSource?(source: { name: string; address: string }): Promise; + updatePluginSource?(source: { id: string; name: string; enabled: boolean }): Promise; + removePluginSource?(id: string, disablePlugins: boolean): Promise; + listPluginCatalog?(sourceId?: string): Promise; + getPluginAuthorPresentation?(request: NetcattyPluginAuthorRequest): Promise; + onPluginCatalogChanged?(callback: (event: { sourceId: string }) => void): () => void; + getPluginCatalogReadme?(id: string, selectionToken?: string, sourceId?: string): Promise; + getPluginCatalogReadmeImages?(id: string, selectionToken?: string, sourceId?: string): Promise>; + installCatalogPlugin?(id: string, selectionToken?: string, sourceId?: string, acceptedSourceId?: string): Promise; + setPluginAIHostReady?(ready: boolean): Promise; + setPluginAgentHostReady?(ready: boolean): Promise; + respondPluginAgentHost?(response: import("@netcatty/plugin-contract").PluginAgentHostResponse): Promise; + onPluginAgentHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAgentHostRequest) => void): () => void; + respondPluginAIHost?(response: import("@netcatty/plugin-contract").PluginAIHostResponse): Promise; + onPluginAIHostRequest?(callback: (request: import("@netcatty/plugin-contract").PluginAIHostRequest) => void): () => void; + setPluginInteractionReady?(ready: boolean): Promise; + respondPluginInteraction?(response: import("@netcatty/plugin-contract").HostInteractionResponse): Promise; + onPluginInteraction?(callback: (event: import("@netcatty/plugin-contract").HostInteractionEvent) => void): () => void; + listPlugins?(): Promise; + setPluginPermissionMode?(pluginId: string, permission: string, mode: PluginPermissionMode, policyRevision: string): Promise; + setPluginPermissionReady?(ready: boolean): Promise; + respondPluginPermission?(response: { requestId: string; actionToken: string; decision: 'allow' | 'deny' | 'cancel' }): Promise; + onPluginPermission?(callback: (event: NetcattyPluginPermissionPrompt | { requestId: string; closed: true }) => void): () => void; + getPluginPermissions?(pluginId: string): Promise; + revokePluginPermissions?(pluginId: string): Promise; + installPluginPackage?(archivePath: string, options?: { enable?: boolean }): Promise; + prepareGitHubPlugin?(repository: string): Promise; + installGitHubPlugin?(token: string): Promise; + discardGitHubPlugin?(token: string): Promise; + setPluginEnabled?(pluginId: string, enabled: boolean): Promise; + restartPlugin?(pluginId: string): Promise; + uninstallPlugin?(pluginId: string): Promise; + setPluginTerminalTarget?(target: import("@netcatty/plugin-contract").HostTerminalTarget): Promise; + getPluginThemes?(): Promise; + applyPluginTheme?(request: import("@netcatty/plugin-contract").ThemePackApplyRequest): Promise; + onPluginThemesChanged?(callback: () => void): () => void; + getPluginContributions?(options?: NetcattyPluginContributionQuery): Promise; + getPluginBrandIcon?(pluginId: string): Promise<{ light: string; dark?: string } | null>; + getPluginContributionIcon?(pluginId: string, icon: Extract): Promise<{ light: string; dark?: string }>; + executePluginCommand?(command: string, args?: unknown, context?: Record): Promise; + updatePluginSetting?(pluginId: string, settingId: string, value: unknown, scopeId?: string): Promise<{ restartRequired: boolean }>; + resetPluginSetting?(pluginId: string, settingId: string, scopeId?: string): Promise<{ restartRequired: boolean }>; + setPluginEnvironment?(environment: NetcattyPluginEnvironment): Promise; + listPluginTerminalProviders?(options: NetcattyTerminalProviderQuery): Promise>; + providePluginTerminal?(request: NetcattyTerminalProviderRequest): Promise>; + cancelPluginTerminalRequest?(requestId: string): Promise; + publishPluginTerminalSessionEvent?(event: NetcattyTerminalSessionEvent): Promise>; + listPluginExtensionProviders?(options: { kind: 'connection' | 'authentication' | 'importer' | 'sync'; locale?: string }): Promise>; + updatePluginCredentialCatalog?(entries: ReadonlyArray<{ id: string; ciphertext: string }>): Promise; + invokePluginExtensionProvider?(request: NetcattyExtensionProviderRequest): Promise; + cancelPluginExtensionRequest?(requestId: string): Promise; + pluginSyncConnect?(request: { + requestId?: string; + providerId: string; + configuration?: unknown; + credential?: unknown; + deadlineMs?: number; + }): Promise<{ account: { id: string; email?: string; name?: string; avatarUrl?: string } }>; + pluginSyncDisconnect?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise; + pluginSyncGetAccount?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise<{ + account: { id: string; email?: string; name?: string; avatarUrl?: string } | null; + }>; + pluginSyncGetCapabilities?(request: { requestId?: string; providerId: string; deadlineMs?: number }): Promise<{ + revisions: boolean; + conditionalWrites: boolean; + atomicReplacement: boolean; + maxObjectBytes?: number; + maxObjects?: number; + }>; + pluginSyncReadObject?(request: { + requestId?: string; + providerId: string; + key: string; + preferStream?: boolean; + deadlineMs?: number; + }): Promise<{ + found: boolean; + key: string; + data?: Uint8Array | null; + streamed?: boolean; + transferId?: string; + byteLength?: number; + revision?: string; + contentType?: string; + }>; + pluginSyncReadChunk?(request: { + requestId: string; + transferId: string; + maxBytes?: number; + }): Promise<{ chunk: Uint8Array; done: boolean }>; + pluginSyncWriteObject?(request: { + requestId?: string; + providerId: string; + key: string; + data: Uint8Array; + expectedRevision?: string | null; + preferStream?: boolean; + deadlineMs?: number; + }): Promise<{ created: boolean; revision?: string }>; + pluginSyncWriteBegin?(request: { + requestId?: string; + providerId: string; + key: string; + byteLength: number; + expectedRevision?: string | null; + deadlineMs?: number; + }): Promise<{ transferId: string; windowBytes: number }>; + pluginSyncWriteChunk?(request: { + requestId: string; + transferId: string; + sequence: number; + chunk: Uint8Array; + }): Promise<{ accepted: number }>; + pluginSyncWriteCommit?(request: { + requestId: string; + transferId: string; + }): Promise<{ created: boolean; revision?: string }>; + pluginSyncDeleteObject?(request: { + requestId?: string; + providerId: string; + key: string; + expectedRevision?: string; + deadlineMs?: number; + }): Promise<{ deleted: boolean }>; + pluginSyncPutSecret?(request: { + providerId: string; + key: string; + value: string; + }): Promise<{ kind: 'secret'; id: string; key: string; created?: boolean }>; + pluginSyncDeleteSecrets?(request: { + providerId: string; + keys?: string[]; + }): Promise<{ deleted: number }>; + pluginSyncRestoreSecrets?(request: { + providerId: string; + keys: string[]; + discard?: boolean; + }): Promise<{ restored: number; discarded?: number }>; + collectPluginSyncSidecars?(): Promise; + applyPluginSyncSidecars?(bundle: unknown): Promise<{ applied: boolean; count?: number; entries?: unknown }>; + pluginHostReady?(): boolean; + startPluginConnection?(request: NetcattyPluginConnectionStartRequest): Promise<{ sessionId: string; providerId: string; status: 'connecting' | 'connected'; diagnostics: ReadonlyArray }>; + writePluginConnection?(sessionId: string, data: Uint8Array): Promise; + controlPluginConnection?(sessionId: string, operation: 'resize' | 'signal' | 'reconnect' | 'close' | 'getStatus', payload?: Record): Promise; + detectPluginImporter?(request: { providerId: string; sample: Uint8Array; fileName?: string; mediaType?: string; deadlineMs?: number }): Promise; + selectPluginImporterFile?(): Promise<{ selectionToken: string; fileName: string; sample: Uint8Array } | null>; + releasePluginImporterFile?(selectionToken: string): Promise; + parsePluginImporterFile?(request: { requestId?: string; providerId: string; selectionToken: string; mediaType?: string; options?: import("@netcatty/plugin-contract").JsonValue; deadlineMs?: number }): Promise; + onPluginImporterProgress?(callback: (event: NetcattyPluginImporterProgressEvent) => void): () => void; + respondPluginAuthenticationChallenge?(response: { + requestId: string; + challengeRequestId: string; + challengeId: string; + response?: string | boolean | ReadonlyArray; + cancelled?: boolean; + }): Promise; + onPluginAuthenticationChallenge?(callback: (event: NetcattyPluginAuthenticationChallengeEvent) => void): () => void; + onPluginConnectionData?(callback: (event: { sessionId: string; data: Uint8Array }) => void): () => void; + onPluginConnectionClosed?(callback: (event: { sessionId: string; reason: string }) => void): () => void; + getPluginViewResource?(payload: import('@netcatty/plugin-contract').PluginViewResourceRequest): Promise; + openHostDrawnPluginView?(payload: NetcattyPluginViewOpenRequest): Promise<{ instanceId: string }>; + closeHostDrawnPluginView?(instanceId: string): Promise; + sendHostDrawnPluginViewEvent?(instanceId: string, event: import('@netcatty/plugin-contract').HostDrawnViewEvent): Promise; + onHostDrawnPluginViewUpdate?(callback: (event: import('@netcatty/plugin-contract').HostDrawnViewMessage & { viewId: string }) => void): () => void; + onPluginContributionsChanged?(callback: (event: { reason: string; pluginId: string | null; revision: number }) => void): () => void; + onPluginViewClosed?(callback: (event: NetcattyPluginViewClosedEvent) => void): () => void; + getPluginScopeCatalog?(): Promise; + setPluginScopeCatalog?(catalog: NetcattyPluginScopeCatalog): Promise; + onPluginScopeCatalogChanged?(callback: (catalog: NetcattyPluginScopeCatalog) => void): () => void; + } + + interface NetcattyPluginContributionQuery { + locale?: string; + context?: Record; + menuContexts?: Partial>>; + scopeIds?: Partial>; + } + + interface NetcattyPluginSettingContribution { + group?: string; + id: string; + label: string; + description?: string; + placeholder?: string; + control: string; + scope: string; + scopeId: string | null; + value?: unknown; + secret?: boolean; + configured: boolean; + visible: boolean; + restartRequired?: boolean; + required?: boolean; + options?: ReadonlyArray<{ value: string; label: string; description?: string }>; + minimum?: number; + maximum?: number; + step?: number; + sortable?: boolean; + valueSchema?: unknown; + } + + type NetcattyPluginIconReference = + | { kind: 'theme'; name: string } + | { kind: 'package'; light: string; dark?: string }; + + interface NetcattyPluginContributionSnapshot { + locale: string; + plugins: ReadonlyArray<{ + id: string; + version: string; + displayName: string; + description: string; + commands: ReadonlyArray<{ id: string; title: string; category?: string; description?: string; icon?: NetcattyPluginIconReference; enabled: boolean }>; + keybindings: ReadonlyArray<{ command: string; key: string; mac?: string; linux?: string; windows?: string; args?: unknown; enabled: boolean }>; + menus: ReadonlyArray<{ + id: string; + command: string; + alt?: string; + location: string; + title: string; + visible: boolean; + enabled: boolean; + checked?: boolean; + order?: number; + group?: string; + shortcut?: string; + showKeybinding?: boolean; + icon?: NetcattyPluginIconReference; + }>; + settings: ReadonlyArray; + views: ReadonlyArray<{ id: string; title: string; location: string; icon?: NetcattyPluginIconReference; order?: number; visible: boolean }>; + }>; + } + + interface NetcattyPluginEnvironment { + locale: string; + theme: string; + reducedMotion: boolean; + highContrast: boolean; + themeTokens?: Record; + } + + type NetcattyTerminalProviderKind = + | 'terminal.completion' + | 'terminal.decoration' + | 'terminal.link' + | 'terminal.hover' + | 'terminal.matcher' + | 'terminal.semantic' + | 'terminal.prompt' + | 'terminal.background' + | 'terminal.theme'; + + interface NetcattyTerminalProviderContribution { + pluginId: string; + pluginVersion: string; + runtimeId?: string; + pluginDisplayName: string; + provider: { + id: string; + label: string; + description?: string; + kind: NetcattyTerminalProviderKind; + capabilities?: ReadonlyArray; + configurationSchema?: unknown; + }; + } + + interface NetcattyTerminalProviderQuery { + kind: NetcattyTerminalProviderKind; + locale?: string; + preferredProviderIds?: ReadonlyArray; + } + + interface NetcattyTerminalSessionSnapshot { + sessionId: string; + hostId?: string; + workspaceId?: string; + protocol: string; + status: 'connecting' | 'connected' | 'disconnected'; + cwd?: string; + title?: string; + shellType?: 'posix' | 'fish' | 'powershell' | 'cmd' | 'unknown'; + cols?: number; + rows?: number; + alternateScreen?: boolean; + } + + interface NetcattyTerminalSessionEvent { + type: + | 'snapshot' + | 'created' + | 'connected' + | 'reconnected' + | 'cwdChanged' + | 'titleChanged' + | 'resized' + | 'alternateScreenChanged' + | 'commandSubmitted' + | 'commandCompleted' + | 'disconnected' + | 'disposed'; + session: NetcattyTerminalSessionSnapshot; + exitCode?: number; + } + + interface NetcattyTerminalProviderRequest { + requestId: string; + kind: NetcattyTerminalProviderKind; + operation: string; + session: NetcattyTerminalSessionSnapshot; + payload?: unknown; + locale?: string; + preferredProviderIds?: ReadonlyArray; + deadlineMs?: number; + } + + type NetcattyTerminalProviderResult = { + pluginId: string; + pluginVersion: string; + runtimeId?: string; + providerId: string; + kind: NetcattyTerminalProviderKind; + requestId: string; + status: 'ok'; + result: unknown; + } | { + pluginId: string; + pluginVersion: string; + runtimeId?: string; + providerId: string; + kind: NetcattyTerminalProviderKind; + requestId: string; + status: 'cancelled'; + } | { + pluginId: string; + pluginVersion: string; + providerId: string; + kind: NetcattyTerminalProviderKind; + requestId: string; + status: 'failed'; + error: { code: number; message: string; data?: unknown }; + }; + + type NetcattyPluginViewOpenRequest = import('@netcatty/plugin-contract').HostDrawnViewOpenRequest; + + interface NetcattyPluginViewClosedEvent { + instanceId: string; + pluginId: string; + viewId: string; + reason: string; + } + + type NetcattyPluginSettingScopeKind = 'workspace' | 'host' | 'session' | 'device'; + + type NetcattyPluginScopeCatalog = Record< + NetcattyPluginSettingScopeKind, + ReadonlyArray<{ id: string; label: string }> + >; + +} + +export {}; diff --git a/types/global/netcatty-bridge-portforward.d.ts b/types/global/netcatty-bridge-portforward.d.ts new file mode 100644 index 000000000..1301be7fb --- /dev/null +++ b/types/global/netcatty-bridge-portforward.d.ts @@ -0,0 +1,109 @@ +declare global { + // Port Forwarding Types + interface PortForwardOptions { + ruleId?: string; + tunnelId: string; + type: 'local' | 'remote' | 'dynamic'; + localPort: number; + bindAddress?: string; + remoteHost?: string; + remotePort?: number; + // SSH connection details + hostname: string; + hostId?: string; + port?: number; + username: string; + authMethod?: import("./domain/models").HostAuthMethod; + requiresMfa?: boolean; + password?: string; + totp?: NetcattyTotpConfig; + privateKey?: string; + certificate?: string; + keyId?: string; + passphrase?: string; + knownHosts?: import("./domain/models").KnownHost[]; + verifyHostKeys?: boolean; + proxy?: NetcattyProxyConfig; + jumpHosts?: NetcattyJumpHost[]; + identityFilePaths?: string[]; + useSshAgent?: boolean; + agentPublicKeys?: string[]; + identityAgent?: string; + identitiesOnly?: boolean; + addKeysToAgent?: string; + useKeychain?: boolean; + legacyAlgorithms?: boolean; + skipEcdsaHostKey?: boolean; + algorithmOverrides?: import("./domain/models").HostAlgorithmOverrides; + // Resolved keepalive for the target connection (caller has already + // applied host override / global fallback). interval in seconds. + keepaliveInterval?: number; + keepaliveCountMax?: number; + sshTcpConnectTimeoutMs?: number; + sshAuthReadyTimeoutMs?: number; + reuseTransport?: boolean; + } + + interface PortForwardResult { + tunnelId: string; + success: boolean; + localPort?: number; + cancelled?: boolean; + blockedByCleanup?: boolean; + reused?: boolean; + status?: 'inactive' | 'connecting' | 'active' | 'error'; + error?: string; + } + + interface PortForwardStatusResult { + tunnelId: string; + status: 'inactive' | 'connecting' | 'active' | 'error'; + type?: 'local' | 'remote' | 'dynamic'; + error?: string; + } + + type PortForwardRuntimePhase = + | 'connecting' + | 'active' + | 'stopping' + | 'error' + | 'inactive'; + + interface PortForwardRuntimeRecord { + ruleId?: string; + tunnelId: string; + phase: PortForwardRuntimePhase | string; + error?: string; + cleanupRequired?: boolean; + revision: number; + updatedAt: number; + } + + interface PortForwardRuntimeSnapshot { + epoch: string; + revision: number; + records: PortForwardRuntimeRecord[]; + } + + type PortForwardRuntimeEvent = + | { + epoch: string; + revision: number; + kind: 'upsert'; + record: PortForwardRuntimeRecord; + } + | { + epoch: string; + revision: number; + kind: 'remove'; + tunnelId: string; + ruleId?: string; + }; + + + type PortForwardStatusCallback = (status: 'inactive' | 'connecting' | 'active' | 'error', error?: string) => void; + type PortForwardRuntimeEventCallback = (event: PortForwardRuntimeEvent) => void; + +} + +export {}; diff --git a/vite.config.ts b/vite.config.ts index b8d4cd963..8e041a68b 100755 --- a/vite.config.ts +++ b/vite.config.ts @@ -111,7 +111,12 @@ export default defineConfig(() => { build: { // The shared runtime is also required by Electron; convert it for browser builds. commonjsOptions: { - include: [/node_modules/, /domain\/sshPublicKey\.shared\.cjs$/, /domain\/systemManager\/containerRuntime\.shared\.cjs$/, /domain\/plugin(?:RuntimePolicy|PermissionDescriptions|ThemePack|RemoteTreePolicy|ViewStylePolicy|GitHubRepository)\.cjs$/], + include: [ + /node_modules/, + /domain\/(?:sshPublicKey|singleChannelSshBanner|terminalPromptSecurity|totpPrompt)\.shared\.cjs$/, + /domain\/systemManager\/containerRuntime\.shared\.cjs$/, + /domain\/plugin(?:RuntimePolicy|PermissionDescriptions|ThemePack|RemoteTreePolicy|ViewStylePolicy|GitHubRepository)\.cjs$/, + ], }, chunkSizeWarningLimit: 3000, target: 'esnext', // Required for top-level await in WASM modules @@ -135,6 +140,9 @@ export default defineConfig(() => { // Keep the renderer alias pre-bundled so dev serves ESM instead of raw CommonJS. '@/domain/systemManager/containerRuntime.shared.cjs', '@/domain/sshPublicKey.shared.cjs', + '@/domain/singleChannelSshBanner.shared.cjs', + '@/domain/terminalPromptSecurity.shared.cjs', + '@/domain/totpPrompt.shared.cjs', '@/domain/pluginRuntimePolicy.cjs', '@/domain/pluginGitHubRepository.cjs', '@/domain/pluginPermissionDescriptions.cjs',