mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-04 00:10:49 +00:00
Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
739a4246f9 | ||
|
|
e6d3047d0a | ||
|
|
f50c18e5c7 | ||
|
|
33b4bd1a43 | ||
|
|
31458b00a4 | ||
|
|
f68570d942 | ||
|
|
9474601fdf | ||
|
|
4cef084e99 | ||
|
|
58eeefb4c1 | ||
|
|
6f8211481c | ||
|
|
6458dbe039 | ||
|
|
6e0eacc6ae | ||
|
|
73ee6c0f31 | ||
|
|
905aed61ad | ||
|
|
13d05b0ea4 | ||
|
|
1045737c68 | ||
|
|
909d3e5ed2 | ||
|
|
cb7e49c409 | ||
|
|
02be8a2e0a | ||
|
|
ca2cdcbd12 | ||
|
|
f7fed5fd6f | ||
|
|
25aa27bbf8 | ||
|
|
7e44b774f8 | ||
|
|
c5c7cfdae3 | ||
|
|
62085cb3c2 |
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}>
|
||||
|
||||
@@ -67,6 +67,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -117,6 +117,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',
|
||||
@@ -328,6 +331,9 @@ 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.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,6 +640,12 @@ 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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -117,6 +117,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',
|
||||
@@ -328,6 +331,9 @@ 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.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,6 +640,12 @@ 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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -117,6 +117,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 +299,9 @@ 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.grok.runtime.acp.default': 'По умолчанию',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
|
||||
@@ -633,6 +639,12 @@ 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': 'Простой',
|
||||
|
||||
@@ -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': 'Навигация',
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -117,6 +117,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': '输入其他答案',
|
||||
@@ -328,6 +331,9 @@ 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.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,6 +640,12 @@ 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': '空闲',
|
||||
|
||||
@@ -574,6 +574,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 +603,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': '导航',
|
||||
|
||||
@@ -117,6 +117,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': '輸入其他答案',
|
||||
@@ -328,6 +331,9 @@ 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.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,6 +639,12 @@ 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': '閒置',
|
||||
|
||||
@@ -574,6 +574,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 +603,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': '導航',
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -343,3 +343,23 @@ 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();
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
+125
-93
@@ -10,6 +10,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 +19,7 @@ import type {
|
||||
HostAIPermission,
|
||||
ChatMessage,
|
||||
AISessionScope,
|
||||
ProviderConfig,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
activateDraftView,
|
||||
@@ -106,6 +108,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;
|
||||
@@ -1010,6 +1033,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 +1049,7 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
config: resolvedTitleConfig,
|
||||
chatSessionId: sessionId,
|
||||
signal: requestController.signal,
|
||||
language: readConfiguredUiLanguage(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1062,11 +1093,18 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
* (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 +1113,19 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
agentProviderMap: agentProviderMapRef.current,
|
||||
agentModelMap: agentModelMapRef.current,
|
||||
});
|
||||
if (!resolvedTitleConfig) return;
|
||||
if (!resolvedTitleConfig) {
|
||||
return { status: 'no-model' };
|
||||
}
|
||||
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,9 +1135,22 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
chatSessionId: sessionId,
|
||||
signal: controller.signal,
|
||||
fallbackOnFailure: false,
|
||||
language: readConfiguredUiLanguage(),
|
||||
onError: (err) => { capturedError = err; },
|
||||
},
|
||||
);
|
||||
if (controller.signal.aborted || !generated || generated === session.title) return;
|
||||
if (controller.signal.aborted) {
|
||||
return { status: 'error', error: 'Aborted' };
|
||||
}
|
||||
if (!generated) {
|
||||
const message = capturedError instanceof Error
|
||||
? capturedError.message
|
||||
: (capturedError ? String(capturedError) : 'Model returned an empty title');
|
||||
return { status: 'error', error: message };
|
||||
}
|
||||
if (generated === session.title) {
|
||||
return { status: 'unchanged', title: generated };
|
||||
}
|
||||
const previousTitle = session.title;
|
||||
const commit = (sessions: AISession[]) => {
|
||||
const result = applySessionTitleIfCurrent(sessions, sessionId, generated, previousTitle);
|
||||
@@ -1105,8 +1165,10 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
emitAIStateChanged(STORAGE_KEY_AI_SESSIONS);
|
||||
void result;
|
||||
}
|
||||
} catch {
|
||||
// Title generation never throws; keep the existing title on failure.
|
||||
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);
|
||||
@@ -1337,20 +1399,12 @@ export function useAIState(options?: UseAIStateOptions) {
|
||||
}, [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 +1415,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 +1442,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 +1495,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]);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
|
||||
@@ -295,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]);
|
||||
@@ -2127,7 +2129,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 +2165,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') {
|
||||
@@ -2437,9 +2444,68 @@ 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 === '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 +2553,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 +2576,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
handleManagerDelete,
|
||||
handleManagerDeleteMany,
|
||||
handleManagerRegenerateTitle,
|
||||
handleManagerRegenerateTitles,
|
||||
handleManagerExport,
|
||||
onFocusAIScopeTarget,
|
||||
]);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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*\/>/);
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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';
|
||||
@@ -556,7 +556,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 +578,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 +1423,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}
|
||||
|
||||
@@ -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,6 +12,7 @@ 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,
|
||||
@@ -946,6 +947,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 +979,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 +1035,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 !== 'grok'))
|
||||
.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,12 @@ 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 formValues = isGrokQuestion
|
||||
? 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 +96,11 @@ 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' : '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(isGrokQuestion
|
||||
? 'ai.grok.userQuestion.description' : 'ai.codebuddy.elicitation.description')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -249,23 +256,23 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
{!isGrokQuestion && <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(isGrokQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -59,7 +59,9 @@ 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;
|
||||
@@ -87,6 +89,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
onDelete,
|
||||
onDeleteMany,
|
||||
onRegenerateTitle,
|
||||
onRegenerateTitles,
|
||||
onExport,
|
||||
selectionMode: controlledSelectionMode,
|
||||
onSelectionModeChange,
|
||||
@@ -103,6 +106,7 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
|
||||
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);
|
||||
|
||||
@@ -243,9 +247,43 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
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 || activeSelectedIds.size === 0) return;
|
||||
activeSelectedIds.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) =>
|
||||
@@ -350,14 +388,17 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
{t('ai.chat.managerSelectedCount', { n: String(activeSelectedIds.size) })}
|
||||
</span>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
{onRegenerateTitle && (
|
||||
{(onRegenerateTitles || onRegenerateTitle) && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={activeSelectedIds.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 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>
|
||||
)}
|
||||
@@ -529,8 +570,11 @@ export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProp
|
||||
</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
|
||||
@@ -571,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>
|
||||
)}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -298,3 +298,11 @@ test("implicit workspace auto-resume excludes other-workspace rank-1 chats after
|
||||
"chat-member",
|
||||
);
|
||||
});
|
||||
|
||||
test("renaming an older chat preserves its position within a scope", () => {
|
||||
const scope = { type: "terminal", targetId: "term-1" } as const;
|
||||
const renamed = { ...createSession("older", scope, 1), updatedAt: 3 };
|
||||
const recent = createSession("recent", scope, 2);
|
||||
const history = getScopedHistorySessions([renamed, recent], "terminal", "term-1", [], new Set());
|
||||
assert.deepEqual(history.map(session => session.id), ["recent", "older"]);
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AISession } from '../../infrastructure/ai/types';
|
||||
import { getSessionLastMessageAt } from './globalSessionManagerRows';
|
||||
import { getSessionScopeMatchRank } from './sessionScopeMatch';
|
||||
|
||||
type HistoryCacheKey = string;
|
||||
@@ -78,7 +79,7 @@ export function getScopedHistorySessions(
|
||||
),
|
||||
}))
|
||||
.filter(({ matchRank }) => matchRank > 0)
|
||||
.sort((a, b) => b.matchRank - a.matchRank || b.session.updatedAt - a.session.updatedAt)
|
||||
.sort((a, b) => b.matchRank - a.matchRank || getSessionLastMessageAt(b.session) - getSessionLastMessageAt(a.session))
|
||||
.map(({ session }) => session);
|
||||
|
||||
scopeCache.set(cacheKey, result);
|
||||
|
||||
@@ -337,22 +337,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{t('cloudSync.localBackups.counts', {
|
||||
hosts: String(backup.preview.hostCount),
|
||||
keys: String(backup.preview.keyCount),
|
||||
snippets: String(backup.preview.snippetCount),
|
||||
notes: String(backup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
|
||||
<div className="text-xs text-muted-foreground mt-0.5">
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(backup.preview.aiSessionCount ?? 0),
|
||||
settings: String(backup.preview.settingCount ?? 0),
|
||||
<div className="text-xs text-muted-foreground mt-1 flex flex-wrap items-center gap-x-1.5">
|
||||
<span>
|
||||
{t('cloudSync.localBackups.counts', {
|
||||
hosts: String(backup.preview.hostCount),
|
||||
keys: String(backup.preview.keyCount),
|
||||
snippets: String(backup.preview.snippetCount),
|
||||
notes: String(backup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</span>
|
||||
{(backup.preview.aiSessionCount || backup.preview.settingCount) ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(backup.preview.aiSessionCount ?? 0),
|
||||
settings: String(backup.preview.settingCount ?? 0),
|
||||
})}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{restoreAllowed && (
|
||||
<Button
|
||||
@@ -443,22 +448,27 @@ export const LocalBackupsPanel: React.FC<LocalBackupsPanelProps> = ({
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-muted-foreground">
|
||||
{t('cloudSync.localBackups.counts', {
|
||||
hosts: String(pendingRestoreBackup.preview.hostCount),
|
||||
keys: String(pendingRestoreBackup.preview.keyCount),
|
||||
snippets: String(pendingRestoreBackup.preview.snippetCount),
|
||||
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
|
||||
<div className="text-muted-foreground mt-0.5">
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
|
||||
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
|
||||
<div className="text-muted-foreground flex flex-wrap items-center gap-x-1.5">
|
||||
<span>
|
||||
{t('cloudSync.localBackups.counts', {
|
||||
hosts: String(pendingRestoreBackup.preview.hostCount),
|
||||
keys: String(pendingRestoreBackup.preview.keyCount),
|
||||
snippets: String(pendingRestoreBackup.preview.snippetCount),
|
||||
notes: String(pendingRestoreBackup.preview.noteCount ?? 0),
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</span>
|
||||
{(pendingRestoreBackup.preview.aiSessionCount || pendingRestoreBackup.preview.settingCount) ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>
|
||||
{t('cloudSync.localBackups.aiCounts', {
|
||||
sessions: String(pendingRestoreBackup.preview.aiSessionCount ?? 0),
|
||||
settings: String(pendingRestoreBackup.preview.settingCount ?? 0),
|
||||
})}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter className="gap-2 sm:gap-0">
|
||||
|
||||
@@ -72,4 +72,12 @@ test("Monaco Cmd+W follows the current close-tab binding", () => {
|
||||
closeTabBinding: { ...closeTabBinding, mac: "⌘ + E" },
|
||||
isMac: true,
|
||||
}), false);
|
||||
assert.equal(isTextEditorCommandWEnabled({
|
||||
hotkeyScheme: "mac",
|
||||
closeTabBindings: [
|
||||
{ ...closeTabBinding, mac: "⌘ + E" },
|
||||
{ ...closeTabBinding, id: "close-tab::extra-0", mac: "⌘ + W", extraOf: "close-tab" },
|
||||
],
|
||||
isMac: true,
|
||||
}), true);
|
||||
});
|
||||
@@ -188,18 +188,22 @@ export function getTextEditorContentStats(content: string): { lineCount: number;
|
||||
export function isTextEditorCommandWEnabled({
|
||||
hotkeyScheme,
|
||||
closeTabBinding,
|
||||
closeTabBindings,
|
||||
isMac,
|
||||
}: {
|
||||
hotkeyScheme: HotkeyScheme;
|
||||
closeTabBinding?: KeyBinding;
|
||||
/** Every close-tab binding, including secondary chords added in Settings. */
|
||||
closeTabBindings?: readonly KeyBinding[];
|
||||
isMac: boolean;
|
||||
}): boolean {
|
||||
if (hotkeyScheme === 'disabled' || !closeTabBinding) return false;
|
||||
return isPrimaryModifierWBinding(
|
||||
hotkeyScheme === 'mac' ? closeTabBinding.mac : closeTabBinding.pc,
|
||||
if (hotkeyScheme === 'disabled') return false;
|
||||
const bindings = closeTabBindings ?? (closeTabBinding ? [closeTabBinding] : []);
|
||||
return bindings.some((binding) => isPrimaryModifierWBinding(
|
||||
hotkeyScheme === 'mac' ? binding.mac : binding.pc,
|
||||
matchesKeyBinding,
|
||||
isMac,
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
export const TextEditorPromoteButton: React.FC<{
|
||||
@@ -265,13 +269,13 @@ const TextEditorPaneInner: React.FC<TextEditorPaneProps> = ({
|
||||
const handlePasteRef = useRef<() => Promise<void>>(() => Promise.resolve());
|
||||
const readClipboardTextRef = useRef<() => Promise<string | null>>(() => Promise.resolve(null));
|
||||
|
||||
const closeTabBinding = useMemo(
|
||||
() => keyBindings.find((binding) => binding.action === 'closeTab'),
|
||||
const closeTabBindings = useMemo(
|
||||
() => keyBindings.filter((binding) => binding.action === 'closeTab'),
|
||||
[keyBindings],
|
||||
);
|
||||
closeTabCommandWEnabledRef.current = isTextEditorCommandWEnabled({
|
||||
hotkeyScheme,
|
||||
closeTabBinding,
|
||||
closeTabBindings,
|
||||
isMac: isMacPlatform,
|
||||
});
|
||||
|
||||
@@ -430,17 +434,19 @@ const TextEditorPaneInner: React.FC<TextEditorPaneProps> = ({
|
||||
// so Cmd/Ctrl+W works even when focus is inside Monaco (which otherwise
|
||||
// swallows the event). Requires an `onRequestClose` prop from the parent.
|
||||
const handleDialogKeyDownCapture = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (hotkeyScheme === 'disabled' || !closeTabBinding || !onRequestClose) return;
|
||||
if (hotkeyScheme === 'disabled' || closeTabBindings.length === 0 || !onRequestClose) return;
|
||||
|
||||
const isMac = hotkeyScheme === 'mac';
|
||||
const keyStr = isMac ? closeTabBinding.mac : closeTabBinding.pc;
|
||||
if (!matchesKeyBinding(e.nativeEvent, keyStr, isMac)) return;
|
||||
const matchesCloseTab = closeTabBindings.some((binding) => (
|
||||
matchesKeyBinding(e.nativeEvent, isMac ? binding.mac : binding.pc, isMac)
|
||||
));
|
||||
if (!matchesCloseTab) return;
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.nativeEvent.stopPropagation();
|
||||
onRequestClose();
|
||||
}, [closeTabBinding, hotkeyScheme, onRequestClose]);
|
||||
}, [closeTabBindings, hotkeyScheme, onRequestClose]);
|
||||
|
||||
// Trigger search dialog
|
||||
const handleSearch = useCallback(() => {
|
||||
|
||||
@@ -58,9 +58,12 @@ export function PluginTerminalSidebarPageHost({ page, tabId, sessionId, getSessi
|
||||
showHeader?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const subscribeHidden = useMemo(() => (hide: () => void) => {
|
||||
const stopTab = activeTabStore.subscribeSync((id) => { if (id !== tabId) hide(); });
|
||||
const stopSession = subscribeSidePanelLiveSnapshot(true, () => { if (getSession() !== sessionId) hide(); });
|
||||
const subscribeHidden = useMemo(() => (onVisibilityChange: (hidden?: boolean) => void) => {
|
||||
const sync = (tab = activeTabStore.getActiveTabId()) => {
|
||||
onVisibilityChange(tab !== tabId || getSession() !== sessionId);
|
||||
};
|
||||
const stopTab = activeTabStore.subscribeSync((id) => sync(id));
|
||||
const stopSession = subscribeSidePanelLiveSnapshot(true, () => sync());
|
||||
return () => { stopTab(); stopSession(); };
|
||||
}, [getSession, sessionId, tabId]);
|
||||
return <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label={`${page.title} — ${page.pluginName}`} data-plugin-terminal-sidebar>
|
||||
|
||||
@@ -15,7 +15,8 @@ import { LazyPluginHostDrawnPage, prewarmPluginView } from './LazyPluginHostDraw
|
||||
import { PluginVaultAISidebar } from './PluginVaultAISidebar';
|
||||
|
||||
type VaultPages = ReturnType<typeof usePluginVaultPages>;
|
||||
const subscribeHidden = (hide: () => void) => activeTabStore.subscribeSync((id) => { if (id !== 'vault') hide(); });
|
||||
const subscribeHidden = (onVisibilityChange: (hidden?: boolean) => void) =>
|
||||
activeTabStore.subscribeSync((id) => { onVisibilityChange(id !== 'vault'); });
|
||||
let nextPluginPromptId = 1;
|
||||
|
||||
export function PluginVaultNavigation({ model, collapsed }: { model: VaultPages; collapsed: boolean }) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Ban, RotateCcw } from "lucide-react";
|
||||
import { Ban, Plus, RotateCcw, X } from "lucide-react";
|
||||
import type { HotkeyScheme, KeyBinding } from "../../../domain/models";
|
||||
import { keyEventToString } from "../../../domain/models";
|
||||
import { useI18n } from "../../../application/i18n/I18nProvider";
|
||||
@@ -19,6 +19,9 @@ export default function SettingsShortcutsTab(props: {
|
||||
setDisableTerminalFontZoom: (enabled: boolean) => void;
|
||||
keyBindings: KeyBinding[];
|
||||
updateKeyBinding?: (bindingId: string, scheme: "mac" | "pc", newKey: string) => void;
|
||||
addKeyBindingExtra?: (bindingId: string, scheme: "mac" | "pc", newKey: string) => void;
|
||||
updateKeyBindingExtra?: (bindingId: string, index: number, scheme: "mac" | "pc", newKey: string) => void;
|
||||
removeKeyBindingExtra?: (bindingId: string, index: number) => void;
|
||||
resetKeyBinding?: (bindingId: string, scheme?: "mac" | "pc") => void;
|
||||
resetAllKeyBindings: () => void;
|
||||
setIsHotkeyRecording?: (isRecording: boolean) => void;
|
||||
@@ -34,6 +37,9 @@ export default function SettingsShortcutsTab(props: {
|
||||
setDisableTerminalFontZoom,
|
||||
keyBindings,
|
||||
updateKeyBinding,
|
||||
addKeyBindingExtra,
|
||||
updateKeyBindingExtra,
|
||||
removeKeyBindingExtra,
|
||||
resetKeyBinding,
|
||||
resetAllKeyBindings,
|
||||
setIsHotkeyRecording,
|
||||
@@ -42,10 +48,13 @@ export default function SettingsShortcutsTab(props: {
|
||||
|
||||
const [recordingBindingId, setRecordingBindingId] = useState<string | null>(null);
|
||||
const [recordingScheme, setRecordingScheme] = useState<"mac" | "pc" | null>(null);
|
||||
// index -1 records a new secondary chord, >= 0 re-records an existing one
|
||||
const [recordingExtra, setRecordingExtra] = useState<{ bindingId: string; index: number } | null>(null);
|
||||
|
||||
const cancelRecording = useCallback(() => {
|
||||
setRecordingBindingId(null);
|
||||
setRecordingScheme(null);
|
||||
setRecordingExtra(null);
|
||||
}, []);
|
||||
|
||||
const getSpecialSuffix = useCallback(
|
||||
@@ -60,6 +69,28 @@ export default function SettingsShortcutsTab(props: {
|
||||
[keyBindings, hotkeyScheme],
|
||||
);
|
||||
|
||||
const commitShortcut = useCallback((keyString: string) => {
|
||||
if (!recordingBindingId || !recordingScheme) return;
|
||||
if (recordingExtra && recordingExtra.bindingId === recordingBindingId) {
|
||||
if (recordingExtra.index < 0) {
|
||||
addKeyBindingExtra?.(recordingBindingId, recordingScheme, keyString);
|
||||
} else {
|
||||
updateKeyBindingExtra?.(recordingBindingId, recordingExtra.index, recordingScheme, keyString);
|
||||
}
|
||||
} else {
|
||||
updateKeyBinding?.(recordingBindingId, recordingScheme, keyString);
|
||||
}
|
||||
cancelRecording();
|
||||
}, [
|
||||
addKeyBindingExtra,
|
||||
cancelRecording,
|
||||
recordingBindingId,
|
||||
recordingExtra,
|
||||
recordingScheme,
|
||||
updateKeyBinding,
|
||||
updateKeyBindingExtra,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!recordingBindingId || !recordingScheme) return;
|
||||
|
||||
@@ -99,15 +130,13 @@ export default function SettingsShortcutsTab(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
updateKeyBinding?.(recordingBindingId, recordingScheme, fullKeyString);
|
||||
cancelRecording();
|
||||
commitShortcut(fullKeyString);
|
||||
return;
|
||||
}
|
||||
|
||||
if (["Meta", "Control", "Alt", "Shift"].includes(e.key)) return;
|
||||
const keyString = keyEventToString(e, recordingScheme === "mac");
|
||||
updateKeyBinding?.(recordingBindingId, recordingScheme, keyString);
|
||||
cancelRecording();
|
||||
commitShortcut(keyString);
|
||||
};
|
||||
|
||||
const handleKeyUp = (e: KeyboardEvent) => {
|
||||
@@ -117,8 +146,7 @@ export default function SettingsShortcutsTab(props: {
|
||||
e.stopPropagation();
|
||||
// Wait for release so a modifier-only editor can capture Ctrl+Alt, etc.
|
||||
if (e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;
|
||||
updateKeyBinding?.(recordingBindingId, recordingScheme, pendingModifierBinding);
|
||||
cancelRecording();
|
||||
commitShortcut(pendingModifierBinding);
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
@@ -137,7 +165,7 @@ export default function SettingsShortcutsTab(props: {
|
||||
window.removeEventListener("keyup", handleKeyUp, true);
|
||||
window.removeEventListener("click", handleClick, true);
|
||||
};
|
||||
}, [recordingBindingId, recordingScheme, updateKeyBinding, cancelRecording, getSpecialSuffix]);
|
||||
}, [recordingBindingId, recordingScheme, commitShortcut, cancelRecording, getSpecialSuffix]);
|
||||
|
||||
useEffect(() => {
|
||||
const isRecording = Boolean(recordingBindingId && recordingScheme);
|
||||
@@ -220,7 +248,7 @@ export default function SettingsShortcutsTab(props: {
|
||||
</div>
|
||||
|
||||
{categories.map((category) => {
|
||||
const categoryBindings = keyBindings.filter((kb) => kb.category === category);
|
||||
const categoryBindings = keyBindings.filter((kb) => kb.category === category && !kb.extraOf);
|
||||
if (categoryBindings.length === 0) return null;
|
||||
return (
|
||||
<div key={category}>
|
||||
@@ -241,23 +269,52 @@ export default function SettingsShortcutsTab(props: {
|
||||
? currentKey.replace(specialSuffix!, "").trim().replace(/\+\s*$/, "").trim()
|
||||
: null;
|
||||
|
||||
const isRecordingThis = recordingBindingId === binding.id;
|
||||
const scheme = hotkeyScheme === "mac" ? "mac" : "pc";
|
||||
const extras = keyBindings
|
||||
.filter((kb) => kb.extraOf === binding.id)
|
||||
.map((kb) => ({ binding: kb, index: Number(kb.id.split("::extra-")[1]) }));
|
||||
const isRecordingThis = recordingBindingId === binding.id && !recordingExtra;
|
||||
|
||||
return (
|
||||
<div key={binding.id} className="flex items-center justify-between px-4 py-2">
|
||||
<span className="text-sm">{t(`settings.shortcuts.binding.${binding.id}`) !== `settings.shortcuts.binding.${binding.id}` ? t(`settings.shortcuts.binding.${binding.id}`) : binding.label}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{isSpecialBinding ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<div key={binding.id}>
|
||||
<div className="flex items-center justify-between px-4 py-2">
|
||||
<span className="text-sm">{t(`settings.shortcuts.binding.${binding.id}`) !== `settings.shortcuts.binding.${binding.id}` ? t(`settings.shortcuts.binding.${binding.id}`) : binding.label}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
{isSpecialBinding ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRecordingExtra(null);
|
||||
setRecordingBindingId(binding.id);
|
||||
setRecordingScheme(scheme);
|
||||
}}
|
||||
className={cn(
|
||||
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[60px] text-center",
|
||||
isRecordingThis
|
||||
? "border-primary bg-primary/10 animate-pulse"
|
||||
: "border-border hover:border-primary/50",
|
||||
)}
|
||||
>
|
||||
{isRecordingThis
|
||||
? t("settings.shortcuts.recording")
|
||||
: modifierPrefix || t("settings.shortcuts.none")}
|
||||
</button>
|
||||
<span className="text-xs text-muted-foreground">+</span>
|
||||
<span className="px-2 py-1 text-xs font-mono rounded border border-border bg-muted/30 text-muted-foreground">
|
||||
{specialSuffix}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRecordingExtra(null);
|
||||
setRecordingBindingId(binding.id);
|
||||
setRecordingScheme(scheme);
|
||||
}}
|
||||
className={cn(
|
||||
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[60px] text-center",
|
||||
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
|
||||
isRecordingThis
|
||||
? "border-primary bg-primary/10 animate-pulse"
|
||||
: "border-border hover:border-primary/50",
|
||||
@@ -265,51 +322,89 @@ export default function SettingsShortcutsTab(props: {
|
||||
>
|
||||
{isRecordingThis
|
||||
? t("settings.shortcuts.recording")
|
||||
: modifierPrefix || t("settings.shortcuts.none")}
|
||||
: currentKey === "Disabled"
|
||||
? t("settings.shortcuts.scheme.disabled")
|
||||
: currentKey || t("settings.shortcuts.scheme.disabled")}
|
||||
</button>
|
||||
<span className="text-xs text-muted-foreground">+</span>
|
||||
<span className="px-2 py-1 text-xs font-mono rounded border border-border bg-muted/30 text-muted-foreground">
|
||||
{specialSuffix}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
)}
|
||||
{!isSpecialBinding && (
|
||||
<button
|
||||
onClick={() => updateKeyBinding?.(binding.id, scheme, "Disabled")}
|
||||
className="p-1 hover:bg-muted rounded"
|
||||
aria-label={t("settings.shortcuts.setDisabled")}
|
||||
>
|
||||
<Ban size={12} />
|
||||
</button>
|
||||
)}
|
||||
{!isSpecialBinding && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRecordingExtra({ bindingId: binding.id, index: -1 });
|
||||
setRecordingBindingId(binding.id);
|
||||
setRecordingScheme(scheme);
|
||||
}}
|
||||
className="p-1 hover:bg-muted rounded"
|
||||
aria-label={t("settings.shortcuts.addExtra")}
|
||||
title={t("settings.shortcuts.addExtra")}
|
||||
>
|
||||
{recordingExtra?.bindingId === binding.id && recordingExtra.index === -1
|
||||
? <span role="status" className="px-1 text-xs font-mono text-primary">{t("settings.shortcuts.recording")}</span>
|
||||
: <Plus size={12} />}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRecordingBindingId(binding.id);
|
||||
setRecordingScheme(scheme);
|
||||
}}
|
||||
className={cn(
|
||||
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
|
||||
isRecordingThis
|
||||
? "border-primary bg-primary/10 animate-pulse"
|
||||
: "border-border hover:border-primary/50",
|
||||
)}
|
||||
>
|
||||
{isRecordingThis
|
||||
? t("settings.shortcuts.recording")
|
||||
: currentKey === "Disabled"
|
||||
? t("settings.shortcuts.scheme.disabled")
|
||||
: currentKey || t("settings.shortcuts.scheme.disabled")}
|
||||
</button>
|
||||
)}
|
||||
{!isSpecialBinding && (
|
||||
<button
|
||||
onClick={() => updateKeyBinding?.(binding.id, scheme, "Disabled")}
|
||||
onClick={() => resetKeyBinding?.(binding.id, scheme)}
|
||||
className="p-1 hover:bg-muted rounded"
|
||||
aria-label={t("settings.shortcuts.setDisabled")}
|
||||
aria-label={t("settings.shortcuts.resetToDefault")}
|
||||
>
|
||||
<Ban size={12} />
|
||||
<RotateCcw size={12} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => resetKeyBinding?.(binding.id, scheme)}
|
||||
className="p-1 hover:bg-muted rounded"
|
||||
aria-label={t("settings.shortcuts.resetToDefault")}
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{extras.map(({ binding: extraBinding, index }) => {
|
||||
const extraKey = hotkeyScheme === "mac" ? extraBinding.mac : extraBinding.pc;
|
||||
const isRecordingExtra = recordingBindingId === binding.id
|
||||
&& recordingExtra?.bindingId === binding.id
|
||||
&& recordingExtra.index === index;
|
||||
return (
|
||||
<div key={extraBinding.id} className="flex items-center justify-between bg-muted/20 px-4 py-2">
|
||||
<span className="pl-4 text-xs text-muted-foreground">
|
||||
{t("settings.shortcuts.additional")}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setRecordingExtra({ bindingId: binding.id, index });
|
||||
setRecordingBindingId(binding.id);
|
||||
setRecordingScheme(scheme);
|
||||
}}
|
||||
className={cn(
|
||||
"px-2 py-1 text-xs font-mono rounded border transition-colors min-w-[80px] text-center",
|
||||
isRecordingExtra
|
||||
? "border-primary bg-primary/10 animate-pulse"
|
||||
: "border-border hover:border-primary/50",
|
||||
)}
|
||||
>
|
||||
{isRecordingExtra
|
||||
? t("settings.shortcuts.recording")
|
||||
: extraKey === "Disabled" || !extraKey
|
||||
? t("settings.shortcuts.none")
|
||||
: extraKey}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => removeKeyBindingExtra?.(binding.id, index)}
|
||||
className="p-1 hover:bg-muted rounded"
|
||||
aria-label={t("settings.shortcuts.removeExtra")}
|
||||
title={t("settings.shortcuts.removeExtra")}
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1603,6 +1603,17 @@ function SettingsTerminalTab(props: {
|
||||
disabled={!terminalSettings.autocompleteEnabled}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
anchorId="terminal-autocomplete-show-snippets"
|
||||
label={t("settings.terminal.autocomplete.showSnippets")}
|
||||
description={t("settings.terminal.autocomplete.showSnippets.desc")}
|
||||
>
|
||||
<Toggle
|
||||
checked={terminalSettings.autocompleteShowSnippets !== false}
|
||||
onChange={(v) => updateTerminalSetting("autocompleteShowSnippets", v)}
|
||||
disabled={!terminalSettings.autocompleteEnabled}
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
|
||||
<SectionHeader title={t("settings.terminal.section.passwordPromptAssist")} />
|
||||
|
||||
@@ -10,6 +10,7 @@ const SEARCH_ICON_PATHS: Record<WebSearchProviderId, string> = {
|
||||
tavily: "/ai/search/tavily.svg",
|
||||
exa: "/ai/search/exa.png",
|
||||
bocha: "/ai/search/bocha.webp",
|
||||
deepseek: "/ai/providers/deepseek.svg",
|
||||
zhipu: "/ai/search/zhipu.png",
|
||||
searxng: "/ai/search/searxng.svg",
|
||||
};
|
||||
|
||||
@@ -97,12 +97,15 @@ export function isSftpNativeClipboardPasteEnabled(
|
||||
keyBindings: KeyBinding[],
|
||||
): boolean {
|
||||
if (hotkeyScheme === "disabled") return false;
|
||||
const pasteBinding = keyBindings.find((binding) => (
|
||||
// A secondary paste chord added in Settings can be the native one even when
|
||||
// the primary chord is not, so every binding for the action has to count.
|
||||
const pasteBindings = keyBindings.filter((binding) => (
|
||||
binding.category === "sftp" && binding.action === "sftpPaste"
|
||||
));
|
||||
if (!pasteBinding) return false;
|
||||
const key = hotkeyScheme === "mac" ? pasteBinding.mac : pasteBinding.pc;
|
||||
return shouldLetNativePasteEventHandleSftpPaste("sftpPaste", key);
|
||||
return pasteBindings.some((binding) => shouldLetNativePasteEventHandleSftpPaste(
|
||||
"sftpPaste",
|
||||
hotkeyScheme === "mac" ? binding.mac : binding.pc,
|
||||
));
|
||||
}
|
||||
|
||||
export interface SftpClipboardUploadRequest {
|
||||
|
||||
@@ -617,9 +617,11 @@ export const useSftpKeyboardShortcuts = ({
|
||||
|
||||
if (hotkeyScheme !== "disabled") {
|
||||
const isMac = hotkeyScheme === "mac";
|
||||
const searchBinding = keyBindings.find((binding) => binding.action === "searchTerminal");
|
||||
const searchKey = searchBinding ? (isMac ? searchBinding.mac : searchBinding.pc) : null;
|
||||
if (searchKey && matchesKeyBinding(e, searchKey, isMac)) {
|
||||
const matchesSearchHotkey = keyBindings.some((binding) => (
|
||||
binding.action === "searchTerminal"
|
||||
&& matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
|
||||
));
|
||||
if (matchesSearchHotkey) {
|
||||
const { pane } = getFocusedPane();
|
||||
if (!pane?.connection) return;
|
||||
|
||||
|
||||
@@ -129,13 +129,14 @@ export function TerminalAutocomplete({
|
||||
hostGroup,
|
||||
cwdSource: options.cwdSource,
|
||||
snippets: options.snippets,
|
||||
showSnippets: options.showSnippets ?? settings?.showSnippets,
|
||||
maximum: options.maxResults ?? 15,
|
||||
historyScope: options.historyScope ?? settings?.historyScope,
|
||||
signal: options.signal,
|
||||
onLatePathSuggestions: options.onLatePathSuggestions,
|
||||
locale: resolvedLocale,
|
||||
});
|
||||
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, status, workspaceId]);
|
||||
}, [allowHostStyleGreaterThanPrompt, hostGroup, hostId, hostOs, isPluginCompletionProviderAvailable, protocol, resolvedLocale, sensitiveInputActiveRef, sessionId, settings?.historyScope, settings?.showSnippets, status, workspaceId]);
|
||||
const autocomplete = useTerminalAutocomplete({
|
||||
termRef,
|
||||
containerRef,
|
||||
|
||||
@@ -210,6 +210,8 @@ export async function getCompletions(
|
||||
cwdSource?: AutocompleteCwdSource;
|
||||
/** Custom snippets to surface at the command position */
|
||||
snippets?: Snippet[];
|
||||
/** Whether to include matching snippets in completions (default: true). */
|
||||
showSnippets?: boolean;
|
||||
/** Which history pool to query (default: current host only). */
|
||||
historyScope?: AutocompleteHistoryScope;
|
||||
/**
|
||||
@@ -376,7 +378,7 @@ export async function getCompletions(
|
||||
// Push without the early seen-text skip: snippets score above history, so if
|
||||
// a snippet's label collides with an existing history entry's text, the
|
||||
// score-sort + final dedup below keeps the snippet (the higher-scored one).
|
||||
if (options.snippets && options.snippets.length > 0) {
|
||||
if (options.showSnippets !== false && options.snippets && options.snippets.length > 0) {
|
||||
const atCommandPosition = ctx.wordIndex === 0;
|
||||
const argumentNeedle = normalizeHistoryPathPrefix(ctx.currentWord);
|
||||
const snippetArgumentMatch = !atCommandPosition
|
||||
|
||||
@@ -10,6 +10,7 @@ type TerminalAutocompleteSettingFields = {
|
||||
autocompleteMinChars?: number;
|
||||
autocompleteMaxSuggestions?: number;
|
||||
autocompleteHistoryScope?: AutocompleteHistoryScope;
|
||||
autocompleteShowSnippets?: boolean;
|
||||
shiftEnterNewlineEnabled?: boolean;
|
||||
};
|
||||
|
||||
@@ -36,6 +37,7 @@ export function resolveTerminalAutocompleteSettings(input: {
|
||||
minChars: terminalSettings?.autocompleteMinChars ?? 1,
|
||||
maxSuggestions: terminalSettings?.autocompleteMaxSuggestions ?? 50,
|
||||
historyScope: terminalSettings?.autocompleteHistoryScope ?? "host",
|
||||
showSnippets: terminalSettings?.autocompleteShowSnippets !== false,
|
||||
shiftEnterNewlineEnabled: terminalSettings?.shiftEnterNewlineEnabled ?? true,
|
||||
};
|
||||
}
|
||||
@@ -58,6 +60,7 @@ export function resolveTerminalAutocompleteSettings(input: {
|
||||
minChars: terminalSettings.autocompleteMinChars ?? 1,
|
||||
maxSuggestions: terminalSettings.autocompleteMaxSuggestions ?? 50,
|
||||
historyScope: terminalSettings.autocompleteHistoryScope ?? "host",
|
||||
showSnippets: terminalSettings.autocompleteShowSnippets !== false,
|
||||
shiftEnterNewlineEnabled: terminalSettings.shiftEnterNewlineEnabled ?? true,
|
||||
};
|
||||
}
|
||||
@@ -159,3 +159,16 @@ test('terminal completion adapter preserves built-in snippet metadata on duplica
|
||||
assert.equal(duplicate?.snippet, snippet);
|
||||
assert.equal(results.filter((item) => item.text === 'deploy').length, 1);
|
||||
});
|
||||
|
||||
test('terminal completion adapter skips built-in snippets when showSnippets is false', async () => {
|
||||
const snippet = { id: 'deploy', label: 'deploy', command: 'kubectl apply -f .' };
|
||||
const results = await provideTerminalCompletions(null, {
|
||||
input: 'dep',
|
||||
session: { sessionId: 'session-1', protocol: 'ssh', status: 'connected' },
|
||||
hostOs: 'linux',
|
||||
snippets: [snippet],
|
||||
showSnippets: false,
|
||||
maximum: 8,
|
||||
});
|
||||
assert.equal(results.some((item) => item.source === 'snippet'), false);
|
||||
});
|
||||
@@ -17,6 +17,8 @@ export interface TerminalCompletionProviderRequest {
|
||||
hostOs: 'linux' | 'windows' | 'macos';
|
||||
cwdSource?: AutocompleteCwdSource;
|
||||
snippets?: Snippet[];
|
||||
/** Whether to include matching snippets in built-in completions (default: true). */
|
||||
showSnippets?: boolean;
|
||||
maximum: number;
|
||||
/** Which history pool built-in suggestions draw from. */
|
||||
historyScope?: AutocompleteHistoryScope;
|
||||
@@ -73,7 +75,8 @@ export async function provideTerminalCompletions(
|
||||
protocol: request.session.protocol,
|
||||
cwd: request.session.cwd,
|
||||
cwdSource: request.cwdSource,
|
||||
snippets: request.snippets,
|
||||
snippets: request.showSnippets === false ? undefined : request.snippets,
|
||||
showSnippets: request.showSnippets,
|
||||
historyScope: request.historyScope,
|
||||
onLatePathSuggestions: request.onLatePathSuggestions,
|
||||
locale: request.locale,
|
||||
|
||||
@@ -68,6 +68,8 @@ export interface AutocompleteSettings {
|
||||
shiftEnterNewlineEnabled: boolean;
|
||||
/** Which history pool suggestions draw from (current host vs all hosts). */
|
||||
historyScope: "host" | "global";
|
||||
/** Whether matching code snippets are included in autocomplete suggestions. */
|
||||
showSnippets: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
|
||||
@@ -82,6 +84,7 @@ export const DEFAULT_AUTOCOMPLETE_SETTINGS: AutocompleteSettings = {
|
||||
fastTypingThresholdMs: 40,
|
||||
shiftEnterNewlineEnabled: true,
|
||||
historyScope: "host",
|
||||
showSnippets: true,
|
||||
};
|
||||
|
||||
/** Max time to poll for shell echo after a pre-echo debounce cycle (#2813). */
|
||||
@@ -302,6 +305,7 @@ export function useTerminalAutocomplete(
|
||||
const settings: AutocompleteSettings = {
|
||||
...rawSettings,
|
||||
showGhostText: rawSettings.showPopupMenu ? false : rawSettings.showGhostText,
|
||||
showSnippets: rawSettings.showSnippets !== false,
|
||||
livePreview: shouldWriteAutocompleteLivePreview(rawSettings.livePreview, isNetworkDevice),
|
||||
};
|
||||
|
||||
@@ -487,6 +491,16 @@ export function useTerminalAutocomplete(
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Drop visible snippet suggestions if the user turns showSnippets off mid-session.
|
||||
useEffect(() => {
|
||||
if (
|
||||
!settings.showSnippets
|
||||
&& stateRef.current.suggestions.some((suggestion) => suggestion.source === "snippet")
|
||||
) {
|
||||
clearState();
|
||||
}
|
||||
}, [settings.showSnippets, clearState]);
|
||||
|
||||
/**
|
||||
* Reconcile the visible popup with the newly edited input synchronously.
|
||||
* The full provider refresh remains debounced, but rows from the previous
|
||||
@@ -1165,7 +1179,8 @@ export function useTerminalAutocomplete(
|
||||
skipPathCompletion: isNetworkDeviceRef.current,
|
||||
cwd: cwdResolution.cwd,
|
||||
cwdSource: cwdResolution.source,
|
||||
snippets: snippetsRef.current,
|
||||
snippets: settingsRef.current.showSnippets ? snippetsRef.current : undefined,
|
||||
showSnippets: settingsRef.current.showSnippets,
|
||||
promptText: prompt.promptText,
|
||||
allowExternalProviders,
|
||||
signal: completionController.signal,
|
||||
@@ -1188,6 +1203,9 @@ export function useTerminalAutocomplete(
|
||||
if (completionAbortRef.current === completionController) completionAbortRef.current = null;
|
||||
}
|
||||
if (completionController.signal.aborted) return;
|
||||
if (!settingsRef.current.showSnippets) {
|
||||
completions = completions.filter((completion) => completion.source !== "snippet");
|
||||
}
|
||||
if (!settingsRef.current.allowLineReplacement) {
|
||||
completions = completions.filter((completion) =>
|
||||
completion.source !== "snippet" && completion.text.startsWith(input),
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { JSDOM } from "jsdom";
|
||||
import type { Terminal as XTerm } from "@xterm/xterm";
|
||||
import { GhostTextAddon } from "./GhostTextAddon.ts";
|
||||
import { getXTermCellDimensions, invalidateCellDimensionCache } from "./xtermUtils.ts";
|
||||
import {
|
||||
keepImeCommittedTextThroughModifierKeyDowns,
|
||||
keepLateImeTextInsert,
|
||||
} from "../runtime/imeModifierKeyDownSeenGuard.ts";
|
||||
|
||||
test("autocomplete on a disposed renderer does not double-send a key (#4539)", async () => {
|
||||
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
|
||||
url: "http://localhost/",
|
||||
pretendToBeVisual: true,
|
||||
});
|
||||
const win = dom.window;
|
||||
win.matchMedia = () => ({
|
||||
matches: false, media: "", onchange: null,
|
||||
addEventListener() {}, removeEventListener() {},
|
||||
addListener() {}, removeListener() {}, dispatchEvent: () => false,
|
||||
});
|
||||
win.HTMLCanvasElement.prototype.getContext = () => ({
|
||||
font: "10px monospace", measureText: () => ({ width: 8 }),
|
||||
}) as unknown as CanvasRenderingContext2D;
|
||||
const globals = {
|
||||
window: win, document: win.document, HTMLElement: win.HTMLElement,
|
||||
HTMLTextAreaElement: win.HTMLTextAreaElement, Node: win.Node,
|
||||
Element: win.Element, getComputedStyle: win.getComputedStyle.bind(win),
|
||||
};
|
||||
const previousGlobals = Object.fromEntries(
|
||||
Object.keys(globals).map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]),
|
||||
);
|
||||
Object.assign(globalThis, globals);
|
||||
const errors: unknown[] = [];
|
||||
win.addEventListener("error", (event) => {
|
||||
errors.push(event.error);
|
||||
event.preventDefault();
|
||||
});
|
||||
let oldTerm: XTerm | undefined;
|
||||
let liveTerm: XTerm | undefined;
|
||||
const ghost = new GhostTextAddon();
|
||||
try {
|
||||
const imported = await import("@xterm/xterm");
|
||||
const Terminal = (imported as { default?: { Terminal: typeof imported.Terminal } }).default?.Terminal
|
||||
?? imported.Terminal;
|
||||
const openTerminal = () => {
|
||||
const parent = win.document.createElement("div");
|
||||
win.document.body.appendChild(parent);
|
||||
const term = new Terminal({ cols: 80, rows: 24, cursorBlink: false });
|
||||
keepImeCommittedTextThroughModifierKeyDowns(term);
|
||||
keepLateImeTextInsert(term);
|
||||
term.open(parent);
|
||||
return term;
|
||||
};
|
||||
oldTerm = openTerminal();
|
||||
ghost.activate(oldTerm);
|
||||
// Runtime replacement leaves the separately activated autocomplete addon
|
||||
// holding the old terminal, whose RenderService still exists after dispose.
|
||||
oldTerm.dispose();
|
||||
liveTerm = openTerminal();
|
||||
const sent: string[] = [];
|
||||
liveTerm.onData((data) => {
|
||||
// Match createXTermRuntime: write first, then notify autocomplete.
|
||||
sent.push(data);
|
||||
ghost.applyKeystroke(data);
|
||||
});
|
||||
const textarea = liveTerm.textarea!;
|
||||
const cancelled: boolean[] = [];
|
||||
const typeKey = (key: string) => {
|
||||
const keyCode = key.toUpperCase().charCodeAt(0);
|
||||
const keydown = new win.KeyboardEvent("keydown", {
|
||||
key, code: `Key${key.toUpperCase()}`, keyCode,
|
||||
bubbles: true, cancelable: true,
|
||||
});
|
||||
textarea.dispatchEvent(keydown);
|
||||
cancelled.push(keydown.defaultPrevented);
|
||||
// JSDOM does not perform native keyboard default actions. Deliver the
|
||||
// browser's keypress/input sequence only when keydown was not cancelled.
|
||||
if (!keydown.defaultPrevented) {
|
||||
textarea.dispatchEvent(new win.KeyboardEvent("keypress", {
|
||||
key, charCode: key.charCodeAt(0), keyCode: key.charCodeAt(0),
|
||||
bubbles: true, cancelable: true,
|
||||
}));
|
||||
for (const type of ["beforeinput", "input"]) {
|
||||
textarea.dispatchEvent(new win.InputEvent(type, {
|
||||
data: key, inputType: "insertText", composed: true, bubbles: true,
|
||||
}));
|
||||
}
|
||||
}
|
||||
textarea.dispatchEvent(new win.KeyboardEvent("keyup", { key, keyCode, bubbles: true }));
|
||||
};
|
||||
typeKey("a");
|
||||
// The first suggestion arrives asynchronously, as in the reporter's trace.
|
||||
await Promise.resolve().then(() => ghost.show("apt update -y", "a")).catch((error) => errors.push(error));
|
||||
typeKey("p");
|
||||
typeKey("t");
|
||||
assert.equal(sent.join(""), "apt", "one PTY write per physical key");
|
||||
assert.deepEqual(cancelled, [true, true, true]);
|
||||
assert.deepEqual(errors, []);
|
||||
// With no cached size, the absent renderer also reaches the DOM fallback.
|
||||
invalidateCellDimensionCache();
|
||||
assert.deepEqual(getXTermCellDimensions(oldTerm), { width: 8, height: 16 });
|
||||
} finally {
|
||||
ghost.dispose();
|
||||
liveTerm?.dispose();
|
||||
oldTerm?.dispose();
|
||||
dom.window.close();
|
||||
invalidateCellDimensionCache();
|
||||
for (const [key, descriptor] of Object.entries(previousGlobals)) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, key);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -33,9 +33,17 @@ function getTermId(term: XTerm): number {
|
||||
export function getXTermCellDimensions(term: XTerm): CellDimensions {
|
||||
// Try xterm core renderer API (fast path)
|
||||
const coreAccess = term as XTerm & {
|
||||
_core?: { _renderService?: { dimensions?: { css?: { cell?: CellDimensions } } } };
|
||||
_core?: { _renderService?: {
|
||||
hasRenderer?: () => boolean;
|
||||
dimensions?: { css?: { cell?: CellDimensions } };
|
||||
} };
|
||||
};
|
||||
const coreDims = coreAccess._core?._renderService?.dimensions?.css?.cell;
|
||||
const renderService = coreAccess._core?._renderService;
|
||||
// The dimensions getter dereferences its renderer even after disposal.
|
||||
// Avoid throwing through onData before xterm can prevent the key's default.
|
||||
const coreDims = renderService?.hasRenderer?.() === false
|
||||
? undefined
|
||||
: renderService?.dimensions?.css?.cell;
|
||||
if (coreDims && coreDims.width > 0 && coreDims.height > 0) {
|
||||
// Update cache while we have a good value
|
||||
const id = getTermId(term);
|
||||
|
||||
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
|
||||
|
||||
import { getCompletions } from "./autocomplete/completionEngine";
|
||||
import { DEFAULT_AUTOCOMPLETE_SETTINGS } from "./autocomplete/useTerminalAutocomplete";
|
||||
import { clearHistory, recordCommand } from "../../application/state/commandHistoryStore";
|
||||
import { getPinyinCacheStatsForTests, resetPinyinCacheForTests } from "../../domain/searchMatcher";
|
||||
import type { Snippet } from "../../domain/models";
|
||||
|
||||
@@ -115,3 +116,83 @@ test("ASCII argument completion retains compact query prefixes", async () => {
|
||||
const result = await getCompletions("git pull foo_bar", { snippets, skipPathCompletion: true });
|
||||
assert.equal(result.find((suggestion) => suggestion.source === "snippet")?.snippet?.id, "compact");
|
||||
});
|
||||
|
||||
test("getCompletions excludes snippet suggestions when showSnippets is false or snippets are omitted", async () => {
|
||||
const chineseSnippet: Snippet = { id: "zh", label: "部署服务", command: "kubectl apply -f ." };
|
||||
const dockerSnippet: Snippet = { id: "doc", label: "docker-deploy", command: "docker compose up -d" };
|
||||
const library: Snippet[] = [deploySnippet, chineseSnippet, dockerSnippet];
|
||||
|
||||
// Baseline: when enabled, English and pinyin queries both surface snippet matches.
|
||||
const enabledEn = await getCompletions("dep", { snippets: library, showSnippets: true });
|
||||
assert.ok(enabledEn.some((suggestion) => suggestion.source === "snippet"));
|
||||
const enabledPinyin = await getCompletions("bushu", { snippets: library, showSnippets: true });
|
||||
assert.ok(enabledPinyin.some((suggestion) => suggestion.source === "snippet" && suggestion.snippet?.id === "zh"));
|
||||
const enabledArg = await getCompletions("git pull dep", { snippets: library, showSnippets: true });
|
||||
assert.ok(enabledArg.some((suggestion) => suggestion.source === "snippet"));
|
||||
|
||||
// Disabled via showSnippets: false — no snippet matches at command or argument positions,
|
||||
// including English and pinyin queries, even though the snippet library is present.
|
||||
for (const input of ["dep", "bushu", "git pull dep"]) {
|
||||
const disabled = await getCompletions(input, {
|
||||
snippets: library,
|
||||
showSnippets: false,
|
||||
skipPathCompletion: true,
|
||||
});
|
||||
assert.equal(
|
||||
disabled.some((suggestion) => suggestion.source === "snippet"),
|
||||
false,
|
||||
`expected no snippet suggestions for ${JSON.stringify(input)} when showSnippets is false`,
|
||||
);
|
||||
}
|
||||
|
||||
// History suggestions still appear when snippets are hidden, while snippets are excluded.
|
||||
const hostId = "host-snippet-toggle-test";
|
||||
const previousLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
|
||||
const store = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
configurable: true,
|
||||
value: {
|
||||
clear: () => store.clear(),
|
||||
getItem: (key: string) => (store.has(key) ? store.get(key)! : null),
|
||||
setItem: (key: string, value: string) => { store.set(key, String(value)); },
|
||||
removeItem: (key: string) => { store.delete(key); },
|
||||
},
|
||||
});
|
||||
try {
|
||||
clearHistory(hostId);
|
||||
recordCommand("docker ps -a", hostId, "linux");
|
||||
const dockerWithSnippets = await getCompletions("doc", {
|
||||
hostId,
|
||||
snippets: library,
|
||||
showSnippets: true,
|
||||
skipPathCompletion: true,
|
||||
});
|
||||
assert.equal(dockerWithSnippets[0]?.source, "snippet");
|
||||
assert.ok(
|
||||
dockerWithSnippets.some((suggestion) => suggestion.source === "history" && suggestion.text === "docker ps -a"),
|
||||
);
|
||||
|
||||
const dockerWithoutSnippets = await getCompletions("doc", {
|
||||
hostId,
|
||||
snippets: library,
|
||||
showSnippets: false,
|
||||
skipPathCompletion: true,
|
||||
});
|
||||
assert.equal(dockerWithoutSnippets.some((suggestion) => suggestion.source === "snippet"), false);
|
||||
assert.equal(dockerWithoutSnippets[0]?.source, "history");
|
||||
assert.equal(dockerWithoutSnippets[0]?.text, "docker ps -a");
|
||||
} finally {
|
||||
clearHistory(hostId);
|
||||
if (previousLocalStorage) {
|
||||
Object.defineProperty(globalThis, "localStorage", previousLocalStorage);
|
||||
} else {
|
||||
delete (globalThis as Record<string, unknown>).localStorage;
|
||||
}
|
||||
}
|
||||
|
||||
// Disabled by omitting snippets (how useTerminalAutocomplete gates the option).
|
||||
for (const snippets of [undefined, [] as Snippet[]]) {
|
||||
const omitted = await getCompletions("dep", { snippets, skipPathCompletion: true });
|
||||
assert.equal(omitted.some((suggestion) => suggestion.source === "snippet"), false);
|
||||
}
|
||||
});
|
||||
@@ -1936,6 +1936,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
// Unchanged ASCII must keep the Kitty press/release path. Composition
|
||||
// encoding under report-all emits unidentified CSI 0 u (or associated
|
||||
// text without a physical key), so ordinary punctuation breaks in TUIs.
|
||||
// Unchanged CJK glyphs use the literal/composition path below so Kitty
|
||||
// cannot turn the physical key back into ASCII (#4653).
|
||||
if (
|
||||
isUnchangedDeferredImeTextInput(deferredKey, text) &&
|
||||
deferredKittyEvent &&
|
||||
@@ -2050,8 +2052,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
const armImeTextInputDeferral = (event: KeyboardEvent) => {
|
||||
clearImeTextInputDeferral();
|
||||
clearBroadcastLegacyDataPending();
|
||||
// Wait for insertText (full-width) before keyup; keyup/blur flushes ASCII
|
||||
// when the IME did not remap the key (English punctuation mode).
|
||||
// Wait for insertText before keyup; keyup/blur flushes the original glyph
|
||||
// when the IME did not remap the key.
|
||||
imeTextInputDeferredKey = event.key;
|
||||
// Keep the physical key even when the source is not in Kitty mode so
|
||||
// broadcast targets can still receive paired key events.
|
||||
@@ -2755,10 +2757,10 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime
|
||||
return false;
|
||||
}
|
||||
|
||||
// Sogou/macOS CJK punctuation: keydown still reports ASCII "," while the
|
||||
// full-width "," arrives on insertText. Returning false (without
|
||||
// preventDefault) stops xterm/Kitty from sending the half-width key so the
|
||||
// input listener can commit the real glyph (#2833).
|
||||
// Sogou/macOS reports ASCII "," before insertText commits "," (#2833);
|
||||
// macOS Pinyin halfwidth mode reports the inverse (#4653). Returning false
|
||||
// (without preventDefault) stops xterm/Kitty from sending the keydown glyph
|
||||
// so the input listener can commit the real glyph.
|
||||
if (shouldDeferKeyDownForImeTextInput(e)) {
|
||||
armImeTextInputDeferral(e);
|
||||
return false;
|
||||
|
||||
@@ -43,27 +43,32 @@ test("shouldDeferKeyDownForImeTextInput defers bare ASCII punctuation keydowns",
|
||||
);
|
||||
});
|
||||
|
||||
test("shouldDeferKeyDownForImeTextInput defers bare CJK punctuation keydowns", () => {
|
||||
for (const key of [",", "。", ";", "?", "、", ":", "!", "「", "」"]) {
|
||||
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), true, key);
|
||||
}
|
||||
});
|
||||
|
||||
test("shouldDeferKeyDownForImeTextInput leaves non-punctuation keys alone", () => {
|
||||
for (const key of ["a", "Z", "0", " ", "Enter", "ArrowLeft", "中", "A", "1", " ", ",,"]) {
|
||||
assert.equal(shouldDeferKeyDownForImeTextInput({ type: "keydown", key }), false, key);
|
||||
}
|
||||
});
|
||||
|
||||
test("shouldDeferKeyDownForImeTextInput leaves composition and modified keys alone", () => {
|
||||
assert.equal(
|
||||
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", keyCode: 229 }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", isComposing: true }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: ",", ctrlKey: true }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldDeferKeyDownForImeTextInput({ type: "keydown", key: "a", keyCode: 65 }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
shouldDeferKeyDownForImeTextInput({ type: "keypress", key: "," }),
|
||||
false,
|
||||
);
|
||||
for (const key of [",", ","]) {
|
||||
for (const event of [
|
||||
{ type: "keydown", key, keyCode: 229 },
|
||||
{ type: "keydown", key, isComposing: true },
|
||||
{ type: "keydown", key, ctrlKey: true },
|
||||
{ type: "keydown", key, altKey: true },
|
||||
{ type: "keydown", key, metaKey: true },
|
||||
{ type: "keypress", key },
|
||||
{ type: "keyup", key },
|
||||
]) {
|
||||
assert.equal(shouldDeferKeyDownForImeTextInput(event), false, JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("shouldBlockKeyPressForImeTextInput only while a deferral is armed", () => {
|
||||
@@ -391,9 +396,22 @@ test("shouldCommitDeferredImeTextInput accepts insertText payloads while deferre
|
||||
);
|
||||
});
|
||||
|
||||
test("isUnchangedDeferredImeTextInput detects English punctuation flush", () => {
|
||||
test("macOS Pinyin halfwidth insertText can commit after a fullwidth keydown (#4653)", () => {
|
||||
let deferredKey: string | null = null;
|
||||
const keydown = { type: "keydown", key: ",", code: "Comma", keyCode: 188 };
|
||||
if (shouldDeferKeyDownForImeTextInput(keydown)) deferredKey = keydown.key;
|
||||
assert.equal(deferredKey, ",");
|
||||
assert.equal(
|
||||
shouldCommitDeferredImeTextInput(deferredKey, { inputType: "insertText", data: "," }),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("isUnchangedDeferredImeTextInput detects only ASCII punctuation flush", () => {
|
||||
assert.equal(isUnchangedDeferredImeTextInput(",", ","), true);
|
||||
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
|
||||
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
|
||||
assert.equal(isUnchangedDeferredImeTextInput(",", ","), false);
|
||||
assert.equal(isUnchangedDeferredImeTextInput(null, ","), false);
|
||||
});
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@
|
||||
* an `input`/`insertText` event. xterm.js sends the keydown character and then
|
||||
* drops the input event because `_keyDownSeen` is set — so the PTY receives
|
||||
* "," instead of ",".
|
||||
* macOS Pinyin halfwidth mode does the inverse: keydown reports "," but
|
||||
* insertText commits "," (#4653).
|
||||
*
|
||||
* Defer those keydowns to the following insertText. If no remap arrives before
|
||||
* keyup/blur, the original ASCII key is flushed. Composition (keyCode 229 /
|
||||
* keyup/blur, the original key is flushed. Composition (keyCode 229 /
|
||||
* isComposing) stays on xterm's CompositionHelper path.
|
||||
*
|
||||
* The deferral must never outlive the keystroke it was armed for: Windows IMEs
|
||||
@@ -32,6 +34,9 @@ export type ImeTextInputEvent = Pick<InputEvent, "data" | "inputType">;
|
||||
/** Printable ASCII punctuation IMEs commonly remap to full-width forms. */
|
||||
const ASCII_PUNCTUATION_RE = /^[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]$/;
|
||||
|
||||
/** Single Unicode punctuation glyphs, including CJK and full-width forms. */
|
||||
const UNICODE_PUNCTUATION_RE = /^\p{P}$/u;
|
||||
|
||||
export function isAsciiPunctuationKey(key: string): boolean {
|
||||
return ASCII_PUNCTUATION_RE.test(key);
|
||||
}
|
||||
@@ -42,7 +47,8 @@ export function shouldDeferKeyDownForImeTextInput(
|
||||
if (event.type !== undefined && event.type !== "keydown") return false;
|
||||
if (event.isComposing === true || event.keyCode === 229) return false;
|
||||
if (event.altKey || event.ctrlKey || event.metaKey) return false;
|
||||
return isAsciiPunctuationKey(event.key);
|
||||
return isAsciiPunctuationKey(event.key) ||
|
||||
(event.key.charCodeAt(0) > 0x7f && UNICODE_PUNCTUATION_RE.test(event.key));
|
||||
}
|
||||
|
||||
/** Key releases that carry no keystroke of their own. */
|
||||
@@ -186,5 +192,5 @@ export function isUnchangedDeferredImeTextInput(
|
||||
deferredKey: string | null | undefined,
|
||||
text: string,
|
||||
): boolean {
|
||||
return deferredKey != null && text === deferredKey;
|
||||
return deferredKey != null && isAsciiPunctuationKey(deferredKey) && text === deferredKey;
|
||||
}
|
||||
@@ -257,19 +257,79 @@ test("does not arm when the hint cannot be shown (overlay unavailable)", () => {
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test("a bare Password prompt does not hint until a su command is submitted", () => {
|
||||
test("a bare Password prompt does not hint until a su or sudo command is submitted", () => {
|
||||
const { autofill, hints } = make();
|
||||
autofill.handleOutput("Password: ");
|
||||
assert.deepEqual(hints, []);
|
||||
// sudo-armed bare Password: is too generic (mysql/ssh); su-armed is expected
|
||||
// macOS / Synology sudo uses the same bare prompt as su (#4628).
|
||||
autofill.armForCommand("sudo whoami");
|
||||
autofill.handleOutput("Password: ");
|
||||
assert.deepEqual(hints, []);
|
||||
assert.deepEqual(hints, [true]);
|
||||
autofill.armForCommand("su -");
|
||||
autofill.handleOutput("Password: ");
|
||||
assert.deepEqual(hints, [true]);
|
||||
assert.deepEqual(hints, [true, false, true]);
|
||||
});
|
||||
|
||||
for (const command of ["sudo ping 192.168.30.4", "sudo su"]) {
|
||||
for (const prompt of ["Password:", "密码:"]) {
|
||||
test(`${command} shows only the host-password hint for ${prompt} (#4628)`, () => {
|
||||
const hints: boolean[] = [];
|
||||
const writes: string[] = [];
|
||||
const autofill = createSudoPasswordAutofill({
|
||||
mode: "picker",
|
||||
password: "host-secret",
|
||||
candidates: [{ id: "other", label: "Other", password: "other-secret" }],
|
||||
write: (data) => writes.push(data),
|
||||
onHint: (active) => {
|
||||
hints.push(active);
|
||||
return true;
|
||||
},
|
||||
onPicker: () => assert.fail("sudo must not open the full keychain picker"),
|
||||
});
|
||||
autofill.armForCommand(command);
|
||||
autofill.handleOutput(prompt);
|
||||
assert.deepEqual(hints, [true]);
|
||||
assert.deepEqual(writes, []);
|
||||
assert.equal(autofill.isPromptPending(), true);
|
||||
assert.equal(autofill.isPickerPending(), false);
|
||||
autofill.confirmFill();
|
||||
assert.deepEqual(writes, ["host-secret\n"]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test("sudo arms still reject child and remote password prompts (#4628)", () => {
|
||||
for (const prompt of ["Enter password:", "Password for user postgres:", "user@host's password:"]) {
|
||||
const { autofill, hints, writes } = make();
|
||||
autofill.armForCommand("sudo su");
|
||||
autofill.handleOutput(prompt);
|
||||
assert.deepEqual(hints, [], prompt);
|
||||
assert.equal(autofill.isPromptPending(), false, prompt);
|
||||
autofill.confirmFill();
|
||||
assert.deepEqual(writes, [], prompt);
|
||||
}
|
||||
});
|
||||
|
||||
for (const { output, retry } of [
|
||||
{ output: "\r\nPassword:", retry: false },
|
||||
{ output: "\r\nSorry, try again.\r\nPassword:", retry: true },
|
||||
{ output: "\r\n[sudo] password for alice:", retry: true },
|
||||
]) {
|
||||
test(`sudo bare prompt after confirmFill requires auth retry evidence: ${JSON.stringify(output)} (#4628)`, () => {
|
||||
const { autofill, hints, writes } = make();
|
||||
autofill.armForCommand("sudo su");
|
||||
autofill.handleOutput("Password:");
|
||||
assert.equal(autofill.isPromptPending(), true);
|
||||
autofill.confirmFill();
|
||||
assert.deepEqual(writes, ["secret\n"]);
|
||||
autofill.handleOutput(output);
|
||||
assert.equal(autofill.isPromptPending(), retry);
|
||||
assert.deepEqual(hints, retry ? [true, false, true] : [true, false]);
|
||||
autofill.confirmFill();
|
||||
assert.deepEqual(writes, retry ? ["secret\n", "secret\n"] : ["secret\n"]);
|
||||
});
|
||||
}
|
||||
|
||||
test("an explicit [sudo] prompt hints without a recorded sudo command", () => {
|
||||
// The [sudo] tag is sudo-specific, so we hint even when arming didn't fire —
|
||||
// manual typing's recordedCommand is flaky (#1281/#1284), and the hint only
|
||||
|
||||
@@ -350,9 +350,10 @@ export const createSudoPasswordAutofill = (_options: {
|
||||
if (!armActive) return false;
|
||||
// su always prompts with a bare Password: line (not Enter password / DB).
|
||||
if (armedKind === "su") return isSuBarePasswordPrompt(line);
|
||||
// sudo: only sudo-scoped prompts, never generic "Enter password:" from
|
||||
// child programs when sudo credentials are already cached.
|
||||
if (armedKind === "sudo") return isSudoScopedBarePasswordPrompt(line);
|
||||
// macOS / Synology / BSD sudo uses the same short bare Password: as su (#4628).
|
||||
if (armedKind === "sudo") {
|
||||
return isSudoScopedBarePasswordPrompt(line) || isSuBarePasswordPrompt(line);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -442,8 +443,8 @@ export const createSudoPasswordAutofill = (_options: {
|
||||
dismissedWhileArmed = false;
|
||||
armedKind = null;
|
||||
}
|
||||
// Explicit "[sudo] …" always; su arm accepts bare Password:; sudo arm only
|
||||
// accepts sudo-scoped bare prompts (not generic Enter password from mysql).
|
||||
// Explicit "[sudo] …" always; su/sudo arms accept short bare Password:;
|
||||
// sudo also accepts scoped prompts (not generic Enter password from mysql).
|
||||
const isPrompt = isArmedPromptLine(lastLine, armActive);
|
||||
if (pending) {
|
||||
// The prompt moved on: a new line arrived and the latest line is no
|
||||
|
||||
@@ -30,6 +30,7 @@ function createContext(input: string) {
|
||||
fastTypingThresholdMs: 40,
|
||||
shiftEnterNewlineEnabled: true,
|
||||
historyScope: "host",
|
||||
showSnippets: true,
|
||||
};
|
||||
const context = {
|
||||
settingsRef: ref(settings),
|
||||
|
||||
@@ -28,6 +28,7 @@ test("keeps autocomplete enabled for shell-like terminal protocols", () => {
|
||||
minChars: 2,
|
||||
maxSuggestions: 6,
|
||||
historyScope: "global",
|
||||
showSnippets: true,
|
||||
shiftEnterNewlineEnabled: false,
|
||||
},
|
||||
);
|
||||
@@ -57,6 +58,7 @@ test("keeps network-device autocomplete popup but disables live preview (#1193)"
|
||||
minChars: 1,
|
||||
maxSuggestions: 8,
|
||||
historyScope: "host",
|
||||
showSnippets: true,
|
||||
shiftEnterNewlineEnabled: true,
|
||||
},
|
||||
);
|
||||
@@ -109,6 +111,7 @@ test("keeps serial autocomplete available but disables input-line preview and re
|
||||
minChars: 1,
|
||||
maxSuggestions: 8,
|
||||
historyScope: "host",
|
||||
showSnippets: true,
|
||||
livePreview: false,
|
||||
allowLineReplacement: false,
|
||||
shiftEnterNewlineEnabled: true,
|
||||
@@ -154,3 +157,33 @@ test('unknown systems do not rewrite the command line while retaining suggestion
|
||||
assert.equal(settings?.allowLineReplacement, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("defaults showSnippets to true and preserves explicit false across protocols", () => {
|
||||
assert.equal(
|
||||
resolveTerminalAutocompleteSettings({
|
||||
protocol: "ssh",
|
||||
terminalSettings: { autocompleteEnabled: true },
|
||||
})?.showSnippets,
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalAutocompleteSettings({
|
||||
protocol: "ssh",
|
||||
terminalSettings: { autocompleteShowSnippets: false },
|
||||
})?.showSnippets,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalAutocompleteSettings({
|
||||
protocol: "serial",
|
||||
terminalSettings: { autocompleteShowSnippets: false },
|
||||
})?.showSnippets,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
resolveTerminalAutocompleteSettings({
|
||||
protocol: "serial",
|
||||
})?.showSnippets,
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -99,3 +99,17 @@ test("clearing command history restores the live-preview baseline (#3632)", () =
|
||||
);
|
||||
});
|
||||
|
||||
test("useTerminalAutocomplete excludes snippets when showSnippets is false", () => {
|
||||
const source = readFileSync(
|
||||
fileURLToPath(new URL("./autocomplete/useTerminalAutocomplete.ts", import.meta.url)),
|
||||
"utf8",
|
||||
);
|
||||
assert.match(source, /showSnippets: true,/);
|
||||
assert.match(source, /snippets: settingsRef\.current\.showSnippets \? snippetsRef\.current : undefined,/);
|
||||
assert.match(source, /showSnippets: settingsRef\.current\.showSnippets,/);
|
||||
assert.match(
|
||||
source,
|
||||
/if \(!settingsRef\.current\.showSnippets\) \{\s*completions = completions\.filter\(\(completion\) => completion\.source !== "snippet"\);/,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Runtime user questions
|
||||
|
||||
Use a runtime's native question callback when one is available. Keep its
|
||||
protocol mapping in the driver; share the application form and its lifecycle.
|
||||
An answer provides context, not permission. It does not change Auto, Confirm,
|
||||
or Observer. Never turn a question into tool approval or collect credentials
|
||||
through the question card.
|
||||
|
||||
## Integration points
|
||||
|
||||
For an in-app SDK turn, the registry can pass `requestUserForm(form, signal)`
|
||||
into a driver. The form uses the existing SDK elicitation create/complete events
|
||||
and the existing renderer form. The broker generates the response ID and
|
||||
accepts a single answer from the originating renderer. It clears the form on
|
||||
cancel, timeout, or turn teardown; delegated turns do not receive this hook.
|
||||
Timeout and cancellation do not fabricate an answer. The existing SDK answer
|
||||
privacy handling applies to renderer replies.
|
||||
|
||||
Grok ACP uses this hook for `_x.ai/ask_user_question`. The adapter checks the
|
||||
ACP session, presents bounded text or offered choices, and maps answers back
|
||||
to Grok's native `accepted` or `cancelled` response. Observer can answer a question
|
||||
without obtaining write permission. Grok's rich previews and special Plan
|
||||
interview actions are out of scope for this adapter.
|
||||
|
||||
## Compatibility snapshot
|
||||
|
||||
| Runtime | Native path and Netcatty status |
|
||||
| --- | --- |
|
||||
| Grok ACP | Native question request wired through the shared SDK form. Streaming-JSON is not changed. |
|
||||
| Codex App Server | Already wired in Netcatty: `item/tool/requestUserInput` is separately routed, answered and tested. A future renderer consolidation can reuse the form without changing the Codex protocol. |
|
||||
| Codex SDK | Do not assume App Server support applies to the SDK path. No equivalent reverse request is wired here. |
|
||||
| Claude Agent SDK | Native `AskUserQuestion` input and SDK tool callbacks exist. Netcatty currently disallows this tool in the Claude UI driver; a separate adapter must own its answer path before removing the block. |
|
||||
| CodeBuddy | Existing SDK MCP elicitation is already wired to this form. That does not enable its separate native `AskUserQuestion` tool. |
|
||||
| GitHub Copilot SDK | SDK offers `onUserInputRequest` for `ask_user`; the current driver does not register it. A separate adapter is needed. |
|
||||
| Cursor CLI, OpenCode, MiMo | This change does not wire or verify a native question path. Inspect the specific runtime before advertising support. |
|
||||
|
||||
No public MCP capability or configuration is added. A future optional
|
||||
MCP question tool should require an identified, live chat and opt-in, expose
|
||||
only bounded non-secret inputs, and apply rate/cancellation limits. A Skill can
|
||||
guide when to ask, but does not grant permissions or implement a reply channel.
|
||||
@@ -0,0 +1,65 @@
|
||||
# In-app agent interactions
|
||||
|
||||
Some agent runtimes need a decision from the user before they can continue.
|
||||
For example, Grok submits its implementation plan for review through its
|
||||
`_x.ai/exit_plan_mode` ACP request. Approving the plan is not the same as
|
||||
granting another tool permission.
|
||||
|
||||
## First integration: Grok plan review
|
||||
|
||||
- The Grok ACP adapter validates the runtime session and maps the specific
|
||||
reverse request to a chat-scoped `plan-review` interaction. The existing
|
||||
main-process approval bridge and renderer approval store handle delivery,
|
||||
response correlation, and cancellation.
|
||||
- **Approve and implement** grants only this plan review. **Keep planning**
|
||||
declines the review without granting permission to implement. There is no
|
||||
persistent or session-wide grant. A running turn can be stopped normally;
|
||||
a timeout or missing review channel never approves the plan.
|
||||
- Generic tool auto-approval does not answer this request. Observer and
|
||||
delegated turns cannot approve implementation through this path.
|
||||
- Unsupported reverse requests return an explicit method-not-found error.
|
||||
The adapter never guesses an answer or converts a different request into a
|
||||
successful permission grant.
|
||||
|
||||
The bridge and interaction discriminator are internal extension points, not
|
||||
public MCP or plugin APIs. A new runtime should map only requests it
|
||||
recognizes, preserve the runtime's decision semantics, and use the existing
|
||||
chat/turn lifecycle rather than opening a second approval channel.
|
||||
|
||||
Today the Grok driver calls
|
||||
`requestApprovalFromRenderer(label, { plan }, chatSessionId, context)`
|
||||
with `interactionKind: "plan-review"`, `requireFreshApproval: true`, and the
|
||||
turn's abort signal in `context`. A literal `true` maps to Grok's
|
||||
`approved` outcome; a negative or unavailable decision maps to `cancelled`
|
||||
while the turn is still live. A terminated turn cannot receive a late approval.
|
||||
This boolean interface is suitable for a decision, not for answers with values.
|
||||
|
||||
## Follow-up design (not implemented)
|
||||
|
||||
Add a second concrete runtime integration first, such as a structured user
|
||||
question with typed choices. Share the request envelope and lifecycle across
|
||||
runtimes, but keep separate response types for questions, plan reviews, tool
|
||||
approvals, and authentication. Approval IDs should be host-owned, bound to
|
||||
the originating agent session and turn, and settled once. A reply from a
|
||||
stale turn or a different chat must not be accepted.
|
||||
|
||||
Keep interaction policy separate from action permission:
|
||||
|
||||
- **Auto:** keep approving eligible tool actions as before; still ask the user
|
||||
when an explicitly supported runtime request requires a human decision.
|
||||
- **Confirm:** keep normal action approvals and also present required runtime
|
||||
interactions. A plan approval does not replace any required action approval.
|
||||
- **Observer:** allow informational questions if enabled, but do not approve
|
||||
implementation or grant write permissions.
|
||||
|
||||
If an unattended run cannot obtain a required answer, report that it could
|
||||
not continue. Do not silently approve or try to override a runtime restriction.
|
||||
A per-agent preference for optional questions can be considered separately from
|
||||
required runtime interactions.
|
||||
|
||||
An MCP capability could later let supported agents without a native interaction
|
||||
protocol ask a structured, chat-scoped question, subject to capability
|
||||
advertising, session validation, and rate limits. Start with a bounded
|
||||
question, not a generic authorization endpoint. A Skill can tell an agent when
|
||||
to invoke the capability, but cannot implement the UI, suspend execution, or
|
||||
grant permissions on its own.
|
||||
@@ -2,14 +2,17 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import {
|
||||
addCustomKeyBindingExtra,
|
||||
areCustomKeyBindingsEqual,
|
||||
nextCustomKeyBindingsSyncVersion,
|
||||
parseCustomKeyBindingsStorageRecord,
|
||||
removeCustomKeyBindingExtra,
|
||||
resetCustomKeyBinding,
|
||||
resolveKeyBindings,
|
||||
serializeCustomKeyBindingsStorageRecord,
|
||||
shouldApplyIncomingCustomKeyBindingsRecord,
|
||||
updateCustomKeyBinding,
|
||||
updateCustomKeyBindingExtra,
|
||||
} from './customKeyBindings.ts';
|
||||
import { DEFAULT_KEY_BINDINGS, keyStringToKeyboardEvent } from './models/keyBindings.ts';
|
||||
import { checkAppShortcut } from '../application/state/useGlobalHotkeys.ts';
|
||||
@@ -258,3 +261,74 @@ test('resetting the last side removes the binding entry entirely', () => {
|
||||
|
||||
assert.deepEqual(next, {});
|
||||
});
|
||||
|
||||
|
||||
test('secondary chord resolves to the same action as its base binding', () => {
|
||||
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
|
||||
'open-local': { extra: [{ pc: 'Ctrl + Shift + E' }] },
|
||||
});
|
||||
|
||||
assert.equal(shortcut('Ctrl + Shift + E', bindings), 'openLocal');
|
||||
assert.equal(shortcut('\u2318 + L', bindings, true), 'openLocal');
|
||||
const extra = bindings.find(binding => binding.extraOf === 'open-local');
|
||||
assert.equal(extra?.id, 'open-local::extra-0');
|
||||
assert.equal(extra?.mac, 'Disabled');
|
||||
});
|
||||
|
||||
test('a secondary chord evicts the default that already occupies it', () => {
|
||||
const bindings = resolveKeyBindings(DEFAULT_KEY_BINDINGS, {
|
||||
'open-local': { extra: [{ pc: 'Ctrl + Shift + T' }] },
|
||||
});
|
||||
|
||||
assert.equal(bindings.find(binding => binding.id === 'reopen-closed-tab')?.pc, 'Disabled');
|
||||
assert.equal(shortcut('Ctrl + Shift + T', bindings), 'openLocal');
|
||||
assert.equal(shortcut('\u2318 + Shift + T', bindings, true), 'reopenClosedTab');
|
||||
});
|
||||
|
||||
test('adding, re-recording, and removing a secondary chord', () => {
|
||||
let custom = addCustomKeyBindingExtra({}, 'open-local', 'mac', '\u2318 + Shift + E');
|
||||
assert.deepEqual(custom, { 'open-local': { extra: [{ mac: '\u2318 + Shift + E' }] } });
|
||||
|
||||
custom = addCustomKeyBindingExtra(custom, 'open-local', 'pc', 'Ctrl + Shift + E');
|
||||
assert.deepEqual(custom['open-local'].extra, [
|
||||
{ mac: '\u2318 + Shift + E' },
|
||||
{ pc: 'Ctrl + Shift + E' },
|
||||
]);
|
||||
|
||||
custom = updateCustomKeyBindingExtra(custom, 'open-local', 1, 'pc', 'Ctrl + Shift + R');
|
||||
assert.deepEqual(custom['open-local'].extra?.[1], { pc: 'Ctrl + Shift + R' });
|
||||
|
||||
custom = removeCustomKeyBindingExtra(custom, 'open-local', 0);
|
||||
assert.deepEqual(custom['open-local'].extra, [{ pc: 'Ctrl + Shift + R' }]);
|
||||
});
|
||||
|
||||
test('resetting one scheme keeps the secondary chords', () => {
|
||||
const custom = addCustomKeyBindingExtra(
|
||||
{ 'open-local': { mac: '\u2318 + Shift + E' } },
|
||||
'open-local',
|
||||
'pc',
|
||||
'Ctrl + Shift + E',
|
||||
);
|
||||
const reset = resetCustomKeyBinding(custom, 'open-local', 'mac');
|
||||
|
||||
assert.deepEqual(reset['open-local'], { extra: [{ pc: 'Ctrl + Shift + E' }] });
|
||||
});
|
||||
|
||||
test('removing the last secondary chord leaves the base override intact', () => {
|
||||
const custom = addCustomKeyBindingExtra(
|
||||
{ 'open-local': { pc: 'Ctrl + L' } },
|
||||
'open-local',
|
||||
'mac',
|
||||
'\u2318 + Shift + E',
|
||||
);
|
||||
const reset = removeCustomKeyBindingExtra(custom, 'open-local', 0);
|
||||
|
||||
assert.deepEqual(reset['open-local'], { pc: 'Ctrl + L', extra: undefined });
|
||||
});
|
||||
|
||||
test('removing the only secondary chord drops the now-empty override', () => {
|
||||
const custom = addCustomKeyBindingExtra({}, 'open-local', 'pc', 'Ctrl + Shift + E');
|
||||
const reset = removeCustomKeyBindingExtra(custom, 'open-local', 0);
|
||||
|
||||
assert.deepEqual(reset, {});
|
||||
});
|
||||
@@ -1,4 +1,32 @@
|
||||
import { CustomKeyBindings, KeyBinding } from './models';
|
||||
import { CustomKeyBindings, KeyBinding, KeyBindingExtra } from './models';
|
||||
|
||||
/**
|
||||
* Expand user-added secondary chords into real bindings so the dispatcher can
|
||||
* match them like any default shortcut. `extraOf` keeps them out of the
|
||||
* one-row-per-action settings list.
|
||||
*/
|
||||
const expandExtraKeyBindings = (
|
||||
bindings: readonly KeyBinding[],
|
||||
customKeyBindings: CustomKeyBindings,
|
||||
): KeyBinding[] => {
|
||||
const expanded: KeyBinding[] = [];
|
||||
for (const binding of bindings) {
|
||||
expanded.push(binding);
|
||||
(customKeyBindings[binding.id]?.extra ?? []).forEach((extra, index) => {
|
||||
const mac = extra.mac ?? 'Disabled';
|
||||
const pc = extra.pc ?? 'Disabled';
|
||||
if (mac === 'Disabled' && pc === 'Disabled') return;
|
||||
expanded.push({
|
||||
...binding,
|
||||
id: `${binding.id}::extra-${index}`,
|
||||
mac,
|
||||
pc,
|
||||
extraOf: binding.id,
|
||||
});
|
||||
});
|
||||
}
|
||||
return expanded;
|
||||
};
|
||||
|
||||
export const resolveKeyBindings = (
|
||||
defaults: readonly KeyBinding[],
|
||||
@@ -20,6 +48,12 @@ export const resolveKeyBindings = (
|
||||
if (customKeyBindings[binding.id]?.[scheme] != null && binding[scheme] !== 'Disabled') {
|
||||
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(binding[scheme]);
|
||||
}
|
||||
for (const extra of customKeyBindings[binding.id]?.extra ?? []) {
|
||||
const chord = extra[scheme];
|
||||
if (chord && chord !== 'Disabled') {
|
||||
customChords[binding.category === 'sftp' ? 'sftp' : 'app'].add(chord);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SFTP has its own input context; all other categories share the app-level handler.
|
||||
@@ -32,7 +66,7 @@ export const resolveKeyBindings = (
|
||||
));
|
||||
}
|
||||
|
||||
return merged;
|
||||
return expandExtraKeyBindings(merged, customKeyBindings);
|
||||
};
|
||||
|
||||
const SYNC_VERSION_FIELD = '__netcattySyncVersion';
|
||||
@@ -166,3 +200,56 @@ export const resetCustomKeyBinding = (
|
||||
[bindingId]: nextBinding,
|
||||
};
|
||||
};
|
||||
|
||||
const writeExtras = (
|
||||
bindings: CustomKeyBindings,
|
||||
bindingId: string,
|
||||
extra: KeyBindingExtra[],
|
||||
): CustomKeyBindings => {
|
||||
const existing = bindings[bindingId] ?? {};
|
||||
const next = { ...existing, extra: extra.length > 0 ? extra : undefined };
|
||||
if (next.mac == null && next.pc == null && !next.extra) {
|
||||
const { [bindingId]: _removed, ...rest } = bindings;
|
||||
return rest;
|
||||
}
|
||||
return {
|
||||
...bindings,
|
||||
[bindingId]: next,
|
||||
};
|
||||
};
|
||||
|
||||
/** Append a secondary chord to a binding without touching its primary chord. */
|
||||
export const addCustomKeyBindingExtra = (
|
||||
bindings: CustomKeyBindings,
|
||||
bindingId: string,
|
||||
scheme: 'mac' | 'pc',
|
||||
newKey: string,
|
||||
): CustomKeyBindings => {
|
||||
const extra = [...(bindings[bindingId]?.extra ?? [])];
|
||||
extra.push({ [scheme]: newKey } as KeyBindingExtra);
|
||||
return writeExtras(bindings, bindingId, extra);
|
||||
};
|
||||
|
||||
export const updateCustomKeyBindingExtra = (
|
||||
bindings: CustomKeyBindings,
|
||||
bindingId: string,
|
||||
index: number,
|
||||
scheme: 'mac' | 'pc',
|
||||
newKey: string,
|
||||
): CustomKeyBindings => {
|
||||
const extra = [...(bindings[bindingId]?.extra ?? [])];
|
||||
if (index < 0 || index >= extra.length) return bindings;
|
||||
extra[index] = { ...extra[index], [scheme]: newKey };
|
||||
return writeExtras(bindings, bindingId, extra);
|
||||
};
|
||||
|
||||
export const removeCustomKeyBindingExtra = (
|
||||
bindings: CustomKeyBindings,
|
||||
bindingId: string,
|
||||
index: number,
|
||||
): CustomKeyBindings => {
|
||||
const extra = [...(bindings[bindingId]?.extra ?? [])];
|
||||
if (index < 0 || index >= extra.length) return bindings;
|
||||
extra.splice(index, 1);
|
||||
return writeExtras(bindings, bindingId, extra);
|
||||
};
|
||||
@@ -8,10 +8,26 @@ export interface KeyBinding {
|
||||
mac: string; // e.g., '⌘+1', '⌘+⌥+arrows'
|
||||
pc: string; // e.g., 'Ctrl+1', 'Ctrl+Alt+arrows'
|
||||
category: 'tabs' | 'terminal' | 'navigation' | 'app' | 'sftp';
|
||||
/**
|
||||
* Set on a user-added secondary shortcut. The entry shares its action with
|
||||
* the default binding whose id this holds, so it never renders as its own row.
|
||||
*/
|
||||
extraOf?: string;
|
||||
}
|
||||
|
||||
/** One user-added secondary shortcut for a default binding. */
|
||||
export interface KeyBindingExtra {
|
||||
mac?: string;
|
||||
pc?: string;
|
||||
}
|
||||
|
||||
// User's custom key bindings - only stores overrides from defaults
|
||||
export type CustomKeyBindings = Record<string, { mac?: string; pc?: string }>;
|
||||
export type CustomKeyBindings = Record<string, {
|
||||
mac?: string;
|
||||
pc?: string;
|
||||
/** Additional chords that trigger the same action as the default binding. */
|
||||
extra?: KeyBindingExtra[];
|
||||
}>;
|
||||
|
||||
// Parse a key string like "⌘ + Shift + K" or "Ctrl + Alt + T" into normalized form
|
||||
export const parseKeyCombo = (keyStr: string): { modifiers: string[]; key: string } | null => {
|
||||
@@ -236,6 +252,22 @@ export const matchesKeyBinding = (e: KeyboardEvent, keyStr: string, isMac: boole
|
||||
return eventKey.toLowerCase() === parsedKey.toLowerCase();
|
||||
};
|
||||
|
||||
/** Every binding that triggers `action`, including user-added secondary chords. */
|
||||
export const findBindingsForAction = (
|
||||
bindings: readonly KeyBinding[],
|
||||
action: string,
|
||||
): KeyBinding[] => bindings.filter((binding) => binding.action === action);
|
||||
|
||||
/** True when any binding of `action` matches the event. */
|
||||
export const matchesActionKeyBinding = (
|
||||
e: KeyboardEvent,
|
||||
bindings: readonly KeyBinding[],
|
||||
action: string,
|
||||
isMac: boolean,
|
||||
): boolean => findBindingsForAction(bindings, action).some((binding) => (
|
||||
matchesKeyBinding(e, isMac ? binding.mac : binding.pc, isMac)
|
||||
));
|
||||
|
||||
export const DEFAULT_KEY_BINDINGS: KeyBinding[] = [
|
||||
// Tab Management
|
||||
{ id: 'switch-tab-1-9', action: 'switchToTab', label: 'Switch to Tab [1...9]', mac: '⌘ + [1...9]', pc: 'Ctrl + [1...9]', category: 'tabs' },
|
||||
|
||||
@@ -269,6 +269,8 @@ export interface TerminalSettings {
|
||||
autocompleteMaxSuggestions: number; // Maximum suggestions in popup menu
|
||||
/** Scope for history-backed autocomplete suggestions (host vs all hosts). */
|
||||
autocompleteHistoryScope: AutocompleteHistoryScope;
|
||||
/** Include matching code snippets in terminal autocomplete suggestions. */
|
||||
autocompleteShowSnippets: boolean;
|
||||
|
||||
/**
|
||||
* Assist for sudo/su password prompts: off, quick Enter-to-paste (hint),
|
||||
@@ -480,6 +482,7 @@ export const normalizeTerminalSettings = (
|
||||
autocompleteHistoryScope: isAutocompleteHistoryScope(settings?.autocompleteHistoryScope)
|
||||
? settings.autocompleteHistoryScope
|
||||
: DEFAULT_TERMINAL_SETTINGS.autocompleteHistoryScope,
|
||||
autocompleteShowSnippets: settings?.autocompleteShowSnippets !== false,
|
||||
oscNotifications: isOscNotificationMode(settings?.oscNotifications)
|
||||
? settings.oscNotifications
|
||||
: DEFAULT_TERMINAL_SETTINGS.oscNotifications,
|
||||
@@ -663,6 +666,7 @@ const DEFAULT_TERMINAL_SETTINGS: TerminalSettings = {
|
||||
autocompleteMinChars: 1, // Start suggesting after 1 character
|
||||
autocompleteMaxSuggestions: 50, // Show up to 50 suggestions (popup scrolls)
|
||||
autocompleteHistoryScope: 'host', // Per-host history suggestions by default (#2595)
|
||||
autocompleteShowSnippets: true, // Include matching code snippets in autocomplete by default
|
||||
passwordPromptAssist: 'hint', // Historical sudo confirm-to-fill; picker is opt-in (#2156)
|
||||
};
|
||||
|
||||
|
||||
@@ -359,3 +359,22 @@ test("settings search finds the SFTP tree view folder double-click option from t
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("settings search finds the autocomplete show code snippets toggle across locales", () => {
|
||||
const tZhReal = (key: string) => zhCN[key] ?? key;
|
||||
const tTwReal = (key: string) => zhTW[key] ?? key;
|
||||
const tEnReal = (key: string) => en[key] ?? key;
|
||||
for (const [t, queries] of [
|
||||
[tZhReal, ["显示代码片段", "代码片段", "补全"]],
|
||||
[tTwReal, ["顯示程式碼片段", "程式碼片段"]],
|
||||
[tEnReal, ["show code snippets", "snippet", "snippets"]],
|
||||
] as const) {
|
||||
for (const query of queries) {
|
||||
const hit = filterSettingsSearchCatalog(query, t).find(
|
||||
(hit) => hit.entry.id === "terminal-autocomplete-show-snippets",
|
||||
);
|
||||
assert.ok(hit, `${query} should find terminal-autocomplete-show-snippets`);
|
||||
assert.equal(hit.entry.tab, "terminal");
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -931,6 +931,14 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "settings.terminal.autocomplete.historyScope.desc",
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
},
|
||||
{
|
||||
id: "terminal-autocomplete-show-snippets",
|
||||
tab: "terminal",
|
||||
labelKey: "settings.terminal.autocomplete.showSnippets",
|
||||
descriptionKey: "settings.terminal.autocomplete.showSnippets.desc",
|
||||
sectionKey: "settings.terminal.section.autocomplete",
|
||||
keywords: ["snippet", "snippets", "code snippets", "代码片段", "程式碼片段", "补全", "補全"],
|
||||
},
|
||||
{
|
||||
id: "terminal-password-prompt-assist",
|
||||
tab: "terminal",
|
||||
@@ -1291,7 +1299,7 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
labelKey: "ai.webSearch.enable",
|
||||
descriptionKey: "ai.webSearch.enable.description",
|
||||
sectionKey: "ai.webSearch.title",
|
||||
keywords: ["tavily", "brave", "web search"],
|
||||
keywords: ["tavily", "brave", "deepseek", "web search"],
|
||||
},
|
||||
{
|
||||
id: "ai-web-search-provider",
|
||||
|
||||
@@ -106,6 +106,31 @@ test("normalizeTerminalSettings falls back for unsupported autocomplete history
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizeTerminalSettings defaults autocompleteShowSnippets to true", () => {
|
||||
assert.equal(normalizeTerminalSettings().autocompleteShowSnippets, true);
|
||||
assert.equal(normalizeTerminalSettings({}).autocompleteShowSnippets, true);
|
||||
});
|
||||
|
||||
test("normalizeTerminalSettings preserves explicit autocompleteShowSnippets values", () => {
|
||||
assert.equal(
|
||||
normalizeTerminalSettings({ autocompleteShowSnippets: false }).autocompleteShowSnippets,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
normalizeTerminalSettings({ autocompleteShowSnippets: true }).autocompleteShowSnippets,
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizeTerminalSettings normalizes missing or non-boolean autocompleteShowSnippets to true", () => {
|
||||
for (const invalid of [undefined, null, "false", 0, {}]) {
|
||||
assert.equal(
|
||||
normalizeTerminalSettings({ autocompleteShowSnippets: invalid as never }).autocompleteShowSnippets,
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizeTerminalSettings enables Shift+Enter newline by default", () => {
|
||||
const settings = normalizeTerminalSettings();
|
||||
|
||||
|
||||
@@ -116,6 +116,26 @@ test("ssh_config import maps ForwardX11 no to disabled host X11 forwarding", ()
|
||||
assert.equal(result.hosts[0].x11Forwarding, false);
|
||||
});
|
||||
|
||||
test("ssh_config import merges an alias declared in several Host blocks", () => {
|
||||
const result = importVaultHostsFromText("ssh_config", [
|
||||
"Host hd-edu-web1",
|
||||
" HostName 10.147.28.11",
|
||||
" User root",
|
||||
"",
|
||||
"Host hd-edu-web1",
|
||||
" IdentityFile ~/.ssh/id_rsa",
|
||||
" IdentitiesOnly yes",
|
||||
].join("\n"));
|
||||
|
||||
assert.equal(result.hosts.length, 1);
|
||||
const [host] = result.hosts;
|
||||
assert.equal(host.label, "hd-edu-web1");
|
||||
assert.equal(host.hostname, "10.147.28.11");
|
||||
assert.equal(host.username, "root");
|
||||
assert.deepEqual(host.identityFilePaths, ["~/.ssh/id_rsa"]);
|
||||
assert.equal(host.identitiesOnly, true);
|
||||
});
|
||||
|
||||
test("ssh_config import enables agent login for the macOS Keychain pattern", () => {
|
||||
const result = importVaultHostsFromText("ssh_config", [
|
||||
"Host aws-sg",
|
||||
|
||||
+96
-55
@@ -1105,70 +1105,111 @@ const importFromSshConfig = (text: string): VaultImportResult => {
|
||||
const makeHostKey = (hostname: string, port?: number) =>
|
||||
`${hostname.toLowerCase()}:${port ?? 22}`;
|
||||
|
||||
for (const block of blocks) {
|
||||
const patterns = block.patterns.filter((p) => p && !isWildcardPattern(p));
|
||||
if (patterns.length === 0) continue;
|
||||
// OpenSSH applies every Host block whose pattern matches an alias and keeps
|
||||
// the first obtained value, so one alias may be declared in several blocks
|
||||
// (for example HostName/User in one block and IdentityFile in another).
|
||||
// Resolve options per literal pattern; treating every block as its own host
|
||||
// imported such an alias twice, and the second copy kept the alias itself as
|
||||
// its hostname with no username.
|
||||
const orderedPatterns: string[] = [];
|
||||
const blockByPattern = new Map<string, Block>();
|
||||
const inheritOption = <K extends keyof Block>(target: Block, source: Block, key: K) => {
|
||||
if (target[key] === undefined && source[key] !== undefined) target[key] = source[key];
|
||||
};
|
||||
|
||||
for (const pat of patterns) {
|
||||
parsed++;
|
||||
const hostname = block.hostname ?? pat;
|
||||
if (!looksLikeHostnameToken(hostname)) {
|
||||
skipped++;
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: `ssh_config: skipped host "${pat}" (invalid hostname).`,
|
||||
for (const block of blocks) {
|
||||
for (const pattern of block.patterns) {
|
||||
if (!pattern || isWildcardPattern(pattern)) continue;
|
||||
const merged = blockByPattern.get(pattern);
|
||||
if (!merged) {
|
||||
blockByPattern.set(pattern, {
|
||||
...block,
|
||||
patterns: [pattern],
|
||||
identityFiles: block.identityFiles ? [...block.identityFiles] : undefined,
|
||||
});
|
||||
orderedPatterns.push(pattern);
|
||||
continue;
|
||||
}
|
||||
inheritOption(merged, block, "hostname");
|
||||
inheritOption(merged, block, "username");
|
||||
inheritOption(merged, block, "port");
|
||||
inheritOption(merged, block, "proxyJump");
|
||||
inheritOption(merged, block, "identityAgent");
|
||||
inheritOption(merged, block, "identitiesOnly");
|
||||
inheritOption(merged, block, "addKeysToAgent");
|
||||
inheritOption(merged, block, "useKeychain");
|
||||
inheritOption(merged, block, "forwardX11");
|
||||
if (block.identityFiles?.length) {
|
||||
const seen = new Set(merged.identityFiles ?? []);
|
||||
for (const identityFile of block.identityFiles) {
|
||||
if (seen.has(identityFile)) continue;
|
||||
seen.add(identityFile);
|
||||
(merged.identityFiles ??= []).push(identityFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const host = createHost({
|
||||
label: pat,
|
||||
hostname,
|
||||
username: block.username,
|
||||
port: block.port,
|
||||
protocol: "ssh",
|
||||
for (const pattern of orderedPatterns) {
|
||||
const block = blockByPattern.get(pattern)!;
|
||||
parsed++;
|
||||
const hostname = block.hostname ?? pattern;
|
||||
if (!looksLikeHostnameToken(hostname)) {
|
||||
skipped++;
|
||||
issues.push({
|
||||
level: "warning",
|
||||
message: `ssh_config: skipped host "${pattern}" (invalid hostname).`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Attach IdentityFile paths if present
|
||||
if (block.identityFiles && block.identityFiles.length > 0) {
|
||||
host.identityFilePaths = [...block.identityFiles];
|
||||
}
|
||||
if (block.identityAgent !== undefined) {
|
||||
host.identityAgent = block.identityAgent;
|
||||
}
|
||||
if (block.identitiesOnly !== undefined) {
|
||||
host.identitiesOnly = block.identitiesOnly;
|
||||
}
|
||||
if (block.addKeysToAgent !== undefined) {
|
||||
host.addKeysToAgent = block.addKeysToAgent;
|
||||
}
|
||||
if (block.useKeychain !== undefined) {
|
||||
host.useKeychain = block.useKeychain;
|
||||
}
|
||||
const identityAgentEnabled = block.identityAgent !== undefined
|
||||
&& block.identityAgent.toLowerCase() !== "none";
|
||||
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
|
||||
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
|
||||
// declaring IdentityAgent. Treat that pair as an agent-backed login so
|
||||
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
|
||||
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
|
||||
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
|
||||
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
|
||||
host.useSshAgent = true;
|
||||
} else if (identityAgentDisabled) {
|
||||
host.useSshAgent = false;
|
||||
}
|
||||
if (block.forwardX11 !== undefined) {
|
||||
host.x11Forwarding = block.forwardX11;
|
||||
}
|
||||
const host = createHost({
|
||||
label: pattern,
|
||||
hostname,
|
||||
username: block.username,
|
||||
port: block.port,
|
||||
protocol: "ssh",
|
||||
});
|
||||
|
||||
parsedHosts.push(host);
|
||||
// Attach IdentityFile paths if present
|
||||
if (block.identityFiles && block.identityFiles.length > 0) {
|
||||
host.identityFilePaths = [...block.identityFiles];
|
||||
}
|
||||
if (block.identityAgent !== undefined) {
|
||||
host.identityAgent = block.identityAgent;
|
||||
}
|
||||
if (block.identitiesOnly !== undefined) {
|
||||
host.identitiesOnly = block.identitiesOnly;
|
||||
}
|
||||
if (block.addKeysToAgent !== undefined) {
|
||||
host.addKeysToAgent = block.addKeysToAgent;
|
||||
}
|
||||
if (block.useKeychain !== undefined) {
|
||||
host.useKeychain = block.useKeychain;
|
||||
}
|
||||
const identityAgentEnabled = block.identityAgent !== undefined
|
||||
&& block.identityAgent.toLowerCase() !== "none";
|
||||
const identityAgentDisabled = block.identityAgent?.toLowerCase() === "none";
|
||||
// The #2119 macOS pattern relies on AddKeysToAgent + UseKeychain without
|
||||
// declaring IdentityAgent. Treat that pair as an agent-backed login so
|
||||
// the bridge can ask Apple's ssh-add to load the configured IdentityFile.
|
||||
// AddKeysToAgent alone still keeps direct-key semantics on other setups.
|
||||
const macKeychainAgentEnabled = hasMacKeychainAgentDirectives(block);
|
||||
if (!identityAgentDisabled && (identityAgentEnabled || macKeychainAgentEnabled)) {
|
||||
host.useSshAgent = true;
|
||||
} else if (identityAgentDisabled) {
|
||||
host.useSshAgent = false;
|
||||
}
|
||||
if (block.forwardX11 !== undefined) {
|
||||
host.x11Forwarding = block.forwardX11;
|
||||
}
|
||||
|
||||
// Store ProxyJump using hostname key (survives deduplication)
|
||||
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
|
||||
const hostKey = makeHostKey(hostname, block.port);
|
||||
hostProxyJumpMap.set(hostKey, block.proxyJump);
|
||||
}
|
||||
parsedHosts.push(host);
|
||||
|
||||
// Store ProxyJump using hostname key (survives deduplication)
|
||||
if (block.proxyJump && block.proxyJump.toLowerCase() !== "none") {
|
||||
const hostKey = makeHostKey(hostname, block.port);
|
||||
hostProxyJumpMap.set(hostKey, block.proxyJump);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -403,6 +403,19 @@ test("loginShellHint selects fish/posix/powershell/cmd without pinning confirmed
|
||||
resolveEffectiveShellKind(undefined, "alice@wsl:/mnt/c$", { loginShellHint: "cmd" }),
|
||||
"posix",
|
||||
);
|
||||
// Nested Kali two-line prompt: the last line alone is a bare `└─$`.
|
||||
assert.equal(
|
||||
resolveEffectiveShellKind(undefined, "┌──(kali㉿kali)-[~]\n\n└─$ ", { loginShellHint: "cmd" }),
|
||||
"posix",
|
||||
);
|
||||
assert.equal(
|
||||
resolveEffectiveShellKind(undefined, "┌──(root㉿kali)-[/tmp]\n\n└─# 1 ⨯", { loginShellHint: "powershell" }),
|
||||
"posix",
|
||||
);
|
||||
assert.equal(
|
||||
resolveEffectiveShellKind(undefined, "random output\n└─$ ", { loginShellHint: "cmd" }),
|
||||
"cmd",
|
||||
);
|
||||
// Confirmed shellKind is never overridden by a login hint.
|
||||
assert.equal(
|
||||
resolveEffectiveShellKind("posix", "user@host:~$", { loginShellHint: "fish" }),
|
||||
|
||||
@@ -7,6 +7,7 @@ const {
|
||||
isDefaultPowerShellPromptLine,
|
||||
isDefaultCmdPromptLine,
|
||||
isDefaultPosixPromptLine,
|
||||
isKaliTwoLinePrompt,
|
||||
} = require("./shellUtils.cjs");
|
||||
const { renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
|
||||
const { classifyLocalShellType } = require("../../../lib/localShell.cjs");
|
||||
@@ -206,7 +207,7 @@ function isPosixPrompt(prompt) {
|
||||
.split("\n")
|
||||
.pop()
|
||||
.replace(/\s+$/, "");
|
||||
return isDefaultPosixPromptLine(lastLine);
|
||||
return isDefaultPosixPromptLine(lastLine) || isKaliTwoLinePrompt(prompt);
|
||||
}
|
||||
|
||||
// Prompt-driven override is intentionally narrow: only flip to PowerShell
|
||||
|
||||
@@ -17,6 +17,15 @@ const {
|
||||
|
||||
const ANSI_ESCAPE_REGEX = /\u001B\[[0-?]*[ -/]*[@-~]/g;
|
||||
const ANSI_OSC_REGEX = /\u001B\][^\u0007]*?(?:\u0007|\u001B\\)/g;
|
||||
// DCS/SOS/PM/APC strings are removed whole so their payload never reads as
|
||||
// visible text. Only ST ends them (BEL is OSC-only), and the payload stops at
|
||||
// the next ESC so runs of unterminated introducers stay linear; an
|
||||
// unterminated one keeps its ESC like an incomplete OSC.
|
||||
const ANSI_CONTROL_STRING_REGEX = /\u001B[PX^_][^\u001B]*\u001B\\/g;
|
||||
// Non-CSI/OSC escapes: zle paints `ESC =` (keypad mode) right after the prompt;
|
||||
// also `ESC 7`/`ESC 8`, `ESC M`, and charset designators like `ESC ( B`.
|
||||
// `[`, `]` and the control-string introducers `P X ^ _` stay excluded.
|
||||
const ANSI_SHORT_ESCAPE_REGEX = /\u001B(?:[ -/]+[0-~]|[0-OQ-WYZ\\`-~])/g;
|
||||
const URL_CANDIDATE_REGEX = /https?:\/\/[^\s]+/g;
|
||||
const WINDOWS_RUNNABLE_EXTENSIONS = [".exe", ".cmd", ".bat", ".com"];
|
||||
const MAX_PROMPT_TRACK_TAIL = 4096;
|
||||
@@ -38,7 +47,11 @@ function execFileAsync(command, args, options) {
|
||||
// ── ANSI stripping ──
|
||||
|
||||
function stripAnsi(input) {
|
||||
return String(input || "").replace(ANSI_OSC_REGEX, "").replace(ANSI_ESCAPE_REGEX, "");
|
||||
return String(input || "")
|
||||
.replace(ANSI_OSC_REGEX, "")
|
||||
.replace(ANSI_CONTROL_STRING_REGEX, "")
|
||||
.replace(ANSI_ESCAPE_REGEX, "")
|
||||
.replace(ANSI_SHORT_ESCAPE_REGEX, "");
|
||||
}
|
||||
|
||||
// ── Synthetic command echo ──
|
||||
@@ -107,6 +120,31 @@ const POSIX_PROMPT_HOST_LINE_PATTERN = /^[^\s@]+@[^\s:]+(?::[^\n\r]*)?$/;
|
||||
// a bare `$`/`#` still does not match.
|
||||
const OH_MY_ZSH_YS_HOST_LINE_PATTERN = /^#\s+[^\s@]+\s+@\s+[^\s]+(?:\s+[^\n\r]+)?$/;
|
||||
|
||||
// Kali Linux default two-line bash/zsh prompt:
|
||||
// ┌──(root㉿kali)-[~]
|
||||
// └─#
|
||||
// Also handles non-root `└─$` and ASCII `@`. Chroot/venv groups precede the
|
||||
// user group: zsh joins them with `─`, bash with `──` (chroot) or nothing (venv).
|
||||
const KALI_PROMPT_HOST_LINE_PATTERN =
|
||||
/^┌──(?:\([^()\r\n]+\)─{0,2})*\([^\s@㉿()]+[@㉿][^\s()]+\)-\[[^\r\n]+\]$/;
|
||||
// Kali's zsh RPROMPT appends ` <code> ⨯` after a failed command and
|
||||
// ` <jobs> ⚙` with background jobs; anything else is pending input.
|
||||
const KALI_PROMPT_MARKER_LINE_PATTERN = /^└─[$#](?:\s+\d+\s+[⨯⚙])*$/;
|
||||
|
||||
// Shell-kind resolution only sees the last line, which for Kali is a bare
|
||||
// `└─$`; check the paired host line so nested Kali (e.g. WSL) reads as POSIX.
|
||||
function isKaliTwoLinePrompt(prompt) {
|
||||
const lines = stripAnsi(String(prompt || ""))
|
||||
.replace(/\r/g, "\n")
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/\s+$/, ""))
|
||||
.filter(Boolean);
|
||||
let index = lines.length - 1;
|
||||
if (index < 1 || !KALI_PROMPT_MARKER_LINE_PATTERN.test(lines[index])) return false;
|
||||
while (index >= 0 && KALI_PROMPT_MARKER_LINE_PATTERN.test(lines[index])) index -= 1;
|
||||
return index >= 0 && KALI_PROMPT_HOST_LINE_PATTERN.test(lines[index]);
|
||||
}
|
||||
|
||||
// Alpine's default ash PS1 omits the username: `\h:\w\$ ` -> `localhost:~# `.
|
||||
// Require a hostname and a home/absolute path, excluding prompt delimiters
|
||||
// within the path so partially entered commands do not count as idle prompts.
|
||||
@@ -174,7 +212,7 @@ function isDefaultCmdPromptLine(line) {
|
||||
}
|
||||
|
||||
function stripLeadingDecorativeToken(line) {
|
||||
// Optional short decorative token, stripped only for recognition (#4354).
|
||||
// Optional short decorative tokens, stripped only for recognition (#4354).
|
||||
return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, "");
|
||||
}
|
||||
|
||||
@@ -183,9 +221,11 @@ function isDefaultPosixPromptLine(line) {
|
||||
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
|
||||
// before the shell prompt. Recognition only; callers still return the full
|
||||
// prompt line so suffix matching sees the visible prefix (#3947).
|
||||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some(
|
||||
(prompt) => (
|
||||
let prompt = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
// Check each candidate before stripping again: a glyph such as the
|
||||
// robbyrussell arrow may be part of the prompt itself (#4354).
|
||||
while (true) {
|
||||
if (
|
||||
POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
BRACKET_PATH_POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
@@ -196,8 +236,11 @@ function isDefaultPosixPromptLine(line) {
|
||||
POWERLEVEL10K_PROMPT_PATTERN.test(prompt) ||
|
||||
POWERLINE_PROMPT_PATTERN.test(prompt) ||
|
||||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt)
|
||||
),
|
||||
);
|
||||
) return true;
|
||||
const stripped = stripLeadingDecorativeToken(prompt);
|
||||
if (stripped === prompt) return false;
|
||||
prompt = stripped;
|
||||
}
|
||||
}
|
||||
|
||||
function extractTrailingIdlePrompt(output) {
|
||||
@@ -241,14 +284,21 @@ function extractTrailingIdlePrompt(output) {
|
||||
// getFreshIdlePrompt uses the same normalize, and hasExpectedPromptSuffix
|
||||
// compares this CR-as-LF form against live PTY bytes. A lone `$`/`#` must
|
||||
// not satisfy endsWith; the previous non-empty line has to be a recognized
|
||||
// host line (classic `user@host[:path]` or Oh My Zsh `ys`).
|
||||
if (rightTrimmed === "$" || rightTrimmed === "#") {
|
||||
// host line (classic `user@host[:path]`, Oh My Zsh `ys`, or Kali `┌──(...)`
|
||||
// paired only with a Kali `└─$`/`└─#` marker).
|
||||
const isBareMarker = rightTrimmed === "$" || rightTrimmed === "#";
|
||||
const isKaliMarker = KALI_PROMPT_MARKER_LINE_PATTERN.test(rightTrimmed);
|
||||
if (isBareMarker || isKaliMarker) {
|
||||
let hostIndex = lines.length - 1;
|
||||
while (hostIndex >= 0) {
|
||||
const candidate = lines[hostIndex].replace(/\s+$/, "");
|
||||
// Some Prompts redraw the same bare marker multiple times with CR + EL.
|
||||
// Those intermediate marker lines are still part of the idle prompt.
|
||||
if (candidate === "" || candidate === rightTrimmed) {
|
||||
if (
|
||||
candidate === ""
|
||||
|| candidate === rightTrimmed
|
||||
|| (isKaliMarker && KALI_PROMPT_MARKER_LINE_PATTERN.test(candidate))
|
||||
) {
|
||||
hostIndex -= 1;
|
||||
} else {
|
||||
break;
|
||||
@@ -259,11 +309,14 @@ function extractTrailingIdlePrompt(output) {
|
||||
// Same optional "(name) " env prefix as isDefaultPosixPromptLine (#3947).
|
||||
// Recognition only; the returned prompt keeps the visible prefix.
|
||||
const previousHostLine = previousRightTrimmed.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
if (
|
||||
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|
||||
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
|
||||
|| extractTerminalPromptHostname(`${previousRightTrimmed}\n${rightTrimmed}`)
|
||||
) {
|
||||
const matched = isKaliMarker
|
||||
? KALI_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|
||||
: (
|
||||
POSIX_PROMPT_HOST_LINE_PATTERN.test(previousHostLine)
|
||||
|| OH_MY_ZSH_YS_HOST_LINE_PATTERN.test(previousHostLine)
|
||||
|| extractTerminalPromptHostname(`${previousRightTrimmed}\n${rightTrimmed}`)
|
||||
);
|
||||
if (matched) {
|
||||
return `${lines.slice(hostIndex).join("\n")}\n${lastLine}${trailingLineBreaks}`;
|
||||
}
|
||||
}
|
||||
@@ -495,8 +548,9 @@ function getVisibleIdlePrompt(session) {
|
||||
if (session.osc133Ready === false) return "";
|
||||
if (!matchesOsc133EmptyPrompt(session, view)) return "";
|
||||
|
||||
const { terminalCursorLine } = require("../terminalLogSanitizer.cjs");
|
||||
const cursorLine = terminalCursorLine(tail, view);
|
||||
const { terminalCursorLine, renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
|
||||
const visibleTail = tail.replace(ANSI_CONTROL_STRING_REGEX, "");
|
||||
const cursorLine = terminalCursorLine(visibleTail, view);
|
||||
const rightTrimmed = cursorLine.replace(/\s+$/, "");
|
||||
if (!rightTrimmed) return "";
|
||||
if (session.osc133Ready === true && session._osc133PromptLine != null) {
|
||||
@@ -504,6 +558,12 @@ function getVisibleIdlePrompt(session) {
|
||||
// and lack of continuation are checked above before bypassing shape checks.
|
||||
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
|
||||
}
|
||||
if (KALI_PROMPT_MARKER_LINE_PATTERN.test(rightTrimmed)) {
|
||||
// After readline or zle erases input, verify the host and marker on the
|
||||
// current screen together. The bare marker alone cannot establish readiness.
|
||||
const screen = renderCursorBoundScreenText(visibleTail, view);
|
||||
return screen ? extractTrailingIdlePrompt(screen.trimmedAboveText) : "";
|
||||
}
|
||||
if (
|
||||
!isDefaultPowerShellPromptLine(rightTrimmed)
|
||||
&& !isDefaultPosixPromptLine(rightTrimmed)
|
||||
@@ -1461,6 +1521,7 @@ module.exports = {
|
||||
isDefaultPowerShellPromptLine,
|
||||
isDefaultCmdPromptLine,
|
||||
isDefaultPosixPromptLine,
|
||||
isKaliTwoLinePrompt,
|
||||
trackSessionIdlePrompt,
|
||||
getSessionReadinessGeneration,
|
||||
bumpSessionReadinessGeneration,
|
||||
|
||||
@@ -518,10 +518,41 @@ test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the f
|
||||
}
|
||||
});
|
||||
|
||||
test("stacked decorative prefixes preserve the full extracted and tracked prompt", () => {
|
||||
for (const prompt of [
|
||||
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
|
||||
`${status} \u26A1 root@testhost:~# `,
|
||||
`${status} \u26A1 root@testhost:~#`,
|
||||
`${status} \u26A1 root@testhost \uE0B0 ~ \uE0B0 `,
|
||||
`(venv) ${status} \u26A1 user@host:~# `,
|
||||
`${status} \u279C netcatty`,
|
||||
`${status} \u279C netcatty `,
|
||||
`${status} \u279C ~ git:(main) \u2717`,
|
||||
`(venv) ${status} \u279C netcatty git:(main) \u2713 `,
|
||||
]),
|
||||
"\u2718 \u2714 \u26A1 root@testhost:~# ",
|
||||
"\u2718 \u2714 \u279C netcatty ",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
const session = {};
|
||||
trackSessionIdlePrompt(session, `welcome\r\n${prompt}`);
|
||||
assert.equal(session.lastIdlePrompt, prompt, prompt);
|
||||
assert.equal(getFreshIdlePrompt(session), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => {
|
||||
for (const line of [
|
||||
"\u26A1 root@testhost:~# echo hi",
|
||||
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
|
||||
"\u2718 \u26A1 root@testhost:~# echo hi",
|
||||
"\u2718 \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
|
||||
...["\u2718", "\u2714", "\u2717", "\u2713"].flatMap(status => [
|
||||
`${status} \u279C netcatty ls`,
|
||||
`(venv) ${status} \u279C netcatty git:(main) \u2713 ls`,
|
||||
]),
|
||||
"\u2718 \u2714 \u279C netcatty ls",
|
||||
"OK root@testhost:~# ",
|
||||
"yes root@testhost:~# ",
|
||||
"git:(main) root@testhost:~# ",
|
||||
@@ -1939,3 +1970,157 @@ test("macOS root pattern rejects cmd drive-letter prompts with pending input (#4
|
||||
assert.equal(isDefaultPosixPromptLine("Password:"), false);
|
||||
assert.equal(extractTrailingIdlePrompt("welcome\r\nPassword:"), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt recognizes Kali Linux default two-line prompts", () => {
|
||||
const rootPrompt = "┌──(root㉿kali)-[~]\r\n└─# ";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`Last login: Tue Dec 1\r\n${rootPrompt}`),
|
||||
"┌──(root㉿kali)-[~]\n\n└─# ",
|
||||
);
|
||||
|
||||
const userPrompt = "┌──(kali㉿kali)-[~/projects]\r\n└─$ ";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`ready\r\n${userPrompt}`),
|
||||
"┌──(kali㉿kali)-[~/projects]\n\n└─$ ",
|
||||
);
|
||||
|
||||
const venvPrompt = "┌──(venv)─(root@kali)-[/etc/ssh]\r\n└─# ";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`ok\r\n${venvPrompt}`),
|
||||
"┌──(venv)─(root@kali)-[/etc/ssh]\n\n└─# ",
|
||||
);
|
||||
|
||||
// Pending input on the second line or bare marker without Kali host line must stay rejected.
|
||||
assert.equal(extractTrailingIdlePrompt("┌──(root㉿kali)-[~]\r\n└─# nmap -V"), "");
|
||||
assert.equal(extractTrailingIdlePrompt("some random output\r\n└─# "), "");
|
||||
assert.equal(extractTrailingIdlePrompt("└─$ "), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt accepts Kali chroot/venv prefixes from bash and zsh", () => {
|
||||
const prompts = [
|
||||
"┌──(venv)(kali㉿kali)-[~]\r\n└─$ ",
|
||||
"┌──(chroot)──(kali㉿kali)-[~]\r\n└─$ ",
|
||||
"┌──(chroot)─(venv)─(kali㉿kali)-[~]\r\n└─$ ",
|
||||
];
|
||||
for (const prompt of prompts) {
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`ok\r\n${prompt}`),
|
||||
`${prompt.replace("\r\n", "\n\n")}`,
|
||||
);
|
||||
}
|
||||
|
||||
assert.equal(extractTrailingIdlePrompt("┌──(venv) (kali㉿kali)-[~]\r\n└─$ "), "");
|
||||
assert.equal(extractTrailingIdlePrompt("┌──(kali kali)-[~]\r\n└─$ "), "");
|
||||
});
|
||||
|
||||
test("extractTrailingIdlePrompt accepts Kali zsh RPROMPT exit-code and job indicators", () => {
|
||||
const failed = "┌──(kali㉿kali)-[~]\r\n└─$ \x1b[60C 1 \x1b[1m⨯\x1b[0m\x1b[64D";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`false\r\n${failed}`),
|
||||
"┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯",
|
||||
);
|
||||
|
||||
const failedWithJobs = "┌──(root㉿kali)-[/tmp]\r\n└─# 130 ⨯ 1 ⚙";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(`^C\r\n${failedWithJobs}`),
|
||||
"┌──(root㉿kali)-[/tmp]\n\n└─# 130 ⨯ 1 ⚙",
|
||||
);
|
||||
|
||||
// zsh may return the cursor with CR after painting RPROMPT.
|
||||
const crReturn = "┌──(kali㉿kali)-[~]\r\n└─$ 1 ⨯\r\x1b[4C";
|
||||
assert.equal(
|
||||
extractTrailingIdlePrompt(crReturn),
|
||||
"┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯\n",
|
||||
);
|
||||
|
||||
assert.equal(extractTrailingIdlePrompt("┌──(kali㉿kali)-[~]\r\n└─$ ls 1 ⨯"), "");
|
||||
assert.equal(extractTrailingIdlePrompt("┌──(kali㉿kali)-[~]\r\n└─$ oops ⨯"), "");
|
||||
assert.equal(extractTrailingIdlePrompt("random output\r\n└─$ 1 ⨯"), "");
|
||||
});
|
||||
|
||||
test("stripAnsi removes short ESC sequences but keeps incomplete CSI/OSC introducers", () => {
|
||||
assert.equal(stripAnsi("a\x1b=b\x1b>c"), "abc");
|
||||
assert.equal(stripAnsi("\x1b7saved\x1b8"), "saved");
|
||||
assert.equal(stripAnsi("\x1b(Btext\x1b)0"), "text");
|
||||
assert.equal(stripAnsi("line\x1bMup"), "lineup");
|
||||
assert.equal(stripAnsi("tail\x1b["), "tail\x1b[");
|
||||
assert.equal(stripAnsi("tail\x1b]0;title"), "tail\x1b]0;title");
|
||||
});
|
||||
|
||||
test("stripAnsi removes DCS/SOS/PM/APC strings whole so payloads never look like prompts", () => {
|
||||
assert.equal(stripAnsi("out\x1bPuser@host:~$ \x1b\\"), "out");
|
||||
assert.equal(stripAnsi("a\x1bXsos\x1b\\b\x1b^pm\x1b\\c\x1b_apc\x1b\\d"), "abcd");
|
||||
// BEL does not end a DCS: the payload after it must not leak as a prompt.
|
||||
assert.equal(stripAnsi("x\x1bPdata\x07user@host:~$ \x1b\\"), "x");
|
||||
assert.equal(extractTrailingIdlePrompt("vim\r\n\x1bPdata\x07user@host:~$ \x1b\\"), "");
|
||||
assert.equal(stripAnsi("tail\x1bPunterminated"), "tail\x1bPunterminated");
|
||||
assert.equal(extractTrailingIdlePrompt("vim\r\n\x1bPuser@host:~$ \x1b\\"), "");
|
||||
});
|
||||
|
||||
test("stripAnsi stays linear on many unterminated control-string introducers", () => {
|
||||
const input = "\x1bP".repeat(200000);
|
||||
const started = Date.now();
|
||||
stripAnsi(input);
|
||||
assert.ok(Date.now() - started < 1000, "stripAnsi should not be quadratic");
|
||||
});
|
||||
|
||||
// Bytes captured from Kali 2026.2 zsh over SSH (xterm-256color, 120 cols).
|
||||
const KALI_ZSH_PROMPT_BYTES =
|
||||
"\x1b[1m\x1b[7m%\x1b[27m\x1b[1m\x1b[0m" + " ".repeat(119) + "\r \r"
|
||||
+ "\x1b]0;root@kali: ~\x07\r\n\r\x1b[0m\x1b[27m\x1b[24m\x1b[J"
|
||||
+ "\x1b[34m┌──(\x1b[1m\x1b[34m\x1b[31mroot㉿kali\x1b[0m\x1b[31m\x1b[34m)-[\x1b[1m\x1b[34m\x1b[39m~\x1b[0m\x1b[34m]\r\n"
|
||||
+ "└─\x1b[1m\x1b[34m\x1b[31m#\x1b[0m\x1b[31m\x1b[39m \x1b[K";
|
||||
const KALI_ZLE_KEYPAD_ON = "\x1b[?1h\x1b=\x1b[?2004h";
|
||||
|
||||
test("real Kali zsh prompt bytes are idle, including zle keypad-mode escapes", () => {
|
||||
const session = {};
|
||||
trackSessionIdlePrompt(session, `false\r\n\x1b[?1l\x1b>\x1b[?2004l\r\r\n${KALI_ZSH_PROMPT_BYTES}${KALI_ZLE_KEYPAD_ON}`);
|
||||
assert.equal(stripAnsi(getFreshIdlePrompt(session)).split("\n").pop(), "└─# ");
|
||||
|
||||
const failed = `${KALI_ZSH_PROMPT_BYTES}\x1b[111C 1 \x1b[31m\x1b[1m\x1b[31m⨯\x1b[0m\x1b[31m\x1b[39m\x1b[115D${KALI_ZLE_KEYPAD_ON}`;
|
||||
const failedSession = {};
|
||||
trackSessionIdlePrompt(failedSession, failed);
|
||||
assert.equal(stripAnsi(getFreshIdlePrompt(failedSession)).split("\n").pop(), "└─# 1 ⨯");
|
||||
|
||||
const pending = `${KALI_ZSH_PROMPT_BYTES}${KALI_ZLE_KEYPAD_ON}l\bls\b\b\x1b[36ml\x1b[36ms\x1b[39m`;
|
||||
assert.equal(extractTrailingIdlePrompt(pending), "");
|
||||
});
|
||||
|
||||
test("real Kali bash prompt bytes with a readline redraw are idle", () => {
|
||||
const bytes = "\x1b[?2004h\x1b]0;root@kali: ~\x07\x1b[;94m┌──(\x1b[1;31mroot㉿kali\x1b[;94m)-[\x1b[0;1m~\x1b[;94m]\r\r\n"
|
||||
+ "\x1b[;94m└─\x1b[1;31m#\x1b[0m \r\x1b[;94m└─\x1b[1;31m#\x1b[0m ";
|
||||
const session = {};
|
||||
trackSessionIdlePrompt(session, `false\r\n\x1b[?2004l\r\r\n${bytes}`);
|
||||
assert.equal(stripAnsi(getFreshIdlePrompt(session)).split("\n").pop(), "└─# ");
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt keeps Kali prompts ready after a failed command", () => {
|
||||
const session = {};
|
||||
const prompt = "┌──(kali㉿kali)-[~]\r\n└─$ \x1b[60C 1 ⨯\x1b[64D";
|
||||
trackSessionIdlePrompt(session, `\r\nfalse\r\n${prompt}`);
|
||||
assert.equal(getFreshIdlePrompt(session), "┌──(kali㉿kali)-[~]\n\n└─$ 1 ⨯");
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt and getFreshIdlePrompt accept Kali Linux two-line prompts", () => {
|
||||
const session = {};
|
||||
const prompt = "┌──(root㉿kali)-[~]\r\n└─# ";
|
||||
trackSessionIdlePrompt(session, `Last login: Tue Dec 1\r\n${prompt}`);
|
||||
assert.equal(getFreshIdlePrompt(session), "┌──(root㉿kali)-[~]\n\n└─# ");
|
||||
|
||||
trackSessionIdlePrompt(session, "\r\nnmap -V\r\nNmap version 7.99\r\n");
|
||||
assert.equal(getFreshIdlePrompt(session), "");
|
||||
});
|
||||
|
||||
test("Kali visible readiness recovers after bash and zsh erase the last character", () => {
|
||||
for (const erase of ["\b\x1b[K", "\b \b"]) {
|
||||
const session = {};
|
||||
const hostLine = "┌──(kali㉿kali)-[~]";
|
||||
trackSessionIdlePrompt(session, hostLine + "\r\n└─$ ");
|
||||
trackSessionIdlePrompt(session, "a");
|
||||
assert.equal(getVisibleIdlePrompt(session), "");
|
||||
trackSessionIdlePrompt(session, erase);
|
||||
assert.equal(getVisibleIdlePrompt(session), hostLine + "\n└─$ ");
|
||||
}
|
||||
assert.equal(getVisibleIdlePrompt({ _promptTrackTail: "text\r\n└─$ a\b\x1b[K" }), "");
|
||||
assert.equal(getVisibleIdlePrompt({ _promptTrackTail: "busy\r\n\x1bPuser@host:~$ \x1b\\" }), "");
|
||||
});
|
||||
@@ -199,6 +199,7 @@ function registerProviderHandlers(ctx) {
|
||||
"api.tavily.com",
|
||||
"api.exa.ai",
|
||||
"api.bochaai.com",
|
||||
"api.deepseek.com",
|
||||
"open.bigmodel.cn",
|
||||
]);
|
||||
// Dynamically populated from configured provider baseURLs
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const { MCP_APPROVAL_TIMEOUT_MS } = require("../../../shared/approvalConstants.cjs");
|
||||
|
||||
// Reuse the SDK elicitation transport, but keep typed form replies separate
|
||||
// from the approval gate. A form reply grants no action permission.
|
||||
function createAgentFormBroker() {
|
||||
const pending = new Map();
|
||||
return {
|
||||
get: (id) => pending.get(id),
|
||||
request(request, { sender, chatSessionId, signal, emitter, validateContent }) {
|
||||
if (!Number.isInteger(sender?.id) || !chatSessionId || sender.isDestroyed?.() || signal?.aborted) return;
|
||||
const elicitationId = `agent-form:${randomUUID()}`;
|
||||
return new Promise((resolve) => {
|
||||
const finish = (value) => {
|
||||
if (!pending.delete(elicitationId)) return;
|
||||
clearTimeout(timer);
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
try {
|
||||
emitter.emitEvent({ type: "elicitation-complete", notification: { elicitationId } });
|
||||
} catch { /* Renderer may have closed. */ }
|
||||
resolve(value);
|
||||
};
|
||||
const onAbort = () => finish(undefined);
|
||||
const timer = setTimeout(onAbort, MCP_APPROVAL_TIMEOUT_MS);
|
||||
pending.set(elicitationId, { sender, chatSessionId, finish, validateContent });
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
try {
|
||||
emitter.emitEvent({ type: "elicitation-create", elicitationId, request });
|
||||
} catch {
|
||||
onAbort();
|
||||
}
|
||||
});
|
||||
},
|
||||
respond(id, sender, action, content) {
|
||||
const entry = pending.get(id);
|
||||
if (!entry || entry.sender.id !== sender?.id) return false;
|
||||
if (!["accept", "decline", "cancel"].includes(action)) return false;
|
||||
entry.finish(action === "accept" ? content : undefined);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createAgentFormBroker };
|
||||
@@ -742,6 +742,14 @@ function handleGrokAcpMessage(message, { emitter, state, pending, onPromptComple
|
||||
const method = String(message.method || "");
|
||||
const params = message.params && typeof message.params === "object" ? message.params : {};
|
||||
|
||||
if (method === "_x.ai/exit_plan_mode") {
|
||||
const id = message.id;
|
||||
if (id == null || typeof state.writeResponse !== "function"
|
||||
|| state.planReviewRequests?.has(id)) return;
|
||||
state.planReviewRequests?.add(id);
|
||||
return reviewGrokPlan(id, params, state);
|
||||
}
|
||||
|
||||
if (method === "session/update" || method === "x.ai/session/update") {
|
||||
// session/load may re-broadcast historical agent_message_chunk events for
|
||||
// client UI rebuild. Those must not be written into the *current* Netcatty
|
||||
@@ -778,6 +786,22 @@ function handleGrokAcpMessage(message, { emitter, state, pending, onPromptComple
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Unsupported reverse requests must not leave Grok waiting for a response.
|
||||
// Notifications have no id and remain safe to ignore.
|
||||
if (method && message.id != null) state.writeUnsupportedMethod?.(message.id);
|
||||
}
|
||||
|
||||
async function reviewGrokPlan(id, params, state) {
|
||||
const isActive = () => !state.planReviewSignal?.aborted && !state.failed && !state.turnCompleted;
|
||||
let approved = false;
|
||||
if (isActive() && state.acceptUpdates === true && state.sessionId
|
||||
&& params.sessionId === state.sessionId && typeof params.toolCallId === "string"
|
||||
&& typeof params.planContent === "string" && params.planContent.trim()) {
|
||||
try {
|
||||
approved = await state.requestPlanReview?.(params.planContent) === true;
|
||||
} catch { /* No review channel, no approval. */ }
|
||||
}
|
||||
if (isActive()) state.writeResponse(id, { outcome: approved ? "approved" : "cancelled" });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -885,11 +909,14 @@ async function runGrokAcpTurn({
|
||||
resumeSessionId,
|
||||
historySeed,
|
||||
injectedMcpServers,
|
||||
chatSessionId,
|
||||
requestApprovalFromRenderer,
|
||||
emitter,
|
||||
signal,
|
||||
spawnImpl,
|
||||
abortGraceMs = GROK_ACP_ABORT_GRACE_MS,
|
||||
forceKillImpl,
|
||||
requestUserForm,
|
||||
// inject for tests: skip real spawn
|
||||
rpcClientFactory,
|
||||
assertSessionValid,
|
||||
@@ -909,6 +936,10 @@ async function runGrokAcpTurn({
|
||||
permissionMode,
|
||||
toolIntegrationMode,
|
||||
});
|
||||
const planReviewLifetime = new AbortController();
|
||||
const planReviewSignal = signal
|
||||
? AbortSignal.any([signal, planReviewLifetime.signal])
|
||||
: planReviewLifetime.signal;
|
||||
|
||||
const state = {
|
||||
sessionId: resumeSessionId || null,
|
||||
@@ -922,6 +953,16 @@ async function runGrokAcpTurn({
|
||||
// Suppress session/load history replay until session/prompt starts.
|
||||
acceptUpdates: false,
|
||||
autoAllowPermissions: String(permissionMode || "confirm").toLowerCase() !== "observer",
|
||||
planReviewRequests: new Set(),
|
||||
planReviewSignal,
|
||||
requestPlanReview: chatSessionId && typeof requestApprovalFromRenderer === "function"
|
||||
&& String(permissionMode || "confirm").toLowerCase() !== "observer"
|
||||
? (plan) => requestApprovalFromRenderer("Grok plan review", { plan }, chatSessionId, {
|
||||
interactionKind: "plan-review",
|
||||
requireFreshApproval: true,
|
||||
signal: planReviewSignal,
|
||||
})
|
||||
: undefined,
|
||||
promptRequestId: null,
|
||||
writeResponse: null,
|
||||
};
|
||||
@@ -968,6 +1009,7 @@ async function runGrokAcpTurn({
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
}
|
||||
}
|
||||
planReviewLifetime.abort();
|
||||
return { sessionId: state.sessionId, runtime: "acp" };
|
||||
}
|
||||
|
||||
@@ -1015,6 +1057,10 @@ async function runGrokAcpTurn({
|
||||
});
|
||||
}
|
||||
|
||||
const questionLifetime = new AbortController();
|
||||
const questionSignal = signal ? AbortSignal.any([signal, questionLifetime.signal]) : questionLifetime.signal;
|
||||
const questionRequests = new Set();
|
||||
|
||||
const writeLine = (line) => {
|
||||
const stdin = child?.stdin;
|
||||
if (!stdin || stdin.destroyed || stdin.writable === false) return;
|
||||
@@ -1030,11 +1076,30 @@ async function runGrokAcpTurn({
|
||||
state.writeResponse = (id, result) => {
|
||||
writeLine(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
|
||||
};
|
||||
state.writeUnsupportedMethod = (id) => {
|
||||
const error = { code: -32601, message: "Unsupported Grok ACP client request" };
|
||||
writeLine(`${JSON.stringify({ jsonrpc: "2.0", id, error })}\n`);
|
||||
};
|
||||
|
||||
rpc = createJsonRpcClient({
|
||||
write: writeLine,
|
||||
onMessage: (message, pending) => {
|
||||
if (signal?.aborted) return;
|
||||
if (message?.method === "_x.ai/ask_user_question") {
|
||||
const { id, params } = message;
|
||||
if (id == null || questionRequests.has(id)) return;
|
||||
questionRequests.add(id);
|
||||
const canRoute = state.acceptUpdates && state.sessionId
|
||||
&& params?.sessionId === state.sessionId && typeof params.toolCallId === "string";
|
||||
const ask = canRoute && requestUserForm
|
||||
? (form, validateContent) => requestUserForm(form, questionSignal, validateContent) : undefined;
|
||||
void require("./grokQuestion.cjs").replyToGrokQuestion(params, ask)
|
||||
.catch(() => ({ outcome: "cancelled" }))
|
||||
.then(result => {
|
||||
if (!questionSignal.aborted && !state.failed && !state.turnCompleted) state.writeResponse(id, result);
|
||||
});
|
||||
return;
|
||||
}
|
||||
handleGrokAcpMessage(message, {
|
||||
emitter,
|
||||
state,
|
||||
@@ -1189,11 +1254,13 @@ async function runGrokAcpTurn({
|
||||
));
|
||||
}
|
||||
} finally {
|
||||
planReviewLifetime.abort();
|
||||
try { child.stdin?.end(); } catch { /* ignore */ }
|
||||
// Give the process a moment to exit cleanly after prompt completes.
|
||||
if (!settled && child.exitCode == null && !child.killed) {
|
||||
signalProcessTree(child, "SIGTERM", forceKillImpl);
|
||||
}
|
||||
questionLifetime.abort();
|
||||
await closePromise;
|
||||
abortGuard?.dispose();
|
||||
}
|
||||
|
||||
@@ -1716,6 +1716,85 @@ test("handleGrokAcpMessage permission reply uses real optionId from params.optio
|
||||
assert.equal(written[0][1].outcome.optionId, "allow-once");
|
||||
});
|
||||
|
||||
test("Grok plan review requires an explicit decision even with auto tool approval", async () => {
|
||||
const written = [];
|
||||
const reviews = [];
|
||||
let decide;
|
||||
const state = {
|
||||
sessionId: "grok-session",
|
||||
acceptUpdates: true,
|
||||
autoAllowPermissions: true,
|
||||
planReviewRequests: new Set(),
|
||||
requestPlanReview: (plan) => {
|
||||
reviews.push(plan);
|
||||
return new Promise(resolve => { decide = resolve; });
|
||||
},
|
||||
writeResponse: (id, result) => written.push([id, result]),
|
||||
};
|
||||
const message = { id: 7, method: "_x.ai/exit_plan_mode", params: {
|
||||
sessionId: "grok-session", toolCallId: "tool-1", planContent: "# A plan",
|
||||
} };
|
||||
const context = { emitter: makeEmitter(), state, pending: new Map() };
|
||||
const decision = handleGrokAcpMessage(message, context);
|
||||
handleGrokAcpMessage(message, context);
|
||||
assert.deepEqual(reviews, ["# A plan"]);
|
||||
assert.deepEqual(written, []);
|
||||
decide(true);
|
||||
await decision;
|
||||
assert.deepEqual(written, [[7, { outcome: "approved" }]]);
|
||||
});
|
||||
|
||||
test("Grok plan review fails closed on rejection, missing UI or session mismatch", async () => {
|
||||
for (const [sessionId, requestPlanReview] of [
|
||||
["grok-session", () => false],
|
||||
["grok-session", undefined],
|
||||
["another-session", () => { assert.fail("must not show another session's plan"); }],
|
||||
["grok-session", () => Promise.reject(new Error("approval unavailable"))],
|
||||
]) {
|
||||
const written = [];
|
||||
const state = {
|
||||
sessionId: "grok-session", acceptUpdates: true, planReviewRequests: new Set(),
|
||||
requestPlanReview, writeResponse: (id, result) => written.push([id, result]),
|
||||
};
|
||||
await handleGrokAcpMessage({ id: 7, method: "_x.ai/exit_plan_mode", params: {
|
||||
sessionId, toolCallId: "tool-1", planContent: "plan",
|
||||
} }, { emitter: makeEmitter(), state, pending: new Map() });
|
||||
assert.deepEqual(written, [[7, { outcome: "cancelled" }]]);
|
||||
}
|
||||
});
|
||||
|
||||
test("Grok plan review does not respond after its turn is aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
const written = [];
|
||||
let decide;
|
||||
const state = {
|
||||
sessionId: "grok-session", acceptUpdates: true, planReviewRequests: new Set(),
|
||||
planReviewSignal: controller.signal,
|
||||
requestPlanReview: () => new Promise(resolve => { decide = resolve; }),
|
||||
writeResponse: (id, result) => written.push([id, result]),
|
||||
};
|
||||
const decision = handleGrokAcpMessage({ id: 8, method: "_x.ai/exit_plan_mode", params: {
|
||||
sessionId: "grok-session", toolCallId: "tool-1", planContent: "plan",
|
||||
} }, { emitter: makeEmitter(), state, pending: new Map() });
|
||||
controller.abort();
|
||||
decide(true);
|
||||
await decision;
|
||||
assert.deepEqual(written, []);
|
||||
});
|
||||
|
||||
test("Grok reverse requests without a supported interaction fail without auto-approval", () => {
|
||||
const unsupported = [];
|
||||
const state = {
|
||||
autoAllowPermissions: true,
|
||||
writeResponse: () => assert.fail("no success response for an unsupported request"),
|
||||
writeUnsupportedMethod: (id) => unsupported.push(id),
|
||||
};
|
||||
const context = { emitter: makeEmitter(), state, pending: new Map() };
|
||||
handleGrokAcpMessage({ method: "_x.ai/ask_user_question", id: 0 }, context);
|
||||
handleGrokAcpMessage({ method: "_x.ai/session_notification" }, context);
|
||||
assert.deepEqual(unsupported, [0]);
|
||||
});
|
||||
|
||||
test("shouldReportGrokProcessExitFailure treats any incomplete close as failure", () => {
|
||||
// Node close(null, "SIGTERM") when killed — must fail unfinished turns.
|
||||
assert.equal(
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
|
||||
const CANCELLED = { outcome: "cancelled" };
|
||||
const isText = (text, max) => typeof text === "string" && text.trim().length > 0 && text.length <= max;
|
||||
|
||||
async function replyToGrokQuestion(params, requestForm) {
|
||||
const questions = params?.questions;
|
||||
if (!requestForm || !Array.isArray(questions) || !questions.length || questions.length > 8) return CANCELLED;
|
||||
const properties = {};
|
||||
const titles = new Set();
|
||||
for (const [index, item] of questions.entries()) {
|
||||
if (!isText(item?.question, 2_000) || titles.has(item.question)) return CANCELLED;
|
||||
titles.add(item.question);
|
||||
const options = item.options ?? [];
|
||||
if (!Array.isArray(options) || options.length > 16
|
||||
|| options.some(option => !isText(option?.label, 500) || (option.description != null
|
||||
&& (typeof option.description !== "string" || option.description.length > 1_000)))
|
||||
|| new Set(options.map(option => option.label)).size !== options.length) return CANCELLED;
|
||||
const oneOf = options.map(({ label, description }, key) => ({
|
||||
const: String(key),
|
||||
title: description ? `${label} - ${description}` : label,
|
||||
}));
|
||||
const title = item.question;
|
||||
properties[`q${index}`] = !options.length
|
||||
? { type: "string", title, minLength: 1, maxLength: 2_000 }
|
||||
: item.multiSelect === true
|
||||
? { type: "array", title, minItems: 1, items: { oneOf } }
|
||||
: { type: "string", title, oneOf };
|
||||
}
|
||||
|
||||
const content = await requestForm({
|
||||
source: "grok",
|
||||
requestedSchema: { type: "object", properties, required: Object.keys(properties) },
|
||||
}, (raw) => mapGrokQuestionAnswers(questions, raw, true).outcome === "accepted");
|
||||
return mapGrokQuestionAnswers(questions, content, false);
|
||||
}
|
||||
|
||||
function mapGrokQuestionAnswers(questions, content, validateRawLength) {
|
||||
if (!content || typeof content !== "object" || Array.isArray(content)) return CANCELLED;
|
||||
const answers = Object.create(null);
|
||||
const annotations = Object.create(null);
|
||||
for (const [index, { question, options = [], multiSelect }] of questions.entries()) {
|
||||
const value = content[`q${index}`];
|
||||
if (!options?.length) {
|
||||
if (typeof value !== "string" || !value.trim()
|
||||
|| (validateRawLength && value.trim().length > 2_000)) return CANCELLED;
|
||||
answers[question] = ["Other"];
|
||||
annotations[question] = { notes: value.trim() };
|
||||
continue;
|
||||
}
|
||||
const keys = multiSelect === true ? value : [value];
|
||||
if (!Array.isArray(keys) || !keys.length || new Set(keys).size !== keys.length
|
||||
|| keys.some(key => typeof key !== "string" || !/^(0|[1-9][0-9]*)$/.test(key)
|
||||
|| !Object.hasOwn(options, Number(key)))) return CANCELLED;
|
||||
answers[question] = keys.map(key => options[Number(key)].label);
|
||||
}
|
||||
return {
|
||||
outcome: "accepted",
|
||||
answers: { ...answers },
|
||||
...(Object.keys(annotations).length ? { annotations: { ...annotations } } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { replyToGrokQuestion };
|
||||
@@ -0,0 +1,60 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { createAgentFormBroker } = require("./agentFormBroker.cjs");
|
||||
const { replyToGrokQuestion } = require("./grokQuestion.cjs");
|
||||
|
||||
test("Grok questions display single and multiple choices and return native labels", async () => {
|
||||
let form;
|
||||
const result = await replyToGrokQuestion({
|
||||
questions: [
|
||||
{ question: "Environment?", options: [{ label: "Staging" }, { label: "Sandbox" }] },
|
||||
{ question: "Checks?", multiSelect: true, options: [{ label: "Unit" }, { label: "Build" }] },
|
||||
{ question: "Note?" },
|
||||
],
|
||||
}, async request => {
|
||||
form = request;
|
||||
return { q0: "1", q1: ["0", "1"], q2: "Nothing to deploy" };
|
||||
});
|
||||
assert.equal(form.requestedSchema.properties.q1.type, "array");
|
||||
assert.deepEqual(result, {
|
||||
outcome: "accepted",
|
||||
answers: { "Environment?": ["Sandbox"], "Checks?": ["Unit", "Build"], "Note?": ["Other"] },
|
||||
annotations: { "Note?": { notes: "Nothing to deploy" } },
|
||||
});
|
||||
});
|
||||
|
||||
test("malformed, missing or unrecognized answers never become approvals", async () => {
|
||||
const request = { questions: [{ question: "__proto__", options: [{ label: "Safe" }] }] };
|
||||
assert.deepEqual(await replyToGrokQuestion(request, async () => ({ q0: "1" })), { outcome: "cancelled" });
|
||||
assert.deepEqual(await replyToGrokQuestion(request, async () => undefined), { outcome: "cancelled" });
|
||||
assert.equal(Object.hasOwn((await replyToGrokQuestion(request, async () => ({ q0: "0" }))).answers, "__proto__"), true);
|
||||
});
|
||||
|
||||
test("Grok validates raw text before masking can expand a valid response", async () => {
|
||||
const result = await replyToGrokQuestion({ questions: [{ question: "Note?" }] },
|
||||
async (_form, validateContent) => {
|
||||
assert.equal(validateContent({ q0: " \t " }), false);
|
||||
assert.equal(validateContent({ q0: "x".repeat(2001) }), false);
|
||||
assert.equal(validateContent({ q0: "x".repeat(1991) + " 10.0.0.1" }), true);
|
||||
return { q0: "x".repeat(1991) + " [NC_IP_token]" };
|
||||
});
|
||||
assert.equal(result.outcome, "accepted");
|
||||
assert.match(result.annotations["Note?"].notes, /\[NC_IP_token\]$/);
|
||||
});
|
||||
|
||||
test("form replies belong to the originating renderer, and an aborted form settles once", async () => {
|
||||
const broker = createAgentFormBroker();
|
||||
const events = [];
|
||||
const sender = { id: 1 };
|
||||
const controller = new AbortController();
|
||||
const req = { sender, chatSessionId: "chat", signal: controller.signal,
|
||||
emitter: { emitEvent: event => events.push(event) } };
|
||||
const answer = broker.request({ source: "grok" }, req);
|
||||
const id = events[0].elicitationId;
|
||||
assert.equal(broker.respond(id, { id: 2 }, "accept", { q0: "0" }), false);
|
||||
controller.abort();
|
||||
assert.equal(await answer, undefined);
|
||||
assert.equal(broker.respond(id, sender, "accept", {}), false);
|
||||
assert.equal(events[1].notification.elicitationId, id);
|
||||
assert.equal(events.length, 2);
|
||||
});
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user