mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-06 19:10:53 +00:00
Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2006ae1568 | ||
|
|
ca7ac3e9e0 | ||
|
|
32ce54b4b5 | ||
|
|
75231954e2 | ||
|
|
34b7df42fb | ||
|
|
d3f328090b | ||
|
|
4501e92e55 | ||
|
|
95b9db74f7 | ||
|
|
a343cf1d8c | ||
|
|
81ecaeb75a | ||
|
|
328bd83cc9 | ||
|
|
bdd393225c | ||
|
|
0d22a31bab | ||
|
|
ae2e3e0d0d | ||
|
|
1c4545f006 | ||
|
|
b664f51731 | ||
|
|
51c317667c | ||
|
|
569b05e7fa | ||
|
|
180a1427be | ||
|
|
5c4c7e3fa8 | ||
|
|
1c41aad9ff | ||
|
|
516314f8ef | ||
|
|
43dd7a43b3 | ||
|
|
0a389e760e | ||
|
|
897c3e23e6 | ||
|
|
12531fbcc5 | ||
|
|
a64029bc0b | ||
|
|
b5815c3064 | ||
|
|
1f91fd54f1 | ||
|
|
2f76061ec8 | ||
|
|
dd9f6e862a | ||
|
|
f688a17f14 | ||
|
|
e6d3047d0a | ||
|
|
f50c18e5c7 | ||
|
|
33b4bd1a43 | ||
|
|
31458b00a4 | ||
|
|
f68570d942 | ||
|
|
9474601fdf | ||
|
|
4cef084e99 | ||
|
|
58eeefb4c1 | ||
|
|
6f8211481c | ||
|
|
6458dbe039 | ||
|
|
6e0eacc6ae | ||
|
|
73ee6c0f31 | ||
|
|
905aed61ad | ||
|
|
13d05b0ea4 | ||
|
|
1045737c68 | ||
|
|
909d3e5ed2 | ||
|
|
cb7e49c409 | ||
|
|
02be8a2e0a | ||
|
|
ca2cdcbd12 | ||
|
|
f7fed5fd6f | ||
|
|
25aa27bbf8 | ||
|
|
7e44b774f8 | ||
|
|
c5c7cfdae3 | ||
|
|
62085cb3c2 | ||
|
|
960cc05219 | ||
|
|
7ad4a7daf5 |
No files matched your search
@@ -25,6 +25,7 @@ import { SessionPublisher } from './application/app/publishers/SessionPublisher'
|
||||
import { SettingsPublisher } from './application/app/publishers/SettingsPublisher';
|
||||
import { VaultPublisher } from './application/app/publishers/VaultPublisher';
|
||||
import { AppLockRuntimePublisher } from './application/app/publishers/AppLockRuntimePublisher';
|
||||
import { useReportRendererReady } from './components/AppLockGate';
|
||||
|
||||
// Initialize fonts eagerly at app startup
|
||||
initializeFonts();
|
||||
@@ -61,8 +62,10 @@ function App() {
|
||||
|
||||
/**
|
||||
* `AppLockGate` (index.tsx) owns `useSettingsState` / `useAppLockState` so the
|
||||
* lock overlay can render before app children mount, and it owns the
|
||||
* splash-removal + rendererReady signal (deep links must wait for unlock).
|
||||
* lock overlay can render before app children mount, and owns splash removal
|
||||
* plus the lock-gated `rendererReady` policy. This lazy route reports ready
|
||||
* after `AppSideEffects` and bridge listeners have mounted so cold-start
|
||||
* intents and deep links never race a suspended chunk.
|
||||
* App forwards the gate's settings instance into SettingsPublisher so the
|
||||
* runtime slot/context still publish a single settings runtime.
|
||||
*/
|
||||
@@ -78,6 +81,9 @@ function AppWithProviders({ settings, appLock }: { settings: SettingsState; appL
|
||||
}, []);
|
||||
|
||||
useExternalMcpGrantPersister();
|
||||
// Signal rendererReady after child effects (AppSideEffects) and bridge setup
|
||||
// have registered in this commit's effect flush.
|
||||
useReportRendererReady();
|
||||
|
||||
return (
|
||||
<SettingsPublisher settings={settings}>
|
||||
|
||||
@@ -54,6 +54,25 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="sponsors"></a>
|
||||
# ❤️ スポンサー
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="middle" width="200">
|
||||
<a href="https://netcatty.hualong-ai.com/" target="_blank">
|
||||
<img src="docs/assets/sponsors/hualong-card.png" alt="HuaLongAI" width="175" />
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
本プロジェクトをご支援いただいている <strong>HuaLongAI(華龍算力)</strong> に感謝いたします!<br />
|
||||
HuaLongAI は Codex、DeepSeek、Claude シリーズモデルを中心に提供する安定かつ高効率な API リレーサービスです。100% 公式ソース直結・高可用性(平均 SLA 99.2% 以上)で、トークン単位の明細を 1 件ずつ検証できる透明な課金体系と法人契約・請求書発行に対応しています。<a href="https://netcatty.hualong-ai.com/" target="_blank">こちらから登録すると $2 の専用無料クレジットをプレゼント</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
<a name="catty-agent"></a>
|
||||
# 🔥 Catty Agent — あなたの IT 運用 AI パートナー
|
||||
|
||||
@@ -108,6 +127,7 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
|
||||
|
||||
# 目次 <!-- omit in toc -->
|
||||
|
||||
- [❤️ スポンサー](#sponsors)
|
||||
- [🔥 Catty Agent — AI パートナー](#catty-agent)
|
||||
- [🧩 プラグインシステム](#plugin-system)
|
||||
- [Netcatty とは](#netcatty-とは)
|
||||
|
||||
@@ -53,6 +53,26 @@
|
||||
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
|
||||
|
||||
|
||||
---
|
||||
|
||||
<a name="sponsors"></a>
|
||||
# ❤️ Sponsors
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="middle" width="200">
|
||||
<a href="https://netcatty.hualong-ai.com/" target="_blank">
|
||||
<img src="docs/assets/sponsors/hualong-card.png" alt="HuaLongAI" width="175" />
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
Thanks to <strong>HuaLongAI</strong> for sponsoring this project!<br />
|
||||
HuaLongAI is a stable, efficient API relay service focused on Codex, DeepSeek, and Claude models: 100% direct from official sources, never diluted, highly available, with average SLA above 99.2%. Billing is transparent, with token-level bills you can verify line by line, and enterprise contracts and invoices are supported.
|
||||
<a href="https://netcatty.hualong-ai.com/" target="_blank">Sign up here for an exclusive $2 free credit</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
<a name="catty-agent"></a>
|
||||
@@ -67,6 +87,8 @@
|
||||
- 🔥 **Intelligent context awareness** — understands your server environment and provides tailored responses
|
||||
- 🚀 **One-click complex operations** — set up clusters, deploy services, and more with simple instructions
|
||||
|
||||
To search the web with DeepSeek, open **Settings → AI → Web Search**, enable web search, select **DeepSeek**, and enter your DeepSeek API key. You can use it with your current chat model. [DeepSeek Search API and pricing](https://api-docs.deepseek.com/guides/search/)
|
||||
|
||||
### 🎬 AI in Action
|
||||
|
||||
#### 🔥 Single Host — Intelligent Server Diagnostics
|
||||
@@ -110,6 +132,7 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
|
||||
|
||||
# Contents <!-- omit in toc -->
|
||||
|
||||
- [❤️ Sponsors](#sponsors)
|
||||
- [🔥 Catty Agent — AI Partner](#catty-agent)
|
||||
- [🧩 Plugin System](#plugin-system)
|
||||
- [What is Netcatty](#what-is-netcatty)
|
||||
@@ -164,6 +187,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
|
||||
- **Fast search** — locate hosts and groups quickly
|
||||
|
||||
### 🖥️ Terminal Workspaces
|
||||
- Right-click a standalone terminal tab and choose **Convert to Workspace** to keep your running shell as the first pane.
|
||||
- **Split panes** — horizontal and vertical splits for multi-tasking
|
||||
- **Session management** — run multiple connections side-by-side
|
||||
- **Save current screen** — right-click a terminal to save the visible final text, without replaying keystrokes or overwritten output; scroll first to save an earlier screen.
|
||||
|
||||
@@ -54,6 +54,25 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="sponsors"></a>
|
||||
# ❤️ 赞助商
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="middle" width="200">
|
||||
<a href="https://netcatty.hualong-ai.com/" target="_blank">
|
||||
<img src="docs/assets/sponsors/hualong-card.png" alt="华龙算力" width="175" />
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
感谢 <strong>华龙算力(HuaLongAI)</strong> 赞助本项目!<br />
|
||||
HuaLongAI(华龙算力)是一家稳定、高效的 API 中转服务商,主营 Codex、DeepSeek 与 Claude 系列模型,100% 官方源直供、不掺假、高可用,平均 SLA 高于 99.2%;计费透明,Token 级账单可逐笔核验,支持企业合同与发票,<a href="https://netcatty.hualong-ai.com/" target="_blank">点击此处注册赠送 2$ 专属使用额度</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
<a name="catty-agent"></a>
|
||||
# 🔥 Catty Agent — 你的 IT 运维 AI 搭档
|
||||
|
||||
@@ -108,6 +127,7 @@
|
||||
|
||||
# 目录 <!-- omit in toc -->
|
||||
|
||||
- [❤️ 赞助商](#sponsors)
|
||||
- [🔥 Catty Agent — AI 搭档](#catty-agent)
|
||||
- [🧩 插件系统](#plugin-system)
|
||||
- [Netcatty 是什么](#netcatty-是什么)
|
||||
|
||||
@@ -54,6 +54,25 @@
|
||||
|
||||
---
|
||||
|
||||
<a name="sponsors"></a>
|
||||
# ❤️ 贊助商
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" valign="middle" width="200">
|
||||
<a href="https://netcatty.hualong-ai.com/" target="_blank">
|
||||
<img src="docs/assets/sponsors/hualong-card.png" alt="華龍算力" width="175" />
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
感謝 <strong>華龍算力(HuaLongAI)</strong> 贊助本專案!<br />
|
||||
HuaLongAI(華龍算力)是一家穩定、高效的 API 中繼服務商,主打 Codex、DeepSeek 與 Claude 系列模型,100% 官方源直供、不摻假、高可用,平均 SLA 高於 99.2%;計費透明,Token 級帳單可逐筆核驗,支援企業合約與發票,<a href="https://netcatty.hualong-ai.com/" target="_blank">點擊此處註冊贈送 2$ 專屬使用額度</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
<a name="catty-agent"></a>
|
||||
# 🔥 Catty Agent —— 你的 IT 維運 AI 夥伴
|
||||
|
||||
@@ -108,6 +127,7 @@
|
||||
|
||||
# 目錄 <!-- omit in toc -->
|
||||
|
||||
- [❤️ 贊助商](#sponsors)
|
||||
- [🔥 Catty Agent —— AI 夥伴](#catty-agent)
|
||||
- [🧩 外掛系統](#plugin-system)
|
||||
- [Netcatty 是什麼](#netcatty-是什麼)
|
||||
|
||||
@@ -270,7 +270,7 @@ export function flushQueuedTrayPanelConnectHostsImpl(getCtx: AppContextGetter) {
|
||||
}
|
||||
|
||||
export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: KeyboardEvent) {
|
||||
const { HOTKEY_DEBUG, closeTabKeyStr, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
|
||||
const { HOTKEY_DEBUG, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding } = getCtx();
|
||||
{
|
||||
if (
|
||||
isTargetInsideRemoteDesktopCapture(e.target, e.composedPath?.bind(e))
|
||||
@@ -280,8 +280,14 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
}
|
||||
|
||||
const isMac = hotkeyScheme === 'mac';
|
||||
// Secondary chords added in Settings share the action of their default
|
||||
// binding, so every "is this action's shortcut?" check must scan all of them.
|
||||
const matchesActionHotkey = (action: string): boolean => keyBindings.some((binding) => (
|
||||
binding.action === action
|
||||
&& matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
|
||||
));
|
||||
const target = e.target as HTMLElement;
|
||||
const isCloseTabHotkey = closeTabKeyStr ? matchesKeyBinding(e, closeTabKeyStr, isMac) : false;
|
||||
const isCloseTabHotkey = matchesActionHotkey('closeTab');
|
||||
const dialogHotkeyScope = target.closest?.('[data-hotkey-close-tab="true"]');
|
||||
|
||||
if (isCloseTabHotkey && dialogHotkeyScope) {
|
||||
@@ -308,15 +314,9 @@ export function handleGlobalHotkeyKeyDownImpl(getCtx: AppContextGetter, e: Keybo
|
||||
target instanceof HTMLElement &&
|
||||
!!target.closest?.(".xterm, .xterm-helper-textarea, .xterm-screen, .xterm-viewport");
|
||||
|
||||
const quickSwitchBinding = keyBindings.find((binding) => binding.action === 'quickSwitch');
|
||||
const quickSwitchKeyStr = quickSwitchBinding ? (isMac ? quickSwitchBinding.mac : quickSwitchBinding.pc) : null;
|
||||
const isQuickSwitchHotkey = quickSwitchKeyStr ? matchesKeyBinding(e, quickSwitchKeyStr, isMac) : false;
|
||||
const paneZoomBinding = keyBindings.find((binding) => binding.action === 'togglePaneZoom');
|
||||
const paneZoomKeyStr = paneZoomBinding ? (isMac ? paneZoomBinding.mac : paneZoomBinding.pc) : null;
|
||||
const isPaneZoomHotkey = paneZoomKeyStr ? matchesKeyBinding(e, paneZoomKeyStr, isMac) : false;
|
||||
const hostTreeBinding = keyBindings.find((binding) => binding.action === 'toggleHostTree');
|
||||
const hostTreeKeyStr = hostTreeBinding ? (isMac ? hostTreeBinding.mac : hostTreeBinding.pc) : null;
|
||||
const isHostTreeHotkey = hostTreeKeyStr ? matchesKeyBinding(e, hostTreeKeyStr, isMac) : false;
|
||||
const isQuickSwitchHotkey = matchesActionHotkey('quickSwitch');
|
||||
const isPaneZoomHotkey = matchesActionHotkey('togglePaneZoom');
|
||||
const isHostTreeHotkey = matchesActionHotkey('toggleHostTree');
|
||||
|
||||
if (
|
||||
(isFormElement || isMonacoElement)
|
||||
|
||||
@@ -66,7 +66,7 @@ import type { PaneMagnificationController } from '../../domain/paneMagnification
|
||||
import { isPluginViewEditingTarget } from '../state/pluginKeybindings';
|
||||
import { resolveCloseIntent } from '../state/resolveCloseIntent';
|
||||
import { resolveSnippetsShortcutIntent } from '../state/resolveSnippetsShortcutIntent';
|
||||
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
|
||||
import { isNativeCloseTabBound, resolveWindowCommandCloseIntent } from '../state/windowCommandClose';
|
||||
import type { SyncPayload } from '../../domain/sync';
|
||||
import { prepareSyncPayloadApply, buildLocalVaultPayloadAsync, hasMeaningfulSyncData } from '../syncPayload';
|
||||
import {
|
||||
@@ -651,7 +651,7 @@ export function AppSideEffects() {
|
||||
const _handleTrayTogglePortForward = useEffectEvent((ruleId: string, start: boolean) => { return handleTrayTogglePortForwardImpl(() => ({ hasRuntimeTunnel, hosts, identities, keys, knownHosts: effectiveKnownHosts, portForwardingRules, resolveEffectiveHost, ruleId, start, startTunnel, stopTunnel, t, terminalSettings, toast, undefined }), ruleId, start); });
|
||||
const _handleTrayPanelConnect = useEffectEvent((hostId: string) => { return handleTrayPanelConnectImpl(() => ({ addConnectionLog, connectToHost, hostId, hosts, identities, keys, resolveEffectiveHost, resolveHostAuth, systemInfoRef, t, toast }), hostId); });
|
||||
const _handleTrayPanelConnectRequest = useEffectEvent((hostId: string) => { return handleTrayPanelConnectRequestImpl(() => ({ connectNow: _handleTrayPanelConnect, hostId, isVaultInitialized, queueConnect: (queuedHostId: string) => setPendingTrayPanelConnectHostIds((prev) => [...prev, queuedHostId]) }), hostId); });
|
||||
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, closeTabKeyStr, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
|
||||
const _handleGlobalHotkeyKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleGlobalHotkeyKeyDownImpl(() => ({ HOTKEY_DEBUG, e, executeHotkeyAction, hotkeyScheme, keyBindings, matchesKeyBinding }), e); });
|
||||
const _handleEscapeKeyDown = useEffectEvent((e: KeyboardEvent) => { return handleEscapeKeyDownImpl(() => ({ e, isQuickSwitcherOpen, setIsQuickSwitcherOpen }), e); });
|
||||
|
||||
// Vault hosts for tray / auto-start; terminalHosts (vault + ephemeral) only for
|
||||
@@ -1082,13 +1082,6 @@ export function AppSideEffects() {
|
||||
setSessionPoppedOut(sessionId, false);
|
||||
}), [setSessionPoppedOut]);
|
||||
|
||||
const closeTabKeyStr = useMemo(() => {
|
||||
if (hotkeyScheme === 'disabled') return null;
|
||||
const closeTabBinding = keyBindings.find((binding) => binding.action === 'closeTab');
|
||||
if (!closeTabBinding) return null;
|
||||
return hotkeyScheme === 'mac' ? closeTabBinding.mac : closeTabBinding.pc;
|
||||
}, [hotkeyScheme, keyBindings]);
|
||||
|
||||
const confirmIfBusyLocalTerminal = useCallback(
|
||||
async (sessionIds: string[]): Promise<boolean> => { return confirmIfBusyLocalTerminalImpl(() => ({ netcattyBridge, sessionIds, sessions, t }), sessionIds); },
|
||||
[sessions, t],
|
||||
@@ -1228,7 +1221,7 @@ export function AppSideEffects() {
|
||||
logViewIds: logViews.map((logView) => logView.id),
|
||||
pluginViewTabIds: pluginViewTabs.map((tab) => tab.id),
|
||||
hasOpenDialog: Boolean(topmostDialogClose),
|
||||
closeTabShortcutEnabled: isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true),
|
||||
closeTabShortcutEnabled: isNativeCloseTabBound(hotkeyScheme, keyBindings, true),
|
||||
});
|
||||
|
||||
if (intent.kind === 'forwardShortcut') {
|
||||
@@ -1261,7 +1254,7 @@ export function AppSideEffects() {
|
||||
}
|
||||
|
||||
await netcattyBridge.get()?.windowClose?.();
|
||||
}, [closeLogView, closeTabKeyStr, editorTabs, executeHotkeyAction, logViews, pluginViewTabs, sessions, workspaces]);
|
||||
}, [closeLogView, editorTabs, executeHotkeyAction, hotkeyScheme, keyBindings, logViews, pluginViewTabs, sessions, workspaces]);
|
||||
|
||||
useEffect(() => {
|
||||
// Cmd/Ctrl+W from the app menu arrives via IPC, not the keydown listener.
|
||||
|
||||
@@ -274,7 +274,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
const {
|
||||
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
convertKnownHostToHost, convertSessionToWorkspace, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
@@ -569,6 +569,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onMoveSessionToNewWindow={moveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={convertSessionToWorkspace}
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
|
||||
@@ -131,6 +131,7 @@ export function ChromeHost() {
|
||||
sessionRenameTarget: session.sessionRenameTarget,
|
||||
setActiveTabId: sessionActions?.setActiveTabId,
|
||||
startSessionRename: sessionActions?.startSessionRename,
|
||||
convertSessionToWorkspace: sessionActions?.convertSessionToWorkspace,
|
||||
renameSessionInline: sessionActions?.renameSessionInline,
|
||||
startWorkspaceRename: sessionActions?.startWorkspaceRename,
|
||||
submitSessionRename: sessionActions?.submitSessionRename,
|
||||
|
||||
@@ -59,6 +59,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -148,6 +149,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -197,6 +199,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createSerialSession,
|
||||
createSessionFromCloneSource,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceWithHosts,
|
||||
getOrderedWorkTabs,
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Choose Grok mode and send…',
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
'ai.chat.deliveredTextFile.source': 'Text included in this reply',
|
||||
'ai.chat.deliveredTextFile.preview': 'Preview',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Hide preview',
|
||||
'ai.chat.deliveredTextFile.save': 'Save as',
|
||||
'ai.chat.deliveredTextFile.saving': 'Saving…',
|
||||
'ai.chat.deliveredTextFile.saved': 'File saved',
|
||||
'ai.chat.deliveredTextFile.exists': 'That file exists. Choose another name.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Could not save this file.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Saving is not available in this window.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Preview is shortened. Saving keeps the full file.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
'ai.chat.preparing': 'Preparing…',
|
||||
@@ -36,6 +47,29 @@ export const enAiMessages: Messages = {
|
||||
'ai.agents': 'Agents',
|
||||
'ai.providers.empty': 'No providers configured. Add a provider to get started.',
|
||||
'ai.providers.add': 'Add Provider',
|
||||
'ai.providers.modal.title': 'Add AI Provider',
|
||||
'ai.providers.modal.searchPlaceholder': 'Search providers, models, or domains...',
|
||||
'ai.providers.modal.clearSearch': 'Clear search',
|
||||
'ai.providers.modal.categoriesLabel': 'Provider categories',
|
||||
'ai.providers.modal.category.all': 'All',
|
||||
'ai.providers.modal.category.sponsor': 'Sponsors',
|
||||
'ai.providers.modal.category.official': 'Official',
|
||||
'ai.providers.modal.category.gateway': 'Gateways',
|
||||
'ai.providers.modal.category.cn': 'China Models',
|
||||
'ai.providers.modal.category.localCustom': 'Local & Custom',
|
||||
'ai.providers.modal.categoryHint.sponsor': 'Supporting Netcatty development',
|
||||
'ai.providers.modal.added': 'Added',
|
||||
'ai.providers.modal.noResults': 'No matching providers',
|
||||
'ai.providers.modal.noResultsHint': 'Try another keyword, or set up any OpenAI / Anthropic / Google compatible endpoint manually.',
|
||||
'ai.providers.modal.useCustom': 'Add Custom Provider',
|
||||
'ai.providers.modal.customName': 'Custom',
|
||||
'ai.providers.modal.subtitle.ollama': 'Local or Ollama Cloud · localhost:11434',
|
||||
'ai.providers.modal.subtitle.custom': 'OpenAI / Anthropic / Google compatible',
|
||||
'ai.providers.sponsor.hualong.name': 'HuaLongAI',
|
||||
'ai.providers.sponsor.hualong.badge': '$2 Free',
|
||||
'ai.providers.sponsor.hualong.tagline': 'Codex · DeepSeek · Claude',
|
||||
'ai.providers.sponsor.hualong.description': 'Stable, high-availability API relay for Codex, DeepSeek, and Claude models. 100% direct from official sources with 99.2%+ average SLA, verifiable token-level billing, and enterprise invoicing.',
|
||||
'ai.providers.sponsor.hualong.cta': 'Claim $2 Credit',
|
||||
'ai.providers.active': 'Active',
|
||||
'ai.providers.apiKeyConfigured': 'API key configured',
|
||||
'ai.providers.noApiKey': 'No API key',
|
||||
@@ -117,6 +151,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'App Server is available for this Codex CLI.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'The live Codex model catalog is unavailable. Using the built-in model list.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Allow for session',
|
||||
'ai.planReview.title': 'Review implementation plan',
|
||||
'ai.planReview.keepPlanning': 'Keep planning',
|
||||
'ai.planReview.approveAndImplement': 'Approve and implement',
|
||||
'ai.codex.appServer.userInput.title': 'Codex needs your input',
|
||||
'ai.codex.appServer.userInput.description': 'Answer these questions to continue the current turn.',
|
||||
'ai.codex.appServer.userInput.other': 'Enter another answer',
|
||||
@@ -305,6 +342,16 @@ export const enAiMessages: Messages = {
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 could not attach an MCP tool. The chat will continue without it.',
|
||||
|
||||
// AI MiMo Code (Xiaomi MiMo Code CLI — OpenCode fork)
|
||||
'ai.agy.title': 'Antigravity CLI (Beta)',
|
||||
'ai.agy.description': "Experimental Beta: Google's Antigravity coding agent CLI connected via the official Agent Client Protocol (agy acp --stdio). Feature coverage is still limited and not yet thoroughly tested — use at your own risk. Sign in with agy in your terminal, then select it as an external coding agent.",
|
||||
'ai.agy.detecting': 'Detecting...',
|
||||
'ai.agy.detected': 'Detected',
|
||||
'ai.agy.notFound': 'Not found',
|
||||
'ai.agy.path': 'Path:',
|
||||
'ai.agy.notFoundHint': 'Could not find agy in PATH. Install Antigravity CLI or specify the executable path below.',
|
||||
'ai.agy.customPathPlaceholder': 'e.g. /usr/local/bin/agy',
|
||||
'ai.agy.check': 'Check',
|
||||
'ai.agy.resetPath': 'Reset',
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': "Xiaomi's MiMo Code CLI, an OpenCode fork. Install it and configure providers in its own config, then select it as an external coding agent.",
|
||||
'ai.mimo.detecting': 'Detecting...',
|
||||
@@ -328,6 +375,13 @@ export const enAiMessages: Messages = {
|
||||
'ai.grok.check': 'Check',
|
||||
'ai.grok.resetPath': 'Reset',
|
||||
'ai.grok.runtime.acp.title': 'Use Grok ACP (agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok needs your input',
|
||||
'ai.grok.userQuestion.description': 'Answers do not grant permissions. Do not include passwords or tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Send answers',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode needs your input',
|
||||
'ai.agentQuestions.title': 'Allow agent questions',
|
||||
'ai.agentQuestions.description': 'Let this agent ask for details during a turn. Answers do not grant tool permissions.',
|
||||
'ai.agentQuestions.codexDescription': 'Let Codex App Server ask for details in default mode. Answers do not grant tool permissions.',
|
||||
'ai.grok.runtime.acp.default': 'Default',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Talk to Grok over Agent Client Protocol (grok agent stdio). Injects Netcatty MCP on session/new. Turn off to use the original headless streaming-json CLI path.',
|
||||
@@ -634,12 +688,20 @@ export const enAiMessages: Messages = {
|
||||
'ai.chat.managerSelectedCount': '{n} selected',
|
||||
'ai.chat.managerSelectRow': 'Select this chat',
|
||||
'ai.chat.managerRegenerateTitle': 'Regenerate title with AI',
|
||||
'ai.chat.managerRegenerateTitleUpdated': 'Chat title updated.',
|
||||
'ai.chat.managerRegenerateTitleUnchanged': 'Chat title is already up to date.',
|
||||
'ai.chat.managerRegenerateTitleNoModel': 'No AI provider/model is configured for title generation. Configure a provider or title model in AI Settings.',
|
||||
'ai.chat.managerRegenerateTitleFailed': 'Failed to regenerate title: {error}',
|
||||
'ai.chat.managerRegenerateTitleBatchDone': 'Updated {n} chat title(s).',
|
||||
'ai.chat.managerRegenerateTitleBatchPartial': 'Updated {updated} title(s), {failed} failed.',
|
||||
'ai.chat.managerExportOne': 'Export this chat',
|
||||
'ai.chat.managerBadgeActive': 'Active',
|
||||
'ai.chat.managerBadgeIdle': 'Idle',
|
||||
'ai.chat.managerMessagesCount': '{n} messages',
|
||||
'ai.chat.managerDeleteTitle': 'Delete this chat?',
|
||||
'ai.chat.managerDeleteMessage': '"{title}" and its messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Delete {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': '{n} selected chats and their messages will be removed from every panel. This cannot be undone.',
|
||||
'ai.chat.justNow': 'Just now',
|
||||
'ai.chat.minutesAgo': '{n}m ago',
|
||||
'ai.chat.hoursAgo': '{n}h ago',
|
||||
@@ -690,13 +752,30 @@ export const enAiMessages: Messages = {
|
||||
'ai.chatShortcuts.selectionAction': 'Show Add to Conversation when selecting terminal text',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Show a small AI button next to selected terminal text.',
|
||||
'ai.chatHistory.title': 'Chat History',
|
||||
'ai.chatHistory.storageUsage': 'Local chat history size',
|
||||
'ai.chatHistory.storageUsage.description': 'Estimate the size of saved chat records as UTF-8 JSON.',
|
||||
'ai.chatHistory.storageUsage.measure': 'Measure',
|
||||
'ai.chatHistory.storageUsage.measuring': 'Measuring…',
|
||||
'ai.chatHistory.storageUsage.result': 'Saved records · {count}. Estimated JSON size · {size}.',
|
||||
'ai.chatHistory.storageUsage.partial': 'Records excluded from the size estimate · {count}.',
|
||||
'ai.chatHistory.storageUsage.error': 'Could not read the local chat history. Try again.',
|
||||
'ai.chatHistory.messageCap': 'Messages kept per chat',
|
||||
'ai.chatHistory.messageCap.description': 'Maximum number of messages stored per chat (50–2000). Lowering it drops the oldest messages from storage on the next write. Larger values increase storage and cloud-sync size.',
|
||||
'ai.chatHistory.messageCap.unit': 'messages',
|
||||
'ai.chatHistory.autoLlmTitle': 'Auto-generate chat titles',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Use a small one-shot LLM call to write a short title after the first message. Falls back to the first line if unavailable. Local setting only.',
|
||||
'ai.chatHistory.titleModel': 'Title model',
|
||||
'ai.chatHistory.titleModel.description': 'Provider and model used to generate chat titles. Pick a small, cheap model. Defaults to the current Catty model.',
|
||||
'ai.chatHistory.namingPreference': 'Manual title template',
|
||||
'ai.chatHistory.namingPreference.help': 'Edit the rules for manually regenerating titles. A saved template replaces the default and stays on this device until used. Do not enter credentials.',
|
||||
'ai.chatHistory.namingPreference.example': 'Example: Put the project first; keep the key technology and aim for 25 characters.',
|
||||
'ai.chatHistory.namingPreference.save': 'Save preference',
|
||||
'ai.chatHistory.namingPreference.reset': 'Restore default',
|
||||
'ai.chatHistory.namingPreference.saved': 'Preference saved.',
|
||||
'ai.chatHistory.namingPreference.resetDone': 'Default restored.',
|
||||
'ai.chatHistory.namingPreference.failed': 'Could not save the preference.',
|
||||
'ai.chat.managerRegenerateTitleEmpty': 'No conversation text is available to rename.',
|
||||
'ai.chat.managerRegenerateTitleBusy': 'A title is already being generated for this chat.',
|
||||
'ai.chatHistory.titleModel.description': 'Provider and model for automatic and manual titles. Manual renaming sends short excerpts from across the conversation. Defaults to the current Catty model.',
|
||||
'ai.chatHistory.titleModel.none': 'No enabled provider available.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Use current Catty model',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Unavailable',
|
||||
|
||||
@@ -1001,6 +1001,9 @@ Highlight the focused split pane:
|
||||
'Choose whether autocomplete history suggestions come from the current host only, or from commands recorded on all hosts.',
|
||||
'settings.terminal.autocomplete.historyScope.host': 'Current host',
|
||||
'settings.terminal.autocomplete.historyScope.global': 'All hosts',
|
||||
'settings.terminal.autocomplete.showSnippets': 'Show code snippets',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'Include matching code snippets in the autocomplete list. Turn this off if snippets crowd out command and history suggestions.',
|
||||
|
||||
// Settings > Terminal > Password prompt assist (sudo/su)
|
||||
'settings.terminal.section.passwordPromptAssist': 'Password prompt assist',
|
||||
@@ -1029,6 +1032,9 @@ Highlight the focused split pane:
|
||||
'settings.shortcuts.recording': 'Press keys...',
|
||||
'settings.shortcuts.none': 'None',
|
||||
'settings.shortcuts.setDisabled': 'Set to disabled',
|
||||
'settings.shortcuts.addExtra': 'Add shortcut',
|
||||
'settings.shortcuts.additional': 'Additional shortcut',
|
||||
'settings.shortcuts.removeExtra': 'Remove shortcut',
|
||||
'settings.shortcuts.category.tabs': 'Tabs',
|
||||
'settings.shortcuts.category.terminal': 'Terminal',
|
||||
'settings.shortcuts.category.navigation': 'Navigation',
|
||||
|
||||
@@ -4,6 +4,24 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Current directory: {path}. Change directory',
|
||||
'terminal.gitBranch.current': 'Git branch: {{value}}',
|
||||
'terminal.gitBranch.detached': 'Detached HEAD: {{value}}',
|
||||
'terminal.gitBranch.search': 'Search local branches...',
|
||||
'terminal.gitBranch.branches': 'Local branches',
|
||||
'terminal.gitBranch.loading': 'Reading branches...',
|
||||
'terminal.gitBranch.empty': 'No local branches yet',
|
||||
'terminal.gitBranch.noMatches': 'No matching branches',
|
||||
'terminal.gitBranch.unavailable': 'Could not read branches for this session.',
|
||||
'terminal.gitBranch.draftDelete': 'Draft deletion of {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Enter sends to this terminal. Esc restores your draft.',
|
||||
'terminal.gitChanges.label': 'Git changes: {{value}}',
|
||||
'terminal.gitChanges.loading': 'Reading changes',
|
||||
'terminal.gitChanges.unavailable': 'Changes unavailable',
|
||||
'terminal.gitChanges.clean': 'Clean',
|
||||
'terminal.gitChanges.files.one': '{{count}} file',
|
||||
'terminal.gitChanges.files.few': '{{count}} files',
|
||||
'terminal.gitChanges.files.many': '{{count}} files',
|
||||
'terminal.gitChanges.files.other': '{{count}} files',
|
||||
'terminal.gitBranch.draftUnavailable': 'The original session or directory is unavailable.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Keep the command on one line.',
|
||||
'terminal.directory.unknown': 'Directory unknown',
|
||||
'terminal.directory.search': 'Search child directories...',
|
||||
'terminal.directory.directories': 'Directories',
|
||||
@@ -707,6 +725,7 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
'tabs.convertToWorkspace': 'Convert to Workspace',
|
||||
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
|
||||
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
|
||||
'tabs.closeOthers': 'Close Others',
|
||||
|
||||
@@ -882,7 +882,7 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Agent Socket',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Do not try unrelated keys currently loaded in the agent',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Start or unlock your SSH agent, or provide its socket path above.',
|
||||
'hostDetails.keys.search': 'Search keys...',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Elegir el modo de Grok y enviar…',
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
'ai.chat.deliveredTextFile.source': 'Texto incluido en esta respuesta',
|
||||
'ai.chat.deliveredTextFile.preview': 'Vista previa',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Ocultar vista previa',
|
||||
'ai.chat.deliveredTextFile.save': 'Guardar como',
|
||||
'ai.chat.deliveredTextFile.saving': 'Guardando…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Archivo guardado',
|
||||
'ai.chat.deliveredTextFile.exists': 'El archivo ya existe. Elige otro nombre.',
|
||||
'ai.chat.deliveredTextFile.failed': 'No se pudo guardar el archivo.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'No se puede guardar en esta ventana.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'La vista previa está abreviada. Se guarda el archivo completo.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
'ai.chat.preparing': 'Preparando…',
|
||||
@@ -36,6 +47,29 @@ export const esAiMessages: Messages = {
|
||||
'ai.agents': 'Agentes',
|
||||
'ai.providers.empty': 'No hay proveedores configurados. Agrega un proveedor para comenzar.',
|
||||
'ai.providers.add': 'Agregar proveedor',
|
||||
'ai.providers.modal.title': 'Agregar proveedor de IA',
|
||||
'ai.providers.modal.searchPlaceholder': 'Buscar proveedores, modelos o dominios...',
|
||||
'ai.providers.modal.clearSearch': 'Limpiar búsqueda',
|
||||
'ai.providers.modal.categoriesLabel': 'Categorías de proveedores',
|
||||
'ai.providers.modal.category.all': 'Todos',
|
||||
'ai.providers.modal.category.sponsor': 'Patrocinadores',
|
||||
'ai.providers.modal.category.official': 'Oficiales',
|
||||
'ai.providers.modal.category.gateway': 'Pasarelas',
|
||||
'ai.providers.modal.category.cn': 'Modelos de China',
|
||||
'ai.providers.modal.category.localCustom': 'Local y personalizado',
|
||||
'ai.providers.modal.categoryHint.sponsor': 'Apoyando el desarrollo de Netcatty',
|
||||
'ai.providers.modal.added': 'Agregado',
|
||||
'ai.providers.modal.noResults': 'No se encontraron proveedores',
|
||||
'ai.providers.modal.noResultsHint': 'Prueba otra palabra clave o configura manualmente cualquier endpoint compatible con OpenAI, Anthropic o Google.',
|
||||
'ai.providers.modal.useCustom': 'Agregar proveedor personalizado',
|
||||
'ai.providers.modal.customName': 'Personalizado',
|
||||
'ai.providers.modal.subtitle.ollama': 'Local u Ollama Cloud · localhost:11434',
|
||||
'ai.providers.modal.subtitle.custom': 'Compatible con OpenAI / Anthropic / Google',
|
||||
'ai.providers.sponsor.hualong.name': 'HuaLongAI',
|
||||
'ai.providers.sponsor.hualong.badge': '$2 gratis',
|
||||
'ai.providers.sponsor.hualong.tagline': 'Codex · DeepSeek · Claude',
|
||||
'ai.providers.sponsor.hualong.description': 'Servicio de relé API estable y de alta disponibilidad para modelos Codex, DeepSeek y Claude. 100% directo de fuentes oficiales, SLA promedio superior al 99.2%, facturación verificable por token y contratos empresariales.',
|
||||
'ai.providers.sponsor.hualong.cta': 'Reclamar $2 gratis',
|
||||
'ai.providers.active': 'Activo',
|
||||
'ai.providers.apiKeyConfigured': 'Clave de API configurada',
|
||||
'ai.providers.noApiKey': 'Sin clave de API',
|
||||
@@ -117,6 +151,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'App Server está disponible para esta Codex CLI.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'El catálogo de modelos de Codex en vivo no está disponible. Se usa la lista de modelos integrada.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Permitir por sesión',
|
||||
'ai.planReview.title': 'Revisar el plan de implementación',
|
||||
'ai.planReview.keepPlanning': 'Seguir planificando',
|
||||
'ai.planReview.approveAndImplement': 'Aprobar e implementar',
|
||||
'ai.codex.appServer.userInput.title': 'Codex necesita tu aporte',
|
||||
'ai.codex.appServer.userInput.description': 'Responde estas preguntas para continuar el turno actual.',
|
||||
'ai.codex.appServer.userInput.other': 'Ingresa otra respuesta',
|
||||
@@ -305,6 +342,16 @@ export const esAiMessages: Messages = {
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 no pudo adjuntar una herramienta MCP. El chat continuará sin ella.',
|
||||
|
||||
// AI MiMo Code (CLI de Xiaomi MiMo Code — fork de OpenCode)
|
||||
'ai.agy.title': 'Antigravity CLI (Beta)',
|
||||
'ai.agy.description': 'Beta experimental: CLI del agente de codificación Antigravity de Google conectado mediante el Agent Client Protocol oficial (agy acp --stdio). El soporte aún es limitado y no ha sido probado a fondo; úsalo bajo tu propia responsabilidad. Inicia sesión con agy en tu terminal y selecciónalo como agente externo.',
|
||||
'ai.agy.detecting': 'Detectando...',
|
||||
'ai.agy.detected': 'Detectado',
|
||||
'ai.agy.notFound': 'No encontrado',
|
||||
'ai.agy.path': 'Ruta:',
|
||||
'ai.agy.notFoundHint': 'No se pudo encontrar agy en el PATH. Instala Antigravity CLI o especifica la ruta del ejecutable a continuación.',
|
||||
'ai.agy.customPathPlaceholder': 'p. ej. /usr/local/bin/agy',
|
||||
'ai.agy.check': 'Verificar',
|
||||
'ai.agy.resetPath': 'Restablecer',
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': 'CLI de MiMo Code de Xiaomi, un fork de OpenCode. Instálalo y configura los proveedores en su propia configuración, luego selecciónalo como agente de codificación externo.',
|
||||
'ai.mimo.detecting': 'Detectando...',
|
||||
@@ -328,6 +375,13 @@ export const esAiMessages: Messages = {
|
||||
'ai.grok.check': 'Verificar',
|
||||
'ai.grok.resetPath': 'Restablecer',
|
||||
'ai.grok.runtime.acp.title': 'Usar Grok ACP (agente stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok necesita tu respuesta',
|
||||
'ai.grok.userQuestion.description': 'Las respuestas no conceden permisos. No incluyas contraseñas ni tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Enviar respuestas',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode necesita tu respuesta',
|
||||
'ai.agentQuestions.title': 'Permitir que el agente haga preguntas',
|
||||
'ai.agentQuestions.description': 'Permite que este agente pida detalles durante un turno. Las respuestas no conceden permisos de herramientas.',
|
||||
'ai.agentQuestions.codexDescription': 'Permite que Codex App Server pida detalles en el modo predeterminado. Las respuestas no conceden permisos de herramientas.',
|
||||
'ai.grok.runtime.acp.default': 'Predeterminado',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Habla con Grok mediante el Protocolo de Cliente de Agente (grok agent stdio). Inyecta el MCP de Netcatty en session/new. Apágalo para usar la ruta original de CLI headless con streaming-json.',
|
||||
@@ -634,12 +688,20 @@ export const esAiMessages: Messages = {
|
||||
'ai.chat.managerSelectedCount': '{n} seleccionados',
|
||||
'ai.chat.managerSelectRow': 'Seleccionar este chat',
|
||||
'ai.chat.managerRegenerateTitle': 'Regenerar título con IA',
|
||||
'ai.chat.managerRegenerateTitleUpdated': 'Título del chat actualizado.',
|
||||
'ai.chat.managerRegenerateTitleUnchanged': 'El título del chat ya está actualizado.',
|
||||
'ai.chat.managerRegenerateTitleNoModel': 'No hay un proveedor o modelo de IA configurado para generar títulos. Configúralo en Ajustes de IA.',
|
||||
'ai.chat.managerRegenerateTitleFailed': 'Error al regenerar el título: {error}',
|
||||
'ai.chat.managerRegenerateTitleBatchDone': 'Se actualizaron {n} título(s) de chat.',
|
||||
'ai.chat.managerRegenerateTitleBatchPartial': 'Se actualizaron {updated} título(s) y fallaron {failed}.',
|
||||
'ai.chat.managerExportOne': 'Exportar este chat',
|
||||
'ai.chat.managerBadgeActive': 'Activo',
|
||||
'ai.chat.managerBadgeIdle': 'Inactivo',
|
||||
'ai.chat.managerMessagesCount': '{n} mensajes',
|
||||
'ai.chat.managerDeleteTitle': '¿Eliminar este chat?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.managerBulkDeleteTitle': '¿Eliminar {n} chats?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Los {n} chats seleccionados y sus mensajes se eliminarán de todos los paneles. Esta acción no se puede deshacer.',
|
||||
'ai.chat.justNow': 'Ahora mismo',
|
||||
'ai.chat.minutesAgo': 'hace {n} min',
|
||||
'ai.chat.hoursAgo': 'hace {n} h',
|
||||
@@ -690,13 +752,30 @@ export const esAiMessages: Messages = {
|
||||
'ai.chatShortcuts.selectionAction': 'Mostrar "Agregar a la conversación" al seleccionar texto de la terminal',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Muestra un pequeño botón de IA junto al texto seleccionado de la terminal.',
|
||||
'ai.chatHistory.title': 'Historial de chat',
|
||||
'ai.chatHistory.storageUsage': 'Tamaño del historial de chats local',
|
||||
'ai.chatHistory.storageUsage.description': 'Calcula el tamaño de los registros guardados como JSON UTF-8.',
|
||||
'ai.chatHistory.storageUsage.measure': 'Calcular',
|
||||
'ai.chatHistory.storageUsage.measuring': 'Calculando…',
|
||||
'ai.chatHistory.storageUsage.result': 'Registros guardados · {count}. Tamaño estimado del JSON · {size}.',
|
||||
'ai.chatHistory.storageUsage.partial': 'Registros excluidos del cálculo · {count}.',
|
||||
'ai.chatHistory.storageUsage.error': 'No se pudo leer el historial de chats local. Vuelve a intentarlo.',
|
||||
'ai.chatHistory.messageCap': 'Mensajes conservados por chat',
|
||||
'ai.chatHistory.messageCap.description': 'Número máximo de mensajes almacenados por chat (50–2000). Al reducirlo, los mensajes más antiguos se descartan del almacenamiento en la siguiente escritura. Los valores más altos aumentan el almacenamiento y el tamaño de la sincronización en la nube.',
|
||||
'ai.chatHistory.messageCap.unit': 'mensajes',
|
||||
'ai.chatHistory.autoLlmTitle': 'Generar títulos automáticamente',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Usa una breve llamada LLM para crear un título corto tras el primer mensaje. Si no está disponible, usa la primera línea. Ajuste solo local.',
|
||||
'ai.chatHistory.titleModel': 'Modelo de título',
|
||||
'ai.chatHistory.titleModel.description': 'Proveedor y modelo usados para generar títulos. Elige un modelo pequeño y económico. Por defecto usa el modelo actual de Catty.',
|
||||
'ai.chatHistory.namingPreference': 'Plantilla manual de títulos',
|
||||
'ai.chatHistory.namingPreference.help': 'Edita las reglas para regenerar títulos. La plantilla guardada sustituye a la predeterminada y solo se envía al usarla. No incluyas credenciales.',
|
||||
'ai.chatHistory.namingPreference.example': 'Ejemplo: pon el proyecto primero, conserva la tecnología clave y procura no superar los 25 caracteres.',
|
||||
'ai.chatHistory.namingPreference.save': 'Guardar preferencias',
|
||||
'ai.chatHistory.namingPreference.reset': 'Restaurar valores predeterminados',
|
||||
'ai.chatHistory.namingPreference.saved': 'Preferencias guardadas.',
|
||||
'ai.chatHistory.namingPreference.resetDone': 'Valores predeterminados restaurados.',
|
||||
'ai.chatHistory.namingPreference.failed': 'No se pudieron guardar las preferencias.',
|
||||
'ai.chat.managerRegenerateTitleEmpty': 'No hay texto de la conversación para generar un título.',
|
||||
'ai.chat.managerRegenerateTitleBusy': 'Ya se está generando un título para este chat.',
|
||||
'ai.chatHistory.titleModel.description': 'Proveedor y modelo para títulos automáticos y manuales. Al cambiar el título manualmente se envían extractos breves de distintas partes de la conversación. Por defecto se usa el modelo actual de Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'No hay proveedores habilitados.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Usar el modelo actual de Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'No disponible',
|
||||
|
||||
@@ -1001,6 +1001,9 @@ Resalta el panel dividido enfocado:
|
||||
'Elige si las sugerencias de autocompletado del historial provienen solo del host actual o de los comandos registrados en todos los hosts.',
|
||||
'settings.terminal.autocomplete.historyScope.host': 'Host actual',
|
||||
'settings.terminal.autocomplete.historyScope.global': 'Todos los hosts',
|
||||
'settings.terminal.autocomplete.showSnippets': 'Mostrar fragmentos de código',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'Incluye fragmentos de código coincidentes en la lista de autocompletado. Desactiva esta opción si los fragmentos desplazan las sugerencias de comandos e historial.',
|
||||
|
||||
// Settings > Terminal > Password prompt assist (sudo/su)
|
||||
'settings.terminal.section.passwordPromptAssist': 'Asistencia para solicitud de contraseña',
|
||||
@@ -1029,6 +1032,9 @@ Resalta el panel dividido enfocado:
|
||||
'settings.shortcuts.recording': 'Presiona teclas...',
|
||||
'settings.shortcuts.none': 'Ninguno',
|
||||
'settings.shortcuts.setDisabled': 'Configurar como desactivado',
|
||||
'settings.shortcuts.addExtra': 'Añadir atajo',
|
||||
'settings.shortcuts.additional': 'Atajo adicional',
|
||||
'settings.shortcuts.removeExtra': 'Eliminar atajo',
|
||||
'settings.shortcuts.category.tabs': 'Pestañas',
|
||||
'settings.shortcuts.category.terminal': 'Terminal',
|
||||
'settings.shortcuts.category.navigation': 'Navegación',
|
||||
|
||||
@@ -4,6 +4,24 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Directorio actual: {path}. Cambiar directorio',
|
||||
'terminal.gitBranch.current': 'Rama de Git: {{value}}',
|
||||
'terminal.gitBranch.detached': 'HEAD separado: {{value}}',
|
||||
'terminal.gitBranch.search': 'Buscar ramas locales...',
|
||||
'terminal.gitBranch.branches': 'Ramas locales',
|
||||
'terminal.gitBranch.loading': 'Leyendo ramas...',
|
||||
'terminal.gitBranch.empty': 'Aún no hay ramas locales',
|
||||
'terminal.gitBranch.noMatches': 'No hay ramas coincidentes',
|
||||
'terminal.gitBranch.unavailable': 'No se pudieron leer las ramas de esta sesión.',
|
||||
'terminal.gitBranch.draftDelete': 'Preparar la eliminación de {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Intro envía a este terminal. Esc restaura el borrador.',
|
||||
'terminal.gitChanges.label': 'Cambios de Git: {{value}}',
|
||||
'terminal.gitChanges.loading': 'Leyendo cambios',
|
||||
'terminal.gitChanges.unavailable': 'Cambios no disponibles',
|
||||
'terminal.gitChanges.clean': 'Sin cambios',
|
||||
'terminal.gitChanges.files.one': '{{count}} archivo',
|
||||
'terminal.gitChanges.files.few': '{{count}} archivos',
|
||||
'terminal.gitChanges.files.many': '{{count}} archivos',
|
||||
'terminal.gitChanges.files.other': '{{count}} archivos',
|
||||
'terminal.gitBranch.draftUnavailable': 'La sesión o el directorio original no está disponible.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Mantén el comando en una sola línea.',
|
||||
'terminal.directory.unknown': 'Directorio desconocido',
|
||||
'terminal.directory.search': 'Buscar subdirectorios...',
|
||||
'terminal.directory.directories': 'Directorios',
|
||||
@@ -709,6 +727,7 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
'tabs.convertToWorkspace': 'Convertir en espacio de trabajo',
|
||||
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
|
||||
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
|
||||
'tabs.closeOthers': 'Cerrar las demás',
|
||||
|
||||
@@ -878,7 +878,7 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Socket del agente',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'No intentar con claves no relacionadas actualmente cargadas en el agente',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Inicia o desbloquea tu agente SSH, o proporciona la ruta de su socket arriba.',
|
||||
'hostDetails.keys.search': 'Buscar claves...',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Выбрать режим Grok и отправить…',
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.deliveredTextFile.source': 'Текст включён в ответ',
|
||||
'ai.chat.deliveredTextFile.preview': 'Предпросмотр',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Скрыть предпросмотр',
|
||||
'ai.chat.deliveredTextFile.save': 'Сохранить как',
|
||||
'ai.chat.deliveredTextFile.saving': 'Сохранение…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Файл сохранён',
|
||||
'ai.chat.deliveredTextFile.exists': 'Файл уже существует. Выберите другое имя.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Не удалось сохранить файл.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Сохранение недоступно в этом окне.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Предпросмотр сокращён. Файл сохранится полностью.',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Настройки агента',
|
||||
@@ -36,6 +47,29 @@ export const ruAiMessages: Messages = {
|
||||
'ai.agents': 'Агенты',
|
||||
'ai.providers.empty': 'Провайдеры не настроены. Добавьте провайдера, чтобы начать.',
|
||||
'ai.providers.add': 'Добавить провайдера',
|
||||
'ai.providers.modal.title': 'Добавить ИИ-провайдера',
|
||||
'ai.providers.modal.searchPlaceholder': 'Поиск провайдеров, моделей или доменов...',
|
||||
'ai.providers.modal.clearSearch': 'Очистить поиск',
|
||||
'ai.providers.modal.categoriesLabel': 'Категории провайдеров',
|
||||
'ai.providers.modal.category.all': 'Все',
|
||||
'ai.providers.modal.category.sponsor': 'Спонсоры',
|
||||
'ai.providers.modal.category.official': 'Официальные',
|
||||
'ai.providers.modal.category.gateway': 'Шлюзы',
|
||||
'ai.providers.modal.category.cn': 'Модели Китая',
|
||||
'ai.providers.modal.category.localCustom': 'Локальные и свои',
|
||||
'ai.providers.modal.categoryHint.sponsor': 'Поддержка разработки Netcatty',
|
||||
'ai.providers.modal.added': 'Добавлен',
|
||||
'ai.providers.modal.noResults': 'Подходящие провайдеры не найдены',
|
||||
'ai.providers.modal.noResultsHint': 'Попробуйте другой запрос или добавьте любой совместимый с OpenAI / Anthropic / Google эндпоинт вручную.',
|
||||
'ai.providers.modal.useCustom': 'Добавить своего провайдера',
|
||||
'ai.providers.modal.customName': 'Пользовательский',
|
||||
'ai.providers.modal.subtitle.ollama': 'Локально или Ollama Cloud · localhost:11434',
|
||||
'ai.providers.modal.subtitle.custom': 'Совместим с OpenAI / Anthropic / Google',
|
||||
'ai.providers.sponsor.hualong.name': 'HuaLongAI',
|
||||
'ai.providers.sponsor.hualong.badge': '$2',
|
||||
'ai.providers.sponsor.hualong.tagline': 'Codex · DeepSeek · Claude',
|
||||
'ai.providers.sponsor.hualong.description': 'Стабильный и высокодоступный API-ретранслятор для моделей Codex, DeepSeek и Claude. 100% официальные источники, средний SLA выше 99.2%, прозрачный биллинг по токенам и корпоративные договоры.',
|
||||
'ai.providers.sponsor.hualong.cta': 'Получить $2',
|
||||
'ai.providers.active': 'Активен',
|
||||
'ai.providers.apiKeyConfigured': 'API-ключ настроен',
|
||||
'ai.providers.noApiKey': 'Нет API-ключа',
|
||||
@@ -117,6 +151,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': 'Эта версия Codex CLI поддерживает App Server.',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Динамический каталог моделей Codex недоступен. Используется встроенный список моделей.',
|
||||
'ai.codex.appServer.approval.allowSession': 'Разрешить для сеанса',
|
||||
'ai.planReview.title': 'Проверить план реализации',
|
||||
'ai.planReview.keepPlanning': 'Продолжить планирование',
|
||||
'ai.planReview.approveAndImplement': 'Одобрить и приступить к реализации',
|
||||
'ai.codex.appServer.userInput.title': 'Codex требуется ваш ответ',
|
||||
'ai.codex.appServer.userInput.description': 'Ответьте на вопросы, чтобы продолжить текущую задачу.',
|
||||
'ai.codex.appServer.userInput.other': 'Введите другой ответ',
|
||||
@@ -296,6 +333,13 @@ export const ruAiMessages: Messages = {
|
||||
'ai.grok.check': 'Проверить',
|
||||
'ai.grok.resetPath': 'Сбросить',
|
||||
'ai.grok.runtime.acp.title': 'Использовать Grok ACP (agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok ждёт вашего ответа',
|
||||
'ai.grok.userQuestion.description': 'Ответы не предоставляют разрешений. Не указывайте пароли и токены.',
|
||||
'ai.grok.userQuestion.submit': 'Отправить ответы',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode ждёт вашего ответа',
|
||||
'ai.agentQuestions.title': 'Разрешить агенту задавать вопросы',
|
||||
'ai.agentQuestions.description': 'Агент сможет запрашивать уточнения во время диалога. Ответы не дают разрешений на использование инструментов.',
|
||||
'ai.agentQuestions.codexDescription': 'Codex App Server сможет запрашивать уточнения в режиме по умолчанию. Ответы не дают разрешений на использование инструментов.',
|
||||
'ai.grok.runtime.acp.default': 'По умолчанию',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
|
||||
@@ -323,6 +367,16 @@ export const ruAiMessages: Messages = {
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 не смог подключить инструмент MCP. Чат продолжится без него.',
|
||||
|
||||
// MiMo Code
|
||||
'ai.agy.title': 'Antigravity CLI (Beta)',
|
||||
'ai.agy.description': 'Экспериментальная бета-версия: CLI агента Google Antigravity через официальный протокол ACP (agy acp --stdio). Поддержка пока ограничена и не прошла полноценного тестирования — используйте на свой страх и риск. Выполните вход через agy в терминале и выберите его как внешнего агента.',
|
||||
'ai.agy.detecting': 'Поиск…',
|
||||
'ai.agy.detected': 'Найден',
|
||||
'ai.agy.notFound': 'Не найден',
|
||||
'ai.agy.path': 'Путь:',
|
||||
'ai.agy.notFoundHint': 'Не удалось найти agy в PATH. Установите Antigravity CLI или укажите путь к исполняемому файлу ниже.',
|
||||
'ai.agy.customPathPlaceholder': 'например, /usr/local/bin/agy',
|
||||
'ai.agy.check': 'Проверить',
|
||||
'ai.agy.resetPath': 'Сбросить',
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': 'MiMo Code от Xiaomi — форк OpenCode с интерфейсом командной строки. Установите его и настройте провайдеров в его конфигурации, затем выберите MiMo Code как внешнего агента для программирования.',
|
||||
'ai.mimo.detecting': 'Поиск…',
|
||||
@@ -633,12 +687,20 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chat.managerSelectedCount': 'Выбрано: {n}',
|
||||
'ai.chat.managerSelectRow': 'Выбрать этот чат',
|
||||
'ai.chat.managerRegenerateTitle': 'Пересоздать заголовок через ИИ',
|
||||
'ai.chat.managerRegenerateTitleUpdated': 'Заголовок чата обновлён.',
|
||||
'ai.chat.managerRegenerateTitleUnchanged': 'Заголовок чата уже актуален.',
|
||||
'ai.chat.managerRegenerateTitleNoModel': 'Не настроен провайдер/модель ИИ для генерации заголовков. Настройте модель в настройках ИИ.',
|
||||
'ai.chat.managerRegenerateTitleFailed': 'Не удалось пересоздать заголовок: {error}',
|
||||
'ai.chat.managerRegenerateTitleBatchDone': 'Обновлено заголовков: {n}.',
|
||||
'ai.chat.managerRegenerateTitleBatchPartial': 'Обновлено {updated}, ошибок: {failed}.',
|
||||
'ai.chat.managerExportOne': 'Экспортировать этот чат',
|
||||
'ai.chat.managerBadgeActive': 'Активен',
|
||||
'ai.chat.managerBadgeIdle': 'Простой',
|
||||
'ai.chat.managerMessagesCount': '{n} сообщений',
|
||||
'ai.chat.managerDeleteTitle': 'Удалить этот чат?',
|
||||
'ai.chat.managerDeleteMessage': '«{title}» и его сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.managerBulkDeleteTitle': 'Удалить выбранные чаты ({n})?',
|
||||
'ai.chat.managerBulkDeleteMessage': 'Выбранные чаты ({n}) и их сообщения будут удалены из всех панелей. Это действие нельзя отменить.',
|
||||
'ai.chat.justNow': 'Только что',
|
||||
'ai.chat.minutesAgo': '{n}м назад',
|
||||
'ai.chat.hoursAgo': '{n}ч назад',
|
||||
@@ -689,13 +751,30 @@ export const ruAiMessages: Messages = {
|
||||
'ai.chatShortcuts.selectionAction': 'Показывать «Добавить в чат» при выделении в терминале',
|
||||
'ai.chatShortcuts.selectionAction.description': 'Показывать небольшую кнопку ИИ рядом с выделенным текстом терминала.',
|
||||
'ai.chatHistory.title': 'История чата',
|
||||
'ai.chatHistory.storageUsage': 'Размер локальной истории чатов',
|
||||
'ai.chatHistory.storageUsage.description': 'Оценивает размер сохранённых записей чатов в формате JSON (UTF-8).',
|
||||
'ai.chatHistory.storageUsage.measure': 'Рассчитать',
|
||||
'ai.chatHistory.storageUsage.measuring': 'Расчёт…',
|
||||
'ai.chatHistory.storageUsage.result': 'Сохранено записей — {count}. Примерный размер JSON — {size}.',
|
||||
'ai.chatHistory.storageUsage.partial': 'Записей, исключённых из расчёта размера, — {count}.',
|
||||
'ai.chatHistory.storageUsage.error': 'Не удалось прочитать локальную историю чатов. Повторите попытку.',
|
||||
'ai.chatHistory.messageCap': 'Сообщений, сохраняемых в чате',
|
||||
'ai.chatHistory.messageCap.description': 'Максимальное число сообщений, хранимых для одного чата (50–2000). При уменьшении самые старые сообщения удаляются из хранилища при следующей записи. Большие значения увеличивают объём хранилища и синхронизации с облаком.',
|
||||
'ai.chatHistory.messageCap.unit': 'сообщений',
|
||||
'ai.chatHistory.autoLlmTitle': 'Автосоздание заголовков чатов',
|
||||
'ai.chatHistory.autoLlmTitle.description': 'Короткий запрос к LLM создаёт заголовок после первого сообщения. Если недоступно, используется первая строка. Локальная настройка.',
|
||||
'ai.chatHistory.titleModel': 'Модель для заголовков',
|
||||
'ai.chatHistory.titleModel.description': 'Провайдер и модель для создания заголовков. Выберите небольшую недорогую модель. По умолчанию — текущая модель Catty.',
|
||||
'ai.chatHistory.namingPreference': 'Шаблон ручного заголовка',
|
||||
'ai.chatHistory.namingPreference.help': 'Измените правила ручного обновления заголовков. Сохранённый шаблон заменяет стандартный и отправляется только при использовании. Не вводите пароли и ключи.',
|
||||
'ai.chatHistory.namingPreference.example': 'Например: сначала проект, затем ключевая технология. Желательно не более 25 символов.',
|
||||
'ai.chatHistory.namingPreference.save': 'Сохранить стиль',
|
||||
'ai.chatHistory.namingPreference.reset': 'Восстановить настройки по умолчанию',
|
||||
'ai.chatHistory.namingPreference.saved': 'Стиль сохранён.',
|
||||
'ai.chatHistory.namingPreference.resetDone': 'Восстановлены настройки по умолчанию.',
|
||||
'ai.chatHistory.namingPreference.failed': 'Не удалось сохранить стиль.',
|
||||
'ai.chat.managerRegenerateTitleEmpty': 'Нет текста беседы для создания заголовка.',
|
||||
'ai.chat.managerRegenerateTitleBusy': 'Для этой беседы уже создаётся заголовок.',
|
||||
'ai.chatHistory.titleModel.description': 'Провайдер и модель для автоматических и ручных заголовков. При ручном переименовании отправляются короткие отрывки из разных частей беседы. По умолчанию используется текущая модель Catty.',
|
||||
'ai.chatHistory.titleModel.none': 'Нет включённых провайдеров.',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': 'Использовать текущую модель Catty',
|
||||
'ai.chatHistory.titleModel.unavailable': 'Недоступно',
|
||||
|
||||
@@ -986,6 +986,9 @@ export const ruCoreMessages: Messages = {
|
||||
'Выберите, брать ли подсказки истории автодополнения только с текущего хоста или со всех хостов.',
|
||||
'settings.terminal.autocomplete.historyScope.host': 'Текущий хост',
|
||||
'settings.terminal.autocomplete.historyScope.global': 'Все хосты',
|
||||
'settings.terminal.autocomplete.showSnippets': 'Показывать сниппеты',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'Включать подходящие сниппеты в список автодополнения. Отключите, если сниппеты вытесняют подсказки команд и истории.',
|
||||
|
||||
// Settings > Terminal > Password prompt assist (sudo/su)
|
||||
'settings.terminal.section.passwordPromptAssist': 'Подсказки пароля',
|
||||
@@ -1014,6 +1017,9 @@ export const ruCoreMessages: Messages = {
|
||||
'settings.shortcuts.recording': 'Нажмите клавиши...',
|
||||
'settings.shortcuts.none': 'Нет',
|
||||
'settings.shortcuts.setDisabled': 'Отключить',
|
||||
'settings.shortcuts.addExtra': 'Добавить сочетание',
|
||||
'settings.shortcuts.additional': 'Дополнительное сочетание',
|
||||
'settings.shortcuts.removeExtra': 'Удалить сочетание',
|
||||
'settings.shortcuts.category.tabs': 'Вкладки',
|
||||
'settings.shortcuts.category.terminal': 'Терминал',
|
||||
'settings.shortcuts.category.navigation': 'Навигация',
|
||||
|
||||
@@ -4,6 +4,24 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.directory.open': 'Текущий каталог: {path}. Сменить каталог',
|
||||
'terminal.gitBranch.current': 'Ветка Git: {{value}}',
|
||||
'terminal.gitBranch.detached': 'Отсоединённый HEAD: {{value}}',
|
||||
'terminal.gitBranch.search': 'Поиск локальных веток...',
|
||||
'terminal.gitBranch.branches': 'Локальные ветки',
|
||||
'terminal.gitBranch.loading': 'Чтение веток...',
|
||||
'terminal.gitBranch.empty': 'Локальных веток пока нет',
|
||||
'terminal.gitBranch.noMatches': 'Ветки не найдены',
|
||||
'terminal.gitBranch.unavailable': 'Не удалось прочитать ветки для этого сеанса.',
|
||||
'terminal.gitBranch.draftDelete': 'Подготовить удаление {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Enter отправляет команду в этот терминал. Esc восстанавливает черновик.',
|
||||
'terminal.gitChanges.label': 'Изменения Git: {{value}}',
|
||||
'terminal.gitChanges.loading': 'Чтение изменений',
|
||||
'terminal.gitChanges.unavailable': 'Изменения недоступны',
|
||||
'terminal.gitChanges.clean': 'Нет изменений',
|
||||
'terminal.gitChanges.files.one': '{{count}} файл',
|
||||
'terminal.gitChanges.files.few': '{{count}} файла',
|
||||
'terminal.gitChanges.files.many': '{{count}} файлов',
|
||||
'terminal.gitChanges.files.other': '{{count}} файла',
|
||||
'terminal.gitBranch.draftUnavailable': 'Исходный сеанс или каталог недоступен.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Команда должна занимать одну строку.',
|
||||
'terminal.directory.unknown': 'Каталог неизвестен',
|
||||
'terminal.directory.search': 'Поиск подкаталогов...',
|
||||
'terminal.directory.directories': 'Каталоги',
|
||||
@@ -722,6 +740,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
'tabs.convertToWorkspace': 'Преобразовать в рабочую область',
|
||||
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
|
||||
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
|
||||
'tabs.closeOthers': 'Закрыть остальные',
|
||||
|
||||
@@ -924,7 +924,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Сокет агента',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Не пробовать другие ключи, загруженные в агент',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Запустите или разблокируйте SSH-агент либо укажите путь к его сокету выше.',
|
||||
'hostDetails.keys.search': 'Поиск ключей...',
|
||||
|
||||
@@ -304,3 +304,20 @@ test("localized settings include SFTP tree folder double-click labels across all
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("localized settings include autocomplete show code snippets labels across all locales", () => {
|
||||
const keys = [
|
||||
"settings.terminal.autocomplete.showSnippets",
|
||||
"settings.terminal.autocomplete.showSnippets.desc",
|
||||
];
|
||||
|
||||
for (const locale of ALL_SETTINGS_LOCALES) {
|
||||
const missing = keys.filter((key) => !locale.messages[key]);
|
||||
assert.deepEqual(missing, [], `${locale.name} is missing autocomplete showSnippets labels`);
|
||||
if (locale.name !== "en") {
|
||||
for (const key of keys) {
|
||||
assert.notEqual(locale.messages[key], en[key], `${locale.name}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '选择 Grok 模式并发送…',
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
'ai.chat.deliveredTextFile.source': '文件正文已包含在回复中',
|
||||
'ai.chat.deliveredTextFile.preview': '预览',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起预览',
|
||||
'ai.chat.deliveredTextFile.save': '另存为',
|
||||
'ai.chat.deliveredTextFile.saving': '正在保存…',
|
||||
'ai.chat.deliveredTextFile.saved': '文件已保存',
|
||||
'ai.chat.deliveredTextFile.exists': '文件已存在,请另选名称。',
|
||||
'ai.chat.deliveredTextFile.failed': '无法保存该文件。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此窗口不支持保存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '预览已截短,保存时保留完整文件。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
'ai.chat.preparing': '准备中…',
|
||||
@@ -36,6 +47,29 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.agents': 'Agent',
|
||||
'ai.providers.empty': '尚未配置提供商。添加一个提供商以开始使用。',
|
||||
'ai.providers.add': '添加提供商',
|
||||
'ai.providers.modal.title': '添加 AI 提供商',
|
||||
'ai.providers.modal.searchPlaceholder': '搜索提供商、模型或域名...',
|
||||
'ai.providers.modal.clearSearch': '清除搜索',
|
||||
'ai.providers.modal.categoriesLabel': '提供商分类',
|
||||
'ai.providers.modal.category.all': '全部',
|
||||
'ai.providers.modal.category.sponsor': '赞助商',
|
||||
'ai.providers.modal.category.official': '官方平台',
|
||||
'ai.providers.modal.category.gateway': '模型聚合',
|
||||
'ai.providers.modal.category.cn': '国内模型',
|
||||
'ai.providers.modal.category.localCustom': '本地与自定义',
|
||||
'ai.providers.modal.categoryHint.sponsor': '感谢赞助商支持 Netcatty 开发',
|
||||
'ai.providers.modal.added': '已添加',
|
||||
'ai.providers.modal.noResults': '未找到匹配的提供商',
|
||||
'ai.providers.modal.noResultsHint': '换个关键词试试,或直接添加自定义 OpenAI / Anthropic / Google 兼容接口。',
|
||||
'ai.providers.modal.useCustom': '添加自定义提供商',
|
||||
'ai.providers.modal.customName': '自定义',
|
||||
'ai.providers.modal.subtitle.ollama': '本地或 Ollama Cloud · localhost:11434',
|
||||
'ai.providers.modal.subtitle.custom': 'OpenAI / Anthropic / Google 兼容接口',
|
||||
'ai.providers.sponsor.hualong.name': '华龙算力',
|
||||
'ai.providers.sponsor.hualong.badge': '送 $2',
|
||||
'ai.providers.sponsor.hualong.tagline': 'Codex · DeepSeek · Claude',
|
||||
'ai.providers.sponsor.hualong.description': '稳定高效的 API 中转服务商,主营 Codex、DeepSeek 与 Claude 系列模型,100% 官方源直供、不掺假,平均 SLA > 99.2%;Token 级账单逐笔可核验,支持企业合同与发票。',
|
||||
'ai.providers.sponsor.hualong.cta': '注册领 $2 额度',
|
||||
'ai.providers.active': '活跃',
|
||||
'ai.providers.apiKeyConfigured': 'API Key 已配置',
|
||||
'ai.providers.noApiKey': '未设置 API Key',
|
||||
@@ -117,6 +151,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': '当前 Codex CLI 支持 App Server。',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Codex 动态模型目录暂不可用,当前将使用内置模型列表。',
|
||||
'ai.codex.appServer.approval.allowSession': '本会话允许',
|
||||
'ai.planReview.title': '审核实施方案',
|
||||
'ai.planReview.keepPlanning': '继续规划',
|
||||
'ai.planReview.approveAndImplement': '批准并实施',
|
||||
'ai.codex.appServer.userInput.title': 'Codex 需要你的输入',
|
||||
'ai.codex.appServer.userInput.description': '回答以下问题以继续当前任务。',
|
||||
'ai.codex.appServer.userInput.other': '输入其他答案',
|
||||
@@ -305,6 +342,16 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 无法接入 MCP 工具,对话会继续,但没有该工具。',
|
||||
|
||||
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
|
||||
'ai.agy.title': 'Antigravity CLI(Beta)',
|
||||
'ai.agy.description': 'Beta 测试中:通过官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。当前支持程度有限且未经充分测试,使用请自担风险。请在终端完成 agy 登录后再作为外部编程 Agent 使用。',
|
||||
'ai.agy.detecting': '检测中...',
|
||||
'ai.agy.detected': '已检测到',
|
||||
'ai.agy.notFound': '未找到',
|
||||
'ai.agy.path': '路径:',
|
||||
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。请安装 Antigravity CLI 或在下方指定可执行文件路径。',
|
||||
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
|
||||
'ai.agy.check': '检查',
|
||||
'ai.agy.resetPath': '重置',
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安装后在它自己的配置里配置 provider 和密钥,检测到后即可作为外部编程 Agent 使用。',
|
||||
'ai.mimo.detecting': '检测中...',
|
||||
@@ -328,6 +375,13 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.check': '检查',
|
||||
'ai.grok.resetPath': '重置',
|
||||
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不会改变权限。请勿填写密码或令牌。',
|
||||
'ai.grok.userQuestion.submit': '发送回答',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode 正在等待你的回答',
|
||||
'ai.agentQuestions.title': '允许 Agent 主动提问',
|
||||
'ai.agentQuestions.description': '允许此 Agent 在对话中询问细节。回答不会授予工具权限。',
|
||||
'ai.agentQuestions.codexDescription': '允许 Codex App Server 在默认模式下询问细节。回答不会授予工具权限。',
|
||||
'ai.grok.runtime.acp.default': '默认',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'通过 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。关闭后使用原始 headless streaming-json CLI 路径。',
|
||||
@@ -634,12 +688,20 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chat.managerSelectedCount': '已选 {n} 个',
|
||||
'ai.chat.managerSelectRow': '选择此会话',
|
||||
'ai.chat.managerRegenerateTitle': '用 AI 重新生成标题',
|
||||
'ai.chat.managerRegenerateTitleUpdated': '会话标题已更新。',
|
||||
'ai.chat.managerRegenerateTitleUnchanged': '会话标题已是最新。',
|
||||
'ai.chat.managerRegenerateTitleNoModel': '未配置用于生成标题的 AI 模型,请在 AI 设置中配置提供商或标题模型。',
|
||||
'ai.chat.managerRegenerateTitleFailed': '重新生成标题失败:{error}',
|
||||
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 个会话标题。',
|
||||
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 个标题,{failed} 个失败。',
|
||||
'ai.chat.managerExportOne': '导出此会话',
|
||||
'ai.chat.managerBadgeActive': '使用中',
|
||||
'ai.chat.managerBadgeIdle': '空闲',
|
||||
'ai.chat.managerMessagesCount': '{n} 条消息',
|
||||
'ai.chat.managerDeleteTitle': '删除此会话?',
|
||||
'ai.chat.managerDeleteMessage': '“{title}”及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.managerBulkDeleteTitle': '删除选中的 {n} 个会话?',
|
||||
'ai.chat.managerBulkDeleteMessage': '选中的 {n} 个会话及其消息将从所有面板中移除,且无法撤销。',
|
||||
'ai.chat.justNow': '刚刚',
|
||||
'ai.chat.minutesAgo': '{n}分钟前',
|
||||
'ai.chat.hoursAgo': '{n}小时前',
|
||||
@@ -690,13 +752,30 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.chatShortcuts.selectionAction': '选中终端内容时显示“添加到对话”',
|
||||
'ai.chatShortcuts.selectionAction.description': '在终端里选中文本后显示 AI 快捷按钮。',
|
||||
'ai.chatHistory.title': '聊天历史',
|
||||
'ai.chatHistory.storageUsage': '本地聊天历史大小',
|
||||
'ai.chatHistory.storageUsage.description': '按 UTF-8 JSON 估算已保存的聊天记录大小。',
|
||||
'ai.chatHistory.storageUsage.measure': '估算',
|
||||
'ai.chatHistory.storageUsage.measuring': '正在估算…',
|
||||
'ai.chatHistory.storageUsage.result': '已保存 {count} 条记录,JSON 大小约为 {size}。',
|
||||
'ai.chatHistory.storageUsage.partial': '其中 {count} 条记录未计入大小估算。',
|
||||
'ai.chatHistory.storageUsage.error': '无法读取本地聊天历史,请重试。',
|
||||
'ai.chatHistory.messageCap': '每个会话保留的消息数',
|
||||
'ai.chatHistory.messageCap.description': '每个会话最多存储的消息条数(50–2000)。调低后会在下一次写入时从存储中丢弃最旧的消息。数值越大,存储占用和云同步体积也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '条消息',
|
||||
'ai.chatHistory.autoLlmTitle': '自动生成会话标题',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首条消息后用一次轻量 LLM 调用生成简短标题;不可用时回退为首句。仅本机生效。',
|
||||
'ai.chatHistory.titleModel': '标题模型',
|
||||
'ai.chatHistory.titleModel.description': '用于生成会话标题的 provider 和模型,建议选小巧便宜的模型。默认使用当前 Catty 模型。',
|
||||
'ai.chatHistory.namingPreference': '手动标题提示词',
|
||||
'ai.chatHistory.namingPreference.help': '可编辑整个命名模板。保存后替换默认模板,仅保存在本机,手动重新生成标题时才会发送。请勿填写密钥或密码。',
|
||||
'ai.chatHistory.namingPreference.example': '例如:项目名放在前面,保留核心技术,尽量不超过 25 字。',
|
||||
'ai.chatHistory.namingPreference.save': '保存偏好',
|
||||
'ai.chatHistory.namingPreference.reset': '恢复默认',
|
||||
'ai.chatHistory.namingPreference.saved': '偏好已保存。',
|
||||
'ai.chatHistory.namingPreference.resetDone': '已恢复默认。',
|
||||
'ai.chatHistory.namingPreference.failed': '未能保存偏好。',
|
||||
'ai.chat.managerRegenerateTitleEmpty': '没有可用于生成标题的对话文本。',
|
||||
'ai.chat.managerRegenerateTitleBusy': '正在为此会话生成标题。',
|
||||
'ai.chatHistory.titleModel.description': '用于自动和手动生成标题的提供商和模型。手动重命名会发送覆盖会话不同阶段的短摘录。默认使用当前 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '没有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用当前 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '不可用',
|
||||
|
||||
@@ -4,6 +4,24 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '当前目录:{path}。更改目录',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分离的 HEAD:{{value}}',
|
||||
'terminal.gitBranch.search': '搜索本地分支…',
|
||||
'terminal.gitBranch.branches': '本地分支',
|
||||
'terminal.gitBranch.loading': '正在读取分支…',
|
||||
'terminal.gitBranch.empty': '还没有本地分支',
|
||||
'terminal.gitBranch.noMatches': '没有匹配的分支',
|
||||
'terminal.gitBranch.unavailable': '无法读取此会话的分支。',
|
||||
'terminal.gitBranch.draftDelete': '拟定删除 {{value}} 的命令',
|
||||
'terminal.gitBranch.draftHint': '回车发送到当前终端,Esc 恢复原草稿。',
|
||||
'terminal.gitChanges.label': 'Git 变更:{{value}}',
|
||||
'terminal.gitChanges.loading': '正在读取变更',
|
||||
'terminal.gitChanges.unavailable': '无法读取变更',
|
||||
'terminal.gitChanges.clean': '无变更',
|
||||
'terminal.gitChanges.files.one': '{{count}} 个文件',
|
||||
'terminal.gitChanges.files.few': '{{count}} 个文件',
|
||||
'terminal.gitChanges.files.many': '{{count}} 个文件',
|
||||
'terminal.gitChanges.files.other': '{{count}} 个文件',
|
||||
'terminal.gitBranch.draftUnavailable': '原会话或目录已不可用。',
|
||||
'terminal.gitBranch.draftSingleLine': '请使用单行命令。',
|
||||
'terminal.directory.unknown': '目录未知',
|
||||
'terminal.directory.search': '搜索当前目录下的文件夹…',
|
||||
'terminal.directory.directories': '目录',
|
||||
@@ -574,6 +592,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'选择自动补全的历史建议来自当前主机,还是所有主机上执行过的命令。',
|
||||
'settings.terminal.autocomplete.historyScope.host': '当前主机',
|
||||
'settings.terminal.autocomplete.historyScope.global': '全部主机',
|
||||
'settings.terminal.autocomplete.showSnippets': '显示代码片段',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'在补全列表中显示匹配的代码片段。若片段较多、排在列表前面,可关闭此项。',
|
||||
'settings.terminal.section.passwordPromptAssist': '密码提示辅助',
|
||||
'settings.terminal.passwordPromptAssist.mode': '辅助模式',
|
||||
'settings.terminal.passwordPromptAssist.mode.desc':
|
||||
@@ -600,6 +621,9 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'settings.shortcuts.recording': '请按键...',
|
||||
'settings.shortcuts.none': '无',
|
||||
'settings.shortcuts.setDisabled': '设为禁用',
|
||||
'settings.shortcuts.addExtra': '添加快捷键',
|
||||
'settings.shortcuts.additional': '附加快捷键',
|
||||
'settings.shortcuts.removeExtra': '移除快捷键',
|
||||
'settings.shortcuts.category.tabs': '标签页',
|
||||
'settings.shortcuts.category.terminal': '终端',
|
||||
'settings.shortcuts.category.navigation': '导航',
|
||||
@@ -805,6 +829,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
'tabs.convertToWorkspace': '转为工作区',
|
||||
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
|
||||
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
|
||||
'tabs.closeOthers': '关闭其他标签',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理地址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不尝试代理中其他无关密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '请启动或解锁密钥服务,或者在上方填写它的地址。',
|
||||
'hostDetails.keys.search': '搜索密钥…',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '選擇 Grok 模式並傳送…',
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
'ai.chat.deliveredTextFile.source': '檔案正文已包含在回覆中',
|
||||
'ai.chat.deliveredTextFile.preview': '預覽',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起預覽',
|
||||
'ai.chat.deliveredTextFile.save': '另存為',
|
||||
'ai.chat.deliveredTextFile.saving': '正在儲存…',
|
||||
'ai.chat.deliveredTextFile.saved': '檔案已儲存',
|
||||
'ai.chat.deliveredTextFile.exists': '檔案已存在,請另選名稱。',
|
||||
'ai.chat.deliveredTextFile.failed': '無法儲存此檔案。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此視窗不支援儲存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '預覽已截短,儲存時保留完整檔案。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
'ai.chat.preparing': '準備中…',
|
||||
@@ -36,6 +47,29 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.agents': 'Agent',
|
||||
'ai.providers.empty': '尚未設定供應商。新增一個供應商以開始使用。',
|
||||
'ai.providers.add': '新增供應商',
|
||||
'ai.providers.modal.title': '新增 AI 供應商',
|
||||
'ai.providers.modal.searchPlaceholder': '搜尋供應商、模型或網域...',
|
||||
'ai.providers.modal.clearSearch': '清除搜尋',
|
||||
'ai.providers.modal.categoriesLabel': '供應商分類',
|
||||
'ai.providers.modal.category.all': '全部',
|
||||
'ai.providers.modal.category.sponsor': '贊助商',
|
||||
'ai.providers.modal.category.official': '官方平台',
|
||||
'ai.providers.modal.category.gateway': '模型聚合',
|
||||
'ai.providers.modal.category.cn': '中國模型',
|
||||
'ai.providers.modal.category.localCustom': '本機與自訂',
|
||||
'ai.providers.modal.categoryHint.sponsor': '感謝贊助商支持 Netcatty 開發',
|
||||
'ai.providers.modal.added': '已新增',
|
||||
'ai.providers.modal.noResults': '找不到相符的供應商',
|
||||
'ai.providers.modal.noResultsHint': '換個關鍵字試試,或直接新增自訂 OpenAI / Anthropic / Google 相容端點。',
|
||||
'ai.providers.modal.useCustom': '新增自訂供應商',
|
||||
'ai.providers.modal.customName': '自訂',
|
||||
'ai.providers.modal.subtitle.ollama': '本機或 Ollama Cloud · localhost:11434',
|
||||
'ai.providers.modal.subtitle.custom': 'OpenAI / Anthropic / Google 相容介面',
|
||||
'ai.providers.sponsor.hualong.name': '華龍算力',
|
||||
'ai.providers.sponsor.hualong.badge': '送 $2',
|
||||
'ai.providers.sponsor.hualong.tagline': 'Codex · DeepSeek · Claude',
|
||||
'ai.providers.sponsor.hualong.description': '穩定高效的 API 中繼服務商,主打 Codex、DeepSeek 與 Claude 系列模型,100% 官方源直供、不摻假,平均 SLA > 99.2%;Token 級帳單逐筆可核驗,支援企業合約與發票。',
|
||||
'ai.providers.sponsor.hualong.cta': '註冊領 $2 額度',
|
||||
'ai.providers.active': '使用中',
|
||||
'ai.providers.apiKeyConfigured': 'API Key 已設定',
|
||||
'ai.providers.noApiKey': '未設定 API Key',
|
||||
@@ -117,6 +151,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.codex.appServer.available': '目前 Codex CLI 支援 App Server。',
|
||||
'ai.codex.appServer.modelCatalogWarning': 'Codex 動態模型目錄暫時無法使用,目前將使用內建模型清單。',
|
||||
'ai.codex.appServer.approval.allowSession': '本工作階段允許',
|
||||
'ai.planReview.title': '審核實作方案',
|
||||
'ai.planReview.keepPlanning': '繼續規劃',
|
||||
'ai.planReview.approveAndImplement': '批准並實作',
|
||||
'ai.codex.appServer.userInput.title': 'Codex 需要你的輸入',
|
||||
'ai.codex.appServer.userInput.description': '回答以下問題以繼續目前任務。',
|
||||
'ai.codex.appServer.userInput.other': '輸入其他答案',
|
||||
@@ -305,6 +342,16 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.opencode.v2.mcpSkipped': 'OpenCode 2 無法掛接 MCP 工具,對話會繼續,但沒有該工具。',
|
||||
|
||||
// AI MiMo Code(小米 MiMo Code CLI,OpenCode 分支)
|
||||
'ai.agy.title': 'Antigravity CLI(Beta)',
|
||||
'ai.agy.description': 'Beta 測試中:透過官方 Agent Client Protocol(agy acp --stdio)接入 Google Antigravity CLI。目前支援程度有限且未經充分測試,使用請自負風險。請在終端完成 agy 登入後再作為外部程式設計 Agent 使用。',
|
||||
'ai.agy.detecting': '偵測中...',
|
||||
'ai.agy.detected': '已偵測到',
|
||||
'ai.agy.notFound': '未找到',
|
||||
'ai.agy.path': '路徑:',
|
||||
'ai.agy.notFoundHint': '在 PATH 中未找到 agy。請安裝 Antigravity CLI 或在下方指定執行檔路徑。',
|
||||
'ai.agy.customPathPlaceholder': '例如 /usr/local/bin/agy',
|
||||
'ai.agy.check': '檢查',
|
||||
'ai.agy.resetPath': '重設',
|
||||
'ai.mimo.title': 'MiMo Code',
|
||||
'ai.mimo.description': '小米 MiMo Code CLI(OpenCode 分支)。安裝後在它自己的設定裡設定 provider 和金鑰,偵測到後即可作為外部程式設計 Agent 使用。',
|
||||
'ai.mimo.detecting': '偵測中...',
|
||||
@@ -328,6 +375,13 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.check': '檢查',
|
||||
'ai.grok.resetPath': '重設',
|
||||
'ai.grok.runtime.acp.title': '使用 Grok ACP(agent stdio)',
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不會變更權限。請勿填寫密碼或權杖。',
|
||||
'ai.grok.userQuestion.submit': '傳送回答',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode 正在等待你的回答',
|
||||
'ai.agentQuestions.title': '允許 Agent 主動提問',
|
||||
'ai.agentQuestions.description': '允許此 Agent 在對話中詢問細節。回答不會授予工具權限。',
|
||||
'ai.agentQuestions.codexDescription': '允許 Codex App Server 在預設模式下詢問細節。回答不會授予工具權限。',
|
||||
'ai.grok.runtime.acp.default': '預設',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'透過 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。關閉後使用原始 headless streaming-json CLI 路徑。',
|
||||
@@ -633,12 +687,20 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chat.managerSelectedCount': '已選 {n} 個',
|
||||
'ai.chat.managerSelectRow': '選擇此工作階段',
|
||||
'ai.chat.managerRegenerateTitle': '用 AI 重新產生標題',
|
||||
'ai.chat.managerRegenerateTitleUpdated': '會話標題已更新。',
|
||||
'ai.chat.managerRegenerateTitleUnchanged': '會話標題已是最新。',
|
||||
'ai.chat.managerRegenerateTitleNoModel': '未設定用於產生標題的 AI 模型,請在 AI 設定中設定供應商或標題模型。',
|
||||
'ai.chat.managerRegenerateTitleFailed': '重新產生標題失敗:{error}',
|
||||
'ai.chat.managerRegenerateTitleBatchDone': '已更新 {n} 個會話標題。',
|
||||
'ai.chat.managerRegenerateTitleBatchPartial': '已更新 {updated} 個標題,{failed} 個失敗。',
|
||||
'ai.chat.managerExportOne': '匯出此會話',
|
||||
'ai.chat.managerBadgeActive': '使用中',
|
||||
'ai.chat.managerBadgeIdle': '閒置',
|
||||
'ai.chat.managerMessagesCount': '{n} 則訊息',
|
||||
'ai.chat.managerDeleteTitle': '刪除此會話?',
|
||||
'ai.chat.managerDeleteMessage': '「{title}」及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.managerBulkDeleteTitle': '刪除選取的 {n} 個工作階段?',
|
||||
'ai.chat.managerBulkDeleteMessage': '選取的 {n} 個工作階段及其訊息將從所有面板中移除,且無法復原。',
|
||||
'ai.chat.justNow': '剛剛',
|
||||
'ai.chat.minutesAgo': '{n}分鐘前',
|
||||
'ai.chat.hoursAgo': '{n}小時前',
|
||||
@@ -689,13 +751,30 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.chatShortcuts.selectionAction': '選取終端內容時顯示「新增到對話」',
|
||||
'ai.chatShortcuts.selectionAction.description': '在終端裡選取文字後顯示 AI 快捷按鈕。',
|
||||
'ai.chatHistory.title': '聊天歷史',
|
||||
'ai.chatHistory.storageUsage': '本機聊天記錄大小',
|
||||
'ai.chatHistory.storageUsage.description': '以 UTF-8 JSON 估算已儲存的聊天記錄大小。',
|
||||
'ai.chatHistory.storageUsage.measure': '估算',
|
||||
'ai.chatHistory.storageUsage.measuring': '正在估算…',
|
||||
'ai.chatHistory.storageUsage.result': '已儲存 {count} 筆記錄,JSON 大小約為 {size}。',
|
||||
'ai.chatHistory.storageUsage.partial': '其中 {count} 筆記錄未計入大小估算。',
|
||||
'ai.chatHistory.storageUsage.error': '無法讀取本機聊天記錄,請再試一次。',
|
||||
'ai.chatHistory.messageCap': '每個會話保留的訊息數',
|
||||
'ai.chatHistory.messageCap.description': '每個會話最多儲存的訊息數(50–2000)。調低後會在下一次寫入時從儲存中捨棄最舊的訊息。數值越大,儲存空間與雲端同步體積也越大。',
|
||||
'ai.chatHistory.messageCap.unit': '則訊息',
|
||||
'ai.chatHistory.autoLlmTitle': '自動產生工作階段標題',
|
||||
'ai.chatHistory.autoLlmTitle.description': '首則訊息後以一次輕量 LLM 呼叫產生簡短標題;不可用時退回首行。僅本機生效。',
|
||||
'ai.chatHistory.titleModel': '標題模型',
|
||||
'ai.chatHistory.titleModel.description': '用於產生工作階段標題的 provider 與模型,建議選擇輕巧便宜的模型。預設使用目前的 Catty 模型。',
|
||||
'ai.chatHistory.namingPreference': '手動標題提示詞',
|
||||
'ai.chatHistory.namingPreference.help': '可編輯整份命名範本。儲存後取代預設範本,只儲存在本機,手動重新產生標題時才會傳送。請勿填寫金鑰或密碼。',
|
||||
'ai.chatHistory.namingPreference.example': '例如:先寫專案名稱,保留關鍵技術,盡量不超過 25 字。',
|
||||
'ai.chatHistory.namingPreference.save': '儲存偏好',
|
||||
'ai.chatHistory.namingPreference.reset': '恢復預設',
|
||||
'ai.chatHistory.namingPreference.saved': '偏好已儲存。',
|
||||
'ai.chatHistory.namingPreference.resetDone': '已恢復預設。',
|
||||
'ai.chatHistory.namingPreference.failed': '無法儲存偏好。',
|
||||
'ai.chat.managerRegenerateTitleEmpty': '沒有可用於產生標題的對話文字。',
|
||||
'ai.chat.managerRegenerateTitleBusy': '正在為此對話產生標題。',
|
||||
'ai.chatHistory.titleModel.description': '用於自動和手動產生標題的供應商與模型。手動重新命名會傳送涵蓋對話不同階段的短摘錄。預設使用目前的 Catty 模型。',
|
||||
'ai.chatHistory.titleModel.none': '沒有可用的 provider。',
|
||||
'ai.chatHistory.titleModel.useCurrentCatty': '使用目前的 Catty 模型',
|
||||
'ai.chatHistory.titleModel.unavailable': '無法使用',
|
||||
|
||||
@@ -4,6 +4,24 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.directory.open': '目前目錄:{path}。變更目錄',
|
||||
'terminal.gitBranch.current': 'Git 分支:{{value}}',
|
||||
'terminal.gitBranch.detached': '分離的 HEAD:{{value}}',
|
||||
'terminal.gitBranch.search': '搜尋本機分支…',
|
||||
'terminal.gitBranch.branches': '本機分支',
|
||||
'terminal.gitBranch.loading': '正在讀取分支…',
|
||||
'terminal.gitBranch.empty': '還沒有本機分支',
|
||||
'terminal.gitBranch.noMatches': '沒有符合的分支',
|
||||
'terminal.gitBranch.unavailable': '無法讀取此工作階段的分支。',
|
||||
'terminal.gitBranch.draftDelete': '擬定刪除 {{value}} 的指令',
|
||||
'terminal.gitBranch.draftHint': 'Enter 傳送到目前的終端機,Esc 還原原稿。',
|
||||
'terminal.gitChanges.label': 'Git 變更:{{value}}',
|
||||
'terminal.gitChanges.loading': '正在讀取變更',
|
||||
'terminal.gitChanges.unavailable': '無法讀取變更',
|
||||
'terminal.gitChanges.clean': '無變更',
|
||||
'terminal.gitChanges.files.one': '{{count}} 個檔案',
|
||||
'terminal.gitChanges.files.few': '{{count}} 個檔案',
|
||||
'terminal.gitChanges.files.many': '{{count}} 個檔案',
|
||||
'terminal.gitChanges.files.other': '{{count}} 個檔案',
|
||||
'terminal.gitBranch.draftUnavailable': '原本的工作階段或目錄已無法使用。',
|
||||
'terminal.gitBranch.draftSingleLine': '請使用單行指令。',
|
||||
'terminal.directory.unknown': '目錄未知',
|
||||
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
|
||||
'terminal.directory.directories': '目錄',
|
||||
@@ -574,6 +592,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'選擇自動補全的歷史建議來自目前主機,還是所有主機上執行過的指令。',
|
||||
'settings.terminal.autocomplete.historyScope.host': '目前主機',
|
||||
'settings.terminal.autocomplete.historyScope.global': '全部主機',
|
||||
'settings.terminal.autocomplete.showSnippets': '顯示程式碼片段',
|
||||
'settings.terminal.autocomplete.showSnippets.desc':
|
||||
'在補全列表中顯示符合的程式碼片段。若片段較多、排在列表前面,可關閉此項。',
|
||||
'settings.terminal.section.passwordPromptAssist': '密碼提示輔助',
|
||||
'settings.terminal.passwordPromptAssist.mode': '輔助模式',
|
||||
'settings.terminal.passwordPromptAssist.mode.desc':
|
||||
@@ -600,6 +621,9 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'settings.shortcuts.recording': '請按鍵...',
|
||||
'settings.shortcuts.none': '無',
|
||||
'settings.shortcuts.setDisabled': '設為停用',
|
||||
'settings.shortcuts.addExtra': '新增快速鍵',
|
||||
'settings.shortcuts.additional': '附加快速鍵',
|
||||
'settings.shortcuts.removeExtra': '移除快速鍵',
|
||||
'settings.shortcuts.category.tabs': '分頁',
|
||||
'settings.shortcuts.category.terminal': '終端',
|
||||
'settings.shortcuts.category.navigation': '導航',
|
||||
@@ -805,6 +829,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
'tabs.convertToWorkspace': '轉為工作區',
|
||||
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
|
||||
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
|
||||
'tabs.closeOthers': '關閉其他分頁',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理位址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不嘗試代理中其他無關金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '請啟動或解鎖金鑰服務,或在上方填寫其位址。',
|
||||
'hostDetails.keys.search': '搜尋金鑰…',
|
||||
|
||||
@@ -79,6 +79,44 @@ test('prepared apply callback runs after the snapshot with sentinel protection',
|
||||
assert.equal(readInterruptedVaultApply(), null);
|
||||
});
|
||||
|
||||
test('protected sync does not apply anything if storage cannot persist its interruption marker', async (t) => {
|
||||
const storage = globalThis.localStorage;
|
||||
const originalSetItem = storage.setItem;
|
||||
t.after(() => { storage.setItem = originalSetItem; });
|
||||
storage.setItem = () => { throw new DOMException('No storage space', 'QuotaExceededError'); };
|
||||
let applied = false;
|
||||
|
||||
await assert.rejects(() => applyProtectedSyncPayload({
|
||||
buildPreApplyPayload: emptyPayload,
|
||||
applyPayload: () => { applied = true; },
|
||||
translateProtectiveBackupFailure: (message) => message,
|
||||
}), /interruption marker/);
|
||||
|
||||
assert.equal(applied, false);
|
||||
assert.equal(readInterruptedVaultApply(), null);
|
||||
});
|
||||
|
||||
test('protected sync rejects a missing backup even when the backup bridge resolves', async (t) => {
|
||||
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
||||
t.after(() => {
|
||||
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
||||
else Reflect.deleteProperty(globalThis, 'window');
|
||||
});
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: {
|
||||
netcatty: { createVaultBackup: async () => ({ backup: null }) },
|
||||
} });
|
||||
let applied = false;
|
||||
|
||||
await assert.rejects(() => applyProtectedSyncPayload({
|
||||
buildPreApplyPayload: () => ({ ...emptyPayload(), settings: { theme: 'light' } }),
|
||||
applyPayload: () => { applied = true; },
|
||||
translateProtectiveBackupFailure: (message) => message,
|
||||
}), /no recoverable backup/);
|
||||
|
||||
assert.equal(applied, false);
|
||||
assert.equal(readInterruptedVaultApply(), null);
|
||||
});
|
||||
|
||||
for (const localRestore of [false, true]) {
|
||||
for (const encryptionFails of [false, true]) {
|
||||
test(`protected header preparation (${localRestore ? 'restore' : 'sync'}, ${encryptionFails ? 'failure' : 'success'})`, async () => {
|
||||
|
||||
@@ -241,7 +241,10 @@ export async function createRequiredProtectiveLocalVaultBackup(
|
||||
reason: 'before_restore',
|
||||
maxCount: getLocalVaultBackupMaxCount(),
|
||||
});
|
||||
return result?.backup ?? null;
|
||||
if (!result?.backup?.id) {
|
||||
throw new Error('Vault backup service returned no recoverable backup');
|
||||
}
|
||||
return result.backup;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new ProtectiveBackupUnavailableError(message);
|
||||
@@ -381,16 +384,11 @@ export function clearInterruptedVaultApply(): void {
|
||||
}
|
||||
|
||||
function writeApplyInProgressSentinel(record: VaultApplyInProgressRecord): void {
|
||||
try {
|
||||
localStorageAdapter.writeString(
|
||||
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
|
||||
JSON.stringify(record),
|
||||
);
|
||||
} catch (error) {
|
||||
// Sentinel write is best-effort: a failure here means a later crash
|
||||
// won't be detected, but does NOT compromise the apply itself.
|
||||
// Log so a systematic storage outage is diagnosable.
|
||||
console.warn('[localVaultBackups] Failed to set apply-in-progress sentinel:', error);
|
||||
if (!localStorageAdapter.writeString(
|
||||
STORAGE_KEY_VAULT_APPLY_IN_PROGRESS,
|
||||
JSON.stringify(record),
|
||||
)) {
|
||||
throw new Error('Cannot persist the sync interruption marker; local data was not changed');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
idbPutSessions,
|
||||
isIndexedDbAvailable,
|
||||
loadOrMigrateAiSessions,
|
||||
measureAiSessionStorageUsage,
|
||||
mirrorActiveSessionMapToIdb,
|
||||
openAiSessionsIdb,
|
||||
readActiveSessionMapFromIdb,
|
||||
@@ -57,6 +58,27 @@ test('module wrapper roundtrips sessions through the object stores', async () =>
|
||||
}
|
||||
});
|
||||
|
||||
test('usage reads UTF-8 JSON sizes without changing unreadable or healthy records', async () => {
|
||||
const idb = installFakeIndexedDb();
|
||||
try {
|
||||
const signal = new AbortController().signal;
|
||||
assert.deepEqual(await measureAiSessionStorageUsage(signal), { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 });
|
||||
const db = await openAiSessionsIdb();
|
||||
const session = { ...makeSession('old-chat', 1), title: '旧聊天 🐈' };
|
||||
const bad = { ...makeSession('cycle', 2), data: {} };
|
||||
bad.data = bad;
|
||||
await idbPutSessions(db, [session, bad]);
|
||||
assert.deepEqual(await measureAiSessionStorageUsage(signal), {
|
||||
recordCount: 2, jsonBytes: Buffer.byteLength(JSON.stringify(session)), unmeasuredCount: 1,
|
||||
});
|
||||
assert.deepEqual(idb.db.opCounts.get('sessions'), { put: 2, delete: 0 });
|
||||
await assert.rejects(measureAiSessionStorageUsage(AbortSignal.abort()), { name: 'AbortError' });
|
||||
} finally {
|
||||
idb.restore();
|
||||
resetAiSessionsIdbForTests();
|
||||
}
|
||||
});
|
||||
|
||||
test('meta store roundtrips schema and active-map records', async () => {
|
||||
const idb = installFakeIndexedDb();
|
||||
try {
|
||||
|
||||
@@ -108,6 +108,47 @@ export async function idbGetAllSessions(db?: IDBDatabase): Promise<AISession[]>
|
||||
return Array.isArray(result) ? result : [];
|
||||
}
|
||||
|
||||
export interface AiSessionStorageUsage {
|
||||
recordCount: number;
|
||||
jsonBytes: number;
|
||||
unmeasuredCount: number;
|
||||
}
|
||||
|
||||
/** Size of the JSON payloads in a consistent read-only snapshot of local history. */
|
||||
export async function measureAiSessionStorageUsage(signal: AbortSignal): Promise<AiSessionStorageUsage> {
|
||||
signal.throwIfAborted();
|
||||
const db = await openAiSessionsIdb();
|
||||
signal.throwIfAborted();
|
||||
const tx = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readonly');
|
||||
const request = tx.objectStore(AI_SESSIONS_IDB_SESSION_STORE).openCursor();
|
||||
const usage = { recordCount: 0, jsonBytes: 0, unmeasuredCount: 0 };
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
tx.onabort = () => reject(tx.error ?? new Error('History scan aborted'));
|
||||
request.onerror = () => reject(request.error);
|
||||
request.onsuccess = () => {
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason);
|
||||
return;
|
||||
}
|
||||
const cursor = request.result;
|
||||
if (!cursor) {
|
||||
resolve(usage);
|
||||
return;
|
||||
}
|
||||
usage.recordCount++;
|
||||
try {
|
||||
usage.jsonBytes += encoder.encode(JSON.stringify(cursor.value)).byteLength;
|
||||
} catch {
|
||||
// Structured clone also accepts cycles and BigInts, which JSON cannot represent.
|
||||
usage.unmeasuredCount++;
|
||||
}
|
||||
cursor.continue();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function idbPutSessions(db: IDBDatabase, sessions: AISession[]): Promise<void> {
|
||||
if (sessions.length === 0) return;
|
||||
const transaction = db.transaction(AI_SESSIONS_IDB_SESSION_STORE, 'readwrite');
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export async function saveDeliveredChatTextFile(file: ChatTextFile): Promise<
|
||||
'saved' | 'cancelled' | 'exists' | 'failed' | 'unavailable'
|
||||
> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.aiChatSaveTextFile) return 'unavailable';
|
||||
try {
|
||||
const { status } = await bridge.aiChatSaveTextFile(file);
|
||||
return status === 'invalid' ? 'failed' : status;
|
||||
} catch {
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -337,3 +337,43 @@ test('explicit CSS matching the last committed value supersedes pending CSS', ()
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
|
||||
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
|
||||
const originalWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
const f = fixture();
|
||||
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
|
||||
const bridgeWithDiag = {
|
||||
...f.bridge,
|
||||
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
|
||||
diagnostics.push(payload);
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
const store = new PluginViewSessions();
|
||||
const view = store.acquire('diag-test', bridgeWithDiag, request);
|
||||
const id = f.opened[0].instanceId;
|
||||
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
|
||||
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
|
||||
assert.equal(view.getSnapshot().error, false);
|
||||
|
||||
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
|
||||
assert.equal(diagnostics.length, 1);
|
||||
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
|
||||
|
||||
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
|
||||
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
|
||||
assert.equal(view.getSnapshot().error, true);
|
||||
assert.equal(diagnostics.length, 2);
|
||||
assert.equal(diagnostics[1].source, 'plugin-view');
|
||||
assert.match(diagnostics[1].message, /Invalid plugin update order/);
|
||||
store.dispose();
|
||||
} finally {
|
||||
console.warn = originalWarn;
|
||||
}
|
||||
});
|
||||
@@ -3,7 +3,9 @@ import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
|
||||
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
|
||||
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
|
||||
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
|
||||
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
|
||||
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
|
||||
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
|
||||
@@ -26,6 +28,7 @@ export class PluginViewSessions {
|
||||
const id = crypto.randomUUID();
|
||||
const tree = createPluginRemoteTree();
|
||||
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
|
||||
let loggedDuplicateNode = false;
|
||||
let lastRawCss: string | null = null;
|
||||
let pendingCss: string | null = null;
|
||||
let pendingRawCss: string | null = null;
|
||||
@@ -48,7 +51,7 @@ export class PluginViewSessions {
|
||||
let stagedRawCss: string | null = null;
|
||||
try {
|
||||
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
|
||||
if (update.cssUnchanged) {
|
||||
if (update.cssUnchanged || update.css === undefined) {
|
||||
// keep pending CSS, if any, for the nextCss fallback below
|
||||
} else if (lastRawCss !== null && update.css === lastRawCss) {
|
||||
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
|
||||
@@ -85,9 +88,23 @@ export class PluginViewSessions {
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
|
||||
const duplicateNode = isDuplicatePluginViewNodeError(error);
|
||||
if (!duplicateNode || !loggedDuplicateNode) {
|
||||
if (duplicateNode) loggedDuplicateNode = true;
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to apply update for ${request.viewId}: ${message}`,
|
||||
extra: {
|
||||
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
|
||||
viewId: request.viewId,
|
||||
sequence: update.sequence,
|
||||
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
|
||||
},
|
||||
}).catch(() => {});
|
||||
}
|
||||
// Recoverable duplicate-only batches are normalized as moves in
|
||||
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
|
||||
if (isDuplicatePluginViewNodeError(error)) {
|
||||
if (duplicateNode) {
|
||||
if (stagedCss !== null && stagedRawCss !== null) {
|
||||
pendingCss = stagedCss;
|
||||
pendingRawCss = stagedRawCss;
|
||||
@@ -130,6 +147,13 @@ export class PluginViewSessions {
|
||||
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
|
||||
if (!disposed) {
|
||||
void bridge.logDiagnostic?.({
|
||||
source: 'plugin-view',
|
||||
message: `Failed to send event for ${request.viewId}: ${message}`,
|
||||
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
|
||||
}).catch(() => {});
|
||||
}
|
||||
dispose(true);
|
||||
});
|
||||
},
|
||||
|
||||
@@ -90,6 +90,7 @@ test('session actions register and unregister', () => {
|
||||
clearSessionFontSizeOverride: noop,
|
||||
createWorkspaceWithHosts: noop,
|
||||
createWorkspaceFromSessions: noop,
|
||||
convertSessionToWorkspace: noop,
|
||||
addSessionToWorkspace: noop,
|
||||
appendHostToWorkspace: noop,
|
||||
appendHostToWorkspaceConfirmed: noop,
|
||||
|
||||
@@ -57,6 +57,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'clearSessionFontSizeOverride'
|
||||
| 'createWorkspaceWithHosts'
|
||||
| 'createWorkspaceFromSessions'
|
||||
| 'convertSessionToWorkspace'
|
||||
| 'addSessionToWorkspace'
|
||||
| 'moveWorkspacePane'
|
||||
| 'appendHostToWorkspace'
|
||||
|
||||
@@ -5,6 +5,8 @@ import { terminalCwdStore } from './terminalCwdStore';
|
||||
import type { TerminalDirectoryIO } from '../../infrastructure/services/terminalDirectory';
|
||||
import { directoryChangeCommand, COMPLETE_DIRECTORY_CAPABILITIES } from '../../domain/directoryPicker';
|
||||
|
||||
import { gitSwitchCommand } from '../../domain/terminalGitHead';
|
||||
|
||||
function setup(overrides: Partial<TerminalDirectoryIO> = {}) {
|
||||
let cwd = '/old'; let ready = true; let current = true;
|
||||
const writes: string[] = [];
|
||||
@@ -269,3 +271,40 @@ for (const cancellation of ['abort', 'dispose'] as const) {
|
||||
await assert.rejects(controller.change('/next', abort.signal, () => {}), { code: 'unavailable' });
|
||||
});
|
||||
}
|
||||
|
||||
test('local command submission rechecks cwd and prompt readiness before writing', async t => {
|
||||
const sessionId = 'local-command';
|
||||
const writes: string[] = [];
|
||||
let ready = true;
|
||||
let finishCwd!: (cwd: string) => void;
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId, localPosixSessionId: 'local-pty', isCurrent: () => true, isReady: () => ready,
|
||||
io: { cwd: () => new Promise(resolve => { finishCwd = resolve; }), list: async () => ({ entries: [], home: null }),
|
||||
realpath: async value => value, write: data => { writes.push(data); } },
|
||||
publish() {},
|
||||
});
|
||||
terminalCwdStore.setCwd(sessionId, '/repo', 'osc7');
|
||||
t.after(() => { controller.dispose(); terminalCwdStore.setCwd(sessionId, null); });
|
||||
const command = gitSwitchCommand("/repo", "topic/it's-$special");
|
||||
assert.ok(command);
|
||||
const send = (signal = new AbortController().signal) => controller.sendLocalCommand(command, '/repo', signal);
|
||||
|
||||
const moved = send();
|
||||
finishCwd('/other');
|
||||
await assert.rejects(moved, { code: 'unavailable' });
|
||||
const busy = send();
|
||||
ready = false;
|
||||
finishCwd('/repo');
|
||||
await assert.rejects(busy, { code: 'busy' });
|
||||
ready = true;
|
||||
const request = new AbortController();
|
||||
const cancelled = send(request.signal);
|
||||
request.abort();
|
||||
finishCwd('/repo');
|
||||
await assert.rejects(cancelled, { code: 'unavailable' });
|
||||
assert.deepEqual(writes, []);
|
||||
const sent = send();
|
||||
finishCwd('/repo');
|
||||
await sent;
|
||||
assert.deepEqual(writes, [command + '\r']);
|
||||
});
|
||||
@@ -185,11 +185,35 @@ export function createTerminalDirectoryController(options: {
|
||||
check(signal);
|
||||
} finally { confirmationFinished = true; changing = false; }
|
||||
}
|
||||
async function sendLocalCommand(command: string, expectedCwd: string, signal: AbortSignal) {
|
||||
ready();
|
||||
check(signal);
|
||||
if (!options.localPosixSessionId || getConfirmedCwd() !== expectedCwd) throw new DirectoryPickerError('unavailable');
|
||||
if (changing) throw new DirectoryPickerError('busy');
|
||||
changing = true;
|
||||
try {
|
||||
const revision = terminalCwdStore.getSessionRevision(options.sessionId);
|
||||
const liveCwd = await bounded(options.io.cwd(), signal);
|
||||
if (!same(liveCwd, expectedCwd)) {
|
||||
const [livePath, expectedPath] = await bounded(Promise.all([
|
||||
options.io.realpath(liveCwd, signal), options.io.realpath(expectedCwd, signal),
|
||||
]), signal);
|
||||
if (!same(livePath, expectedPath)) throw new DirectoryPickerError('unavailable');
|
||||
}
|
||||
check(signal);
|
||||
ready();
|
||||
if (getConfirmedCwd() !== expectedCwd || terminalCwdStore.getSessionRevision(options.sessionId) !== revision) {
|
||||
throw new DirectoryPickerError('unavailable');
|
||||
}
|
||||
options.io.write(command + '\r');
|
||||
} finally { changing = false; }
|
||||
}
|
||||
return {
|
||||
target,
|
||||
localPosixSessionId: options.localPosixSessionId,
|
||||
capabilities,
|
||||
getConfirmedCwd,
|
||||
sendLocalCommand,
|
||||
subscribeCwd(listener: () => void) {
|
||||
const unsubscribe = terminalCwdStore.subscribe(listener);
|
||||
cwdListeners.add(listener);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Minimal in-memory IndexedDB stub covering the exact subset used by
|
||||
* `aiSessionIdbStorage.ts`: open + upgrade (createObjectStore), readonly
|
||||
* getAll/get, readwrite put/delete/clear, and meta-store records. Not a
|
||||
* getAll/get/openCursor, readwrite put/delete/clear, and meta-store records. Not a
|
||||
* general-purpose IDB implementation — extend deliberately if the wrapper
|
||||
* grows new usage.
|
||||
*/
|
||||
@@ -70,6 +70,24 @@ export class FakeObjectStore {
|
||||
return new FakeRequest(this.records.get(String(key)));
|
||||
}
|
||||
|
||||
openCursor() {
|
||||
const entries = this.records.values();
|
||||
type Cursor = { value: unknown; continue: () => void };
|
||||
const next = (): Cursor | null => {
|
||||
const entry = entries.next();
|
||||
if (entry.done) return null;
|
||||
return {
|
||||
value: entry.value,
|
||||
continue: () => queueMicrotask(() => {
|
||||
request.result = next();
|
||||
request.onsuccess?.(request);
|
||||
}),
|
||||
};
|
||||
};
|
||||
const request: FakeRequest<Cursor | null> = new FakeRequest(next());
|
||||
return request;
|
||||
}
|
||||
|
||||
getAll(): FakeRequest<unknown[]> {
|
||||
return new FakeRequest(Array.from(this.records.values()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useState } from 'react';
|
||||
import { normalizeTitleNamingPreference } from '../../domain/aiSessionTitle';
|
||||
import { STORAGE_KEY_AI_TITLE_NAMING_PREFERENCE } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
|
||||
// Intentionally local; this key is not part of the sync/settings payload.
|
||||
export function readTitleNamingPreference(): string {
|
||||
return normalizeTitleNamingPreference(localStorageAdapter.readString(STORAGE_KEY_AI_TITLE_NAMING_PREFERENCE));
|
||||
}
|
||||
|
||||
export function saveTitleNamingPreference(value: string): boolean {
|
||||
return localStorageAdapter.writeString(
|
||||
STORAGE_KEY_AI_TITLE_NAMING_PREFERENCE,
|
||||
normalizeTitleNamingPreference(value),
|
||||
);
|
||||
}
|
||||
|
||||
export function useTitleNamingPreference() {
|
||||
const [saved, setSaved] = useState(readTitleNamingPreference);
|
||||
|
||||
function save(value: string): boolean {
|
||||
const normalized = normalizeTitleNamingPreference(value);
|
||||
if (!saveTitleNamingPreference(normalized)) return false;
|
||||
setSaved(normalized);
|
||||
return true;
|
||||
}
|
||||
|
||||
return { saved, save, reset: () => save('') };
|
||||
}
|
||||
@@ -139,6 +139,7 @@ export interface SendToExternalContext {
|
||||
defaultTargetSession?: DefaultTargetSessionHint;
|
||||
providers: ProviderConfig[];
|
||||
selectedAgentModel?: string;
|
||||
chooseGrokMode?: boolean;
|
||||
toolIntegrationMode: AIToolIntegrationMode;
|
||||
selectedUserSkillSlugs?: string[];
|
||||
permissionMode: AIPermissionMode;
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
STORAGE_KEY_AI_TITLE_MODEL,
|
||||
} from '../../infrastructure/config/storageKeys.ts';
|
||||
import { useAIState, type UseAIStateOptions } from './useAIState.ts';
|
||||
import { readTitleNamingPreference, saveTitleNamingPreference } from './titleNamingPreference.ts';
|
||||
import { useAISessionsStore } from './aiSessionsStore.ts';
|
||||
import {
|
||||
__resetIdbPersistenceForTests,
|
||||
@@ -343,3 +344,106 @@ test('autoTitleSession respects autoLlmTitle=false and removeProvider clears dan
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a queued regeneration preserves a title renamed before its request starts', async () => {
|
||||
const session = untitledSession();
|
||||
let calls = 0;
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [session],
|
||||
providers: [providerA],
|
||||
activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => { calls += 1; return 'Generated'; },
|
||||
});
|
||||
try {
|
||||
await act(async () => { capture.ai!.updateSessionTitle(session.id, 'Manual'); });
|
||||
const result = await capture.ai!.regenerateSessionTitle(session.id, session.title);
|
||||
assert.deepEqual(result, { status: 'unchanged', title: 'Manual' });
|
||||
assert.equal(calls, 0);
|
||||
assert.equal(capture.sessions[0].title, 'Manual');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('manual rename uses history mode and applies its result with auto-title off', async () => {
|
||||
const session = { ...untitledSession(), title: 'Old title', agentId: 'opencode' as const };
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [session],
|
||||
providers: [providerA, providerB],
|
||||
activeProviderId: providerA.id,
|
||||
autoLlmTitle: false,
|
||||
titleModel: { providerId: providerB.id, modelId: 'gpt-4o-mini' },
|
||||
generateSessionTitle: async (_source, opts) => {
|
||||
assert.equal(opts.mode, 'history');
|
||||
assert.equal(opts.config?.id, providerB.id);
|
||||
assert.equal(opts.namingPreference, 'Project name before issue');
|
||||
return 'New title';
|
||||
},
|
||||
});
|
||||
try {
|
||||
assert.equal(readTitleNamingPreference(), '');
|
||||
assert.equal(saveTitleNamingPreference(' Project name before issue '), true);
|
||||
await act(async () => {
|
||||
assert.deepEqual(await capture.ai!.regenerateSessionTitle(session.id), {
|
||||
status: 'updated', title: 'New title',
|
||||
});
|
||||
});
|
||||
assert.equal(capture.sessions[0]?.title, 'New title');
|
||||
assert.equal(saveTitleNamingPreference('x'.repeat(900)), true);
|
||||
assert.equal(readTitleNamingPreference().length, 480);
|
||||
assert.equal(saveTitleNamingPreference(''), true);
|
||||
assert.equal(readTitleNamingPreference(), '');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('manual regeneration does not claim success after a concurrent title change', async () => {
|
||||
const session = { ...untitledSession(), title: 'Old title' };
|
||||
const pending = deferred<string>();
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [session], providers: [providerA], activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => pending.promise,
|
||||
});
|
||||
try {
|
||||
let result!: ReturnType<NonNullable<Capture['ai']>['regenerateSessionTitle']>;
|
||||
await act(async () => {
|
||||
result = capture.ai!.regenerateSessionTitle(session.id);
|
||||
});
|
||||
setLatestAISessionsSnapshot([{ ...session, title: 'Changed elsewhere' }]);
|
||||
await act(async () => {
|
||||
pending.resolve('AI title');
|
||||
assert.deepEqual(await result, { status: 'unchanged', title: 'Changed elsewhere' });
|
||||
});
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('manual regeneration preserves batched streaming edits in this and other chats', async () => {
|
||||
const session = untitledSession('title-target');
|
||||
const other = untitledSession('other-chat');
|
||||
const pending = deferred<string>();
|
||||
const { capture, cleanup } = await setupHook({
|
||||
sessions: [session, other], providers: [providerA], activeProviderId: providerA.id,
|
||||
generateSessionTitle: async () => pending.promise,
|
||||
});
|
||||
try {
|
||||
const result = capture.ai!.regenerateSessionTitle(session.id);
|
||||
await act(async () => {
|
||||
capture.ai!.addMessageToSession(session.id, {
|
||||
id: 'stream', role: 'assistant', content: 'partial', timestamp: 2,
|
||||
});
|
||||
capture.ai!.updateMessageById(session.id, 'stream', message => ({ ...message, content: 'complete' }));
|
||||
capture.ai!.addMessageToSession(other.id, {
|
||||
id: 'other-stream', role: 'assistant', content: 'other reply', timestamp: 3,
|
||||
});
|
||||
pending.resolve('Generated title');
|
||||
assert.deepEqual(await result, { status: 'updated', title: 'Generated title' });
|
||||
});
|
||||
assert.equal(capture.sessions.find(s => s.id === session.id)?.messages.at(-1)?.content, 'complete');
|
||||
assert.equal(capture.sessions.find(s => s.id === other.id)?.messages.at(-1)?.content, 'other reply');
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
});
|
||||
@@ -128,3 +128,64 @@ test('restored workspace enters a blank draft when New Chat is clicked', async (
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('async clearDraftForScope propagates draft removal to sibling useAIState subscribers', async () => {
|
||||
const dom = new JSDOM('<!doctype html><html><body></body></html>', {
|
||||
url: 'http://localhost',
|
||||
});
|
||||
Object.defineProperty(globalThis, 'window', { configurable: true, value: dom.window });
|
||||
Object.defineProperty(globalThis, 'document', { configurable: true, value: dom.window.document });
|
||||
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: dom.window.localStorage });
|
||||
Object.defineProperty(globalThis, 'CustomEvent', { configurable: true, value: dom.window.CustomEvent });
|
||||
Object.defineProperty(globalThis, 'Event', { configurable: true, value: dom.window.Event });
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
|
||||
|
||||
let writer: ReturnType<typeof useAIState> | null = null;
|
||||
let readerDraftText: string | undefined;
|
||||
|
||||
function Writer() {
|
||||
writer = useAIState();
|
||||
return null;
|
||||
}
|
||||
|
||||
function Reader() {
|
||||
useAIState();
|
||||
const state = useAISessionsStore();
|
||||
readerDraftText = state.draftsByScope[SCOPE_KEY]?.text;
|
||||
return <span data-draft={readerDraftText ?? ''} />;
|
||||
}
|
||||
|
||||
const container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<>
|
||||
<Writer />
|
||||
<Reader />
|
||||
</>,
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
writer!.updateDraft(SCOPE_KEY, 'catty', () => ({
|
||||
text: 'sent message',
|
||||
agentId: 'catty',
|
||||
attachments: [],
|
||||
selectedUserSkillSlugs: [],
|
||||
updatedAt: Date.now(),
|
||||
}));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
writer!.clearDraftForScope(SCOPE_KEY);
|
||||
});
|
||||
|
||||
assert.equal(readerDraftText, undefined);
|
||||
assert.equal(container.querySelector('span')?.dataset.draft, '');
|
||||
|
||||
await act(async () => root.unmount());
|
||||
container.remove();
|
||||
dom.window.close();
|
||||
});
|
||||
+179
-149
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { readTitleNamingPreference } from './titleNamingPreference';
|
||||
import {
|
||||
STORAGE_KEY_AI_HOST_PERMISSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AGENT_THINKING_MAP,
|
||||
STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS,
|
||||
STORAGE_KEY_UI_LANGUAGE,
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import type {
|
||||
AIDraft,
|
||||
@@ -18,6 +20,7 @@ import type {
|
||||
HostAIPermission,
|
||||
ChatMessage,
|
||||
AISessionScope,
|
||||
ProviderConfig,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
activateDraftView,
|
||||
@@ -106,6 +109,27 @@ import {
|
||||
} from '../../domain/aiSessionTitle';
|
||||
import type { generateSessionLlmTitle as GenerateSessionLlmTitleFn } from '../../infrastructure/ai/sessionTitleGeneration';
|
||||
|
||||
export type RegenerateSessionTitleResult =
|
||||
| { status: 'updated'; title: string }
|
||||
| { status: 'unchanged'; title: string }
|
||||
| { status: 'busy' }
|
||||
| { status: 'no-model' }
|
||||
| { status: 'empty' }
|
||||
| { status: 'error'; error: string };
|
||||
|
||||
function readConfiguredUiLanguage(): string | undefined {
|
||||
try {
|
||||
const stored = localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE);
|
||||
if (stored && stored.trim()) return stored.trim();
|
||||
} catch {
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
if (typeof navigator !== 'undefined' && typeof navigator.language === 'string' && navigator.language.trim()) {
|
||||
return navigator.language.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface UseAIStateOptions {
|
||||
/** Optional test injection for one-shot LLM title generation. */
|
||||
generateSessionTitle?: typeof GenerateSessionLlmTitleFn;
|
||||
@@ -322,7 +346,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
// Ref that always holds the latest sessions for use inside debounced callbacks
|
||||
const sessionsRef = useRef(sessions);
|
||||
useEffect(() => {
|
||||
sessionsRef.current = sessions;
|
||||
sessionsRef.current = latestAISessionsSnapshot ?? sessions;
|
||||
}, [sessions]);
|
||||
// Per-scope active session: keyed by `${scopeType}:${scopeTargetId}`
|
||||
const [activeSessionIdMap, setActiveSessionIdMapRaw] = useState<Record<string, string | null>>(() =>
|
||||
@@ -444,7 +468,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
setLatestAISessionsSnapshot(sessions);
|
||||
if (latestAISessionsSnapshot === null) setLatestAISessionsSnapshot(sessions);
|
||||
}, [sessions]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -702,6 +726,19 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
// Commit against the shared session snapshot at the time of the mutation.
|
||||
// Only the render is batched. A title result or another message arriving
|
||||
// in the same batch must see every earlier mutation, including other chats.
|
||||
const mutateSessions = useCallback((update: (current: AISession[]) => AISession[]) => {
|
||||
if (!mountedRef.current) return;
|
||||
const current = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const next = update(current);
|
||||
if (next === current) return;
|
||||
setLatestAISessionsSnapshot(next);
|
||||
sessionsRef.current = next;
|
||||
setSessionsRaw(next);
|
||||
}, []);
|
||||
|
||||
const debouncedPersistSessions = useCallback(() => {
|
||||
if (persistTimerRef.current) clearTimeout(persistTimerRef.current);
|
||||
persistTimerRef.current = setTimeout(() => {
|
||||
@@ -771,17 +808,16 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
if (plan.contextCompaction) {
|
||||
fork.contextCompaction = plan.contextCompaction;
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
// Keep the source alongside its branch within the existing history limit.
|
||||
const next = [fork, { ...source, updatedAt: now }, ...prev.filter(session => session.id !== source.id)];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
const scopeKey = `${fork.scope.type}:${fork.scope.targetId ?? ''}`;
|
||||
setActiveSessionId(scopeKey, fork.id);
|
||||
return fork;
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
}, [mutateSessions, persistSessions, setActiveSessionId]);
|
||||
|
||||
const createSession = useCallback((
|
||||
scope: AISessionScope,
|
||||
@@ -802,16 +838,15 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
updatedAt: now,
|
||||
};
|
||||
pendingCreatedSessionIdsRef.current.add(session.id);
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = [session, ...prev];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
const scopeKey = `${scope.type}:${scope.targetId ?? ''}`;
|
||||
setActiveSessionId(scopeKey, session.id);
|
||||
return session;
|
||||
}, [defaultAgentId, persistSessions, setActiveSessionId]);
|
||||
}, [mutateSessions, defaultAgentId, persistSessions, setActiveSessionId]);
|
||||
|
||||
// Non-destructive "undo last turn": branch the session at the boundary
|
||||
// before the latest user message and keep the original in history intact.
|
||||
@@ -835,17 +870,16 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
if (viewingScope) {
|
||||
branched.scope = { ...branched.scope, ...viewingScope };
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
// Keep both recently used chats within the existing history limit.
|
||||
const next = [branched, { ...source, updatedAt: branched.updatedAt }, ...prev.filter(session => session.id !== source.id)];
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
const scopeKey = `${branched.scope.type}:${branched.scope.targetId ?? ''}`;
|
||||
setActiveSessionId(scopeKey, branched.id);
|
||||
return { sessionId: branched.id, restored: result.restored };
|
||||
}, [persistSessions, setActiveSessionId]);
|
||||
}, [mutateSessions, persistSessions, setActiveSessionId]);
|
||||
|
||||
const deleteSession = useCallback((sessionId: string, scopeKey?: string) => {
|
||||
pendingCreatedSessionIdsRef.current.delete(sessionId);
|
||||
@@ -859,9 +893,8 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
persistTimerRef.current = null;
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.filter(s => s.id !== sessionId);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next, [sessionId]);
|
||||
return next;
|
||||
});
|
||||
@@ -890,7 +923,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
return next;
|
||||
});
|
||||
}
|
||||
}, [persistSessions]);
|
||||
}, [mutateSessions, persistSessions]);
|
||||
|
||||
const deleteSessionsByTarget = useCallback((scopeType: 'terminal' | 'workspace', targetId: string) => {
|
||||
const removedSessionIds = sessionsRef.current
|
||||
@@ -909,11 +942,10 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
clearTimeout(persistTimerRef.current);
|
||||
persistTimerRef.current = null;
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.filter(s => {
|
||||
return !(s.scope.type === scopeType && s.scope.targetId === targetId);
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next, removedSessionIds);
|
||||
return next;
|
||||
});
|
||||
@@ -928,7 +960,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}, [persistSessions]);
|
||||
}, [mutateSessions, persistSessions]);
|
||||
|
||||
const updateSessionTitle = useCallback((sessionId: string, title: string) => {
|
||||
// Manual rename supersedes any in-flight automatic title generation.
|
||||
@@ -937,13 +969,12 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
pendingTitleController.abort();
|
||||
}
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => s.id === sessionId ? { ...s, title, updatedAt: Date.now() } : s);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
}, [persistSessions]);
|
||||
}, [mutateSessions, persistSessions]);
|
||||
|
||||
/**
|
||||
* Auto-title a session if it still carries the placeholder title. Writes a
|
||||
@@ -968,10 +999,9 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
const fallback = buildFallbackTitle(text);
|
||||
|
||||
// Phase 1: Atomically apply the deterministic fallback while still untitled.
|
||||
setSessionsRaw((prev) => {
|
||||
mutateSessions((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
@@ -1010,6 +1040,13 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
: (text ? [{ role: 'user' as const, content: text }] : []);
|
||||
if (sourceMessages.length === 0) return;
|
||||
|
||||
const bridge = getAIBridge() as {
|
||||
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
|
||||
} | undefined;
|
||||
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
|
||||
await bridge.aiSyncProviders(providersRef.current);
|
||||
}
|
||||
|
||||
const generateTitle = generateSessionTitleRef.current
|
||||
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
|
||||
|
||||
@@ -1019,6 +1056,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: requestController.signal,
|
||||
language: readConfiguredUiLanguage(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1029,10 +1067,9 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
// Phase 2: Atomically promote the LLM title only if the session still
|
||||
// exists and still holds the exact fallback title applied in Phase 1.
|
||||
if (mountedRef.current) {
|
||||
setSessionsRaw((prev) => {
|
||||
mutateSessions((prev) => {
|
||||
const result = applySessionTitleIfCurrent(prev, sessionId, generated, fallback);
|
||||
if (!result.updated) return prev;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
});
|
||||
@@ -1055,18 +1092,25 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}, [persistSessions]);
|
||||
}, [mutateSessions, persistSessions]);
|
||||
|
||||
/**
|
||||
* Explicitly regenerate an existing chat's title with the configured LLM
|
||||
* (session-history management: no placeholder gate). The old title is the
|
||||
* expected value, so a user rename during generation still wins.
|
||||
*/
|
||||
const regenerateSessionTitle = useCallback(async (sessionId: string): Promise<void> => {
|
||||
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) return;
|
||||
const regenerateSessionTitle = useCallback(async (sessionId: string, expectedTitle?: string): Promise<RegenerateSessionTitleResult> => {
|
||||
if (!sessionId || titleAbortControllersRef.current.has(sessionId)) {
|
||||
return { status: 'busy' };
|
||||
}
|
||||
const snapshot = latestAISessionsSnapshot ?? sessionsRef.current;
|
||||
const session = snapshot.find((s) => s.id === sessionId);
|
||||
if (!session || session.messages.length === 0) return;
|
||||
if (!session || session.messages.length === 0) {
|
||||
return { status: 'empty' };
|
||||
}
|
||||
if (expectedTitle !== undefined && session.title !== expectedTitle) {
|
||||
return { status: 'unchanged', title: session.title };
|
||||
}
|
||||
const resolvedTitleConfig = resolveEffectiveTitleModelConfig({
|
||||
titleModel: titleModelRef.current,
|
||||
providers: providersRef.current,
|
||||
@@ -1075,10 +1119,20 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
if (!resolvedTitleConfig) {
|
||||
return { status: 'no-model' };
|
||||
}
|
||||
const namingPreference = readTitleNamingPreference();
|
||||
const controller = new AbortController();
|
||||
titleAbortControllersRef.current.set(sessionId, controller);
|
||||
let capturedError: unknown = null;
|
||||
try {
|
||||
const bridge = getAIBridge() as {
|
||||
aiSyncProviders?: (providers: ProviderConfig[]) => Promise<unknown>;
|
||||
} | undefined;
|
||||
if (bridge?.aiSyncProviders && providersRef.current.length > 0) {
|
||||
await bridge.aiSyncProviders(providersRef.current);
|
||||
}
|
||||
const generateTitle = generateSessionTitleRef.current
|
||||
?? (await import('../../infrastructure/ai/sessionTitleGeneration')).generateSessionLlmTitle;
|
||||
const generated = await generateTitle(
|
||||
@@ -1088,25 +1142,37 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
chatSessionId: sessionId,
|
||||
signal: controller.signal,
|
||||
fallbackOnFailure: false,
|
||||
mode: 'history',
|
||||
namingPreference,
|
||||
language: readConfiguredUiLanguage(),
|
||||
onError: (err) => { capturedError = err; },
|
||||
},
|
||||
);
|
||||
if (controller.signal.aborted || !generated || generated === session.title) return;
|
||||
const previousTitle = session.title;
|
||||
const commit = (sessions: AISession[]) => {
|
||||
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
|
||||
if (!result.updated) return sessions;
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
return result.sessions;
|
||||
};
|
||||
if (mountedRef.current) setSessionsRaw(commit);
|
||||
else {
|
||||
const result = commit(latestAISessionsSnapshot ?? getPersistedAiSessionsSnapshot());
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
void result;
|
||||
if (controller.signal.aborted) {
|
||||
return { status: 'error', error: 'Aborted' };
|
||||
}
|
||||
} catch {
|
||||
// Title generation never throws; keep the existing title on failure.
|
||||
if (!generated) {
|
||||
const message = capturedError instanceof Error
|
||||
? capturedError.message
|
||||
: (capturedError ? String(capturedError) : 'Model returned an empty title');
|
||||
return { status: 'error', error: message };
|
||||
}
|
||||
const current = latestAISessionsSnapshot ?? (mountedRef.current ? sessionsRef.current : getPersistedAiSessionsSnapshot());
|
||||
const currentSession = current.find((item) => item.id === sessionId);
|
||||
if (!currentSession) return { status: 'empty' };
|
||||
const result = applySessionTitleIfCurrent(current, sessionId, generated, session.title);
|
||||
if (!result.updated) return { status: 'unchanged', title: currentSession.title };
|
||||
setLatestAISessionsSnapshot(result.sessions);
|
||||
persistSessions(result.sessions);
|
||||
if (mountedRef.current) {
|
||||
sessionsRef.current = result.sessions;
|
||||
setSessionsRaw(result.sessions);
|
||||
}
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
return { status: 'updated', title: generated };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return { status: 'error', error: message };
|
||||
} finally {
|
||||
if (titleAbortControllersRef.current.get(sessionId) === controller) {
|
||||
titleAbortControllersRef.current.delete(sessionId);
|
||||
@@ -1132,7 +1198,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
latestAIActiveSessionMapSnapshot
|
||||
?? localStorageAdapter.read<Record<string, string | null>>(STORAGE_KEY_AI_ACTIVE_SESSION_MAP)
|
||||
?? {};
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId) return s;
|
||||
const { scopeDangling: _cleared, ...rest } = s;
|
||||
@@ -1157,7 +1223,6 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
updatedAt: Date.now(),
|
||||
} as AISession;
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
@@ -1194,7 +1259,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
sessionId,
|
||||
),
|
||||
);
|
||||
}, [persistSessions, setPanelViewByScope]);
|
||||
}, [mutateSessions, persistSessions, setPanelViewByScope]);
|
||||
|
||||
// Manual durability escape hatch (issue #4015 follow-up): export the
|
||||
// current store to a user-chosen JSON file, or import one back in.
|
||||
@@ -1250,17 +1315,16 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, []);
|
||||
|
||||
const updateSessionExternalSessionId = useCallback((sessionId: string, externalSessionId: string | undefined) => {
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => (
|
||||
s.id === sessionId
|
||||
? { ...s, externalSessionId, updatedAt: Date.now() }
|
||||
: s
|
||||
));
|
||||
setLatestAISessionsSnapshot(next);
|
||||
debouncedPersistSessions();
|
||||
return next;
|
||||
});
|
||||
}, [debouncedPersistSessions]);
|
||||
}, [mutateSessions, debouncedPersistSessions]);
|
||||
|
||||
// Local-only retention. Synced history must match the full-history storage
|
||||
// policy. The in-memory bound follows the user-configurable per-session cap
|
||||
@@ -1272,7 +1336,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
const addMessageToSession = useCallback((sessionId: string, message: ChatMessage) => {
|
||||
const syncEnabled = localStorageAdapter.read<{ enabled?: boolean }>(STORAGE_KEY_CLOUD_SYNC_AI_SESSIONS)?.enabled === true;
|
||||
const inMemoryCap = Math.max(readAiSessionMessageCap(), MIN_IN_MEMORY_MESSAGES_PER_SESSION);
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId) return s;
|
||||
let msgs = [...s.messages, message];
|
||||
@@ -1286,28 +1350,26 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}
|
||||
return { ...s, messages: msgs, updatedAt: Date.now() };
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
debouncedPersistSessions();
|
||||
return next;
|
||||
});
|
||||
}, [debouncedPersistSessions]);
|
||||
}, [mutateSessions, debouncedPersistSessions]);
|
||||
|
||||
const updateLastMessage = useCallback((sessionId: string, updater: (msg: ChatMessage) => ChatMessage) => {
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId || s.messages.length === 0) return s;
|
||||
const msgs = [...s.messages];
|
||||
msgs[msgs.length - 1] = updater(msgs[msgs.length - 1]);
|
||||
return { ...s, messages: msgs, updatedAt: Date.now() };
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
debouncedPersistSessions();
|
||||
return next;
|
||||
});
|
||||
}, [debouncedPersistSessions]);
|
||||
}, [mutateSessions, debouncedPersistSessions]);
|
||||
|
||||
const updateMessageById = useCallback((sessionId: string, messageId: string, updater: (msg: ChatMessage) => ChatMessage) => {
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => {
|
||||
if (s.id !== sessionId) return s;
|
||||
const idx = s.messages.findIndex(m => m.id === messageId);
|
||||
@@ -1316,41 +1378,31 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
msgs[idx] = updater(msgs[idx]);
|
||||
return { ...s, messages: msgs, updatedAt: Date.now() };
|
||||
});
|
||||
setLatestAISessionsSnapshot(next);
|
||||
debouncedPersistSessions();
|
||||
return next;
|
||||
});
|
||||
}, [debouncedPersistSessions]);
|
||||
}, [mutateSessions, debouncedPersistSessions]);
|
||||
|
||||
const persistContextCompaction = useCallback((
|
||||
sessionId: string,
|
||||
contextCompaction: AISessionContextCompaction,
|
||||
) => {
|
||||
setSessionsRaw(prev => {
|
||||
mutateSessions(prev => {
|
||||
const next = prev.map(s => s.id === sessionId
|
||||
? { ...s, contextCompaction, updatedAt: Date.now() }
|
||||
: s);
|
||||
setLatestAISessionsSnapshot(next);
|
||||
persistSessions(next);
|
||||
return next;
|
||||
});
|
||||
}, [persistSessions]);
|
||||
}, [mutateSessions, persistSessions]);
|
||||
|
||||
const ensureDraftForScope = useCallback((scopeKey: string, agentId: string): void => {
|
||||
let nextDraftsByScope: DraftsByScope | null = null;
|
||||
let textOnly = false;
|
||||
|
||||
setDraftsByScopeRaw((prev) => {
|
||||
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
|
||||
if (next === prev) return prev;
|
||||
nextDraftsByScope = next;
|
||||
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (!nextDraftsByScope) return;
|
||||
|
||||
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
|
||||
const prev = latestAIDraftsByScopeSnapshot;
|
||||
const next = ensureDraftForScopeState(prev, scopeKey, agentId);
|
||||
if (next === prev) return;
|
||||
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
setLatestAIDraftsByScopeSnapshot(next);
|
||||
setDraftsByScopeRaw(next);
|
||||
if (textOnly) return;
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
|
||||
@@ -1361,31 +1413,24 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
fallbackAgentId: string,
|
||||
updater: (draft: AIDraft) => AIDraft,
|
||||
): void => {
|
||||
let nextDraftsByScope: DraftsByScope | null = null;
|
||||
let textOnly = false;
|
||||
|
||||
setDraftsByScopeRaw((prev) => {
|
||||
const next = updateDraftForScope(
|
||||
prev,
|
||||
scopeKey,
|
||||
fallbackAgentId,
|
||||
(draft) => {
|
||||
const updated = updater(draft);
|
||||
if (updated === draft) return draft;
|
||||
return {
|
||||
...updated,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
},
|
||||
);
|
||||
if (next === prev) return prev;
|
||||
nextDraftsByScope = next;
|
||||
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (!nextDraftsByScope) return;
|
||||
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
|
||||
const prev = latestAIDraftsByScopeSnapshot;
|
||||
const next = updateDraftForScope(
|
||||
prev,
|
||||
scopeKey,
|
||||
fallbackAgentId,
|
||||
(draft) => {
|
||||
const updated = updater(draft);
|
||||
if (updated === draft) return draft;
|
||||
return {
|
||||
...updated,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
},
|
||||
);
|
||||
if (next === prev) return;
|
||||
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
setLatestAIDraftsByScopeSnapshot(next);
|
||||
setDraftsByScopeRaw(next);
|
||||
if (textOnly) return;
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
|
||||
@@ -1395,32 +1440,25 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
scopeKey: string,
|
||||
updater: (draft: AIDraft) => AIDraft,
|
||||
): void => {
|
||||
let nextDraftsByScope: DraftsByScope | null = null;
|
||||
let textOnly = false;
|
||||
const prev = latestAIDraftsByScopeSnapshot;
|
||||
const currentDraft = prev[scopeKey];
|
||||
if (!currentDraft) return;
|
||||
|
||||
setDraftsByScopeRaw((prev) => {
|
||||
const currentDraft = prev[scopeKey];
|
||||
if (!currentDraft) return prev;
|
||||
|
||||
const updated = updater(currentDraft);
|
||||
const nextDraft = updated === currentDraft
|
||||
? currentDraft
|
||||
: {
|
||||
...updated,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
if (nextDraft === currentDraft) return prev;
|
||||
const next = {
|
||||
...prev,
|
||||
[scopeKey]: nextDraft,
|
||||
const updated = updater(currentDraft);
|
||||
const nextDraft = updated === currentDraft
|
||||
? currentDraft
|
||||
: {
|
||||
...updated,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
nextDraftsByScope = next;
|
||||
textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (!nextDraftsByScope) return;
|
||||
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
|
||||
if (nextDraft === currentDraft) return;
|
||||
const next: DraftsByScope = {
|
||||
...prev,
|
||||
[scopeKey]: nextDraft,
|
||||
};
|
||||
const textOnly = draftsByScopeEqualIgnoringAllComposerText(prev, next);
|
||||
setLatestAIDraftsByScopeSnapshot(next);
|
||||
setDraftsByScopeRaw(next);
|
||||
if (textOnly) return;
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
|
||||
@@ -1455,38 +1493,30 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, [setPanelViewByScope]);
|
||||
|
||||
const clearDraftForScope = useCallback((scopeKey: string) => {
|
||||
const currentPanelViewByScope = panelViewByScope;
|
||||
let nextDraftsByScope: DraftsByScope | null = null;
|
||||
let nextPanelViewByScope: PanelViewByScope | null = null;
|
||||
let draftsChanged = false;
|
||||
let panelViewChanged = false;
|
||||
|
||||
setDraftsByScopeRaw((prevDraftsByScope) => {
|
||||
const next = clearScopeDraftState(
|
||||
prevDraftsByScope,
|
||||
currentPanelViewByScope,
|
||||
scopeKey,
|
||||
);
|
||||
draftsChanged = next.draftsByScope !== prevDraftsByScope;
|
||||
panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
|
||||
nextDraftsByScope = next.draftsByScope;
|
||||
nextPanelViewByScope = next.panelViewByScope;
|
||||
return draftsChanged ? next.draftsByScope : prevDraftsByScope;
|
||||
});
|
||||
const prevDraftsByScope = latestAIDraftsByScopeSnapshot;
|
||||
const currentPanelViewByScope = latestAIPanelViewByScopeSnapshot ?? panelViewByScope;
|
||||
const next = clearScopeDraftState(
|
||||
prevDraftsByScope,
|
||||
currentPanelViewByScope,
|
||||
scopeKey,
|
||||
);
|
||||
const draftsChanged = next.draftsByScope !== prevDraftsByScope;
|
||||
const panelViewChanged = next.panelViewByScope !== currentPanelViewByScope;
|
||||
|
||||
if (!draftsChanged && !panelViewChanged) return;
|
||||
|
||||
bumpDraftMutationVersion(scopeKey);
|
||||
bumpDraftUploadGeneration(scopeKey);
|
||||
|
||||
if (draftsChanged && nextDraftsByScope) {
|
||||
setLatestAIDraftsByScopeSnapshot(nextDraftsByScope);
|
||||
if (draftsChanged) {
|
||||
setLatestAIDraftsByScopeSnapshot(next.draftsByScope);
|
||||
setDraftsByScopeRaw(next.draftsByScope);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_DRAFTS_BY_SCOPE);
|
||||
}
|
||||
|
||||
if (panelViewChanged && nextPanelViewByScope) {
|
||||
setLatestAIPanelViewByScopeSnapshot(nextPanelViewByScope);
|
||||
setPanelViewByScopeRaw(nextPanelViewByScope);
|
||||
if (panelViewChanged) {
|
||||
setLatestAIPanelViewByScopeSnapshot(next.panelViewByScope);
|
||||
setPanelViewByScopeRaw(next.panelViewByScope);
|
||||
emitAIStateChanged(AI_STATE_CHANGED_PANEL_VIEW_BY_SCOPE);
|
||||
}
|
||||
}, [panelViewByScope]);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { measureAiSessionStorageUsage, type AiSessionStorageUsage } from './aiSessionIdbStorage';
|
||||
|
||||
type Measurement =
|
||||
| { status: 'idle' | 'loading' | 'error' }
|
||||
| { status: 'ready'; usage: AiSessionStorageUsage };
|
||||
|
||||
export function useAiSessionStorageUsage() {
|
||||
const [measurement, setMeasurement] = useState<Measurement>({ status: 'idle' });
|
||||
const active = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => active.current?.abort(), []);
|
||||
|
||||
async function measure() {
|
||||
if (active.current) return;
|
||||
const controller = new AbortController();
|
||||
active.current = controller;
|
||||
setMeasurement({ status: 'loading' });
|
||||
try {
|
||||
const usage = await measureAiSessionStorageUsage(controller.signal);
|
||||
if (!controller.signal.aborted) setMeasurement({ status: 'ready', usage });
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setMeasurement({ status: 'error' });
|
||||
} finally {
|
||||
active.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
return { measurement, measure };
|
||||
}
|
||||
@@ -27,8 +27,8 @@ test('Git chip follows confirmed cwd and ignores an old worktree result', async
|
||||
const unregister = registerTerminalDirectory(id, controller);
|
||||
const stopObserving = observeTerminalDirectory(id);
|
||||
let root!: ReactTestRenderer;
|
||||
let head: ReturnType<typeof useComposeGitBranch>;
|
||||
function Harness() { head = useComposeGitBranch(id); return null; }
|
||||
let head: ReturnType<typeof useComposeGitBranch>['head'];
|
||||
function Harness() { head = useComposeGitBranch(id).head; return null; }
|
||||
const waitForCalls = async (count: number) => {
|
||||
for (let i = 0; calls.length < count && i < 100; i++) await new Promise(resolve => setTimeout(resolve, 10));
|
||||
assert.equal(calls.length, count);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, useSyncExternalStore } from 'react';
|
||||
import type { TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { DirectoryPickerError } from '../../domain/directoryPicker';
|
||||
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
|
||||
import { gitDeleteBranchCommand, gitSwitchCommand, scopeGitBranchDraft, type TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
@@ -8,7 +9,14 @@ const noCwd = () => null;
|
||||
const noSubscription = () => () => {};
|
||||
const REFRESH_DELAY_MS = 150;
|
||||
|
||||
export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
|
||||
type BranchCommandResult = 'sent' | 'busy' | 'unavailable';
|
||||
|
||||
export type GitBranchCommandDraft = {
|
||||
text: string;
|
||||
send: (text: string, signal: AbortSignal) => Promise<BranchCommandResult>;
|
||||
};
|
||||
|
||||
export function useComposeGitBranch(sessionId: string) {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const backendId = controller?.localPosixSessionId;
|
||||
const cwd = useSyncExternalStore(
|
||||
@@ -18,6 +26,11 @@ export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
|
||||
);
|
||||
const [result, setResult] = useState<{ controller: TerminalDirectoryController; cwd: string; head: TerminalGitHead | null } | null>(null);
|
||||
|
||||
const scope = useMemo(() => controller && backendId && cwd ? { controller, backendId, cwd, sessionId } : null,
|
||||
[backendId, controller, cwd, sessionId]);
|
||||
const isCurrent = () => scope !== null && getTerminalDirectory(sessionId) === scope.controller
|
||||
&& scope.controller.getConfirmedCwd() === scope.cwd;
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!controller || !backendId || !cwd || !bridge?.readLocalSessionGitHead) return;
|
||||
@@ -63,5 +76,42 @@ export function useComposeGitBranch(sessionId: string): TerminalGitHead | null {
|
||||
};
|
||||
}, [backendId, controller, cwd, sessionId]);
|
||||
|
||||
return result?.controller === controller && result.cwd === cwd ? result.head : null;
|
||||
const head = result?.controller === controller && result.cwd === cwd ? result.head : null;
|
||||
const bridge = netcattyBridge.get();
|
||||
async function sendCommand(command: string | null, signal: AbortSignal): Promise<BranchCommandResult> {
|
||||
if (!command || !scope || !isCurrent()) return 'unavailable';
|
||||
try {
|
||||
await scope.controller.sendLocalCommand(command, scope.cwd, signal);
|
||||
return 'sent';
|
||||
} catch (error) {
|
||||
return error instanceof DirectoryPickerError && error.code === 'busy' ? 'busy' : 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
head,
|
||||
scope,
|
||||
canSwitch: Boolean(bridge?.listLocalSessionGitBranches),
|
||||
async list(worktreeRoot: string) {
|
||||
try {
|
||||
if (scope && isCurrent()) {
|
||||
const next = await bridge?.listLocalSessionGitBranches?.(scope.backendId, scope.cwd, worktreeRoot);
|
||||
if (isCurrent() && next) return next;
|
||||
}
|
||||
} catch { /* The menu displays the unavailable state. */ }
|
||||
return { kind: 'unavailable' } as const;
|
||||
},
|
||||
switchBranch(worktreeRoot: string, name: string, signal: AbortSignal) {
|
||||
return sendCommand(gitSwitchCommand(worktreeRoot, name), signal);
|
||||
},
|
||||
deleteBranchDraft(menuHead: TerminalGitHead, name: string): GitBranchCommandDraft | null {
|
||||
const { worktreeRoot } = menuHead;
|
||||
if (head?.worktreeRoot !== worktreeRoot || (menuHead.kind === 'branch' && menuHead.name === name) || !isCurrent()) return null;
|
||||
const text = gitDeleteBranchCommand(name);
|
||||
return text ? {
|
||||
text,
|
||||
send: (draft, signal) => sendCommand(scopeGitBranchDraft(worktreeRoot, draft), signal),
|
||||
} : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import type { TerminalGitChangesResult } from '../../domain/terminalGitChanges';
|
||||
import { createTerminalDirectoryController } from './terminalDirectoryController';
|
||||
import { observeTerminalDirectory, refreshObservedTerminalDirectory, registerTerminalDirectory } from './terminalDirectoryRegistry';
|
||||
import { terminalCwdStore } from './terminalCwdStore';
|
||||
import { useComposeGitChanges } from './useComposeGitChanges';
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
test('Git Changes never shows a previous worktree result and refreshes only when visible', async t => {
|
||||
let now = 0;
|
||||
t.mock.method(performance, 'now', () => now);
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const advance = (ms: number) => act(async () => {
|
||||
now += ms;
|
||||
t.mock.timers.tick(ms);
|
||||
});
|
||||
const id = 'git-changes-test';
|
||||
const backendId = 'local-pty';
|
||||
const calls: { cwd: string; root: string; refresh: boolean; resolve: (result: TerminalGitChangesResult) => void }[] = [];
|
||||
const doc = Object.assign(new EventTarget(), { visibilityState: 'visible' });
|
||||
const globals = { document: doc, window: { netcatty: {
|
||||
readLocalSessionGitChanges: (_id: string, cwd: string, root: string, refresh: boolean) =>
|
||||
new Promise<TerminalGitChangesResult>(resolve => {
|
||||
assert.equal(_id, backendId);
|
||||
calls.push({ cwd, root, refresh, resolve });
|
||||
}),
|
||||
} } };
|
||||
const previous = Object.keys(globals).map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)] as const);
|
||||
for (const [key, value] of Object.entries(globals)) Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
|
||||
let cwd = '/old/child';
|
||||
const controller = createTerminalDirectoryController({
|
||||
sessionId: id, localPosixSessionId: backendId, isCurrent: () => true, isReady: () => true,
|
||||
io: { cwd: async () => cwd, list: async () => ({ entries: [], home: null }), realpath: async value => value, write() {} },
|
||||
publish: value => terminalCwdStore.setCwd(id, value, 'backend-strict'),
|
||||
});
|
||||
const unregister = registerTerminalDirectory(id, controller);
|
||||
const stopObserving = observeTerminalDirectory(id);
|
||||
const scope = () => ({ sessionId: id, controller, backendId, cwd });
|
||||
let result: ReturnType<typeof useComposeGitChanges>;
|
||||
function Harness(props: { scope: ReturnType<typeof scope>; root?: string }) {
|
||||
result = useComposeGitChanges(props.scope, props.root);
|
||||
return null;
|
||||
}
|
||||
let renderer: ReactTestRenderer;
|
||||
t.after(async () => {
|
||||
await act(async () => renderer?.unmount());
|
||||
stopObserving(); unregister(); terminalCwdStore.setCwd(id, null);
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
});
|
||||
terminalCwdStore.setCwd(id, cwd, 'osc7');
|
||||
const firstScope = scope();
|
||||
await act(async () => { renderer = create(React.createElement(Harness, { scope: firstScope, root: '/old' })); });
|
||||
assert.deepEqual(result!, { kind: 'loading' });
|
||||
await advance(0);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.deepEqual([calls[0].cwd, calls[0].root], ['/old/child', '/old']);
|
||||
|
||||
cwd = '/other';
|
||||
terminalCwdStore.setCwd(id, cwd, 'osc7');
|
||||
const nextScope = scope();
|
||||
await act(async () => renderer.update(React.createElement(Harness, { scope: nextScope, root: '/other' })));
|
||||
assert.deepEqual(result!, { kind: 'loading' });
|
||||
await advance(0);
|
||||
assert.equal(calls.length, 2);
|
||||
assert.equal(calls[1].root, '/other');
|
||||
const clean = { kind: 'summary', files: 0, additions: 0, deletions: 0 } as const;
|
||||
await act(async () => calls[1].resolve(clean));
|
||||
await act(async () => calls[0].resolve({ kind: 'summary', files: 9, additions: 9, deletions: 9 }));
|
||||
assert.deepEqual(result!, clean);
|
||||
|
||||
// External file edits or branch changes have no terminal-output event.
|
||||
await advance(9999);
|
||||
assert.equal(calls.length, 2);
|
||||
await advance(1);
|
||||
assert.equal(calls.length, 3);
|
||||
assert.equal(calls[2].refresh, false);
|
||||
const changed = { kind: 'summary', files: 1, additions: 2, deletions: 1 } as const;
|
||||
await act(async () => calls[2].resolve(changed));
|
||||
assert.deepEqual(result!, changed);
|
||||
|
||||
doc.visibilityState = 'hidden';
|
||||
doc.dispatchEvent(new Event('visibilitychange'));
|
||||
await act(async () => { refreshObservedTerminalDirectory(id); });
|
||||
await advance(10_000);
|
||||
assert.equal(calls.length, 3);
|
||||
doc.visibilityState = 'visible';
|
||||
doc.dispatchEvent(new Event('visibilitychange'));
|
||||
await advance(0);
|
||||
assert.equal(calls.length, 4);
|
||||
assert.equal(calls[3].refresh, true);
|
||||
await act(async () => calls[3].resolve({ kind: 'unavailable' }));
|
||||
assert.deepEqual(result!, { kind: 'unavailable' });
|
||||
await act(async () => { refreshObservedTerminalDirectory(id); });
|
||||
await advance(999);
|
||||
assert.equal(calls.length, 4);
|
||||
await advance(1);
|
||||
assert.equal(calls.length, 5);
|
||||
assert.equal(calls[4].refresh, true);
|
||||
await act(async () => calls[4].resolve(clean));
|
||||
assert.deepEqual(result!, clean);
|
||||
await act(async () => renderer.update(React.createElement(Harness, { scope: nextScope })));
|
||||
assert.equal(result!, null);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { TerminalGitChangesResult } from '../../domain/terminalGitChanges';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { useComposeGitBranch } from './useComposeGitBranch';
|
||||
|
||||
const POLL_MS = 10_000;
|
||||
const REFRESH_DELAY_MS = 150;
|
||||
const MIN_READ_INTERVAL_MS = 1000;
|
||||
const loading = { kind: 'loading' } as const;
|
||||
const unavailable = { kind: 'unavailable' } as const;
|
||||
type Scope = NonNullable<ReturnType<typeof useComposeGitBranch>['scope']>;
|
||||
|
||||
export function useComposeGitChanges(scope: Scope | null, worktreeRoot: string | undefined) {
|
||||
const readChanges = netcattyBridge.get()?.readLocalSessionGitChanges;
|
||||
const [snapshot, setSnapshot] = useState<{
|
||||
scope: Scope;
|
||||
worktreeRoot: string;
|
||||
result: TerminalGitChangesResult;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!scope || !worktreeRoot || !readChanges) return;
|
||||
const { sessionId, controller, backendId, cwd } = scope;
|
||||
const request = (refresh: boolean) => readChanges(backendId, cwd, worktreeRoot, refresh);
|
||||
const publish = (result: TerminalGitChangesResult) => setSnapshot({ scope, worktreeRoot, result });
|
||||
const visibility = typeof document === 'undefined' ? null : document;
|
||||
let active = true;
|
||||
let pending = false;
|
||||
let lastCompletedAt = -Infinity;
|
||||
let refreshAgain = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const isCurrent = () => active && getTerminalDirectory(sessionId) === controller
|
||||
&& controller.getConfirmedCwd() === cwd;
|
||||
const canSchedule = () => isCurrent() && visibility?.visibilityState !== 'hidden';
|
||||
const schedule = (delay: number, refresh = false) => {
|
||||
clearTimeout(timer);
|
||||
if (!canSchedule()) return;
|
||||
if (pending) {
|
||||
refreshAgain = true;
|
||||
return;
|
||||
}
|
||||
const cooldown = MIN_READ_INTERVAL_MS - (performance.now() - lastCompletedAt);
|
||||
timer = setTimeout(() => { void read(refresh); }, Math.max(delay, cooldown));
|
||||
};
|
||||
async function read(refresh: boolean) {
|
||||
if (!canSchedule()) return;
|
||||
pending = true;
|
||||
let result: TerminalGitChangesResult;
|
||||
try {
|
||||
result = await request(refresh);
|
||||
} catch {
|
||||
result = unavailable;
|
||||
}
|
||||
if (isCurrent()) publish(result);
|
||||
pending = false;
|
||||
lastCompletedAt = performance.now();
|
||||
const again = refreshAgain;
|
||||
refreshAgain = false;
|
||||
schedule(again ? REFRESH_DELAY_MS : POLL_MS, again);
|
||||
}
|
||||
|
||||
const onVisibilityChange = () => schedule(0, true);
|
||||
visibility?.addEventListener('visibilitychange', onVisibilityChange);
|
||||
const unsubscribe = subscribeTerminalDirectoryRefresh(sessionId, () => schedule(REFRESH_DELAY_MS, true));
|
||||
schedule(0);
|
||||
return () => {
|
||||
active = false;
|
||||
clearTimeout(timer);
|
||||
visibility?.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [scope, worktreeRoot, readChanges]);
|
||||
|
||||
if (!scope || !worktreeRoot || !readChanges) return null;
|
||||
return snapshot?.scope === scope && snapshot.worktreeRoot === worktreeRoot ? snapshot.result : loading;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { GitBranchCommandDraft } from './useComposeGitBranch';
|
||||
|
||||
type DraftStatus = 'ready' | 'sending' | 'busy' | 'unavailable' | 'singleLine';
|
||||
|
||||
type DraftSnapshot = {
|
||||
text: string;
|
||||
selectionStart: number;
|
||||
selectionEnd: number;
|
||||
};
|
||||
|
||||
export function useGitBranchDraft(sessionId: string, restore: (snapshot: DraftSnapshot) => void) {
|
||||
const staged = useRef<{ draft: GitBranchCommandDraft; previous: DraftSnapshot; request?: AbortController } | null>(null);
|
||||
const [status, setStatus] = useState<DraftStatus | null>(null);
|
||||
const getDraft = useCallback(() => staged.current?.draft ?? null, []);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
const current = staged.current;
|
||||
if (!current) return;
|
||||
staged.current = null;
|
||||
current.request?.abort();
|
||||
restore(current.previous);
|
||||
}, [restore]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setStatus(null);
|
||||
return clear;
|
||||
}, [sessionId, clear]);
|
||||
|
||||
const stage = useCallback((draft: GitBranchCommandDraft, previous: DraftSnapshot) => {
|
||||
if (staged.current) return false;
|
||||
staged.current = { draft, previous };
|
||||
setStatus('ready');
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
clear();
|
||||
setStatus(null);
|
||||
}, [clear]);
|
||||
|
||||
const send = useCallback(async (text: string) => {
|
||||
const current = staged.current;
|
||||
if (!current || current.request || !text.trim()) return;
|
||||
// The command goes directly to the shell prompt, followed by Enter.
|
||||
if (Array.from(text).some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
|
||||
setStatus('singleLine');
|
||||
return;
|
||||
}
|
||||
const request = new AbortController();
|
||||
current.request = request;
|
||||
setStatus('sending');
|
||||
const result = await current.draft.send(text, request.signal);
|
||||
if (staged.current !== current || request.signal.aborted) return;
|
||||
current.request = undefined;
|
||||
if (result === 'sent') cancel();
|
||||
else setStatus(result);
|
||||
}, [cancel]);
|
||||
|
||||
return { status, getDraft, stage, cancel, send };
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { useAppLockChrome } from './appRuntimeBridge';
|
||||
import { resolvePluginViewWindowScope } from './pluginViewScopes';
|
||||
import { pluginViewSessions, type PluginViewSnapshot } from './pluginViewSession';
|
||||
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
@@ -7,15 +8,17 @@ import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
|
||||
const initial = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
|
||||
export function useHostDrawnPluginView({ viewId, version, slot, active, context, subscribeHidden, unavailable }: {
|
||||
viewId: string; version: string; slot: string; active: boolean; context: Record<string, unknown>;
|
||||
subscribeHidden(listener: () => void): () => void; unavailable(): void;
|
||||
subscribeHidden(listener: (hidden?: boolean) => void): () => void; unavailable(): void;
|
||||
}) {
|
||||
const { locked } = useAppLockChrome();
|
||||
const effectiveActive = active && !locked;
|
||||
const contextKey = JSON.stringify(context);
|
||||
const key = JSON.stringify([viewId, version, slot, contextKey]);
|
||||
const scopeId = typeof window !== 'undefined'
|
||||
? resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` })
|
||||
: '';
|
||||
const sessionKey = scopeId ? JSON.stringify([scopeId, key]) : '';
|
||||
const cachedSession = active && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const cachedSession = effectiveActive && sessionKey ? pluginViewSessions.peek(sessionKey) : null;
|
||||
const [state, setState] = useState<{
|
||||
key: string;
|
||||
snapshot: PluginViewSnapshot;
|
||||
@@ -29,7 +32,7 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const unavailableRef = useRef(unavailable); unavailableRef.current = unavailable;
|
||||
const sessionRef = useRef<{ key: string; image(path: string): Promise<string>; send(event: HostDrawnViewEvent): void } | null>(null);
|
||||
useEffect(() => {
|
||||
if (!active) {
|
||||
if (!effectiveActive) {
|
||||
setHidden(false);
|
||||
return;
|
||||
}
|
||||
@@ -38,22 +41,31 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
const resolvedScopeId = resolvePluginViewWindowScope({ pathname: window.location.pathname, search: window.location.search, hash: `${window.location.hash}|plugin-slot:${slot}` });
|
||||
try {
|
||||
const session = pluginViewSessions.acquire(JSON.stringify([resolvedScopeId, key]), bridge, { viewId, scopeId: resolvedScopeId, context: JSON.parse(contextKey) });
|
||||
sessionRef.current = { key, send: session.send, image: session.image };
|
||||
const activeHandle = { key, send: session.send, image: session.image };
|
||||
sessionRef.current = activeHandle;
|
||||
const update = () => {
|
||||
const snapshot = session.getSnapshot();
|
||||
if (snapshot.error) sessionRef.current = null;
|
||||
setState({ key, snapshot, image: session.image });
|
||||
};
|
||||
const stop = session.subscribe(update); update(); setHidden(false);
|
||||
const stopHidden = subscribeHidden(() => { sessionRef.current = null; setHidden(true); });
|
||||
const stopHidden = subscribeHidden((nextHidden = true) => {
|
||||
if (nextHidden) {
|
||||
sessionRef.current = null;
|
||||
setHidden(true);
|
||||
} else {
|
||||
if (!session.getSnapshot().error) sessionRef.current = activeHandle;
|
||||
setHidden(false);
|
||||
}
|
||||
});
|
||||
return () => { sessionRef.current = null; stopHidden(); stop(); session.release(); };
|
||||
} catch { unavailableRef.current(); }
|
||||
}, [active, contextKey, key, slot, subscribeHidden, viewId]);
|
||||
}, [effectiveActive, contextKey, key, slot, subscribeHidden, viewId]);
|
||||
const fallbackLoadImage = useCallback((path: string) => {
|
||||
const session = sessionRef.current;
|
||||
return active && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [active, key]);
|
||||
const hasCurrentState = active
|
||||
return effectiveActive && session?.key === key ? session.image(path) : Promise.reject(new Error('Plugin view unavailable'));
|
||||
}, [effectiveActive, key]);
|
||||
const hasCurrentState = effectiveActive
|
||||
&& state.key === key
|
||||
&& (cachedSession !== null ? state.image === cachedSession.image : state.snapshot.error);
|
||||
const resolvedSnapshot = hasCurrentState
|
||||
@@ -65,9 +77,9 @@ export function useHostDrawnPluginView({ viewId, version, slot, active, context,
|
||||
? state.image
|
||||
: (cachedSession?.image ?? fallbackLoadImage);
|
||||
const sendEvent = useCallback((event: HostDrawnViewEvent) => {
|
||||
const session = sessionRef.current; if (active && session?.key === key) session.send(event);
|
||||
}, [active, key]);
|
||||
const session = sessionRef.current; if (effectiveActive && session?.key === key) session.send(event);
|
||||
}, [effectiveActive, key]);
|
||||
// A newly selected plugin must never receive values from the previous tree,
|
||||
// even during the render before effect cleanup and the next activation.
|
||||
return { ...resolvedSnapshot, visible: active && !hidden, loadImage, sendEvent };
|
||||
return { ...resolvedSnapshot, visible: effectiveActive && !hidden, loadImage, sendEvent };
|
||||
}
|
||||
@@ -73,15 +73,31 @@ export function usePluginHostActions() {
|
||||
if (entry.prompt.request.kind === 'vault.requestHostDraft' && vault.managedSources !== entry.managedSources) throw new Error('Managed sources changed during draft review');
|
||||
}, [getVault]);
|
||||
|
||||
const clearReview = useCallback((entry: Review) => {
|
||||
if (current.current !== entry) return;
|
||||
current.current = null;
|
||||
responding.current = false;
|
||||
setReview(null);
|
||||
setRemember(false);
|
||||
setBusy(false);
|
||||
setError(false);
|
||||
}, []);
|
||||
|
||||
const fail = useCallback(async (entry: Review) => {
|
||||
if (current.current !== entry) return;
|
||||
setError(true);
|
||||
try {
|
||||
await netcattyBridge.get()?.respondPluginInteraction?.({
|
||||
const accepted = await netcattyBridge.get()?.respondPluginInteraction?.({
|
||||
requestId: entry.prompt.requestId, actionToken: entry.completionToken ?? entry.prompt.actionToken, action: 'fail',
|
||||
});
|
||||
} catch { /* A stopped runtime or closed window already invalidates it. */ }
|
||||
}, []);
|
||||
if (accepted === false) {
|
||||
clearReview(entry);
|
||||
}
|
||||
} catch {
|
||||
// A stopped runtime, closed window, or already-settled prompt will never send { closed: true }.
|
||||
clearReview(entry);
|
||||
}
|
||||
}, [clearReview]);
|
||||
|
||||
const execute = useCallback(async (entry: Review) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
@@ -140,7 +156,8 @@ export function usePluginHostActions() {
|
||||
entry.claimed = true;
|
||||
assertCurrent(entry);
|
||||
await openHostSession(entry.host);
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
if (completed === false) clearReview(entry);
|
||||
return;
|
||||
}
|
||||
let action: PluginHostAction;
|
||||
@@ -161,9 +178,16 @@ export function usePluginHostActions() {
|
||||
},
|
||||
connect: openHostSession,
|
||||
});
|
||||
await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
const completed = await bridge.respondPluginInteraction({ requestId: entry.prompt.requestId, actionToken: entry.completionToken!, action: 'complete' });
|
||||
if (completed === false) clearReview(entry);
|
||||
} catch { await fail(entry); }
|
||||
}, [assertCurrent, fail, getVault]);
|
||||
finally {
|
||||
if (current.current === entry) {
|
||||
responding.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}, [assertCurrent, clearReview, fail, getVault]);
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = netcattyBridge.get();
|
||||
@@ -282,7 +306,7 @@ export function usePluginHostActions() {
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
responding.current = true; setBusy(true); setError(false);
|
||||
try {
|
||||
assertCurrent(entry);
|
||||
if (action !== 'cancel') assertCurrent(entry);
|
||||
const request = entry.prompt.request;
|
||||
const selected = request.kind === 'vault.selectHosts' && action === 'submit' ? selectedIds.map((id) => {
|
||||
const revision = entry.candidateRevisions.get(id);
|
||||
@@ -296,18 +320,24 @@ export function usePluginHostActions() {
|
||||
|| request.kind === 'network.stream.tlsConfirm'
|
||||
);
|
||||
const effectiveRemember = rememberOverride ?? remember;
|
||||
await netcattyBridge.require().respondPluginInteraction?.({
|
||||
const accepted = await netcattyBridge.require().respondPluginInteraction?.({
|
||||
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
|
||||
...(selected === undefined ? {} : { resources: selected }),
|
||||
...(draft === undefined ? {} : { draft }),
|
||||
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
|
||||
...(includeRemember && effectiveRemember ? { remember: true } : {}),
|
||||
});
|
||||
} catch { await fail(entry); }
|
||||
if (accepted === false) {
|
||||
clearReview(entry);
|
||||
}
|
||||
} catch {
|
||||
if (action === 'cancel') clearReview(entry);
|
||||
else await fail(entry);
|
||||
}
|
||||
finally {
|
||||
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
|
||||
}
|
||||
}, [assertCurrent, fail, remember, selectedIds]);
|
||||
}, [assertCurrent, clearReview, fail, remember, selectedIds]);
|
||||
|
||||
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function usePluginHostInteractions() {
|
||||
if (current.current?.requestId !== event.requestId) return;
|
||||
current.current = null; setPrompt(null);
|
||||
} else {
|
||||
if (event.request.kind.startsWith('vault.') || event.request.kind === 'network.stream.connectViaHost') return;
|
||||
if (event.request.kind.startsWith('vault.') || event.request.kind.startsWith('network.stream.')) return;
|
||||
current.current = event as UiPrompt;
|
||||
if (event.request.kind === 'terminal.selection.read' && event.phase === 'request') {
|
||||
setPrompt(null);
|
||||
|
||||
@@ -68,9 +68,15 @@ export function usePluginManager() {
|
||||
if (!bridge.uninstallPlugin) throw new Error('Plugin management unavailable');
|
||||
const source = clearSource ? await bridge.getPluginSourceBinding?.(id) : null;
|
||||
await bridge.uninstallPlugin(id);
|
||||
if (clearSource && source) {
|
||||
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
|
||||
await bridge.resetPluginSource(id, source.id);
|
||||
try {
|
||||
if (clearSource && source) {
|
||||
if (!bridge.resetPluginSource) throw new Error('Private source reset unavailable');
|
||||
await bridge.resetPluginSource(id, source.id);
|
||||
}
|
||||
} finally {
|
||||
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function') {
|
||||
window.dispatchEvent(new Event('netcatty:plugin-packages-changed'));
|
||||
}
|
||||
}
|
||||
}, true),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { activeTabStore, useIsVaultActive } from './activeTabStore';
|
||||
import { collectPluginVaultPages, PLUGIN_VAULT_PAGE_PREFIX, resolvePluginVaultPage } from './pluginVaultPages';
|
||||
import { usePluginContributions } from './usePluginContributions';
|
||||
@@ -6,6 +7,18 @@ import { OPEN_PLUGIN_VIEW_EVENT, type OpenPluginViewDetail } from './usePluginVi
|
||||
|
||||
const CONTEXT = Object.freeze({ 'netcatty.surface': 'vault-page' });
|
||||
|
||||
function areStringArraysEqual(
|
||||
left: readonly string[] | undefined,
|
||||
right: readonly string[] | undefined,
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (!left || !right || left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
if (left[i] !== right[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function usePluginVaultPages({ locale, section, select }: {
|
||||
locale: string;
|
||||
section: string;
|
||||
@@ -18,6 +31,41 @@ export function usePluginVaultPages({ locale, section, select }: {
|
||||
useEffect(() => () => { if (focusFrame.current !== null) cancelAnimationFrame(focusFrame.current); }, []);
|
||||
const contributions = usePluginContributions({ locale, context: CONTEXT });
|
||||
const pages = useMemo(() => collectPluginVaultPages(contributions.snapshot.plugins), [contributions.snapshot.plugins]);
|
||||
const [installedPluginIds, setInstalledPluginIds] = useState<readonly string[] | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
const bridge = typeof window === 'undefined' ? undefined : netcattyBridge.get();
|
||||
if (!contributions.available || !bridge?.listPlugins) {
|
||||
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
let generation = 0;
|
||||
const loadInstalled = () => {
|
||||
const requestId = ++generation;
|
||||
void bridge.listPlugins!()
|
||||
.then((plugins) => {
|
||||
if (cancelled || requestId !== generation) return;
|
||||
const next = Array.from(
|
||||
new Set(
|
||||
plugins
|
||||
.map((plugin) => plugin.id)
|
||||
.filter((id): id is string => typeof id === 'string' && id.length > 0),
|
||||
),
|
||||
).sort();
|
||||
setInstalledPluginIds((current) => (areStringArraysEqual(current, next) ? current : next));
|
||||
})
|
||||
.catch(() => {
|
||||
if (cancelled || requestId !== generation) return;
|
||||
setInstalledPluginIds((current) => (current === undefined ? current : undefined));
|
||||
});
|
||||
};
|
||||
loadInstalled();
|
||||
window.addEventListener('netcatty:plugin-packages-changed', loadInstalled);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.removeEventListener('netcatty:plugin-packages-changed', loadInstalled);
|
||||
};
|
||||
}, [contributions.available, contributions.snapshot]);
|
||||
const selected = resolvePluginVaultPage(pages, section);
|
||||
const fallback = useCallback(() => {
|
||||
select('hosts');
|
||||
@@ -43,5 +91,5 @@ export function usePluginVaultPages({ locale, section, select }: {
|
||||
window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
|
||||
return () => window.removeEventListener(OPEN_PLUGIN_VIEW_EVENT, open);
|
||||
}, [pages, select]);
|
||||
return { pages, selected, active, select, fallback, contributions, context: CONTEXT };
|
||||
return { pages, selected, active, select, fallback, contributions, installedPluginIds, context: CONTEXT };
|
||||
}
|
||||
@@ -149,7 +149,12 @@ export function usePluginViewLifecycle({
|
||||
}, [contributions.loading, contributions.snapshot.plugins]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!requested || activeView?.view.location !== 'tab') return;
|
||||
if (!requested || viewContributions.loading) return;
|
||||
if (!resolvedActiveView) {
|
||||
setRequested(null);
|
||||
return;
|
||||
}
|
||||
if (activeView?.view.location !== 'tab') return;
|
||||
pluginViewTabStore.open({
|
||||
pluginId: activeView.plugin.id,
|
||||
pluginName: activeView.plugin.displayName,
|
||||
@@ -159,7 +164,7 @@ export function usePluginViewLifecycle({
|
||||
context: requested.context,
|
||||
});
|
||||
setRequested(null);
|
||||
}, [activeView, requested]);
|
||||
}, [activeView, requested, resolvedActiveView, viewContributions.loading]);
|
||||
|
||||
useEffect(() => {
|
||||
const stop = pluginViewTabStore.onDidClose(({ tab }) => closePluginViewSessionIfLoaded(tab.viewId));
|
||||
|
||||
@@ -57,6 +57,40 @@ async function mountSessionState(t: test.TestContext) {
|
||||
return () => latestState;
|
||||
}
|
||||
|
||||
test('converting a standalone tab keeps the live session, tab position and focus', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
let first = '';
|
||||
let target = '';
|
||||
let last = '';
|
||||
await act(async () => {
|
||||
first = getState().createLocalTerminal();
|
||||
target = getState().createLocalTerminal({ shellName: 'Build shell' });
|
||||
last = getState().createLocalTerminal();
|
||||
});
|
||||
await act(async () => { getState().updateSessionStatus(target, 'connected'); });
|
||||
const before = getState().sessions;
|
||||
await act(async () => {
|
||||
getState().convertSessionToWorkspace(target);
|
||||
getState().convertSessionToWorkspace(target);
|
||||
});
|
||||
assert.equal(getState().workspaces.length, 1);
|
||||
const [workspace] = getState().workspaces;
|
||||
assert.equal(workspace.root.type, 'pane');
|
||||
assert.equal(workspace.root.sessionId, target);
|
||||
assert.equal(workspace.focusedSessionId, target);
|
||||
assert.deepEqual(getState().sessions, before.map(session =>
|
||||
session.id === target ? { ...session, workspaceId: workspace.id } : session));
|
||||
assert.deepEqual(getState().orderedTabs, [first, workspace.id, last]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
|
||||
|
||||
// A reordered editor tab must keep its place alongside terminal tabs.
|
||||
const editor = 'editor:test';
|
||||
await act(async () => { getState().reorderTabs(editor, last, 'before', [editor]); });
|
||||
await act(async () => { getState().convertSessionToWorkspace(last); });
|
||||
const secondWorkspace = getState().workspaces[1];
|
||||
assert.deepEqual(getState().getOrderedWorkTabs([editor]), [first, workspace.id, editor, secondWorkspace.id]);
|
||||
});
|
||||
|
||||
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
|
||||
@@ -766,13 +766,14 @@ export const useSessionState = ({
|
||||
const preferredTabId = activeTabStore.getPreviousActiveTabId();
|
||||
const tabOrderSnapshot = tabOrderRef.current;
|
||||
const sessionsSnapshot = sessionsRef.current;
|
||||
// Queue removal outside the workspace updater so React retains it when
|
||||
// lower-priority session updates are rebased after this close.
|
||||
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
|
||||
setTabOrder(prevTabOrder => prevTabOrder.filter(id => id !== workspaceId));
|
||||
setWorkspaces(prevWorkspaces => {
|
||||
const remainingWorkspaces = prevWorkspaces.filter(w => w.id !== workspaceId);
|
||||
const remainingSessions = sessionsSnapshot.filter(s => s.workspaceId !== workspaceId);
|
||||
|
||||
setSessions(prevSessions => prevSessions.filter(s => s.workspaceId !== workspaceId));
|
||||
|
||||
const nextActiveTabId = resolveActiveTabAfterCloseWorkspace({
|
||||
currentActiveTabId: activeTabStore.getActiveTabId(),
|
||||
closedWorkspaceId: workspaceId,
|
||||
@@ -1502,6 +1503,30 @@ export const useSessionState = ({
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const convertSessionToWorkspace = useCallback((sessionId: string) => {
|
||||
const standaloneIds = orphanSessionsRef.current.map(session => session.id);
|
||||
const workspace = createWorkspaceFromSessionIds([sessionId], {
|
||||
title: DEFAULT_WORKSPACE_TITLE,
|
||||
autoTitle: true,
|
||||
viewMode: 'focus',
|
||||
});
|
||||
|
||||
setSessions(prev => {
|
||||
const source = prev.find(session => session.id === sessionId);
|
||||
if (!source || source.workspaceId || source.hiddenFromTabs) return prev;
|
||||
|
||||
setWorkspaces(current => addWorkspaceIfMissing(current, workspace));
|
||||
setTabOrder(current => {
|
||||
if (current.includes(workspace.id)) return current;
|
||||
// Unreordered terminal tabs may only have an implicit position.
|
||||
const order = current.includes(sessionId) ? current : [...new Set([...current, ...standaloneIds])];
|
||||
return order.map(id => id === sessionId ? workspace.id : id);
|
||||
});
|
||||
setActiveTabId(workspace.id);
|
||||
return prev.map(session => session === source ? { ...session, workspaceId: workspace.id } : session);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Copy a session - creates a new session with the same host connection
|
||||
const copySession = useCallback((sessionId: string, options?: {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
@@ -1793,6 +1818,7 @@ export const useSessionState = ({
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
removeSessionFromWorkspace,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { useEffect } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import { useSessionState } from './useSessionState';
|
||||
import type { Host } from '../../domain/models';
|
||||
|
||||
const settle = (ms = 20) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
|
||||
test('workspace Close does not restore removed panes when a queued session update is rebased', async () => {
|
||||
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const [key, value] of Object.entries({
|
||||
window: dom.window, document: dom.window.document,
|
||||
localStorage: dom.window.localStorage, CustomEvent: dom.window.CustomEvent,
|
||||
Event: dom.window.Event,
|
||||
})) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, value });
|
||||
}
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
let state!: ReturnType<typeof useSessionState>;
|
||||
let closingId = '';
|
||||
const mounts = new Map<string, number>();
|
||||
function Pane({ id }: { id: string }) {
|
||||
useEffect(() => { mounts.set(id, (mounts.get(id) ?? 0) + 1); }, [id]);
|
||||
return null;
|
||||
}
|
||||
function Probe() {
|
||||
state = useSessionState({ persistSessionRestore: false });
|
||||
return <>
|
||||
<button onClick={() => state.closeWorkspace(closingId)}>Close</button>
|
||||
{state.sessions.map(s => <Pane key={s.id} id={s.id} />)}
|
||||
</>;
|
||||
}
|
||||
async function connect(name: string, count: number) {
|
||||
const hosts = Array.from({ length: count }, (_, i) => ({
|
||||
id: `${name}-${i}`, label: `${name}-${i}`, hostname: 'host.test',
|
||||
username: 'alice', protocol: 'ssh',
|
||||
} as Host));
|
||||
flushSync(() => state.createWorkspaceWithHosts(name, hosts));
|
||||
await settle();
|
||||
const workspace = state.workspaces.at(-1)!;
|
||||
flushSync(() => {
|
||||
for (const s of state.sessions.filter(s => s.workspaceId === workspace.id)) {
|
||||
state.updateSessionStatus(s.id, 'connected');
|
||||
}
|
||||
});
|
||||
await settle();
|
||||
return workspace;
|
||||
}
|
||||
async function close(id: string, queueCwd = false) {
|
||||
closingId = id;
|
||||
// A cwd observation without pendingInitialCwd queues a no-op update at
|
||||
// default priority. The discrete Close runs first; React later rebases
|
||||
// that queue. Wrapping this preparation in act would hide the schedule.
|
||||
const session = state.sessions.find(s => s.workspaceId === id)!;
|
||||
if (queueCwd) state.updateSessionRestoreCwd(session.id, '/home/alice');
|
||||
document.querySelector('button')!.click();
|
||||
await settle(100);
|
||||
assert(!state.workspaces.some(w => w.id === id));
|
||||
assert(!state.sessions.some(s => s.workspaceId === id), 'closed workspace sessions must stay removed after queued updates settle');
|
||||
}
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
flushSync(() => root.render(<Probe />));
|
||||
const left = await connect('left', 2);
|
||||
const target = await connect('target', 6);
|
||||
const targetIds = state.sessions.filter(s => s.workspaceId === target.id).map(s => s.id);
|
||||
// Keep the target mounted while other connected workspaces are used.
|
||||
for (let i = 0; i < 3; i++) await close((await connect(`warm-${i}`, 2)).id);
|
||||
const right = await connect('right', 2);
|
||||
await close(right.id);
|
||||
await close(left.id);
|
||||
assert.deepEqual(state.sessions.map(s => s.id), targetIds);
|
||||
assert(state.sessions.every(s => s.status === 'connected'));
|
||||
assert.equal(activeTabStore.getActiveTabId(), target.id);
|
||||
await close(target.id, true);
|
||||
assert.equal(state.sessions.length, 0);
|
||||
assert.equal(state.workspaces.length, 0);
|
||||
assert.equal(activeTabStore.getActiveTabId(), 'vault');
|
||||
assert([...mounts.values()].every(count => count === 1), 'Close must not remount any closed pane');
|
||||
} finally {
|
||||
flushSync(() => root.unmount());
|
||||
activeTabStore.setActiveTabId('vault', { recordPrevious: false });
|
||||
await settle();
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -99,14 +99,17 @@ import {
|
||||
} from '../../infrastructure/config/storageKeys';
|
||||
import { resolveDefaultUiLocale, resolveSupportedLocale } from '../../infrastructure/config/i18n';
|
||||
import {
|
||||
addCustomKeyBindingExtra,
|
||||
areCustomKeyBindingsEqual,
|
||||
nextCustomKeyBindingsSyncVersion,
|
||||
parseCustomKeyBindingsStorageRecord,
|
||||
removeCustomKeyBindingExtra,
|
||||
resetCustomKeyBinding,
|
||||
resolveKeyBindings,
|
||||
serializeCustomKeyBindingsStorageRecord,
|
||||
shouldApplyIncomingCustomKeyBindingsRecord,
|
||||
updateCustomKeyBinding as updateCustomKeyBindingRecord,
|
||||
updateCustomKeyBindingExtra,
|
||||
} from '../../domain/customKeyBindings';
|
||||
import { resolveGlobalTerminalAppearance, idleThemeUserIntent } from '../../domain/terminalAppearanceRuntime';
|
||||
import { DEFAULT_FONT_SIZE, TERMINAL_FONT_AUTO } from '../../infrastructure/config/fonts';
|
||||
@@ -2131,6 +2134,21 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
setCustomKeyBindings(prev => resetCustomKeyBinding(prev, bindingId, scheme));
|
||||
}, [setCustomKeyBindings]);
|
||||
|
||||
// Add a secondary chord that triggers the same action as the default binding
|
||||
const addKeyBindingExtra = useCallback((bindingId: string, scheme: 'mac' | 'pc', newKey: string) => {
|
||||
setCustomKeyBindings(prev => addCustomKeyBindingExtra(prev, bindingId, scheme, newKey));
|
||||
}, [setCustomKeyBindings]);
|
||||
|
||||
// Re-record an existing secondary chord
|
||||
const updateKeyBindingExtra = useCallback((bindingId: string, index: number, scheme: 'mac' | 'pc', newKey: string) => {
|
||||
setCustomKeyBindings(prev => updateCustomKeyBindingExtra(prev, bindingId, index, scheme, newKey));
|
||||
}, [setCustomKeyBindings]);
|
||||
|
||||
// Remove a secondary chord
|
||||
const removeKeyBindingExtra = useCallback((bindingId: string, index: number) => {
|
||||
setCustomKeyBindings(prev => removeCustomKeyBindingExtra(prev, bindingId, index));
|
||||
}, [setCustomKeyBindings]);
|
||||
|
||||
// Reset all key bindings to defaults
|
||||
const resetAllKeyBindings = useCallback(() => {
|
||||
setCustomKeyBindings({});
|
||||
@@ -2370,6 +2388,9 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
|
||||
keyBindings,
|
||||
customKeyBindings,
|
||||
updateKeyBinding,
|
||||
updateKeyBindingExtra,
|
||||
addKeyBindingExtra,
|
||||
removeKeyBindingExtra,
|
||||
resetKeyBinding,
|
||||
resetAllKeyBindings,
|
||||
isHotkeyRecording,
|
||||
|
||||
@@ -6,6 +6,8 @@ const DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.main' as const;
|
||||
const MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.main' as const;
|
||||
const OFFICIAL_DB_PLUGIN = 'plugin-vault:com.binaricat.netcatty-database.workbench' as const;
|
||||
const OFFICIAL_MONITOR_PLUGIN = 'plugin-vault:com.binaricat.netcatty-monitor.workbench' as const;
|
||||
const DB_PLUGIN_ID = 'com.binaricat.netcatty-database';
|
||||
const MONITOR_PLUGIN_ID = 'com.binaricat.netcatty-monitor';
|
||||
|
||||
test('useVaultNavConfig persists order & visibility, survives cold-start loading, prunes uninstalled plugins, and resets cleanly', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
@@ -31,11 +33,17 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof DB_PLUGIN | typeof MONITOR_PLUGIN)[] = [DB_PLUGIN, MONITOR_PLUGIN];
|
||||
let installedPluginIds: string[] | undefined = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({ activePluginIds, pluginsLoading, pluginsAvailable });
|
||||
model = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading,
|
||||
pluginsAvailable,
|
||||
installedPluginIds,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
@@ -85,6 +93,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
});
|
||||
const coldRoot = createRoot(document.getElementById('root')!);
|
||||
activePluginIds = [];
|
||||
installedPluginIds = undefined;
|
||||
pluginsLoading = true;
|
||||
pluginsAvailable = false;
|
||||
await act(async () => {
|
||||
@@ -96,6 +105,7 @@ test('useVaultNavConfig persists order & visibility, survives cold-start loading
|
||||
|
||||
// Plugins finish loading, but DB_PLUGIN was uninstalled.
|
||||
activePluginIds = [MONITOR_PLUGIN];
|
||||
installedPluginIds = [MONITOR_PLUGIN_ID];
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await act(async () => {
|
||||
@@ -249,3 +259,334 @@ test('useVaultNavConfig preserves saved plugin order when settled with pluginsAv
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('useVaultNavConfig preserves custom plugin order across in-place plugin update gap and prunes only after uninstall', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: true,
|
||||
});
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let model!: ReturnType<typeof useVaultNavConfig>;
|
||||
let activePluginIds: (typeof OFFICIAL_DB_PLUGIN | typeof OFFICIAL_MONITOR_PLUGIN)[] = [
|
||||
OFFICIAL_DB_PLUGIN,
|
||||
OFFICIAL_MONITOR_PLUGIN,
|
||||
];
|
||||
let installedPluginIds: string[] = [DB_PLUGIN_ID, MONITOR_PLUGIN_ID];
|
||||
let pluginOwnerByNavId: Record<string, string> = {
|
||||
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
|
||||
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
|
||||
};
|
||||
let pluginsLoading = false;
|
||||
let pluginsAvailable = true;
|
||||
|
||||
function Fixture() {
|
||||
model = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading,
|
||||
pluginsAvailable,
|
||||
installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const render = async () => {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await render();
|
||||
|
||||
await act(async () => {
|
||||
model.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
|
||||
model.setVisible('logs', false);
|
||||
});
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Mid-update gap: beforeActivate disables the plugin while it remains installed.
|
||||
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
|
||||
pluginsLoading = false;
|
||||
pluginsAvailable = true;
|
||||
await render();
|
||||
|
||||
assert.equal(model.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
const persistedDuringGap = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedDuringGap.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.deepEqual(persistedDuringGap.hidden, ['logs']);
|
||||
|
||||
// Updated version re-enables and returns the same workbench nav key.
|
||||
activePluginIds = [OFFICIAL_DB_PLUGIN, OFFICIAL_MONITOR_PLUGIN];
|
||||
pluginOwnerByNavId = {
|
||||
[OFFICIAL_DB_PLUGIN]: DB_PLUGIN_ID,
|
||||
[OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID,
|
||||
};
|
||||
await render();
|
||||
|
||||
assert.equal(model.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(model.isHidden('logs'), true);
|
||||
const persistedAfterUpdate = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUpdate.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// True uninstall removes the plugin from installedPluginIds and prunes its nav slot.
|
||||
activePluginIds = [OFFICIAL_MONITOR_PLUGIN];
|
||||
installedPluginIds = [MONITOR_PLUGIN_ID];
|
||||
pluginOwnerByNavId = { [OFFICIAL_MONITOR_PLUGIN]: MONITOR_PLUGIN_ID };
|
||||
await render();
|
||||
|
||||
assert.equal(model.config.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
const persistedAfterUninstall = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.deepEqual(persistedAfterUninstall.hidden, ['logs']);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('usePluginVaultPages + useVaultNavConfig preserve custom order across simulated 0.3.5 -> 0.3.6 update', async () => {
|
||||
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost' });
|
||||
const previous = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'localStorage', 'StorageEvent', 'CustomEvent', 'Event']) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window],
|
||||
});
|
||||
}
|
||||
for (const [key, value] of Object.entries({
|
||||
requestAnimationFrame: (cb: FrameRequestCallback) => setTimeout(() => cb(Date.now()), 0),
|
||||
cancelAnimationFrame: (id: number) => clearTimeout(id),
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
|
||||
const dbEntry = (version: string) => ({
|
||||
id: DB_PLUGIN_ID,
|
||||
version,
|
||||
displayName: 'Database',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: `${DB_PLUGIN_ID}.workbench`, title: 'Database', location: 'vault-page', visible: true },
|
||||
],
|
||||
});
|
||||
const monitorEntry = {
|
||||
id: MONITOR_PLUGIN_ID,
|
||||
version: '1.0.0',
|
||||
displayName: 'Monitor',
|
||||
commands: [],
|
||||
keybindings: [],
|
||||
menus: [],
|
||||
settings: [],
|
||||
views: [
|
||||
{ id: `${MONITOR_PLUGIN_ID}.workbench`, title: 'Monitor', location: 'vault-page', visible: true },
|
||||
],
|
||||
};
|
||||
|
||||
let snapshot = { locale: 'en', plugins: [dbEntry('0.3.5'), monitorEntry] };
|
||||
let installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.5' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
Object.assign(dom.window, {
|
||||
netcatty: {
|
||||
async getPluginRuntimeStatus() { return { available: true }; },
|
||||
async getPluginContributions() { return { ...snapshot, plugins: [...snapshot.plugins] }; },
|
||||
async listPlugins() { return [...installed]; },
|
||||
onPluginContributionsChanged(cb: () => void) {
|
||||
listeners.add(cb);
|
||||
return () => { listeners.delete(cb); };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { default: React, act, useMemo, useState } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { usePluginVaultPages } = await import('./usePluginVaultPages');
|
||||
const { useVaultNavConfig } = await import('./useVaultNavConfig');
|
||||
const { STORAGE_KEY_VAULT_NAV_CONFIG } = await import('../../infrastructure/config/storageKeys');
|
||||
|
||||
let nav!: ReturnType<typeof useVaultNavConfig>;
|
||||
|
||||
function Fixture() {
|
||||
const [section, setSection] = useState<'hosts' | `plugin-vault:${string}`>('hosts');
|
||||
const pluginVault = usePluginVaultPages({ locale: 'en', section, select: setSection });
|
||||
const activePluginIds = useMemo(
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const pluginOwnerByNavId = useMemo(
|
||||
() => Object.fromEntries(pluginVault.pages.map((page) => [page.key, page.pluginId])),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
nav = useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
installedPluginIds: pluginVault.installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
return <div />;
|
||||
}
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 25));
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<Fixture />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
await settle();
|
||||
});
|
||||
assert.ok(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN));
|
||||
assert.ok(nav.visibleIds.includes(OFFICIAL_MONITOR_PLUGIN));
|
||||
|
||||
await act(async () => {
|
||||
nav.reorder(OFFICIAL_DB_PLUGIN, 'hosts', 'after');
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// beforeActivate disables Database 0.3.5 (still installed) and emits contributions-changed.
|
||||
snapshot = { locale: 'en', plugins: [monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.5' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
|
||||
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
const persistedMidUpdate = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedMidUpdate.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Database 0.3.6 activates and emits contributions-changed.
|
||||
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
|
||||
assert.equal(nav.visibleIds[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
|
||||
// Hide Database, then simulate uninstall where plugin-disabled arrives before package removal
|
||||
// followed by post-uninstall contributions-changed once listPlugins no longer contains it.
|
||||
await act(async () => {
|
||||
nav.setVisible(OFFICIAL_DB_PLUGIN, false);
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
snapshot = { locale: 'en', plugins: [monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: false, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.config.order[1], OFFICIAL_DB_PLUGIN);
|
||||
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
|
||||
// Post-uninstall refresh (from onPluginUninstalled) sees DB removed and prunes slot + hidden flag.
|
||||
installed = [
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.config.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(nav.config.hidden.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
const persistedAfterUninstall = JSON.parse(
|
||||
dom.window.localStorage.getItem(STORAGE_KEY_VAULT_NAV_CONFIG) ?? '{}',
|
||||
);
|
||||
assert.equal(persistedAfterUninstall.order.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
assert.equal(persistedAfterUninstall.hidden.includes(OFFICIAL_DB_PLUGIN), false);
|
||||
|
||||
// Reinstalling in the same session restores the page visible by default at the end.
|
||||
snapshot = { locale: 'en', plugins: [dbEntry('0.3.6'), monitorEntry] };
|
||||
installed = [
|
||||
{ id: DB_PLUGIN_ID, enabled: true, activeVersion: '0.3.6' },
|
||||
{ id: MONITOR_PLUGIN_ID, enabled: true, activeVersion: '1.0.0' },
|
||||
];
|
||||
await act(async () => {
|
||||
for (const listener of listeners) listener();
|
||||
await settle();
|
||||
});
|
||||
assert.equal(nav.visibleIds.includes(OFFICIAL_DB_PLUGIN), true);
|
||||
assert.equal(nav.isHidden(OFFICIAL_DB_PLUGIN), false);
|
||||
|
||||
await act(async () => {
|
||||
root.unmount();
|
||||
});
|
||||
} finally {
|
||||
for (const [key, descriptor] of previous) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
getManageableVaultNavIds,
|
||||
getVisibleVaultNavIds,
|
||||
isCustomVaultNavConfig,
|
||||
isPluginVaultNavId,
|
||||
moveVaultNavItem,
|
||||
normalizeVaultNavConfig,
|
||||
reconcileVaultNavConfig,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
setVaultNavItemVisibility,
|
||||
toggleVaultNavItemVisibility,
|
||||
type PluginVaultNavId,
|
||||
type ReconcileVaultNavOptions,
|
||||
type VaultNavConfig,
|
||||
type VaultNavDropPosition,
|
||||
type VaultNavItemId,
|
||||
@@ -30,6 +32,17 @@ export interface UseVaultNavConfigOptions {
|
||||
pluginsLoading?: boolean;
|
||||
/** Pass true once plugin contributions are available from the plugin runtime. */
|
||||
pluginsAvailable?: boolean;
|
||||
/**
|
||||
* Installed plugin package IDs (including disabled/updating plugins).
|
||||
* When omitted, saved plugin-vault:* entries are preserved rather than pruned
|
||||
* solely because they are absent from `activePluginIds`.
|
||||
*/
|
||||
installedPluginIds?: readonly string[];
|
||||
/**
|
||||
* Optional nav-key to owning plugin package ID map for currently active pages.
|
||||
* Cached across renders so a vanished page can still be attributed to its plugin.
|
||||
*/
|
||||
pluginOwnerByNavId?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface UseVaultNavConfigResult {
|
||||
@@ -57,11 +70,11 @@ export interface UseVaultNavConfigResult {
|
||||
|
||||
function readStoredVaultNavConfig(
|
||||
activePluginIds: readonly PluginVaultNavId[],
|
||||
pruneMissingPlugins: boolean,
|
||||
options: ReconcileVaultNavOptions,
|
||||
): VaultNavConfig {
|
||||
try {
|
||||
const raw = localStorageAdapter.read(STORAGE_KEY_VAULT_NAV_CONFIG);
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, { pruneMissingPlugins });
|
||||
return normalizeVaultNavConfig(raw, activePluginIds, options);
|
||||
} catch {
|
||||
return resetVaultNavConfig(activePluginIds);
|
||||
}
|
||||
@@ -79,16 +92,36 @@ export function useVaultNavConfig({
|
||||
activePluginIds,
|
||||
pluginsLoading = false,
|
||||
pluginsAvailable = false,
|
||||
installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
}: UseVaultNavConfigOptions): UseVaultNavConfigResult {
|
||||
const pluginKey = activePluginIds.join('\0');
|
||||
const stablePluginIds = useMemo<PluginVaultNavId[]>(
|
||||
() => (pluginKey ? (pluginKey.split('\0') as PluginVaultNavId[]) : []),
|
||||
[pluginKey],
|
||||
);
|
||||
const pruneMissingPlugins = !pluginsLoading && pluginsAvailable;
|
||||
const installedKey = installedPluginIds ? installedPluginIds.join('\0') : null;
|
||||
const stableInstalledPluginIds = useMemo<readonly string[] | undefined>(
|
||||
() => (installedKey === null ? undefined : installedKey ? installedKey.split('\0') : []),
|
||||
[installedKey],
|
||||
);
|
||||
const pluginOwnerCacheRef = useRef<Map<PluginVaultNavId, string>>(new Map());
|
||||
if (pluginOwnerByNavId) {
|
||||
for (const [navId, ownerId] of Object.entries(pluginOwnerByNavId)) {
|
||||
if (isPluginVaultNavId(navId) && ownerId) {
|
||||
pluginOwnerCacheRef.current.set(navId, ownerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pruneMissingPlugins =
|
||||
!pluginsLoading && pluginsAvailable && stableInstalledPluginIds !== undefined;
|
||||
|
||||
const [config, setConfig] = useState<VaultNavConfig>(() =>
|
||||
readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins),
|
||||
readStoredVaultNavConfig(stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
}),
|
||||
);
|
||||
const configRef = useRef<VaultNavConfig>(config);
|
||||
configRef.current = config;
|
||||
@@ -100,6 +133,8 @@ export function useVaultNavConfig({
|
||||
const current = configRef.current;
|
||||
const reconciled = reconcileVaultNavConfig(current, stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(current, reconciled)) {
|
||||
configRef.current = reconciled;
|
||||
@@ -120,7 +155,7 @@ export function useVaultNavConfig({
|
||||
// Ignore storage read errors.
|
||||
}
|
||||
}
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
|
||||
|
||||
// Cross-window and adapter sync.
|
||||
useEffect(() => {
|
||||
@@ -134,7 +169,11 @@ export function useVaultNavConfig({
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, pruneMissingPlugins);
|
||||
const next = readStoredVaultNavConfig(stablePluginIds, {
|
||||
pruneMissingPlugins,
|
||||
installedPluginIds: stableInstalledPluginIds,
|
||||
pluginOwnerByNavId: pluginOwnerCacheRef.current,
|
||||
});
|
||||
if (!areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
configRef.current = next;
|
||||
setConfig(next);
|
||||
@@ -146,7 +185,7 @@ export function useVaultNavConfig({
|
||||
window.removeEventListener('storage', sync);
|
||||
window.removeEventListener(LOCAL_STORAGE_ADAPTER_CHANGED_EVENT, sync);
|
||||
};
|
||||
}, [pruneMissingPlugins, stablePluginIds]);
|
||||
}, [pruneMissingPlugins, stableInstalledPluginIds, stablePluginIds]);
|
||||
|
||||
const commit = useCallback((next: VaultNavConfig): VaultNavConfig => {
|
||||
if (areVaultNavConfigsEqual(configRef.current, next)) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { matchesKeyBinding } from "../../domain/models.ts";
|
||||
import { isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
|
||||
import { isNativeCloseTabBound, isPrimaryModifierWBinding, resolveWindowCommandCloseIntent } from "./windowCommandClose.ts";
|
||||
|
||||
test("primary-modifier W only belongs to the matching close-tab binding", () => {
|
||||
assert.equal(isPrimaryModifierWBinding("⌘ + W", matchesKeyBinding, true), true);
|
||||
@@ -176,3 +176,12 @@ test("Cmd+W closes the window when nothing else is active", () => {
|
||||
{ kind: "closeWindow" },
|
||||
);
|
||||
});
|
||||
|
||||
test("native close matches a secondary Command-W for the active Close Tab action", () => {
|
||||
const primary = { id: "close-tab", action: "closeTab", label: "Close", category: "tabs" as const, mac: "F9", pc: "F9" };
|
||||
const secondary = { ...primary, id: "close-tab::extra-0", mac: "⌘ + W", pc: "Disabled" };
|
||||
assert.equal(isNativeCloseTabBound("mac", [primary, secondary], true), true);
|
||||
assert.equal(isNativeCloseTabBound("pc", [primary, secondary], true), false);
|
||||
assert.equal(isNativeCloseTabBound("disabled", [primary, secondary], true), false);
|
||||
assert.equal(isNativeCloseTabBound("mac", [primary, { ...secondary, action: "quickSwitch" }], true), false);
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import { matchesKeyBinding, type HotkeyScheme, type KeyBinding } from '../../domain/models/keyBindings';
|
||||
|
||||
export type WindowCommandCloseIntent =
|
||||
| { kind: 'forwardShortcut' }
|
||||
| { kind: 'closeDialog' }
|
||||
@@ -25,6 +27,16 @@ export function isPrimaryModifierWBinding(
|
||||
);
|
||||
}
|
||||
|
||||
export function isNativeCloseTabBound(
|
||||
scheme: HotkeyScheme,
|
||||
bindings: readonly KeyBinding[],
|
||||
isMac: boolean,
|
||||
): boolean {
|
||||
return scheme !== 'disabled' && bindings.some((binding) =>
|
||||
binding.action === 'closeTab' && isPrimaryModifierWBinding(binding[scheme], matchesKeyBinding, isMac)
|
||||
);
|
||||
}
|
||||
|
||||
interface ResolveWindowCommandCloseIntentInput {
|
||||
activeTabId: string | null;
|
||||
editorTabIds: string[];
|
||||
|
||||
@@ -309,7 +309,7 @@ const SYNCABLE_TERMINAL_KEYS = [
|
||||
'inlineImagesEnabled', 'inlineImageKittyEnabled', 'inlineImageSixelEnabled', 'inlineImageIipEnabled',
|
||||
'autocompleteEnabled', 'autocompleteGhostText', 'autocompletePopupMenu',
|
||||
'autocompleteDebounceMs', 'autocompleteMinChars', 'autocompleteMaxSuggestions',
|
||||
'autocompleteHistoryScope',
|
||||
'autocompleteHistoryScope', 'autocompleteShowSnippets',
|
||||
] as const;
|
||||
|
||||
export const SYNCABLE_SETTING_STORAGE_KEYS = [
|
||||
|
||||
+8
-7
@@ -160,14 +160,15 @@
|
||||
${andIf} ${FileExists} "$oldDesktopLink"
|
||||
Rename "$oldDesktopLink" "$newDesktopLink"
|
||||
WinShell::UninstShortcut "$oldDesktopLink"
|
||||
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${elseIfNot} ${FileExists} "$newDesktopLink"
|
||||
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
|
||||
ClearErrors
|
||||
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
${endif}
|
||||
|
||||
; #4672: Always rewrite the .lnk from the newly installed $appExe so in-app
|
||||
; updates do not leave an existing desktop shortcut with a stale/blank icon.
|
||||
CreateShortCut "$newDesktopLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}"
|
||||
ClearErrors
|
||||
WinShell::SetLnkAUMI "$newDesktopLink" "${APP_ID}"
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x00002000, i 0x0005, w "$newDesktopLink", i 0)'
|
||||
System::Call 'Shell32::SHChangeNotify(i 0x8000000, i 0, i 0, i 0)'
|
||||
!macroend
|
||||
|
||||
!macro removeDesktopShortcut
|
||||
|
||||
@@ -62,6 +62,7 @@ interface AIChatPanelContentProps {
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
@@ -176,6 +177,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
@@ -574,6 +576,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={onSendWithGrokMode}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CheckSquare, Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react';
|
||||
import type { AISession } from '../infrastructure/ai/types';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { cn } from '../lib/utils';
|
||||
@@ -9,6 +9,8 @@ import { Input } from './ui/input';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
|
||||
import { SESSION_HISTORY_ROW_CLASSNAMES } from './ai/sessionHistoryLayout';
|
||||
import { getSessionLastMessageAt } from './ai/globalSessionManagerRows';
|
||||
import { GlobalSessionSelectionContext } from './ai/sessionHistorySelectionContext';
|
||||
import { useSessionHistorySearch } from '../application/state/useSessionHistorySearch';
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
@@ -52,6 +54,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
const { t } = useI18n();
|
||||
const [view, setView] = useState<'scoped' | 'global'>('scoped');
|
||||
const [headerMenuOpen, setHeaderMenuOpen] = useState(false);
|
||||
const [globalSelectionMode, setGlobalSelectionMode] = useState(false);
|
||||
const [renderCount, setRenderCount] = useState(SESSION_RENDER_BATCH);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
@@ -70,6 +73,22 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
setRenderCount(SESSION_RENDER_BATCH);
|
||||
}, [sessions, searchQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
if (view !== 'global' || !globalManager) {
|
||||
setGlobalSelectionMode(false);
|
||||
}
|
||||
}, [view, globalManager]);
|
||||
|
||||
const selectionContextValue = useMemo(
|
||||
() => ({
|
||||
selectionMode: globalSelectionMode,
|
||||
setSelectionMode: setGlobalSelectionMode,
|
||||
}),
|
||||
[globalSelectionMode],
|
||||
);
|
||||
const canSelectGlobalChats = view === 'global' && Boolean(globalManager);
|
||||
const hasHeaderMenu = Boolean(canSelectGlobalChats || onImportSessions || onExportSessions);
|
||||
|
||||
const displayedSessions = filteredSessions.slice(0, renderCount);
|
||||
const hiddenSessionCount = Math.max(0, filteredSessions.length - renderCount);
|
||||
|
||||
@@ -132,7 +151,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
{hasHeaderMenu && (
|
||||
<Dropdown open={headerMenuOpen} onOpenChange={setHeaderMenuOpen}>
|
||||
<DropdownTrigger asChild>
|
||||
<button
|
||||
@@ -144,6 +163,31 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="end" className="min-w-[152px] p-1" keyboardNavigation>
|
||||
{canSelectGlobalChats && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setHeaderMenuOpen(false);
|
||||
setGlobalSelectionMode((prev) => !prev);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
|
||||
>
|
||||
<CheckSquare
|
||||
size={12}
|
||||
className={cn(
|
||||
'shrink-0',
|
||||
globalSelectionMode ? 'text-primary' : 'text-muted-foreground',
|
||||
)}
|
||||
/>
|
||||
<span>{t('ai.chat.managerToggleSelection')}</span>
|
||||
</button>
|
||||
{(onImportSessions || onExportSessions) && (
|
||||
<div className="my-1 h-px bg-border/50" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{onImportSessions && (
|
||||
<button
|
||||
type="button"
|
||||
@@ -184,7 +228,9 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
{view === 'global' && globalManager ? (
|
||||
globalManager
|
||||
<GlobalSessionSelectionContext.Provider value={selectionContextValue}>
|
||||
{globalManager}
|
||||
</GlobalSessionSelectionContext.Provider>
|
||||
) : (
|
||||
<>
|
||||
<div className="px-3 py-2 shrink-0 border-b border-border/30">
|
||||
@@ -250,7 +296,7 @@ export const SessionHistoryDrawer: React.FC<SessionHistoryDrawerProps> = ({
|
||||
)}
|
||||
{displayedSessions.map((session) => {
|
||||
const isActive = session.id === activeSessionId;
|
||||
const time = new Date(session.updatedAt);
|
||||
const time = new Date(getSessionLastMessageAt(session));
|
||||
const timeStr = formatRelativeTime(time, t);
|
||||
|
||||
return (
|
||||
|
||||
@@ -840,7 +840,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setComposerValueRevision((rev) => rev + 1);
|
||||
}, []);
|
||||
|
||||
const draftGenerationRef = useRef(0);
|
||||
const clearScopeDraft = useCallback((options?: { keepPendingText?: boolean }) => {
|
||||
draftGenerationRef.current += 1;
|
||||
if (!options?.keepPendingText) discardPendingComposerText();
|
||||
clearDraftForScope(scopeKey);
|
||||
}, [clearDraftForScope, discardPendingComposerText, scopeKey]);
|
||||
@@ -1737,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
|
||||
const handleSend = useCallback(async (
|
||||
textOverride?: string,
|
||||
options?: { includeDraftAttachments?: boolean },
|
||||
options?: { includeDraftAttachments?: boolean; chooseGrokMode?: boolean },
|
||||
) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
@@ -1962,6 +1964,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
scopeType,
|
||||
scopeTargetId,
|
||||
existingSessionId: existingExternalSessionId,
|
||||
chooseGrokMode: options?.chooseGrokMode,
|
||||
updateExternalSessionId: updateSessionExternalSessionId,
|
||||
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
|
||||
terminalSessions,
|
||||
@@ -2127,7 +2130,9 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
if (!sessionId || !draft || steeringSessionId || !canSteerCurrentTurn) return;
|
||||
|
||||
if (!validateNoteMentions(draft.attachments)) return;
|
||||
const trimmed = draft.text.trim();
|
||||
const submittedText = draft.text;
|
||||
const draftGeneration = draftGenerationRef.current;
|
||||
const trimmed = submittedText.trim();
|
||||
const attachments = draft.attachments.map((file) => ({
|
||||
base64Data: file.base64Data,
|
||||
mediaType: file.mediaType,
|
||||
@@ -2161,7 +2166,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
attachedImages: modelAttachments,
|
||||
});
|
||||
if (result.status === 'accepted') {
|
||||
if (currentDraftRef.current === draft) clearScopeDraft();
|
||||
if (draftGenerationRef.current !== draftGeneration || activeSessionRef.current?.id !== sessionId) return;
|
||||
const pending = pendingComposerTextRef.current;
|
||||
const keepPendingText = pending != null && pending !== submittedText;
|
||||
clearScopeDraft({ keepPendingText });
|
||||
return;
|
||||
}
|
||||
if (result.status !== 'cancelled') {
|
||||
@@ -2182,6 +2190,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
return registerGrantPersister((rule) => { addGrant(rule); });
|
||||
}, [addGrant]);
|
||||
|
||||
const handleSendWithGrokMode = useCallback((text: string) => {
|
||||
void handleSend(text, { includeDraftAttachments: true, chooseGrokMode: true });
|
||||
}, [handleSend]);
|
||||
|
||||
const handleSendQuickPrompt = useCallback((promptText: string) => {
|
||||
void handleSend(promptText, { includeDraftAttachments: true });
|
||||
}, [handleSend]);
|
||||
@@ -2437,9 +2449,72 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
|
||||
// Regeneration lives in useAIState so it can reuse the maintainer's
|
||||
// title-model resolution and atomic title-write helpers.
|
||||
const handleManagerRegenerateTitle = useCallback((sessionId: string) => {
|
||||
void regenerateSessionTitle?.(sessionId);
|
||||
}, [regenerateSessionTitle]);
|
||||
const handleManagerRegenerateTitle = useCallback(async (sessionId: string) => {
|
||||
if (!regenerateSessionTitle) return;
|
||||
const result = await regenerateSessionTitle(sessionId);
|
||||
if (!result) return;
|
||||
if (result.status === 'updated') {
|
||||
toast.success(t('ai.chat.managerRegenerateTitleUpdated'));
|
||||
} else if (result.status === 'unchanged') {
|
||||
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
|
||||
} else if (result.status === 'no-model') {
|
||||
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
|
||||
} else if (result.status === 'empty') {
|
||||
toast.info(t('ai.chat.managerRegenerateTitleEmpty'));
|
||||
} else if (result.status === 'busy') {
|
||||
toast.info(t('ai.chat.managerRegenerateTitleBusy'));
|
||||
} else if (result.status === 'error') {
|
||||
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', result.error));
|
||||
}
|
||||
}, [regenerateSessionTitle, t]);
|
||||
|
||||
const handleManagerRegenerateTitles = useCallback(async (sessionIds: string[]) => {
|
||||
if (!regenerateSessionTitle || sessionIds.length === 0) return;
|
||||
let updated = 0;
|
||||
let unchanged = 0;
|
||||
let noModel = 0;
|
||||
let failed = 0;
|
||||
let lastError = '';
|
||||
const expectedTitles = new Map(sessionsRef.current.map(session => [session.id, session.title]));
|
||||
const concurrency = 2;
|
||||
let cursor = 0;
|
||||
const workers = Array.from({ length: Math.min(concurrency, sessionIds.length) }, async () => {
|
||||
while (cursor < sessionIds.length) {
|
||||
const currentId = sessionIds[cursor];
|
||||
cursor += 1;
|
||||
const expectedTitle = expectedTitles.get(currentId);
|
||||
if (expectedTitle === undefined) continue;
|
||||
const result = await regenerateSessionTitle(currentId, expectedTitle);
|
||||
if (!result) continue;
|
||||
if (result.status === 'updated') updated += 1;
|
||||
else if (result.status === 'unchanged') unchanged += 1;
|
||||
else if (result.status === 'no-model') noModel += 1;
|
||||
else if (result.status === 'error') {
|
||||
failed += 1;
|
||||
lastError = result.error;
|
||||
}
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
|
||||
if (noModel === sessionIds.length) {
|
||||
toast.warning(t('ai.chat.managerRegenerateTitleNoModel'));
|
||||
return;
|
||||
}
|
||||
if (updated > 0 && failed === 0) {
|
||||
toast.success(t('ai.chat.managerRegenerateTitleBatchDone').replace('{n}', String(updated)));
|
||||
} else if (updated > 0 && failed > 0) {
|
||||
toast.warning(
|
||||
t('ai.chat.managerRegenerateTitleBatchPartial')
|
||||
.replace('{updated}', String(updated))
|
||||
.replace('{failed}', String(failed)),
|
||||
);
|
||||
} else if (failed > 0) {
|
||||
toast.error(t('ai.chat.managerRegenerateTitleFailed').replace('{error}', lastError || 'Unknown error'));
|
||||
} else if (unchanged > 0) {
|
||||
toast.info(t('ai.chat.managerRegenerateTitleUnchanged'));
|
||||
}
|
||||
}, [regenerateSessionTitle, t]);
|
||||
|
||||
const handleManagerDeleteMany = useCallback(async (sessionIds: string[]) => {
|
||||
for (const sessionId of sessionIds) {
|
||||
@@ -2487,7 +2562,8 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
onRename={handleRenameSession}
|
||||
onDelete={(sessionId) => { void handleManagerDelete(sessionId); }}
|
||||
onDeleteMany={(ids) => { void handleManagerDeleteMany(ids); }}
|
||||
onRegenerateTitle={(sessionId) => { void handleManagerRegenerateTitle(sessionId); }}
|
||||
onRegenerateTitle={(sessionId) => handleManagerRegenerateTitle(sessionId)}
|
||||
onRegenerateTitles={(ids) => handleManagerRegenerateTitles(ids)}
|
||||
onExport={handleManagerExport}
|
||||
/>
|
||||
)
|
||||
@@ -2509,6 +2585,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
handleManagerDelete,
|
||||
handleManagerDeleteMany,
|
||||
handleManagerRegenerateTitle,
|
||||
handleManagerRegenerateTitles,
|
||||
handleManagerExport,
|
||||
onFocusAIScopeTarget,
|
||||
]);
|
||||
@@ -2586,6 +2663,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={getExternalAgentSdkBackend(currentAgentConfig ?? undefined) === 'grok' && currentAgentConfig?.grokRuntime !== 'streaming-json' ? handleSendWithGrokMode : undefined}
|
||||
handleCompact={handleCompact}
|
||||
onRenameSession={handleRenameSession}
|
||||
onRenameActiveChat={handleRenameSlashCommand}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
|
||||
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
|
||||
import type { Host, Snippet, VaultNote } from '../types';
|
||||
import type { RegenerateSessionTitleResult } from '../application/state/useAIState';
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Props
|
||||
@@ -46,7 +47,7 @@ export interface AIChatSidePanelProps {
|
||||
updateSessionTitle: (sessionId: string, title: string) => void;
|
||||
autoTitleSession?: (sessionId: string, text: string, signal?: AbortSignal) => void | Promise<void>;
|
||||
/** Explicitly regenerate an existing chat title with the configured LLM. */
|
||||
regenerateSessionTitle?: (sessionId: string) => void | Promise<void>;
|
||||
regenerateSessionTitle?: (sessionId: string, expectedTitle?: string) => void | Promise<RegenerateSessionTitleResult | void>;
|
||||
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
|
||||
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
|
||||
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
|
||||
|
||||
@@ -400,6 +400,7 @@ export function shouldLoadSdkRuntimeModels(agent?: ExternalAgentConfig): boolean
|
||||
return sdkBackend === 'codex'
|
||||
|| sdkBackend === 'claude'
|
||||
|| sdkBackend === 'copilot'
|
||||
|| sdkBackend === 'agy'
|
||||
|| sdkBackend === 'cursor'
|
||||
|| sdkBackend === 'codebuddy'
|
||||
|| sdkBackend === 'opencode'
|
||||
|
||||
@@ -4,7 +4,7 @@ import React from "react";
|
||||
|
||||
import { useAppLockBridge } from "../application/state/useAppLockBridge.ts";
|
||||
import { useAppLockState } from "../application/state/useAppLockState.ts";
|
||||
import { createAppLockGate } from "./AppLockGate.tsx";
|
||||
import { ReportRendererReady, createAppLockGate } from "./AppLockGate.tsx";
|
||||
import { APP_LOCK_AUTO_PROMPT_DELAY_MS } from "./AppLockOverlay.tsx";
|
||||
import { createAppLockBridgeHarness } from "./test-support/createAppLockBridgeHarness.ts";
|
||||
import {
|
||||
@@ -1024,3 +1024,285 @@ test("reopen resync does not unlock a gate when runtime is still locked", async
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("rendererReady waits for lazy route mount and runs after child effects", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
const events: string[] = [];
|
||||
const bridgeHarness = createAppLockBridgeHarness({
|
||||
runtimeState: {
|
||||
initialized: true,
|
||||
locked: false,
|
||||
reason: null,
|
||||
version: 1,
|
||||
lastLockedAt: null,
|
||||
lastUnlockedAt: 1_000,
|
||||
lastActivityAt: 1_000,
|
||||
},
|
||||
});
|
||||
const baseBridge = bridgeHarness.bridge;
|
||||
const wrappedBridge: NetcattyBridge = {
|
||||
...baseBridge,
|
||||
rendererReady: () => {
|
||||
events.push("rendererReady");
|
||||
baseBridge.rendererReady?.();
|
||||
},
|
||||
};
|
||||
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
|
||||
const bridge = useAppLockBridge();
|
||||
return {
|
||||
...bridge,
|
||||
notifyRendererReady: () => {
|
||||
dom.window.netcatty?.rendererReady?.();
|
||||
},
|
||||
};
|
||||
};
|
||||
const AppLockGate = createAppLockGate({
|
||||
useSettingsState: () => ({
|
||||
uiLanguage: "en",
|
||||
appLockSettings: {
|
||||
enabled: false,
|
||||
timeoutMinutes: 15,
|
||||
passwordVerifier: null,
|
||||
},
|
||||
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
|
||||
useAppLockState,
|
||||
useAppLockBridge: useIsolatedAppLockBridge,
|
||||
});
|
||||
|
||||
let resolveLazy!: (mod: { default: React.FC }) => void;
|
||||
const LazyRoute = React.lazy(
|
||||
() =>
|
||||
new Promise<{ default: React.FC }>((resolve) => {
|
||||
resolveLazy = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const ChildSubscriber: React.FC = () => {
|
||||
React.useEffect(() => {
|
||||
events.push("childSubscribed");
|
||||
}, []);
|
||||
return React.createElement("div", { id: "lazy-route-content" }, "Mounted");
|
||||
};
|
||||
|
||||
const previousWindowNetcatty = dom.window.netcatty;
|
||||
dom.window.netcatty = wrappedBridge;
|
||||
|
||||
try {
|
||||
await renderer.render(
|
||||
React.createElement(AppLockGate, {
|
||||
notifyRendererReady: true,
|
||||
children: () =>
|
||||
React.createElement(
|
||||
React.Suspense,
|
||||
{ fallback: React.createElement("div", { id: "lazy-fallback" }, "Loading") },
|
||||
React.createElement(LazyRoute),
|
||||
),
|
||||
}),
|
||||
);
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
// Gate allowed children, but LazyRoute is still suspended -> must NOT signal ready.
|
||||
assert.equal(dom.document.getElementById("lazy-fallback")?.textContent, "Loading");
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
|
||||
assert.deepEqual(events, []);
|
||||
|
||||
await runWithAct(async () => {
|
||||
resolveLazy({
|
||||
default: () =>
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement(ChildSubscriber),
|
||||
React.createElement(ReportRendererReady),
|
||||
),
|
||||
});
|
||||
});
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
assert.equal(dom.document.getElementById("lazy-route-content")?.textContent, "Mounted");
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
|
||||
assert.deepEqual(events, ["childSubscribed", "rendererReady"]);
|
||||
} finally {
|
||||
dom.window.netcatty = previousWindowNetcatty;
|
||||
await renderer.unmount();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("startup-locked gate withholds rendererReady until unlock and lazy route mount", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
const bridgeHarness = createAppLockBridgeHarness({
|
||||
runtimeState: {
|
||||
initialized: true,
|
||||
locked: true,
|
||||
reason: "startup",
|
||||
version: 1,
|
||||
lastLockedAt: 1_000,
|
||||
lastUnlockedAt: null,
|
||||
lastActivityAt: 1_000,
|
||||
},
|
||||
});
|
||||
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
|
||||
const bridge = useAppLockBridge();
|
||||
return {
|
||||
...bridge,
|
||||
notifyRendererReady: () => {
|
||||
dom.window.netcatty?.rendererReady?.();
|
||||
},
|
||||
};
|
||||
};
|
||||
const AppLockGate = createAppLockGate({
|
||||
useSettingsState: () => ({
|
||||
uiLanguage: "en",
|
||||
appLockSettings: {
|
||||
enabled: true,
|
||||
timeoutMinutes: 15,
|
||||
passwordVerifier: {
|
||||
version: 1,
|
||||
algorithm: "PBKDF2-SHA256",
|
||||
iterations: 210000,
|
||||
salt: "AAAAAAAAAAAAAAAAAAAAAA==",
|
||||
hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
|
||||
},
|
||||
},
|
||||
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
|
||||
useAppLockState,
|
||||
useAppLockBridge: useIsolatedAppLockBridge,
|
||||
});
|
||||
|
||||
let resolveLazy!: (mod: { default: React.FC }) => void;
|
||||
const LazyRoute = React.lazy(
|
||||
() =>
|
||||
new Promise<{ default: React.FC }>((resolve) => {
|
||||
resolveLazy = resolve;
|
||||
}),
|
||||
);
|
||||
|
||||
const previousWindowNetcatty = dom.window.netcatty;
|
||||
dom.window.netcatty = bridgeHarness.bridge;
|
||||
|
||||
try {
|
||||
await renderer.render(
|
||||
React.createElement(AppLockGate, {
|
||||
notifyRendererReady: true,
|
||||
children: () =>
|
||||
React.createElement(
|
||||
React.Suspense,
|
||||
{ fallback: React.createElement("div", { id: "locked-lazy-fallback" }, "Loading") },
|
||||
React.createElement(LazyRoute),
|
||||
),
|
||||
}),
|
||||
);
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
// Locked first paint: children withheld, must not notify.
|
||||
assert.equal(dom.document.getElementById("locked-lazy-fallback"), null);
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
|
||||
|
||||
// Unlock: children allowed, but LazyRoute still suspended -> still must not notify.
|
||||
await runWithAct(async () => {
|
||||
bridgeHarness.setRuntimeState({
|
||||
locked: false,
|
||||
reason: null,
|
||||
lastUnlockedAt: 2_000,
|
||||
lastActivityAt: 2_000,
|
||||
});
|
||||
});
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
assert.equal(dom.document.getElementById("locked-lazy-fallback")?.textContent, "Loading");
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
|
||||
|
||||
// Resolve lazy chunk -> mounts real page and reports ready once.
|
||||
await runWithAct(async () => {
|
||||
resolveLazy({
|
||||
default: () =>
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement("div", { id: "locked-lazy-mounted" }, "Ready"),
|
||||
React.createElement(ReportRendererReady),
|
||||
),
|
||||
});
|
||||
});
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
assert.equal(dom.document.getElementById("locked-lazy-mounted")?.textContent, "Ready");
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 1);
|
||||
} finally {
|
||||
dom.window.netcatty = previousWindowNetcatty;
|
||||
await renderer.unmount();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("notifyRendererReady=false suppresses ReportRendererReady signals", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
const bridgeHarness = createAppLockBridgeHarness({
|
||||
runtimeState: {
|
||||
initialized: true,
|
||||
locked: false,
|
||||
reason: null,
|
||||
version: 1,
|
||||
lastLockedAt: null,
|
||||
lastUnlockedAt: 1_000,
|
||||
lastActivityAt: 1_000,
|
||||
},
|
||||
});
|
||||
const useIsolatedAppLockBridge: typeof useAppLockBridge = () => {
|
||||
const bridge = useAppLockBridge();
|
||||
return {
|
||||
...bridge,
|
||||
notifyRendererReady: () => {
|
||||
dom.window.netcatty?.rendererReady?.();
|
||||
},
|
||||
};
|
||||
};
|
||||
const AppLockGate = createAppLockGate({
|
||||
useSettingsState: () => ({
|
||||
uiLanguage: "en",
|
||||
appLockSettings: {
|
||||
enabled: false,
|
||||
timeoutMinutes: 15,
|
||||
passwordVerifier: null,
|
||||
},
|
||||
}) as ReturnType<typeof import("../application/state/useSettingsState.ts").useSettingsState>,
|
||||
useAppLockState,
|
||||
useAppLockBridge: useIsolatedAppLockBridge,
|
||||
});
|
||||
|
||||
const previousWindowNetcatty = dom.window.netcatty;
|
||||
dom.window.netcatty = bridgeHarness.bridge;
|
||||
|
||||
try {
|
||||
await renderer.render(
|
||||
React.createElement(AppLockGate, {
|
||||
notifyRendererReady: false,
|
||||
children: () =>
|
||||
React.createElement(
|
||||
React.Fragment,
|
||||
null,
|
||||
React.createElement("div", { id: "opt-out-content" }, "OptOut"),
|
||||
React.createElement(ReportRendererReady),
|
||||
),
|
||||
}),
|
||||
);
|
||||
await flushEffects();
|
||||
await flushEffects();
|
||||
|
||||
assert.equal(dom.document.getElementById("opt-out-content")?.textContent, "OptOut");
|
||||
assert.equal(bridgeHarness.getRendererReadyCallCount(), 0);
|
||||
} finally {
|
||||
dom.window.netcatty = previousWindowNetcatty;
|
||||
await renderer.unmount();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
shouldDeferExternalActionWhileAppLocked,
|
||||
shouldNotifyAppLockGateRendererReady,
|
||||
shouldRenderAppLockGateChildren,
|
||||
shouldReportAppLockGateRendererReady,
|
||||
} from "./AppLockGate.tsx";
|
||||
|
||||
test("shouldRenderAppLockGateChildren withholds startup-locked route children until unlock", () => {
|
||||
@@ -140,6 +141,44 @@ test("shouldNotifyAppLockGateRendererReady waits until locked children can mount
|
||||
);
|
||||
});
|
||||
|
||||
test("shouldReportAppLockGateRendererReady requires gate permission and mounted content", () => {
|
||||
// Gate allowing children (e.g. Suspense fallback) is not sufficient.
|
||||
assert.equal(
|
||||
shouldReportAppLockGateRendererReady({
|
||||
notifyRendererReady: true,
|
||||
renderChildren: true,
|
||||
contentMounted: false,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
// Locked first paint must not notify even if contentMounted were true.
|
||||
assert.equal(
|
||||
shouldReportAppLockGateRendererReady({
|
||||
notifyRendererReady: true,
|
||||
renderChildren: false,
|
||||
contentMounted: true,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
// Routes that opt out (terminal-popup / editor-window) must not notify.
|
||||
assert.equal(
|
||||
shouldReportAppLockGateRendererReady({
|
||||
notifyRendererReady: false,
|
||||
renderChildren: true,
|
||||
contentMounted: true,
|
||||
}),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldReportAppLockGateRendererReady({
|
||||
notifyRendererReady: true,
|
||||
renderChildren: true,
|
||||
contentMounted: true,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("shouldDeferExternalActionWhileAppLocked queues actions only while locked", () => {
|
||||
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: true }), true);
|
||||
assert.equal(shouldDeferExternalActionWhileAppLocked({ locked: false }), false);
|
||||
|
||||
+74
-22
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { I18nProvider } from '../application/i18n/I18nProvider';
|
||||
import { useAppLockBridge } from '../application/state/useAppLockBridge';
|
||||
@@ -67,6 +67,33 @@ export function shouldNotifyAppLockGateRendererReady(input: {
|
||||
return input.notifyRendererReady && input.renderChildren;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy route chunks suspend after AppLockGate allows children to render.
|
||||
* Only emit rendererReady once the gate permits it and the lazy route's real
|
||||
* content has mounted (so AppSideEffects / IPC listeners are registered).
|
||||
*/
|
||||
export function shouldReportAppLockGateRendererReady(input: {
|
||||
notifyRendererReady: boolean;
|
||||
renderChildren: boolean;
|
||||
contentMounted: boolean;
|
||||
}): boolean {
|
||||
return shouldNotifyAppLockGateRendererReady(input) && input.contentMounted;
|
||||
}
|
||||
|
||||
const RendererReadyContext = createContext<(() => void) | null>(null);
|
||||
|
||||
export function useReportRendererReady(): void {
|
||||
const reportRendererReady = useContext(RendererReadyContext);
|
||||
useEffect(() => {
|
||||
reportRendererReady?.();
|
||||
}, [reportRendererReady]);
|
||||
}
|
||||
|
||||
export const ReportRendererReady: React.FC = () => {
|
||||
useReportRendererReady();
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Queue external actions (e.g. ssh:// deep links) while the app lock is held. */
|
||||
export function shouldDeferExternalActionWhileAppLocked(input: {
|
||||
locked: boolean;
|
||||
@@ -88,6 +115,8 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
|
||||
onAppLockReopen,
|
||||
} = deps.useAppLockBridge();
|
||||
const hasRenderedChildrenRef = useRef(false);
|
||||
const contentMountedRef = useRef(false);
|
||||
const hasNotifiedRendererReadyRef = useRef(false);
|
||||
const [reopenSignal, setReopenSignal] = useState(0);
|
||||
const renderChildren = shouldRenderAppLockGateChildren({
|
||||
initialized: appLock.initialized,
|
||||
@@ -99,10 +128,31 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
|
||||
if (renderChildren) {
|
||||
hasRenderedChildrenRef.current = true;
|
||||
}
|
||||
const shouldNotifyRendererReady = shouldNotifyAppLockGateRendererReady({
|
||||
notifyRendererReady,
|
||||
renderChildren,
|
||||
});
|
||||
|
||||
const emitRendererReadyIfAllowed = useCallback(() => {
|
||||
if (hasNotifiedRendererReadyRef.current) return;
|
||||
if (
|
||||
!shouldReportAppLockGateRendererReady({
|
||||
notifyRendererReady,
|
||||
renderChildren,
|
||||
contentMounted: contentMountedRef.current,
|
||||
})
|
||||
) {
|
||||
return;
|
||||
}
|
||||
hasNotifiedRendererReadyRef.current = true;
|
||||
try {
|
||||
performance.mark('netcatty:renderer:ready');
|
||||
notifyAppLockRendererReady();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, [notifyAppLockRendererReady, notifyRendererReady, renderChildren]);
|
||||
|
||||
const reportRendererReady = useCallback(() => {
|
||||
contentMountedRef.current = true;
|
||||
emitRendererReadyIfAllowed();
|
||||
}, [emitRendererReadyIfAllowed]);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
@@ -111,14 +161,14 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
|
||||
splash.classList.add('fade-out');
|
||||
setTimeout(() => splash.remove(), 200);
|
||||
}
|
||||
if (shouldNotifyRendererReady) {
|
||||
performance.mark('netcatty:renderer:ready');
|
||||
notifyAppLockRendererReady();
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, [notifyAppLockRendererReady, shouldNotifyRendererReady]);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
emitRendererReadyIfAllowed();
|
||||
}, [emitRendererReadyIfAllowed]);
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = onAppLockReopen(() => {
|
||||
@@ -149,18 +199,20 @@ export function createAppLockGate(deps: AppLockGateDeps): React.FC<AppLockGatePr
|
||||
<I18nProvider locale={settings.uiLanguage}>
|
||||
<ToastProvider>
|
||||
<TooltipProvider delayDuration={300}>
|
||||
{renderChildren ? (
|
||||
<div
|
||||
// React 19 supports the HTML inert attribute; when true, the
|
||||
// subtree is non-interactive and removed from sequential focus.
|
||||
inert={lockedBackground ? true : undefined}
|
||||
aria-hidden={lockedBackground || undefined}
|
||||
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
|
||||
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
|
||||
>
|
||||
{children({ settings, appLock })}
|
||||
</div>
|
||||
) : null}
|
||||
<RendererReadyContext.Provider value={reportRendererReady}>
|
||||
{renderChildren ? (
|
||||
<div
|
||||
// React 19 supports the HTML inert attribute; when true, the
|
||||
// subtree is non-interactive and removed from sequential focus.
|
||||
inert={lockedBackground ? true : undefined}
|
||||
aria-hidden={lockedBackground || undefined}
|
||||
className={lockedBackground ? 'h-full pointer-events-none' : 'h-full'}
|
||||
data-app-lock-background={lockedBackground ? 'locked' : 'unlocked'}
|
||||
>
|
||||
{children({ settings, appLock })}
|
||||
</div>
|
||||
) : null}
|
||||
</RendererReadyContext.Provider>
|
||||
<AppLockOverlay
|
||||
locked={appLock.locked}
|
||||
reason={appLock.lockReason}
|
||||
|
||||
@@ -31,3 +31,13 @@ test("terminal popups wait for app-lock initialization before starting a termina
|
||||
/allowTerminalStart=\{appLock\.initialized\s*&&\s*!appLock\.locked\}/,
|
||||
);
|
||||
});
|
||||
|
||||
test("lazy routes gated by AppLockGate report rendererReady after mounting", () => {
|
||||
const appSource = readComponentSource("../App.tsx");
|
||||
const settingsPage = readComponentSource("./SettingsPage.tsx");
|
||||
const trayPanel = readComponentSource("./TrayPanel.tsx");
|
||||
|
||||
assert.match(appSource, /\buseReportRendererReady\s*\(\)/);
|
||||
assert.match(settingsPage, /<ReportRendererReady\s*\/>/);
|
||||
assert.match(trayPanel, /<ReportRendererReady\s*\/>/);
|
||||
});
|
||||
@@ -383,8 +383,8 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
|
||||
active
|
||||
? "bg-primary/12 text-primary border border-primary/25"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
|
||||
? "bg-primary/12 text-primary"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
+12
-16
@@ -802,6 +802,13 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
? 'select'
|
||||
: 'connect';
|
||||
|
||||
const activation = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
@@ -837,17 +844,11 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
if (!ids) e.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
if (activation === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (action === 'select') {
|
||||
if (activation === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -856,17 +857,11 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
if (activation === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (action === 'select') {
|
||||
if (activation === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -980,6 +975,7 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<HostTreeHostContextMenuContent
|
||||
enterConnects={activation === 'connect'}
|
||||
host={host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
|
||||
@@ -624,13 +624,55 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<VaultPageHeader>
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 flex flex-wrap items-center gap-2">
|
||||
<VaultHeaderSearch
|
||||
placeholder={t("knownHosts.search.placeholder")}
|
||||
className="flex-1 max-w-xs"
|
||||
className="flex-1 min-w-[160px] max-w-xs"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex h-10 shrink-0 items-center rounded-md bg-secondary/70 p-1 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* View Mode Toggle */}
|
||||
@@ -720,52 +762,6 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
)}
|
||||
</VaultPageHeader>
|
||||
|
||||
{/* Segmented Tab Strip: SSH Host Keys | Remote Desktop Certificates */}
|
||||
<div className="px-4 py-2 border-b border-border/50 bg-background/60 shrink-0">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex items-center rounded-lg bg-secondary/70 p-0.5 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<ScrollArea className="flex-1">
|
||||
{activeTab === "certs" ? (
|
||||
|
||||
@@ -712,7 +712,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{hostRow}</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onSelect(host)}>
|
||||
<ContextMenuItem shortcut={isSelected ? "Enter" : undefined} onClick={() => onSelect(host)}>
|
||||
{t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onEditHost(host)}>
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useWindowControls } from "../application/state/useWindowControls";
|
||||
import { useUpdateCheck } from "../application/state/useUpdateCheck";
|
||||
import { I18nProvider, useI18n } from "../application/i18n/I18nProvider";
|
||||
import { sanitizePortForwardingRulesForSync } from "../application/syncPayload";
|
||||
import type { AppLockGateRenderContext } from "./AppLockGate";
|
||||
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
|
||||
import { toast } from "./ui/toast";
|
||||
import { SettingsTabContent } from "./settings/settings-ui";
|
||||
import { SettingsFocusProvider, useSettingsFocus } from "./settings/SettingsFocusContext";
|
||||
@@ -28,8 +28,7 @@ import { setupMcpApprovalBridge } from "../infrastructure/ai/shared/approvalGate
|
||||
import { usePluginContributions } from "../application/state/usePluginContributions";
|
||||
import { PluginContributionHost } from "./plugins/PluginContributionHost";
|
||||
import { PluginPermissionHost } from "./plugins/PluginPermissionHost";
|
||||
import { matchesKeyBinding } from "../domain/models";
|
||||
import { isPrimaryModifierWBinding } from "../application/state/windowCommandClose";
|
||||
import { isNativeCloseTabBound } from "../application/state/windowCommandClose";
|
||||
import { getSettingsWindowClassName } from "./settings/settingsWindowChrome";
|
||||
|
||||
const LazySettingsApplicationTab = lazy(() => import("./SettingsApplicationTab"));
|
||||
@@ -341,7 +340,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
const pluginThemeTokens = useMemo(() => selectPluginThemeTokens(committedAppThemeStyle as Record<string, unknown>), [committedAppThemeStyle]);
|
||||
const { t } = useI18n();
|
||||
const { request, clearFocus, openSearch } = useSettingsFocus();
|
||||
const { notifyRendererReady, closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
|
||||
const { closeSettingsWindow, onWindowCommandCloseRequested } = useWindowControls();
|
||||
const { updateState, checkNow, installUpdate, openReleasePage, startDownload, isUpdateDemoMode } = useUpdateCheck({
|
||||
autoUpdateEnabled: settings.autoUpdateEnabled,
|
||||
// Install blocked by unsaved editors in the main window — surface a toast
|
||||
@@ -351,17 +350,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
const [activeTab, setActiveTab] = useState("application");
|
||||
const [mountedTabs, setMountedTabs] = useState(() => new Set(["application"]));
|
||||
const { available: pluginRuntimeAvailable } = usePluginContributions();
|
||||
const closeTabKeyStr = useMemo(() => {
|
||||
if (settings.hotkeyScheme === "disabled") return null;
|
||||
const binding = settings.keyBindings.find((item) => item.action === "closeTab");
|
||||
if (!binding) return null;
|
||||
return settings.hotkeyScheme === "mac" ? binding.mac : binding.pc;
|
||||
}, [settings.hotkeyScheme, settings.keyBindings]);
|
||||
const nativeCommandWClosesSettings = isPrimaryModifierWBinding(closeTabKeyStr, matchesKeyBinding, true);
|
||||
|
||||
useEffect(() => {
|
||||
notifyRendererReady();
|
||||
}, [notifyRendererReady]);
|
||||
const nativeCommandWClosesSettings = isNativeCloseTabBound(settings.hotkeyScheme, settings.keyBindings, true);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -648,6 +637,9 @@ const SettingsPageContent: React.FC<{ settings: SettingsState; appLock?: AppLock
|
||||
setDisableTerminalFontZoom={settings.setDisableTerminalFontZoom}
|
||||
keyBindings={settings.keyBindings}
|
||||
updateKeyBinding={settings.updateKeyBinding}
|
||||
addKeyBindingExtra={settings.addKeyBindingExtra}
|
||||
updateKeyBindingExtra={settings.updateKeyBindingExtra}
|
||||
removeKeyBindingExtra={settings.removeKeyBindingExtra}
|
||||
resetKeyBinding={settings.resetKeyBinding}
|
||||
resetAllKeyBindings={settings.resetAllKeyBindings}
|
||||
setIsHotkeyRecording={settings.setIsHotkeyRecording}
|
||||
@@ -757,6 +749,7 @@ export default function SettingsPage({
|
||||
<I18nProvider locale={settings.uiLanguage}>
|
||||
<SettingsFocusProvider>
|
||||
<SettingsPageContent settings={settings} appLock={appLock} />
|
||||
<ReportRendererReady />
|
||||
</SettingsFocusProvider>
|
||||
</I18nProvider>
|
||||
);
|
||||
|
||||
@@ -251,4 +251,11 @@ test("native clipboard paste follows SFTP paste shortcut availability", () => {
|
||||
]),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isSftpNativeClipboardPasteEnabled("pc", [
|
||||
{ id: "sftp-paste", action: "sftpPaste", label: "Paste", mac: "⌘ + V", pc: "F9", category: "sftp" },
|
||||
{ id: "sftp-paste::extra-0", action: "sftpPaste", label: "Paste", mac: "Disabled", pc: "Ctrl + V", category: "sftp", extraOf: "sftp-paste" },
|
||||
]),
|
||||
true,
|
||||
);
|
||||
});
|
||||
+10
-4
@@ -1,7 +1,7 @@
|
||||
import { terminalCwdStore } from '../application/state/terminalCwdStore';
|
||||
import { useTerminalExternalEditor } from '../application/state/useTerminalExternalEditor';
|
||||
import { useTerminalDirectorySession } from '../application/state/useTerminalDirectorySession';
|
||||
import { refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
|
||||
import { getTerminalDirectory, refreshObservedTerminalDirectory, scheduleObservedTerminalDirectoryRefresh } from '../application/state/terminalDirectoryRegistry';
|
||||
import { publishTerminalSelectionTarget } from "../infrastructure/plugins/terminalSelectionRegistry";
|
||||
import { usePluginTerminalSelection } from "../application/state/usePluginTerminalSelection";
|
||||
import { clearTerminalBroadcastUserInput, markTerminalBroadcastUserInput } from "./terminal/runtime/terminalPacedBroadcast";
|
||||
@@ -640,12 +640,18 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
const onTerminalDataCaptureRef = useRef(onTerminalDataCapture);
|
||||
const onSessionExitRef = useRef(onSessionExit);
|
||||
const commandBufferRef = useRef<string>("");
|
||||
const detectCommandPrompt = useCallback((term: XTerm) => {
|
||||
const directory = getTerminalDirectory(sessionId);
|
||||
const macShellCwd = directory?.localPosixSessionId && detectLocalOs(navigator.platform) === "macos"
|
||||
? directory.getConfirmedCwd() : null;
|
||||
return detectPrompt(term, macShellCwd);
|
||||
}, [sessionId]);
|
||||
useEffect(() => registerTerminalCommandInjectionReadyReader(
|
||||
sessionId,
|
||||
(options) => {
|
||||
const term = termRef.current;
|
||||
if (!term) return false;
|
||||
const prompt = detectPrompt(term);
|
||||
const prompt = detectCommandPrompt(term);
|
||||
const readiness = {
|
||||
sensitiveInputActive: passwordPromptActiveRef.current,
|
||||
hasLiveTerminal: true,
|
||||
@@ -662,7 +668,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
() => {
|
||||
const term = termRef.current;
|
||||
if (!term) return null;
|
||||
const prompt = detectPrompt(term);
|
||||
const prompt = detectCommandPrompt(term);
|
||||
if (!prompt.isAtPrompt) return null;
|
||||
return {
|
||||
promptText: prompt.promptText,
|
||||
@@ -670,7 +676,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
pendingTypedInput: commandBufferRef.current,
|
||||
};
|
||||
},
|
||||
), [sessionId]);
|
||||
), [sessionId, detectCommandPrompt]);
|
||||
const promptLineBreakStateRef = useRef<PromptLineBreakState>(createPromptLineBreakState());
|
||||
const [hasMouseTracking, setHasMouseTracking] = useState(false);
|
||||
const mouseTrackingRef = useRef(false);
|
||||
|
||||
+48
-31
@@ -1,6 +1,7 @@
|
||||
import { Folder, FolderLock, Lock, Menu, MoreHorizontal, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import { Folder, FolderLock, Lock, Menu, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { activeTabStore, fromEditorTabId, isEditorTabId, toEditorTabId } from '../application/state/activeTabStore';
|
||||
import { applySessionPresentation } from '../application/state/sessionPresentationStore';
|
||||
import { topTabsSessionsEqual } from '../domain/topTabsSessionsEqual';
|
||||
import { isHostTreeWorkTabSurface } from '../application/app/workTabSurface';
|
||||
import { buildTabShortcutNumberById } from '../application/app/tabShortcutTargets';
|
||||
@@ -35,6 +36,8 @@ import { GlobalSftpTransferCenter } from './GlobalSftpTransferCenter';
|
||||
import { TopTabsQuickControls } from './TopTabsQuickControls';
|
||||
import {
|
||||
ActiveTabAutoScroller,
|
||||
formatSessionTopTabLabel,
|
||||
resolveWorkspaceTopTabLabel,
|
||||
EditorTopTab,
|
||||
LogViewTopTab,
|
||||
PluginViewTopTab,
|
||||
@@ -53,6 +56,7 @@ import {
|
||||
scheduleAfterInstantThemeSwitch,
|
||||
scheduleChromeLayoutAnimation,
|
||||
} from '../application/state/useActiveChromeTheme';
|
||||
import { TopTabOverflowMenu, type OverflowTab } from './top-tabs/TopTabOverflowMenu';
|
||||
import { useTopTabLifecycleAnimations } from './top-tabs/useTopTabLifecycleAnimations';
|
||||
|
||||
// Helper styles for Electron drag regions (use type assertion to include non-standard WebkitAppRegion)
|
||||
@@ -191,6 +195,7 @@ interface TopTabsProps {
|
||||
onCopySession: (sessionId: string) => void;
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onRenameWorkspace: (workspaceId: string) => void;
|
||||
@@ -249,6 +254,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
onRenameWorkspace,
|
||||
onCopyWorkspace,
|
||||
@@ -856,6 +862,42 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
}).filter(Boolean);
|
||||
}, [orderedTabs, editorTabMap, pluginViewTabMap, orphanSessionMap, workspaceMap, logViewMap, workspacePaneCounts]);
|
||||
|
||||
const getOverflowTabs = (): OverflowTab[] => {
|
||||
const tabs: OverflowTab[] = [{ id: 'vault', label: 'Vaults' }];
|
||||
if (showSftpTab) tabs.push({ id: 'sftp', label: 'SFTP' });
|
||||
for (const item of orderedTabItems) {
|
||||
if (!item) continue;
|
||||
const { id } = item;
|
||||
switch (item.type) {
|
||||
case 'session':
|
||||
tabs.push({ id, label: formatSessionTopTabLabel(applySessionPresentation(item.session), dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'workspace':
|
||||
tabs.push({ id, label: resolveWorkspaceTopTabLabel(item.workspace, workspaceTabSessions.get(id)?.sessions ?? [], dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'editor': {
|
||||
const editor = item.editorTab;
|
||||
tabs.push({
|
||||
id,
|
||||
label: (editorTabFileNameCounts.get(editor.fileName) ?? 0) > 1 ? editor.remotePath : editor.fileName,
|
||||
activate: editor.placement === 'window' ? () => onFocusEditorWindowTab?.(editor.id) : undefined,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'pluginView':
|
||||
tabs.push({ id, label: item.pluginViewTab.title });
|
||||
break;
|
||||
case 'logView': {
|
||||
const { protocol, hostname } = item.logView.log;
|
||||
const host = protocol === 'local' || hostname === 'localhost' ? t('tabs.logLocal') : hostname;
|
||||
tabs.push({ id, label: `${t('tabs.logPrefix')} ${host}` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return tabs;
|
||||
};
|
||||
|
||||
// Bulk-close menu items shared by session and workspace context menus.
|
||||
// Anchor is the tab the user right-clicked on (matches VSCode/JetBrains UX).
|
||||
const renderBulkCloseItems = useCallback((anchorId: string) => {
|
||||
@@ -992,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession={onDuplicateSession}
|
||||
onCopySessionToNewWindow={onCopySessionToNewWindow}
|
||||
onMoveSessionToNewWindow={onMoveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={onConvertSessionToWorkspace}
|
||||
onEditHost={onEditHost}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
dynamicTabTitleMode={dynamicTabTitleMode}
|
||||
@@ -1210,17 +1253,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
)}
|
||||
|
||||
<div className="relative min-w-0 flex-1 flex app-drag" style={dragRegionStyle}>
|
||||
{/* Left fade mask */}
|
||||
{canScrollLeft && (
|
||||
<div
|
||||
className="absolute left-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to right, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Scrollable container */}
|
||||
<div
|
||||
ref={tabsContainerRef}
|
||||
data-fade-left={canScrollLeft || undefined}
|
||||
data-fade-right={canScrollRight || undefined}
|
||||
className="top-tab-scroll-viewport min-w-0 flex items-end gap-0 overflow-x-auto scrollbar-none app-no-drag max-w-full"
|
||||
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none', ...noDragRegionStyle }}
|
||||
onClick={handleScrollableTabClick}
|
||||
@@ -1255,14 +1292,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* Keep unused space and the drag handle outside the scroll viewport's exclusion. */}
|
||||
<div className="flex-1 app-drag" style={dragRegionStyle} />
|
||||
<div className="min-w-[20px] h-7 app-drag flex-shrink-0 self-end" style={dragRegionStyle} />
|
||||
|
||||
{/* Right fade mask */}
|
||||
{canScrollRight && (
|
||||
<div
|
||||
className="absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to left, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -1270,20 +1299,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* More tabs button - only when overflowing */}
|
||||
{hasOverflow && (
|
||||
<div className="contents" data-section="top-tabs-toolbar-actions">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 flex-shrink-0 app-no-drag self-end rounded-none"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
onClick={onOpenQuickSwitcher}
|
||||
>
|
||||
<MoreHorizontal size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('topTabs.moreTabs')}</TooltipContent>
|
||||
</Tooltip>
|
||||
<TopTabOverflowMenu getTabs={getOverflowTabs} onOpenQuickSwitcher={onOpenQuickSwitcher} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1391,6 +1407,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onCopySession === next.onCopySession &&
|
||||
prev.onDuplicateSession === next.onDuplicateSession &&
|
||||
prev.onCopySessionToNewWindow === next.onCopySessionToNewWindow &&
|
||||
prev.onConvertSessionToWorkspace === next.onConvertSessionToWorkspace &&
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
|
||||
@@ -16,7 +16,7 @@ import { getEffectiveKnownHosts } from "../infrastructure/syncHelpers";
|
||||
import { PortForwardHostKeyTrayPrompt } from "./port-forwarding";
|
||||
import { X, Maximize2, ChevronRight, ChevronDown, Power } from "lucide-react";
|
||||
import { AppLogo } from "./AppLogo";
|
||||
import type { AppLockGateRenderContext } from "./AppLockGate";
|
||||
import { ReportRendererReady, type AppLockGateRenderContext } from "./AppLockGate";
|
||||
|
||||
const StatusDot: React.FC<{ status: "success" | "warning" | "error" | "neutral"; spinning?: boolean }> = ({
|
||||
status,
|
||||
@@ -505,6 +505,7 @@ const TrayPanel: React.FC<{ settings: SettingsState }> = ({ settings }) => {
|
||||
return (
|
||||
<I18nProvider locale={settings.uiLanguage}>
|
||||
<TrayPanelContent />
|
||||
<ReportRendererReady />
|
||||
</I18nProvider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -391,10 +391,16 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
() => pluginVault.pages.map((page) => page.key),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const pluginOwnerByNavId = useMemo(
|
||||
() => Object.fromEntries(pluginVault.pages.map((page) => [page.key, page.pluginId])),
|
||||
[pluginVault.pages],
|
||||
);
|
||||
const vaultNavConfig = useVaultNavConfig({
|
||||
activePluginIds: activePluginNavIds,
|
||||
pluginsLoading: pluginVault.contributions.loading,
|
||||
pluginsAvailable: pluginVault.contributions.available,
|
||||
installedPluginIds: pluginVault.installedPluginIds,
|
||||
pluginOwnerByNavId,
|
||||
});
|
||||
const previousHiddenNavRef = useRef<ReadonlySet<VaultNavItemId>>(vaultNavConfig.hiddenSet);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
|
||||
test('a completed reply has file actions but a streaming reply does not', () => {
|
||||
const content = '```netcatty-file\n{"name":"report.md","content":"# Example content"}\n```';
|
||||
const render = (isAnimating: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en"><ChatFileReply content={content} isAnimating={isAnimating} /></I18nProvider>,
|
||||
);
|
||||
const completed = render(false);
|
||||
assert.match(completed, /data-chat-text-file/);
|
||||
assert.match(completed, /report\.md/);
|
||||
assert.match(completed, /Save as/);
|
||||
assert.match(completed, /Preview/);
|
||||
assert.doesNotMatch(completed, /# Example content/);
|
||||
assert.doesNotMatch(render(true), /data-chat-text-file/);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Download, FileText } from 'lucide-react';
|
||||
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { saveDeliveredChatTextFile } from '../../application/state/chatTextFileDelivery';
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { splitChatTextFileOffers } from '../../domain/chatTextFileOffers';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
|
||||
const previewLimit = 32 * 1024;
|
||||
|
||||
function ChatFileOffer({ file }: { file: ChatTextFile }) {
|
||||
const { t } = useI18n();
|
||||
const [preview, setPreview] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [status, setStatus] = useState<'saved' | 'exists' | 'failed' | 'unavailable'>();
|
||||
const saveFile = async () => {
|
||||
setStatus(undefined);
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await saveDeliveredChatTextFile(file);
|
||||
if (result !== 'cancelled') setStatus(result);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="my-2 min-w-0 rounded-md border border-border bg-muted/35 px-3 py-2" data-chat-text-file>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 items-start gap-2 text-sm">
|
||||
<FileText size={16} aria-hidden="true" className="mt-0.5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0">
|
||||
<div className="break-all font-semibold">{file.name}</div>
|
||||
<div className="text-muted-foreground">{t('ai.chat.deliveredTextFile.source')}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="rounded px-1 py-0.5 text-sm underline focus-visible:outline-2 focus-visible:outline-ring"
|
||||
aria-expanded={preview} onClick={() => setPreview(value => !value)}
|
||||
>{t(`ai.chat.deliveredTextFile.${preview ? 'hidePreview' : 'preview'}`)}</button>
|
||||
<button type="button" className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-60"
|
||||
disabled={saving} onClick={() => { void saveFile(); }}
|
||||
><Download size={14} aria-hidden="true" />{t(`ai.chat.deliveredTextFile.${saving ? 'saving' : 'save'}`)}</button>
|
||||
</div>
|
||||
{status && <p role="status" className="mt-2 text-sm">{t(`ai.chat.deliveredTextFile.${status}`)}</p>}
|
||||
{preview && (
|
||||
<>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm border border-border bg-background px-2 py-1 font-mono text-xs">{file.content.slice(0, previewLimit)}</pre>
|
||||
{file.content.length > previewLimit && <p className="mt-1 text-sm text-muted-foreground">{t('ai.chat.deliveredTextFile.previewPartial')}</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatFileReply({ content, isAnimating }: { content: string; isAnimating?: boolean }) {
|
||||
const parsed = useMemo(() => isAnimating ? null : splitChatTextFileOffers(content), [content, isAnimating]);
|
||||
if (!parsed?.files.length) return <LazyMessageResponse isAnimating={isAnimating}>{content}</LazyMessageResponse>;
|
||||
return (
|
||||
<>
|
||||
{parsed.markdown.trim() && <LazyMessageResponse>{parsed.markdown}</LazyMessageResponse>}
|
||||
{parsed.files.map((file, index) => <ChatFileOffer key={`${index}:${file.name}`} file={file} />)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ test('first keystrokes stay local so IME and Chromium spellcheck cannot stall th
|
||||
assert.match(source, /autoCapitalize="off"/);
|
||||
assert.match(source, /nativeEvent\.isComposing/);
|
||||
assert.match(source, /onCompositionEnd=/);
|
||||
assert.match(source, /onBlur=\{\(\) => commitComposerText\(readComposerText\(\)\)\}/);
|
||||
assert.match(source, /onBlur=\{syncUncommittedComposerText\}/);
|
||||
assert.match(source, /onChangeRef\.current\(textareaRef\.current\?\.value \?\? composerTextRef\.current\)/);
|
||||
assert.doesNotMatch(source, /onSend\(\);\s*commitComposerText\(''\);/);
|
||||
assert.match(source, /defaultValue=\{value\}/);
|
||||
@@ -425,4 +425,7 @@ test('valueRevision clears the uncontrolled textarea even when value stays empty
|
||||
assert.match(sidePanelSource, /setComposerValueRevision\(\(rev\) => rev \+ 1\)/);
|
||||
assert.match(sidePanelSource, /inputValueRevision=\{composerValueRevision\}/);
|
||||
assert.match(contentSource, /valueRevision=\{inputValueRevision\}/);
|
||||
assert.match(chatInputSource, /useLayoutEffect\(\(\) => \{\s*const revisionChanged = valueRevision !== lastValueRevisionRef\.current/);
|
||||
assert.match(chatInputSource, /onBlur=\{syncUncommittedComposerText\}/);
|
||||
assert.match(sidePanelSource, /const keepPendingText = pending != null && pending !== submittedText;/);
|
||||
});
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
type UserSkillSlashOption,
|
||||
} from '../../infrastructure/ai/quickMessages';
|
||||
import { SlashCommandPicker } from './SlashCommandPicker';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { createPortal } from 'react-dom';
|
||||
import type { FormEvent } from 'react';
|
||||
@@ -263,6 +263,7 @@ interface ChatInputProps {
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean; protocol?: string }>;
|
||||
/** Explicit signal that the active tab/scope is a VNC or RDP remote desktop. */
|
||||
isRemoteDesktopContext?: boolean;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
/** Optional handler invoked when a remote desktop quick prompt chip is clicked. */
|
||||
onSendQuickPrompt?: (promptText: string) => void;
|
||||
/** Force-show remote desktop quick prompt chips (auto-shown when a remote screen image is attached). */
|
||||
@@ -342,6 +343,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
hosts = [],
|
||||
isRemoteDesktopContext = false,
|
||||
onSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
showRemoteScreenQuickPrompts,
|
||||
notes = [],
|
||||
onMentionNote,
|
||||
@@ -556,7 +558,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
), []);
|
||||
|
||||
const lastValueRevisionRef = useRef(valueRevision);
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
const revisionChanged = valueRevision !== lastValueRevisionRef.current;
|
||||
lastValueRevisionRef.current = valueRevision;
|
||||
if (!revisionChanged && value === pushedParentTextRef.current) return;
|
||||
@@ -578,13 +580,20 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
onChange(next);
|
||||
}, [onChange, syncHasComposerText]);
|
||||
|
||||
const syncUncommittedComposerText = useCallback(() => {
|
||||
const current = readComposerText();
|
||||
if (current !== pushedParentTextRef.current) {
|
||||
commitComposerText(current);
|
||||
}
|
||||
}, [commitComposerText, readComposerText]);
|
||||
|
||||
const parkedRef = useRef(parked);
|
||||
useEffect(() => {
|
||||
const becameParked = parked && !parkedRef.current;
|
||||
parkedRef.current = parked;
|
||||
if (!becameParked) return;
|
||||
commitComposerText(readComposerText());
|
||||
}, [commitComposerText, parked, readComposerText]);
|
||||
syncUncommittedComposerText();
|
||||
}, [parked, syncUncommittedComposerText]);
|
||||
|
||||
const onChangeRef = useRef(onChange);
|
||||
onChangeRef.current = onChange;
|
||||
@@ -1416,7 +1425,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
setAiComposerComposing(false);
|
||||
handleInputChange(e.currentTarget.value);
|
||||
}}
|
||||
onBlur={() => commitComposerText(readComposerText())}
|
||||
onBlur={syncUncommittedComposerText}
|
||||
onKeyDown={handleTextareaKeyDown}
|
||||
placeholder={placeholder || (isStreaming && canSteer ? t('ai.codex.steer.placeholder') : defaultPlaceholder)}
|
||||
disabled={composerDisabled}
|
||||
@@ -1682,6 +1691,22 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
<span className="flex-1 text-foreground/85">{t('ai.chat.menuMentionHost')}</span>
|
||||
{hosts.length > 0 && <ChevronRight size={10} className="text-muted-foreground/50" />}
|
||||
</button>
|
||||
{onSendWithGrokMode && (
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
disabled={composerDisabled || isStreaming || (!hasTextStore.get() && !hasTerminalSelectionAttachment && !hasImageAttachment)}
|
||||
onClick={() => {
|
||||
const text = readComposerText();
|
||||
closeAllMenus();
|
||||
onSendWithGrokMode(text);
|
||||
}}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 cursor-pointer whitespace-nowrap disabled:opacity-40"
|
||||
>
|
||||
<MessageSquare size={13} className="text-muted-foreground/60" />
|
||||
{t('ai.grok.chooseModeAndSend')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@@ -2019,6 +2044,7 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
|
||||
&& prev.onRemoveFile === next.onRemoveFile
|
||||
&& prev.hosts === next.hosts
|
||||
&& prev.isRemoteDesktopContext === next.isRemoteDesktopContext
|
||||
&& prev.onSendWithGrokMode === next.onSendWithGrokMode
|
||||
&& prev.onSendQuickPrompt === next.onSendQuickPrompt
|
||||
&& prev.showRemoteScreenQuickPrompts === next.showRemoteScreenQuickPrompts
|
||||
&& prev.notes === next.notes
|
||||
|
||||
@@ -7,7 +7,7 @@ import { act, create, type ReactTestRenderer } from "react-test-renderer";
|
||||
|
||||
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
|
||||
import type { ChatMessage } from "../../infrastructure/ai/types.ts";
|
||||
import type { ApprovalRequest } from "../../infrastructure/ai/shared/approvalGate.ts";
|
||||
import { setupMcpApprovalBridge, type ApprovalRequest } from "../../infrastructure/ai/shared/approvalGate.ts";
|
||||
import ChatMessageList, {
|
||||
buildCodexApprovalRenderPlan,
|
||||
pruneResolvedApprovals,
|
||||
@@ -629,6 +629,59 @@ test("Codex approval render plan preserves every approval for the same item", ()
|
||||
);
|
||||
});
|
||||
|
||||
test("plan review shows the complete plan only in its chat and approves once", async t => {
|
||||
const previousWindow = globalThis.window;
|
||||
const actGlobal = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
|
||||
const previousActEnvironment = actGlobal.IS_REACT_ACT_ENVIRONMENT;
|
||||
type WireReview = { approvalId: string; chatSessionId: string; toolName: string;
|
||||
args: { plan: string }; interactionKind: 'plan-review'; allowSession: false };
|
||||
let receive!: (review: WireReview) => void;
|
||||
let clear!: (event: { approvalIds: string[] }) => void;
|
||||
const responses: unknown[][] = [];
|
||||
globalThis.window = {
|
||||
setTimeout, clearTimeout,
|
||||
netcatty: {
|
||||
onMcpApprovalRequest: (cb: typeof receive) => { receive = cb; return () => {}; },
|
||||
onMcpApprovalCleared: (cb: typeof clear) => { clear = cb; return () => {}; },
|
||||
respondMcpApproval: async (...args: unknown[]) => {
|
||||
responses.push(args); return { ok: true, accepted: true };
|
||||
},
|
||||
},
|
||||
} as unknown as Window & typeof globalThis;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = true;
|
||||
const unsubscribe = setupMcpApprovalBridge();
|
||||
t.after(() => {
|
||||
clear({ approvalIds: ['mcp_approval_review_1', 'mcp_approval_review_2'] });
|
||||
unsubscribe();
|
||||
globalThis.window = previousWindow;
|
||||
actGlobal.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
|
||||
});
|
||||
let renderer!: ReactTestRenderer;
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
<I18nProvider locale="en"><TooltipProvider>
|
||||
<ChatMessageList messages={[makeMessage(1)]} activeSessionId="chat-1" isStreaming />
|
||||
</TooltipProvider></I18nProvider>,
|
||||
);
|
||||
for (const index of [1, 2]) receive({
|
||||
approvalId: `mcp_approval_review_${index}`, chatSessionId: `chat-${index}`,
|
||||
toolName: 'Grok plan review', args: { plan: `# Proposed steps ${index}\nNo changes yet` },
|
||||
interactionKind: 'plan-review', allowSession: false,
|
||||
});
|
||||
});
|
||||
const [card, ...otherCards] = renderer.root.findAllByType('section')
|
||||
.filter(node => node.props['aria-label'] === 'Review implementation plan');
|
||||
assert.ok(card);
|
||||
assert.equal(otherCards.length, 0);
|
||||
assert.match(JSON.stringify(card.findByProps({ tabIndex: 0 }).children), /Proposed steps 1/);
|
||||
const buttons = card.findAllByType('button');
|
||||
assert.deepEqual(buttons.map(button => button.children.join('')), ['Keep planning', 'Approve and implement']);
|
||||
assert.deepEqual(responses, []);
|
||||
await act(async () => { buttons[1].props.onClick(); });
|
||||
assert.deepEqual(responses, [['mcp_approval_review_1', true, 'once']]);
|
||||
await act(async () => { renderer.unmount(); });
|
||||
});
|
||||
|
||||
test('fork is offered only for safe completed replies and hidden while streaming', () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ id: 'u', role: 'user', content: 'hello', timestamp: 1 },
|
||||
|
||||
@@ -12,12 +12,13 @@ import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { AISessionContextCompaction, ChatMessage, ToolCall as AgentToolCall } from '../../infrastructure/ai/types';
|
||||
import { getForkableMessageIds } from '../../domain/aiSessionFork';
|
||||
import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
|
||||
import { Button } from '../ui/button';
|
||||
import {
|
||||
Conversation,
|
||||
ConversationContent,
|
||||
ConversationScrollButton,
|
||||
} from '../ai-elements/conversation';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
import { Message, MessageContent } from '../ai-elements/messageShell';
|
||||
import { warmAiMarkdownRenderer } from './aiMarkdownWarmup';
|
||||
import { ToolCall } from '../ai-elements/tool-call';
|
||||
@@ -832,9 +833,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
: (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Markdown')}>
|
||||
<div data-ai-content="markdown">
|
||||
<LazyMessageResponse isAnimating={!!isThisStreaming}>
|
||||
{message.content}
|
||||
</LazyMessageResponse>
|
||||
<ChatFileReply content={message.content} isAnimating={!!isThisStreaming} />
|
||||
</div>
|
||||
</React.Profiler>
|
||||
)
|
||||
@@ -946,6 +945,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
{!hideToolCalls && Array.from(pendingApprovals.entries())
|
||||
.filter(([id, req]) => {
|
||||
if (!id.startsWith('mcp_approval_')) return false;
|
||||
if (req.interactionKind === 'plan-review') return false;
|
||||
// External MCP approvals render in ExternalMcpApprovalsHost so they
|
||||
// remain visible even when the Catty AI panel is closed.
|
||||
if (req.chatSessionId === '__external_mcp__') return false;
|
||||
@@ -977,6 +977,26 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
);
|
||||
})}
|
||||
|
||||
{Array.from(pendingApprovals.entries())
|
||||
.filter(([, request]) => request.interactionKind === 'plan-review'
|
||||
&& activeSessionId && request.chatSessionId === activeSessionId)
|
||||
.map(([id, request]) => (
|
||||
<section key={id} aria-label={t('ai.planReview.title')} className="min-w-0 space-y-2 rounded-md border border-border bg-card p-3">
|
||||
<h3 className="text-xs font-semibold">{t('ai.planReview.title')}</h3>
|
||||
<div tabIndex={0} className="max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm bg-muted/50 p-2 text-xs leading-relaxed focus-visible:outline focus-visible:outline-ring">
|
||||
{typeof request.args.plan === 'string' ? request.args.plan : null}
|
||||
</div>
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => handleReject(id)}>
|
||||
{t('ai.planReview.keepPlanning')}
|
||||
</Button>
|
||||
<Button type="button" size="sm" onClick={() => handleApproveOnce(id)}>
|
||||
{t('ai.planReview.approveAndImplement')}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
{!hideToolCalls && standaloneCodexApprovals
|
||||
.map(({ approvalId, request }) => (
|
||||
<React.Profiler key={approvalId} {...getAIPanelProfilerProps('AIChatPanel.ToolCall.Approval')}>
|
||||
@@ -1013,7 +1033,8 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
/>
|
||||
))}
|
||||
{(Array.from(pendingCodebuddyElicitations.values()) as CodebuddyElicitation[])
|
||||
.filter((elicitation) => !activeSessionId || elicitation.chatSessionId === activeSessionId)
|
||||
.filter((elicitation) => elicitation.chatSessionId === activeSessionId
|
||||
|| (!activeSessionId && !elicitation.request.source))
|
||||
.map((elicitation) => (
|
||||
<CodebuddyElicitationCard
|
||||
key={`${elicitation.elicitationId}:${elicitation.requestInstanceId ?? 0}`}
|
||||
|
||||
@@ -51,6 +51,50 @@ test('CodebuddyElicitationCard renders MCP form fields and response actions', ()
|
||||
assert.doesNotMatch(markup, /role="alert"/);
|
||||
});
|
||||
|
||||
test('the same form displays Grok questions without an action approval', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<I18nProvider locale="en"><CodebuddyElicitationCard
|
||||
elicitation={{ elicitationId: 'grok-1', chatSessionId: 'chat-1', request: {
|
||||
source: 'grok', requestedSchema: {
|
||||
type: 'object', required: ['q0'], properties: {
|
||||
q0: { type: 'string', title: 'Which color?', oneOf: [{ const: '0', title: 'Blue' }] },
|
||||
},
|
||||
},
|
||||
} }}
|
||||
onRespond={async () => {}}
|
||||
/></I18nProvider>,
|
||||
);
|
||||
assert.match(markup, /Grok needs your input/);
|
||||
assert.match(markup, /Which color\?/);
|
||||
assert.match(markup, /<option value="variant:0">Blue<\/option>/);
|
||||
assert.match(markup, /Send answers/);
|
||||
assert.doesNotMatch(markup, /Decline|Approve|CodeBuddy needs/);
|
||||
});
|
||||
|
||||
test('Grok text questions keep submission disabled for whitespace and cleared answers', async () => {
|
||||
let renderer!: ReactTestRenderer;
|
||||
await act(async () => { renderer = create(
|
||||
<I18nProvider locale="en"><CodebuddyElicitationCard
|
||||
elicitation={{ elicitationId: 'grok-text', chatSessionId: 'chat-1', request: {
|
||||
source: 'grok', requestedSchema: { type: 'object', required: ['q0'],
|
||||
properties: { q0: { type: 'string', title: 'Note', minLength: 1, maxLength: 2000 } } },
|
||||
} }}
|
||||
onRespond={async () => {}}
|
||||
/></I18nProvider>,
|
||||
); });
|
||||
const submit = () => renderer.root.findAllByType('button').find(button => button.children.includes('Send answers'))!;
|
||||
const change = async (value: string) => act(async () => {
|
||||
renderer.root.findByType('input').props.onChange({ target: { value } });
|
||||
});
|
||||
await change('valid');
|
||||
assert.equal(submit().props.disabled, false);
|
||||
await change(' \t ');
|
||||
assert.equal(submit().props.disabled, true);
|
||||
await change('');
|
||||
assert.equal(submit().props.disabled, true);
|
||||
await act(async () => renderer.unmount());
|
||||
});
|
||||
|
||||
test('CodebuddyElicitationCard renders constraint errors and blocks submission', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<I18nProvider locale="en">
|
||||
|
||||
@@ -56,7 +56,13 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const validationIssues = validateCodebuddyElicitationValues(fields, values);
|
||||
const isGrokQuestion = elicitation.request.source === 'grok';
|
||||
const isNativeQuestion = Boolean(elicitation.request.source);
|
||||
const formValues = isNativeQuestion
|
||||
? Object.fromEntries(Object.entries(values).map(([id, value]) =>
|
||||
[id, typeof value === 'string' ? value.trim() : value]))
|
||||
: values;
|
||||
const validationIssues = validateCodebuddyElicitationValues(fields, formValues);
|
||||
const validationByField = new Map(
|
||||
validationIssues.map((validationIssue) => [validationIssue.fieldId, validationIssue]),
|
||||
);
|
||||
@@ -91,9 +97,12 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
<div className="flex items-start gap-2">
|
||||
<MessageCircleQuestion size={16} className="mt-0.5 shrink-0 text-blue-500" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t('ai.codebuddy.elicitation.title')}</div>
|
||||
<div className="text-sm font-medium">{t(isGrokQuestion ? 'ai.grok.userQuestion.title'
|
||||
: elicitation.request.source === 'opencode-native' ? 'ai.opencode.userQuestion.title'
|
||||
: 'ai.codebuddy.elicitation.title')}</div>
|
||||
<div className="text-xs text-muted-foreground leading-5">
|
||||
{elicitation.request.message || t('ai.codebuddy.elicitation.description')}
|
||||
{elicitation.request.message || t(isNativeQuestion
|
||||
? 'ai.grok.userQuestion.description' : 'ai.codebuddy.elicitation.description')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -249,23 +258,23 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
{!isNativeQuestion && <Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={submitting}
|
||||
onClick={() => void respond('decline')}
|
||||
>
|
||||
{t('ai.codebuddy.elicitation.decline')}
|
||||
</Button>
|
||||
</Button>}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={submitting || !complete}
|
||||
onClick={() => void respond(
|
||||
'accept',
|
||||
buildCodebuddyElicitationContent(values, fields),
|
||||
buildCodebuddyElicitationContent(formValues, fields),
|
||||
)}
|
||||
>
|
||||
{t('ai.codebuddy.elicitation.accept')}
|
||||
{t(isNativeQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -566,9 +566,16 @@ test("subtitle styling keeps agent label emphasized and message count normal whe
|
||||
}
|
||||
});
|
||||
|
||||
test("selection mode batches delete and title regeneration without activating rows", async () => {
|
||||
test("selection mode is triggered from the drawer overflow menu, confirms bulk delete, and supports Cancel/Escape/tab exit", async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const restoreGlobals = installRadixGlobals(dom);
|
||||
try {
|
||||
const { SessionHistoryDrawer } = await import("../AIChatSessionHistoryDrawer.tsx");
|
||||
const { GlobalAIChatSessionManager } = await import("./GlobalAIChatSessionManager.tsx");
|
||||
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("../ui/tooltip.tsx");
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
|
||||
const props = baseProps();
|
||||
props.sessions = [
|
||||
makeSession({ id: "s-a", title: "A" }),
|
||||
@@ -581,30 +588,141 @@ test("selection mode batches delete and title regeneration without activating ro
|
||||
props.onRegenerateTitle = (id) => regenerated.push(id);
|
||||
props.onSelect = (id) => activated.push(id);
|
||||
|
||||
const renderer = await renderManager(dom, props);
|
||||
const toggle = renderer.container.querySelector<HTMLElement>(
|
||||
`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`,
|
||||
await renderer.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<SessionHistoryDrawer
|
||||
sessions={props.sessions}
|
||||
activeSessionId="s-a"
|
||||
onSelect={() => {}}
|
||||
onDelete={() => {}}
|
||||
onExportSessions={() => {}}
|
||||
onClose={() => {}}
|
||||
globalManager={<GlobalAIChatSessionManager {...props} />}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
assert.ok(toggle, "selection toggle present");
|
||||
await dispatchDomEvent(toggle, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
|
||||
// Clicking rows toggles selection instead of opening the chat.
|
||||
const openHeaderMenu = async () => {
|
||||
const trigger = renderer.container.querySelector<HTMLButtonElement>(
|
||||
`button[aria-label="${t("ai.chat.managerMoreActions")}"]`,
|
||||
);
|
||||
assert.ok(trigger, "drawer overflow trigger present");
|
||||
await dispatchDomEvent(trigger, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
};
|
||||
|
||||
// On the default "Current chats" tab, "Select chats" is not shown in the overflow menu.
|
||||
await openHeaderMenu();
|
||||
const scopedSelectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
|
||||
assert.equal(scopedSelectItem, undefined, "Select chats is hidden on current tab");
|
||||
// Close header menu before switching tabs.
|
||||
await openHeaderMenu();
|
||||
|
||||
// Switch to the "All chats" tab.
|
||||
const tabs = renderer.container.querySelectorAll<HTMLButtonElement>('[role="tab"]');
|
||||
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
|
||||
// Search/filter bar must not contain an inline selection toggle button.
|
||||
const manager = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
|
||||
assert.equal(
|
||||
manager.querySelector(`button[aria-label="${t("ai.chat.managerToggleSelection")}"]`),
|
||||
null,
|
||||
"no standalone selection button in filter bar",
|
||||
);
|
||||
|
||||
// Trigger selection mode from the drawer's top-right overflow menu.
|
||||
await openHeaderMenu();
|
||||
const selectItem = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"));
|
||||
assert.ok(selectItem, "Select chats menu item present on All chats tab");
|
||||
await dispatchDomEvent(selectItem, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.ok(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
"selection action bar opens",
|
||||
);
|
||||
|
||||
// Clicking Cancel exits selection mode cleanly.
|
||||
const cancelBtn = Array.from(
|
||||
manager.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.trim() === t("common.cancel"));
|
||||
assert.ok(cancelBtn, "Cancel button present in selection bar");
|
||||
await dispatchDomEvent(cancelBtn, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.equal(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"Cancel exits selection mode",
|
||||
);
|
||||
|
||||
// Re-enter selection mode, verify Escape exits, then re-enter for bulk actions.
|
||||
await openHeaderMenu();
|
||||
const selectItem2 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItem2, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
assert.equal(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"Escape exits selection mode",
|
||||
);
|
||||
|
||||
// Switching back to "Current chats" and returning to "All chats" clears selection mode.
|
||||
await openHeaderMenu();
|
||||
const selectItemTab = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItemTab, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.ok(
|
||||
manager.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
"selection bar open before tab switch",
|
||||
);
|
||||
await dispatchDomEvent(tabs[0], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(tabs[1], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
const managerAfterTabSwitch = renderer.container.querySelector('[data-section="ai-global-session-manager"]')!;
|
||||
assert.equal(
|
||||
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"switching away from All chats resets selection mode",
|
||||
);
|
||||
|
||||
await openHeaderMenu();
|
||||
const selectItem3 = Array.from(dom.document.body.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.trim() === t("ai.chat.managerToggleSelection"))!;
|
||||
await dispatchDomEvent(selectItem3, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
|
||||
// Clicking and keyboard-activating rows toggles selection instead of opening the chat.
|
||||
await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(rows(renderer)[1], new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await dispatchDomEvent(rows(renderer)[1], new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
|
||||
assert.deepEqual(activated, []);
|
||||
|
||||
const bulkRegen = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
|
||||
const bulkRegen = Array.from(
|
||||
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.includes(t("ai.chat.managerRegenerateTitle")));
|
||||
assert.ok(bulkRegen, "bulk regenerate button present");
|
||||
await dispatchDomEvent(bulkRegen, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.deepEqual(regenerated.sort(), ["s-a", "s-b"]);
|
||||
|
||||
const bulkDelete = Array.from(renderer.container.querySelectorAll<HTMLButtonElement>("button"))
|
||||
.find((b) => b.textContent?.includes(t("common.delete")));
|
||||
// Bulk delete is confirm-gated.
|
||||
const bulkDelete = Array.from(
|
||||
managerAfterTabSwitch.querySelectorAll<HTMLButtonElement>('[data-section="ai-global-session-selection-bar"] button'),
|
||||
).find((b) => b.textContent?.includes(t("common.delete")));
|
||||
assert.ok(bulkDelete, "bulk delete button present");
|
||||
await dispatchDomEvent(bulkDelete, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
assert.deepEqual(deletedMany, [], "no bulk deletion before confirmation");
|
||||
|
||||
const confirmButton = dom.document.body.querySelector<HTMLButtonElement>("button.bg-destructive");
|
||||
assert.ok(confirmButton, "destructive confirm button rendered for bulk delete");
|
||||
await dispatchDomEvent(confirmButton, new dom.window.MouseEvent("click", { bubbles: true }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
assert.deepEqual(deletedMany, [["s-a", "s-b"]]);
|
||||
assert.equal(
|
||||
managerAfterTabSwitch.querySelector('[data-section="ai-global-session-selection-bar"]'),
|
||||
null,
|
||||
"selection mode exits after confirmed bulk delete",
|
||||
);
|
||||
} finally {
|
||||
restoreGlobals();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { CheckSquare, Download, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Square, Trash2, X } from 'lucide-react';
|
||||
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
} from '../ui/select';
|
||||
import { ConfirmDialog } from '../ui/confirm-dialog';
|
||||
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
|
||||
import { GlobalSessionSelectionContext } from './sessionHistorySelectionContext';
|
||||
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
|
||||
import {
|
||||
buildGlobalManagerRows,
|
||||
@@ -58,8 +59,13 @@ interface GlobalAIChatSessionManagerProps {
|
||||
onDelete: (sessionId: string) => void;
|
||||
onDeleteMany?: (sessionIds: string[]) => void;
|
||||
/** Re-run LLM title generation for an existing chat (no placeholder gate). */
|
||||
onRegenerateTitle?: (sessionId: string) => void;
|
||||
onRegenerateTitle?: (sessionId: string) => void | Promise<unknown>;
|
||||
/** Batch re-run LLM title generation for multiple selected chats. */
|
||||
onRegenerateTitles?: (sessionIds: string[]) => void | Promise<unknown>;
|
||||
onExport: (sessionId: string) => void;
|
||||
/** Optional controlled selection mode; falls back to SessionHistoryDrawer context. */
|
||||
selectionMode?: boolean;
|
||||
onSelectionModeChange?: (active: boolean) => void;
|
||||
}
|
||||
|
||||
const MANAGER_RENDER_BATCH = 80;
|
||||
@@ -83,21 +89,44 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
onDelete,
|
||||
onDeleteMany,
|
||||
onRegenerateTitle,
|
||||
onRegenerateTitles,
|
||||
onExport,
|
||||
selectionMode: controlledSelectionMode,
|
||||
onSelectionModeChange,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const selectionContext = useContext(GlobalSessionSelectionContext);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [agentFilter, setAgentFilter] = useState<string>('all');
|
||||
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
|
||||
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
|
||||
const [bulkDeleteConfirmOpen, setBulkDeleteConfirmOpen] = useState(false);
|
||||
const [moveSession, setMoveSession] = useState<AISession | null>(null);
|
||||
const [openMenuSessionId, setOpenMenuSessionId] = useState<string | null>(null);
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState(false);
|
||||
const [uncontrolledSelectionMode, setUncontrolledSelectionMode] = useState(false);
|
||||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||
const [regeneratingIds, setRegeneratingIds] = useState<Set<string>>(new Set());
|
||||
const [renameDraft, setRenameDraft] = useState('');
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const selectionMode =
|
||||
controlledSelectionMode ?? selectionContext?.selectionMode ?? uncontrolledSelectionMode;
|
||||
const setSelectionMode = useCallback(
|
||||
(active: boolean) => {
|
||||
if (controlledSelectionMode !== undefined) {
|
||||
onSelectionModeChange?.(active);
|
||||
} else if (selectionContext) {
|
||||
selectionContext.setSelectionMode(active);
|
||||
onSelectionModeChange?.(active);
|
||||
} else {
|
||||
setUncontrolledSelectionMode(active);
|
||||
onSelectionModeChange?.(active);
|
||||
}
|
||||
},
|
||||
[controlledSelectionMode, onSelectionModeChange, selectionContext],
|
||||
);
|
||||
|
||||
const rows = useMemo(
|
||||
() => buildGlobalManagerRows({
|
||||
sessions,
|
||||
@@ -136,6 +165,26 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
if (renamingSessionId) renameInputRef.current?.focus();
|
||||
}, [renamingSessionId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode) {
|
||||
setSelectedIds(new Set());
|
||||
setBulkDeleteConfirmOpen(false);
|
||||
}
|
||||
}, [selectionMode]);
|
||||
|
||||
const rowSessionIds = useMemo(
|
||||
() => new Set(rows.map((row) => row.session.id)),
|
||||
[rows],
|
||||
);
|
||||
const activeSelectedIds = useMemo(() => {
|
||||
if (selectedIds.size === 0) return selectedIds;
|
||||
const next = new Set<string>();
|
||||
selectedIds.forEach((id) => {
|
||||
if (rowSessionIds.has(id)) next.add(id);
|
||||
});
|
||||
return next;
|
||||
}, [selectedIds, rowSessionIds]);
|
||||
|
||||
const displayedRows = filteredRows.slice(0, renderCount);
|
||||
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
|
||||
|
||||
@@ -166,10 +215,24 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
return next;
|
||||
});
|
||||
};
|
||||
const exitSelectionMode = () => {
|
||||
const exitSelectionMode = useCallback(() => {
|
||||
setSelectionMode(false);
|
||||
setSelectedIds(new Set());
|
||||
};
|
||||
setBulkDeleteConfirmOpen(false);
|
||||
}, [setSelectionMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectionMode || bulkDeleteConfirmOpen || renamingSessionId) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
exitSelectionMode();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [selectionMode, bulkDeleteConfirmOpen, renamingSessionId, exitSelectionMode]);
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
const visibleIds = displayedRows.map((row) => row.session.id);
|
||||
setSelectedIds((prev) => {
|
||||
@@ -178,15 +241,49 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
});
|
||||
};
|
||||
const commitBulkDelete = () => {
|
||||
if (selectedIds.size === 0) return;
|
||||
const ids = [...selectedIds];
|
||||
if (activeSelectedIds.size === 0) return;
|
||||
const ids = [...activeSelectedIds];
|
||||
if (onDeleteMany) onDeleteMany(ids);
|
||||
else ids.forEach((id) => onDelete(id));
|
||||
exitSelectionMode();
|
||||
};
|
||||
const runSingleRegenerate = useCallback((sessionId: string) => {
|
||||
if (!onRegenerateTitle) return;
|
||||
setRegeneratingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.add(sessionId);
|
||||
return next;
|
||||
});
|
||||
void Promise.resolve(onRegenerateTitle(sessionId)).finally(() => {
|
||||
setRegeneratingIds((prev) => {
|
||||
if (!prev.has(sessionId)) return prev;
|
||||
const next = new Set(prev);
|
||||
next.delete(sessionId);
|
||||
return next;
|
||||
});
|
||||
});
|
||||
}, [onRegenerateTitle]);
|
||||
|
||||
const commitBulkRegenerate = () => {
|
||||
if (!onRegenerateTitle || selectedIds.size === 0) return;
|
||||
selectedIds.forEach((id) => onRegenerateTitle(id));
|
||||
if ((!onRegenerateTitles && !onRegenerateTitle) || activeSelectedIds.size === 0) return;
|
||||
const ids = [...activeSelectedIds];
|
||||
setRegeneratingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
ids.forEach((id) => next.add(id));
|
||||
return next;
|
||||
});
|
||||
const clearIds = () => {
|
||||
setRegeneratingIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
ids.forEach((id) => next.delete(id));
|
||||
return next;
|
||||
});
|
||||
};
|
||||
if (onRegenerateTitles) {
|
||||
void Promise.resolve(onRegenerateTitles(ids)).finally(clearIds);
|
||||
return;
|
||||
}
|
||||
void Promise.all(ids.map((id) => Promise.resolve(onRegenerateTitle!(id)))).finally(clearIds);
|
||||
};
|
||||
|
||||
const getOtherMoveTargets = (session: AISession) =>
|
||||
@@ -252,18 +349,6 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('ai.chat.managerToggleSelection')}
|
||||
title={t('ai.chat.managerToggleSelection')}
|
||||
onClick={() => (selectionMode ? exitSelectionMode() : setSelectionMode(true))}
|
||||
className={cn(
|
||||
'h-8 w-8 shrink-0 grid place-items-center rounded-md transition-colors cursor-pointer',
|
||||
selectionMode ? 'bg-primary/15 text-primary' : 'text-muted-foreground/60 hover:text-foreground hover:bg-muted',
|
||||
)}
|
||||
>
|
||||
<CheckSquare size={14} />
|
||||
</button>
|
||||
{showAgentMeta && (
|
||||
<Select value={effectiveAgentFilter} onValueChange={setAgentFilter}>
|
||||
<SelectTrigger
|
||||
@@ -286,38 +371,53 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
)}
|
||||
</div>
|
||||
{selectionMode && (
|
||||
<div className="px-3 py-1.5 shrink-0 border-b border-border/30 flex items-center gap-2 text-[12px]">
|
||||
<div
|
||||
className="px-3 py-1.5 shrink-0 border-b border-border/30 bg-muted/30 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]"
|
||||
data-section="ai-global-session-selection-bar"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleSelectAll}
|
||||
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground cursor-pointer"
|
||||
className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
{displayedRows.length > 0 && displayedRows.every((row) => selectedIds.has(row.session.id))
|
||||
? <CheckSquare size={13} /> : <Square size={13} />}
|
||||
{displayedRows.length > 0 && displayedRows.every((row) => activeSelectedIds.has(row.session.id))
|
||||
? <CheckSquare size={13} className="text-primary" /> : <Square size={13} />}
|
||||
{t('ai.chat.managerSelectAll')}
|
||||
</button>
|
||||
<span className="text-muted-foreground/60">{t('ai.chat.managerSelectedCount', { n: String(selectedIds.size) })}</span>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
{onRegenerateTitle && (
|
||||
<span className="text-muted-foreground/60 whitespace-nowrap">
|
||||
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{(onRegenerateTitles || onRegenerateTitle) && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={selectedIds.size === 0}
|
||||
disabled={activeSelectedIds.size === 0 || [...activeSelectedIds].some((id) => regeneratingIds.has(id))}
|
||||
onClick={commitBulkRegenerate}
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 cursor-pointer"
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
<RefreshCw size={12} />
|
||||
<RefreshCw
|
||||
size={12}
|
||||
className={[...activeSelectedIds].some((id) => regeneratingIds.has(id)) ? 'animate-spin' : undefined}
|
||||
/>
|
||||
{t('ai.chat.managerRegenerateTitle')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={selectedIds.size === 0}
|
||||
onClick={commitBulkDelete}
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 cursor-pointer"
|
||||
disabled={activeSelectedIds.size === 0}
|
||||
onClick={() => setBulkDeleteConfirmOpen(true)}
|
||||
className="flex items-center gap-1 rounded px-2 py-1 text-destructive hover:bg-destructive/10 disabled:opacity-40 whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={exitSelectionMode}
|
||||
className="rounded px-2 py-1 text-muted-foreground hover:text-foreground hover:bg-muted whitespace-nowrap cursor-pointer"
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -362,7 +462,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
<React.Fragment key={row.session.id}>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={row.canActivate ? 0 : -1}
|
||||
tabIndex={selectionMode || row.canActivate ? 0 : -1}
|
||||
onClick={() => {
|
||||
if (selectionMode) {
|
||||
toggleSelected(row.session.id);
|
||||
@@ -389,87 +489,94 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
row.isCurrentActive
|
||||
? 'text-foreground'
|
||||
: 'text-foreground/75 hover:text-foreground',
|
||||
!row.canActivate && 'cursor-default',
|
||||
!selectionMode && !row.canActivate && 'cursor-default',
|
||||
)}
|
||||
data-session-id={row.session.id}
|
||||
data-scope-state={row.scopeState}
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className={cn('min-w-0', selectionMode && 'flex items-center gap-2.5')}>
|
||||
{selectionMode && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('ai.chat.managerSelectRow')}
|
||||
aria-pressed={activeSelectedIds.has(row.session.id)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleSelected(row.session.id);
|
||||
}}
|
||||
className="float-left mr-2 mt-0.5 text-muted-foreground/60 hover:text-primary cursor-pointer"
|
||||
className="shrink-0 text-muted-foreground/60 hover:text-primary cursor-pointer"
|
||||
>
|
||||
{selectedIds.has(row.session.id)
|
||||
{activeSelectedIds.has(row.session.id)
|
||||
? <CheckSquare size={14} className="text-primary" />
|
||||
: <Square size={14} />}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{row.isCurrentActive && (
|
||||
<span
|
||||
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
|
||||
{isRenaming ? (
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
type="text"
|
||||
value={renameDraft}
|
||||
aria-label={t('ai.chat.renameChat')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
className="h-6 text-[12px]"
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
{row.isCurrentActive && (
|
||||
<span
|
||||
className="h-1.5 w-1.5 shrink-0 rounded-full bg-primary"
|
||||
aria-hidden
|
||||
/>
|
||||
) : (
|
||||
row.title
|
||||
)}
|
||||
</span>
|
||||
{row.isActiveElsewhere && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
|
||||
{t('ai.chat.managerBadgeActive')}
|
||||
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
|
||||
{isRenaming ? (
|
||||
<Input
|
||||
ref={renameInputRef}
|
||||
type="text"
|
||||
value={renameDraft}
|
||||
aria-label={t('ai.chat.renameChat')}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitRename();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setRenamingSessionId(null);
|
||||
setRenameDraft('');
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setRenameDraft(e.target.value)}
|
||||
onBlur={commitRename}
|
||||
className="h-6 text-[12px]"
|
||||
/>
|
||||
) : (
|
||||
row.title
|
||||
)}
|
||||
</span>
|
||||
{row.isActiveElsewhere && (
|
||||
<span className="shrink-0 rounded bg-muted px-1 text-[10px] leading-4 text-muted-foreground/75">
|
||||
{t('ai.chat.managerBadgeActive')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{subtitleParts.length > 0 && (
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
|
||||
{subtitleParts.map((part, index) => (
|
||||
<React.Fragment key={`${row.session.id}-meta-${index}`}>
|
||||
{index > 0 && <span aria-hidden>·</span>}
|
||||
<span className={cn(
|
||||
part.truncate ? 'truncate' : 'shrink-0',
|
||||
part.bold && 'font-medium',
|
||||
)}>
|
||||
{part.text}
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{subtitleParts.length > 0 && (
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/70 min-w-0">
|
||||
{subtitleParts.map((part, index) => (
|
||||
<React.Fragment key={`${row.session.id}-meta-${index}`}>
|
||||
{index > 0 && <span aria-hidden>·</span>}
|
||||
<span className={cn(
|
||||
part.truncate ? 'truncate' : 'shrink-0',
|
||||
part.bold && 'font-medium',
|
||||
)}>
|
||||
{part.text}
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={SESSION_HISTORY_ROW_CLASSNAMES.meta}>
|
||||
{regeneratingIds.has(row.session.id) && (
|
||||
<RefreshCw size={11} className="animate-spin text-muted-foreground/70 shrink-0" />
|
||||
)}
|
||||
<span className={SESSION_HISTORY_ROW_CLASSNAMES.time}>
|
||||
{formatRelativeTime(new Date(row.session.updatedAt), t)}
|
||||
{formatRelativeTime(new Date(row.lastMessageAt), t)}
|
||||
</span>
|
||||
{!selectionMode && (
|
||||
<Dropdown
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => setOpenMenuSessionId(open ? row.session.id : null)}
|
||||
@@ -508,14 +615,21 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
{onRegenerateTitle && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={regeneratingIds.has(row.session.id)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setOpenMenuSessionId(null);
|
||||
onRegenerateTitle(row.session.id);
|
||||
runSingleRegenerate(row.session.id);
|
||||
}}
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted cursor-pointer"
|
||||
className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground/85 hover:bg-muted disabled:opacity-40 cursor-pointer"
|
||||
>
|
||||
<RefreshCw size={12} className="shrink-0 text-muted-foreground" />
|
||||
<RefreshCw
|
||||
size={12}
|
||||
className={cn(
|
||||
'shrink-0 text-muted-foreground',
|
||||
regeneratingIds.has(row.session.id) && 'animate-spin',
|
||||
)}
|
||||
/>
|
||||
<span>{t('ai.chat.managerRegenerateTitle')}</span>
|
||||
</button>
|
||||
)}
|
||||
@@ -562,6 +676,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
</button>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{moveSession?.id === row.session.id && (
|
||||
@@ -622,6 +737,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
}}
|
||||
onConfirm={commitDelete}
|
||||
/>
|
||||
<ConfirmDialog
|
||||
open={bulkDeleteConfirmOpen && activeSelectedIds.size > 0}
|
||||
title={t('ai.chat.managerBulkDeleteTitle', { n: String(activeSelectedIds.size) })}
|
||||
message={t('ai.chat.managerBulkDeleteMessage', { n: String(activeSelectedIds.size) })}
|
||||
confirmLabel={t('common.delete')}
|
||||
destructive
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setBulkDeleteConfirmOpen(false);
|
||||
}}
|
||||
onConfirm={commitBulkDelete}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -199,6 +199,30 @@ test("workspace member and hidden terminal active pointers are not treated as ju
|
||||
assert.equal(byId.get("s-hidden-active")!.scopeState, "idle");
|
||||
});
|
||||
|
||||
test("renaming an older chat (bumping updatedAt) keeps its lastMessageAt and sort order", () => {
|
||||
const input = baseInput();
|
||||
input.sessions = [
|
||||
baseSession({
|
||||
id: "older-renamed",
|
||||
title: "AI Renamed Older Chat",
|
||||
createdAt: 1_000,
|
||||
updatedAt: 999_999,
|
||||
messages: [{ id: "m1", role: "user", timestamp: 2_000, content: "old question" }],
|
||||
}),
|
||||
baseSession({
|
||||
id: "newer-chat",
|
||||
title: "Newer Chat",
|
||||
createdAt: 5_000,
|
||||
updatedAt: 6_000,
|
||||
messages: [{ id: "m2", role: "user", timestamp: 6_000, content: "recent question" }],
|
||||
}),
|
||||
] as AISession[];
|
||||
const rows = buildGlobalManagerRows(input);
|
||||
assert.deepEqual(rows.map((row) => row.session.id), ["newer-chat", "older-renamed"]);
|
||||
assert.equal(rows[0].lastMessageAt, 6_000);
|
||||
assert.equal(rows[1].lastMessageAt, 2_000);
|
||||
});
|
||||
|
||||
test("rows sort by updatedAt descending and carry agent labels + counts", () => {
|
||||
const input = baseInput();
|
||||
input.sessions = [
|
||||
|
||||
@@ -60,6 +60,8 @@ export interface GlobalManagerRow {
|
||||
*/
|
||||
canActivate: boolean;
|
||||
messageCount: number;
|
||||
/** Timestamp of the last user/assistant message (falls back to createdAt/updatedAt). */
|
||||
lastMessageAt: number;
|
||||
}
|
||||
|
||||
export interface BuildGlobalManagerRowsInput {
|
||||
@@ -92,6 +94,21 @@ function resolveHistoricalHostLabel(
|
||||
return `${names[0]}, ${names[1]} +${names.length - 2}`;
|
||||
}
|
||||
|
||||
export function getSessionLastMessageAt(session: AISession): number {
|
||||
for (let index = session.messages.length - 1; index >= 0; index--) {
|
||||
const message = session.messages[index];
|
||||
if (
|
||||
(message.role === 'user' || message.role === 'assistant')
|
||||
&& Number.isFinite(message.timestamp)
|
||||
) {
|
||||
return message.timestamp;
|
||||
}
|
||||
}
|
||||
return Number.isFinite(session.createdAt) && session.createdAt > 0
|
||||
? session.createdAt
|
||||
: session.updatedAt;
|
||||
}
|
||||
|
||||
export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): GlobalManagerRow[] {
|
||||
const {
|
||||
sessions,
|
||||
@@ -212,10 +229,12 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob
|
||||
activeElsewhereTarget,
|
||||
canActivate: Boolean(isCurrentView || currentScopeTargetId || isActiveElsewhere),
|
||||
messageCount: session.messages.length,
|
||||
lastMessageAt: getSessionLastMessageAt(session),
|
||||
} satisfies GlobalManagerRow;
|
||||
})
|
||||
// Newest first; the filter helpers preserve this order.
|
||||
.sort((a, b) => b.session.updatedAt - a.session.updatedAt);
|
||||
// Newest conversation first; renaming updates `updatedAt` for sync but must
|
||||
// not reorder rows or turn old chats into "just now".
|
||||
.sort((a, b) => b.lastMessageAt - a.lastMessageAt);
|
||||
}
|
||||
|
||||
export interface GlobalManagerFilter {
|
||||
|
||||
@@ -40,6 +40,21 @@ test('buildManagedAgentState removes stale managed agents when path detection fa
|
||||
assert.equal(state.defaultAgentId, 'catty');
|
||||
});
|
||||
|
||||
test('a temporary unavailable probe preserves the per-agent question preference', () => {
|
||||
for (const key of ['codex', 'codebuddy', 'opencode'] as const) {
|
||||
const id = `discovered_${key}`;
|
||||
const state = buildManagedAgentState([{
|
||||
id, name: key, command: key, enabled: true, sdkBackend: key, allowNativeUserQuestions: true,
|
||||
}], id, key, null);
|
||||
assert.equal(state.agents[0]?.available, false);
|
||||
assert.equal(state.agents[0]?.allowNativeUserQuestions, true);
|
||||
const recovered = buildManagedAgentState(state.agents, id, key, {
|
||||
available: true, path: key, version: '1.0',
|
||||
});
|
||||
assert.equal(recovered.agents[0]?.allowNativeUserQuestions, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('buildManagedAgentState keeps unrelated defaults when removing stale managed agents', () => {
|
||||
const agents: ExternalAgentConfig[] = [
|
||||
{
|
||||
|
||||
Loaded 100 of 360 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user