mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-04 08:42:31 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c379067977 |
No files matched your search
@@ -166,7 +166,6 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
|
||||
- **Fast search** — locate hosts and groups quickly
|
||||
|
||||
### 🖥️ Terminal Workspaces
|
||||
- Right-click a standalone terminal tab and choose **Convert to Workspace** to keep your running shell as the first pane.
|
||||
- **Split panes** — horizontal and vertical splits for multi-tasking
|
||||
- **Session management** — run multiple connections side-by-side
|
||||
- **Save current screen** — right-click a terminal to save the visible final text, without replaying keystrokes or overwritten output; scroll first to save an earlier screen.
|
||||
|
||||
@@ -274,7 +274,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
const {
|
||||
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
convertKnownHostToHost, convertSessionToWorkspace, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
@@ -569,7 +569,6 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onMoveSessionToNewWindow={moveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={convertSessionToWorkspace}
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
|
||||
@@ -131,7 +131,6 @@ export function ChromeHost() {
|
||||
sessionRenameTarget: session.sessionRenameTarget,
|
||||
setActiveTabId: sessionActions?.setActiveTabId,
|
||||
startSessionRename: sessionActions?.startSessionRename,
|
||||
convertSessionToWorkspace: sessionActions?.convertSessionToWorkspace,
|
||||
renameSessionInline: sessionActions?.renameSessionInline,
|
||||
startWorkspaceRename: sessionActions?.startWorkspaceRename,
|
||||
submitSessionRename: sessionActions?.submitSessionRename,
|
||||
|
||||
@@ -59,7 +59,6 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -149,7 +148,6 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -199,7 +197,6 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createSerialSession,
|
||||
createSessionFromCloneSource,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceWithHosts,
|
||||
getOrderedWorkTabs,
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Choose Grok mode and send…',
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
'ai.chat.deliveredTextFile.source': 'Text included in this reply',
|
||||
'ai.chat.deliveredTextFile.preview': 'Preview',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Hide preview',
|
||||
'ai.chat.deliveredTextFile.save': 'Save as',
|
||||
'ai.chat.deliveredTextFile.saving': 'Saving…',
|
||||
'ai.chat.deliveredTextFile.saved': 'File saved',
|
||||
'ai.chat.deliveredTextFile.exists': 'That file exists. Choose another name.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Could not save this file.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Saving is not available in this window.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Preview is shortened. Saving keeps the full file.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
'ai.chat.preparing': 'Preparing…',
|
||||
@@ -355,10 +344,6 @@ export const enAiMessages: Messages = {
|
||||
'ai.grok.userQuestion.title': 'Grok needs your input',
|
||||
'ai.grok.userQuestion.description': 'Answers do not grant permissions. Do not include passwords or tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Send answers',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode needs your input',
|
||||
'ai.agentQuestions.title': 'Allow agent questions',
|
||||
'ai.agentQuestions.description': 'Let this agent ask for details during a turn. Answers do not grant tool permissions.',
|
||||
'ai.agentQuestions.codexDescription': 'Let Codex App Server ask for details in default mode. Answers do not grant tool permissions.',
|
||||
'ai.grok.runtime.acp.default': 'Default',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Talk to Grok over Agent Client Protocol (grok agent stdio). Injects Netcatty MCP on session/new. Turn off to use the original headless streaming-json CLI path.',
|
||||
|
||||
@@ -1287,7 +1287,11 @@ Highlight the focused split pane:
|
||||
'vault.hosts.newLocalShell': 'Local Shell (CMD)',
|
||||
'vault.hosts.newGroup': 'New Group',
|
||||
'vault.hosts.import': 'Import',
|
||||
'vault.hosts.export': 'Export',
|
||||
'vault.hosts.export': 'Export CSV',
|
||||
'vault.hosts.export.sshConfig': 'Export SSH config',
|
||||
'vault.hosts.export.sshEmpty': 'No SSH hosts with an exportable route',
|
||||
'vault.hosts.export.sshSkipped': 'Skipped {count} hosts with unsupported protocols or routes',
|
||||
'vault.hosts.export.sshFailed': 'Could not export SSH config',
|
||||
'vault.hosts.export.toast.success': 'Exported {count} hosts to CSV',
|
||||
'vault.hosts.export.toast.successWithSkipped': 'Exported {count} hosts to CSV ({skipped} unsupported hosts skipped)',
|
||||
'vault.hosts.export.toast.passphrasesSkipped': '{count} saved key passphrases could not be read and were left blank',
|
||||
|
||||
@@ -10,10 +10,6 @@ export const enTerminalMessages: Messages = {
|
||||
'terminal.gitBranch.empty': 'No local branches yet',
|
||||
'terminal.gitBranch.noMatches': 'No matching branches',
|
||||
'terminal.gitBranch.unavailable': 'Could not read branches for this session.',
|
||||
'terminal.gitBranch.draftDelete': 'Draft deletion of {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Enter sends to this terminal. Esc restores your draft.',
|
||||
'terminal.gitBranch.draftUnavailable': 'The original session or directory is unavailable.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Keep the command on one line.',
|
||||
'terminal.directory.unknown': 'Directory unknown',
|
||||
'terminal.directory.search': 'Search child directories...',
|
||||
'terminal.directory.directories': 'Directories',
|
||||
@@ -717,7 +713,6 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
'tabs.convertToWorkspace': 'Convert to Workspace',
|
||||
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
|
||||
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
|
||||
'tabs.closeOthers': 'Close Others',
|
||||
|
||||
@@ -882,7 +882,7 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Agent Socket',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Do not try unrelated keys currently loaded in the agent',
|
||||
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Start or unlock your SSH agent, or provide its socket path above.',
|
||||
'hostDetails.keys.search': 'Search keys...',
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Elegir el modo de Grok y enviar…',
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
'ai.chat.deliveredTextFile.source': 'Texto incluido en esta respuesta',
|
||||
'ai.chat.deliveredTextFile.preview': 'Vista previa',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Ocultar vista previa',
|
||||
'ai.chat.deliveredTextFile.save': 'Guardar como',
|
||||
'ai.chat.deliveredTextFile.saving': 'Guardando…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Archivo guardado',
|
||||
'ai.chat.deliveredTextFile.exists': 'El archivo ya existe. Elige otro nombre.',
|
||||
'ai.chat.deliveredTextFile.failed': 'No se pudo guardar el archivo.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'No se puede guardar en esta ventana.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'La vista previa está abreviada. Se guarda el archivo completo.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
'ai.chat.preparing': 'Preparando…',
|
||||
@@ -355,10 +344,6 @@ export const esAiMessages: Messages = {
|
||||
'ai.grok.userQuestion.title': 'Grok necesita tu respuesta',
|
||||
'ai.grok.userQuestion.description': 'Las respuestas no conceden permisos. No incluyas contraseñas ni tokens.',
|
||||
'ai.grok.userQuestion.submit': 'Enviar respuestas',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode necesita tu respuesta',
|
||||
'ai.agentQuestions.title': 'Permitir que el agente haga preguntas',
|
||||
'ai.agentQuestions.description': 'Permite que este agente pida detalles durante un turno. Las respuestas no conceden permisos de herramientas.',
|
||||
'ai.agentQuestions.codexDescription': 'Permite que Codex App Server pida detalles en el modo predeterminado. Las respuestas no conceden permisos de herramientas.',
|
||||
'ai.grok.runtime.acp.default': 'Predeterminado',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Habla con Grok mediante el Protocolo de Cliente de Agente (grok agent stdio). Inyecta el MCP de Netcatty en session/new. Apágalo para usar la ruta original de CLI headless con streaming-json.',
|
||||
|
||||
@@ -1287,7 +1287,11 @@ Resalta el panel dividido enfocado:
|
||||
'vault.hosts.newLocalShell': 'Shell local (CMD)',
|
||||
'vault.hosts.newGroup': 'Nuevo grupo',
|
||||
'vault.hosts.import': 'Importar',
|
||||
'vault.hosts.export': 'Exportar',
|
||||
'vault.hosts.export': 'Exportar CSV',
|
||||
'vault.hosts.export.sshConfig': 'Exportar configuración SSH',
|
||||
'vault.hosts.export.sshEmpty': 'No hay hosts SSH con una ruta exportable',
|
||||
'vault.hosts.export.sshSkipped': 'Se omitieron {count} hosts con protocolos o rutas incompatibles',
|
||||
'vault.hosts.export.sshFailed': 'No se pudo exportar la configuración SSH',
|
||||
'vault.hosts.export.toast.success': 'Se exportaron {count} hosts a CSV',
|
||||
'vault.hosts.export.toast.successWithSkipped': 'Se exportaron {count} hosts a CSV (se omitieron {skipped} hosts no compatibles)',
|
||||
'vault.hosts.export.toast.passphrasesSkipped': 'No se pudieron leer {count} frases de contraseña de claves guardadas y se dejaron en blanco',
|
||||
|
||||
@@ -10,10 +10,6 @@ export const esTerminalMessages: Messages = {
|
||||
'terminal.gitBranch.empty': 'Aún no hay ramas locales',
|
||||
'terminal.gitBranch.noMatches': 'No hay ramas coincidentes',
|
||||
'terminal.gitBranch.unavailable': 'No se pudieron leer las ramas de esta sesión.',
|
||||
'terminal.gitBranch.draftDelete': 'Preparar la eliminación de {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Intro envía a este terminal. Esc restaura el borrador.',
|
||||
'terminal.gitBranch.draftUnavailable': 'La sesión o el directorio original no está disponible.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Mantén el comando en una sola línea.',
|
||||
'terminal.directory.unknown': 'Directorio desconocido',
|
||||
'terminal.directory.search': 'Buscar subdirectorios...',
|
||||
'terminal.directory.directories': 'Directorios',
|
||||
@@ -719,7 +715,6 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
'tabs.convertToWorkspace': 'Convertir en espacio de trabajo',
|
||||
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
|
||||
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
|
||||
'tabs.closeOthers': 'Cerrar las demás',
|
||||
|
||||
@@ -878,7 +878,7 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Socket del agente',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'No intentar con claves no relacionadas actualmente cargadas en el agente',
|
||||
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Inicia o desbloquea tu agente SSH, o proporciona la ruta de su socket arriba.',
|
||||
'hostDetails.keys.search': 'Buscar claves...',
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Выбрать режим Grok и отправить…',
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.deliveredTextFile.source': 'Текст включён в ответ',
|
||||
'ai.chat.deliveredTextFile.preview': 'Предпросмотр',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Скрыть предпросмотр',
|
||||
'ai.chat.deliveredTextFile.save': 'Сохранить как',
|
||||
'ai.chat.deliveredTextFile.saving': 'Сохранение…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Файл сохранён',
|
||||
'ai.chat.deliveredTextFile.exists': 'Файл уже существует. Выберите другое имя.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Не удалось сохранить файл.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Сохранение недоступно в этом окне.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Предпросмотр сокращён. Файл сохранится полностью.',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Настройки агента',
|
||||
@@ -313,10 +302,6 @@ export const ruAiMessages: Messages = {
|
||||
'ai.grok.userQuestion.title': 'Grok ждёт вашего ответа',
|
||||
'ai.grok.userQuestion.description': 'Ответы не предоставляют разрешений. Не указывайте пароли и токены.',
|
||||
'ai.grok.userQuestion.submit': 'Отправить ответы',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode ждёт вашего ответа',
|
||||
'ai.agentQuestions.title': 'Разрешить агенту задавать вопросы',
|
||||
'ai.agentQuestions.description': 'Агент сможет запрашивать уточнения во время диалога. Ответы не дают разрешений на использование инструментов.',
|
||||
'ai.agentQuestions.codexDescription': 'Codex App Server сможет запрашивать уточнения в режиме по умолчанию. Ответы не дают разрешений на использование инструментов.',
|
||||
'ai.grok.runtime.acp.default': 'По умолчанию',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'Подключение к Grok через Agent Client Protocol (grok agent stdio). Netcatty MCP внедряется в session/new. Выключите, чтобы использовать исходный headless streaming-json CLI.',
|
||||
|
||||
@@ -10,10 +10,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'terminal.gitBranch.empty': 'Локальных веток пока нет',
|
||||
'terminal.gitBranch.noMatches': 'Ветки не найдены',
|
||||
'terminal.gitBranch.unavailable': 'Не удалось прочитать ветки для этого сеанса.',
|
||||
'terminal.gitBranch.draftDelete': 'Подготовить удаление {{value}}',
|
||||
'terminal.gitBranch.draftHint': 'Enter отправляет команду в этот терминал. Esc восстанавливает черновик.',
|
||||
'terminal.gitBranch.draftUnavailable': 'Исходный сеанс или каталог недоступен.',
|
||||
'terminal.gitBranch.draftSingleLine': 'Команда должна занимать одну строку.',
|
||||
'terminal.directory.unknown': 'Каталог неизвестен',
|
||||
'terminal.directory.search': 'Поиск подкаталогов...',
|
||||
'terminal.directory.directories': 'Каталоги',
|
||||
@@ -732,7 +728,6 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
'tabs.convertToWorkspace': 'Преобразовать в рабочую область',
|
||||
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
|
||||
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
|
||||
'tabs.closeOthers': 'Закрыть остальные',
|
||||
|
||||
@@ -90,7 +90,11 @@ export const ruVaultMessages: Messages = {
|
||||
'vault.hosts.newLocalShell': 'Локальная оболочка (CMD)',
|
||||
'vault.hosts.newGroup': 'Новая группа',
|
||||
'vault.hosts.import': 'Импорт',
|
||||
'vault.hosts.export': 'Экспорт',
|
||||
'vault.hosts.export': 'Экспорт CSV',
|
||||
'vault.hosts.export.sshConfig': 'Экспорт конфигурации SSH',
|
||||
'vault.hosts.export.sshEmpty': 'Нет SSH-хостов с доступным для экспорта маршрутом',
|
||||
'vault.hosts.export.sshSkipped': 'Пропущено хостов с неподдерживаемым протоколом или маршрутом: {count}',
|
||||
'vault.hosts.export.sshFailed': 'Не удалось экспортировать конфигурацию SSH',
|
||||
'vault.hosts.export.toast.success': 'Экспортировано {count} хостов в CSV',
|
||||
'vault.hosts.export.toast.successWithSkipped': 'Экспортировано {count} хостов в CSV ({skipped} неподдерживаемых хостов пропущено)',
|
||||
'vault.hosts.export.toast.passphrasesSkipped': 'Не удалось прочитать {count} сохранённых парольных фраз ключей; они оставлены пустыми',
|
||||
@@ -924,7 +928,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Сокет агента',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Не пробовать другие ключи, загруженные в агент',
|
||||
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Запустите или разблокируйте SSH-агент либо укажите путь к его сокету выше.',
|
||||
'hostDetails.keys.search': 'Поиск ключей...',
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '选择 Grok 模式并发送…',
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
'ai.chat.deliveredTextFile.source': '文件正文已包含在回复中',
|
||||
'ai.chat.deliveredTextFile.preview': '预览',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起预览',
|
||||
'ai.chat.deliveredTextFile.save': '另存为',
|
||||
'ai.chat.deliveredTextFile.saving': '正在保存…',
|
||||
'ai.chat.deliveredTextFile.saved': '文件已保存',
|
||||
'ai.chat.deliveredTextFile.exists': '文件已存在,请另选名称。',
|
||||
'ai.chat.deliveredTextFile.failed': '无法保存该文件。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此窗口不支持保存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '预览已截短,保存时保留完整文件。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
'ai.chat.preparing': '准备中…',
|
||||
@@ -355,10 +344,6 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不会改变权限。请勿填写密码或令牌。',
|
||||
'ai.grok.userQuestion.submit': '发送回答',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode 正在等待你的回答',
|
||||
'ai.agentQuestions.title': '允许 Agent 主动提问',
|
||||
'ai.agentQuestions.description': '允许此 Agent 在对话中询问细节。回答不会授予工具权限。',
|
||||
'ai.agentQuestions.codexDescription': '允许 Codex App Server 在默认模式下询问细节。回答不会授予工具权限。',
|
||||
'ai.grok.runtime.acp.default': '默认',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'通过 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。关闭后使用原始 headless streaming-json CLI 路径。',
|
||||
|
||||
@@ -840,7 +840,11 @@ Vaults 标签保持扁平,不使用这块背景。
|
||||
'vault.hosts.newLocalShell': '本地终端 (CMD)',
|
||||
'vault.hosts.newGroup': '新建分组',
|
||||
'vault.hosts.import': '导入',
|
||||
'vault.hosts.export': '导出',
|
||||
'vault.hosts.export': '导出 CSV',
|
||||
'vault.hosts.export.sshConfig': '导出 SSH 配置',
|
||||
'vault.hosts.export.sshEmpty': '没有可导出连接配置的 SSH 主机',
|
||||
'vault.hosts.export.sshSkipped': '已跳过 {count} 个协议或连接路径不受支持的主机',
|
||||
'vault.hosts.export.sshFailed': '无法导出 SSH 配置',
|
||||
'vault.hosts.export.toast.success': '已导出 {count} 个主机到 CSV',
|
||||
'vault.hosts.export.toast.successWithSkipped': '已导出 {count} 个主机到 CSV(跳过 {skipped} 个不支持的主机)',
|
||||
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 个已保存的密钥口令无法读取,导出时已留空',
|
||||
|
||||
@@ -10,10 +10,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'terminal.gitBranch.empty': '还没有本地分支',
|
||||
'terminal.gitBranch.noMatches': '没有匹配的分支',
|
||||
'terminal.gitBranch.unavailable': '无法读取此会话的分支。',
|
||||
'terminal.gitBranch.draftDelete': '拟定删除 {{value}} 的命令',
|
||||
'terminal.gitBranch.draftHint': '回车发送到当前终端,Esc 恢复原草稿。',
|
||||
'terminal.gitBranch.draftUnavailable': '原会话或目录已不可用。',
|
||||
'terminal.gitBranch.draftSingleLine': '请使用单行命令。',
|
||||
'terminal.directory.unknown': '目录未知',
|
||||
'terminal.directory.search': '搜索当前目录下的文件夹…',
|
||||
'terminal.directory.directories': '目录',
|
||||
@@ -821,7 +817,6 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
'tabs.convertToWorkspace': '转为工作区',
|
||||
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
|
||||
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
|
||||
'tabs.closeOthers': '关闭其他标签',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理地址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不尝试代理中其他无关密钥',
|
||||
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '请启动或解锁密钥服务,或者在上方填写它的地址。',
|
||||
'hostDetails.keys.search': '搜索密钥…',
|
||||
|
||||
@@ -1,20 +1,9 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '選擇 Grok 模式並傳送…',
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
'ai.chat.deliveredTextFile.source': '檔案正文已包含在回覆中',
|
||||
'ai.chat.deliveredTextFile.preview': '預覽',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起預覽',
|
||||
'ai.chat.deliveredTextFile.save': '另存為',
|
||||
'ai.chat.deliveredTextFile.saving': '正在儲存…',
|
||||
'ai.chat.deliveredTextFile.saved': '檔案已儲存',
|
||||
'ai.chat.deliveredTextFile.exists': '檔案已存在,請另選名稱。',
|
||||
'ai.chat.deliveredTextFile.failed': '無法儲存此檔案。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此視窗不支援儲存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '預覽已截短,儲存時保留完整檔案。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
'ai.chat.preparing': '準備中…',
|
||||
@@ -355,10 +344,6 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.userQuestion.title': 'Grok 正在等待你的回答',
|
||||
'ai.grok.userQuestion.description': '回答不會變更權限。請勿填寫密碼或權杖。',
|
||||
'ai.grok.userQuestion.submit': '傳送回答',
|
||||
'ai.opencode.userQuestion.title': 'OpenCode 正在等待你的回答',
|
||||
'ai.agentQuestions.title': '允許 Agent 主動提問',
|
||||
'ai.agentQuestions.description': '允許此 Agent 在對話中詢問細節。回答不會授予工具權限。',
|
||||
'ai.agentQuestions.codexDescription': '允許 Codex App Server 在預設模式下詢問細節。回答不會授予工具權限。',
|
||||
'ai.grok.runtime.acp.default': '預設',
|
||||
'ai.grok.runtime.acp.description':
|
||||
'透過 Agent Client Protocol(grok agent stdio)接入 Grok。在 session/new 注入 Netcatty MCP。關閉後使用原始 headless streaming-json CLI 路徑。',
|
||||
|
||||
@@ -840,7 +840,11 @@ Vaults 分頁維持扁平,不使用這塊背景。
|
||||
'vault.hosts.newLocalShell': '本地終端 (CMD)',
|
||||
'vault.hosts.newGroup': '新增群組',
|
||||
'vault.hosts.import': '匯入',
|
||||
'vault.hosts.export': '匯出',
|
||||
'vault.hosts.export': '匯出 CSV',
|
||||
'vault.hosts.export.sshConfig': '匯出 SSH 設定',
|
||||
'vault.hosts.export.sshEmpty': '沒有可匯出連線設定的 SSH 主機',
|
||||
'vault.hosts.export.sshSkipped': '已略過 {count} 個通訊協定或連線路徑不受支援的主機',
|
||||
'vault.hosts.export.sshFailed': '無法匯出 SSH 設定',
|
||||
'vault.hosts.export.toast.success': '已匯出 {count} 個主機到 CSV',
|
||||
'vault.hosts.export.toast.successWithSkipped': '已匯出 {count} 個主機到 CSV(跳過 {skipped} 個不支援的主機)',
|
||||
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 個已儲存的金鑰密碼無法讀取,匯出時已留空',
|
||||
|
||||
@@ -10,10 +10,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'terminal.gitBranch.empty': '還沒有本機分支',
|
||||
'terminal.gitBranch.noMatches': '沒有符合的分支',
|
||||
'terminal.gitBranch.unavailable': '無法讀取此工作階段的分支。',
|
||||
'terminal.gitBranch.draftDelete': '擬定刪除 {{value}} 的指令',
|
||||
'terminal.gitBranch.draftHint': 'Enter 傳送到目前的終端機,Esc 還原原稿。',
|
||||
'terminal.gitBranch.draftUnavailable': '原本的工作階段或目錄已無法使用。',
|
||||
'terminal.gitBranch.draftSingleLine': '請使用單行指令。',
|
||||
'terminal.directory.unknown': '目錄未知',
|
||||
'terminal.directory.search': '搜尋目前目錄下的資料夾…',
|
||||
'terminal.directory.directories': '目錄',
|
||||
@@ -821,7 +817,6 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
'tabs.convertToWorkspace': '轉為工作區',
|
||||
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
|
||||
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
|
||||
'tabs.closeOthers': '關閉其他分頁',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理位址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不嘗試代理中其他無關金鑰',
|
||||
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '請啟動或解鎖金鑰服務,或在上方填寫其位址。',
|
||||
'hostDetails.keys.search': '搜尋金鑰…',
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export async function saveDeliveredChatTextFile(file: ChatTextFile): Promise<
|
||||
'saved' | 'cancelled' | 'exists' | 'failed' | 'unavailable'
|
||||
> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.aiChatSaveTextFile) return 'unavailable';
|
||||
try {
|
||||
const { status } = await bridge.aiChatSaveTextFile(file);
|
||||
return status === 'invalid' ? 'failed' : status;
|
||||
} catch {
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,6 @@ test('session actions register and unregister', () => {
|
||||
clearSessionFontSizeOverride: noop,
|
||||
createWorkspaceWithHosts: noop,
|
||||
createWorkspaceFromSessions: noop,
|
||||
convertSessionToWorkspace: noop,
|
||||
addSessionToWorkspace: noop,
|
||||
appendHostToWorkspace: noop,
|
||||
appendHostToWorkspaceConfirmed: noop,
|
||||
|
||||
@@ -57,7 +57,6 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'clearSessionFontSizeOverride'
|
||||
| 'createWorkspaceWithHosts'
|
||||
| 'createWorkspaceFromSessions'
|
||||
| 'convertSessionToWorkspace'
|
||||
| 'addSessionToWorkspace'
|
||||
| 'moveWorkspacePane'
|
||||
| 'appendHostToWorkspace'
|
||||
|
||||
@@ -139,7 +139,6 @@ export interface SendToExternalContext {
|
||||
defaultTargetSession?: DefaultTargetSessionHint;
|
||||
providers: ProviderConfig[];
|
||||
selectedAgentModel?: string;
|
||||
chooseGrokMode?: boolean;
|
||||
toolIntegrationMode: AIToolIntegrationMode;
|
||||
selectedUserSkillSlugs?: string[];
|
||||
permissionMode: AIPermissionMode;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { DirectoryPickerError } from '../../domain/directoryPicker';
|
||||
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
|
||||
import { gitDeleteBranchCommand, gitSwitchCommand, scopeGitBranchDraft, type TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { gitSwitchCommand, type TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
@@ -9,13 +9,6 @@ const noCwd = () => null;
|
||||
const noSubscription = () => () => {};
|
||||
const REFRESH_DELAY_MS = 150;
|
||||
|
||||
type BranchCommandResult = 'sent' | 'busy' | 'unavailable';
|
||||
|
||||
export type GitBranchCommandDraft = {
|
||||
text: string;
|
||||
send: (text: string, signal: AbortSignal) => Promise<BranchCommandResult>;
|
||||
};
|
||||
|
||||
export function useComposeGitBranch(sessionId: string) {
|
||||
const controller = useSyncExternalStore(subscribeTerminalDirectories, () => getTerminalDirectory(sessionId), () => null);
|
||||
const backendId = controller?.localPosixSessionId;
|
||||
@@ -78,16 +71,6 @@ export function useComposeGitBranch(sessionId: string) {
|
||||
|
||||
const head = result?.controller === controller && result.cwd === cwd ? result.head : null;
|
||||
const bridge = netcattyBridge.get();
|
||||
async function sendCommand(command: string | null, signal: AbortSignal): Promise<BranchCommandResult> {
|
||||
if (!command || !scope || !isCurrent()) return 'unavailable';
|
||||
try {
|
||||
await scope.controller.sendLocalCommand(command, scope.cwd, signal);
|
||||
return 'sent';
|
||||
} catch (error) {
|
||||
return error instanceof DirectoryPickerError && error.code === 'busy' ? 'busy' : 'unavailable';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
head,
|
||||
scope,
|
||||
@@ -101,17 +84,15 @@ export function useComposeGitBranch(sessionId: string) {
|
||||
} catch { /* The menu displays the unavailable state. */ }
|
||||
return { kind: 'unavailable' } as const;
|
||||
},
|
||||
switchBranch(worktreeRoot: string, name: string, signal: AbortSignal) {
|
||||
return sendCommand(gitSwitchCommand(worktreeRoot, name), signal);
|
||||
},
|
||||
deleteBranchDraft(menuHead: TerminalGitHead, name: string): GitBranchCommandDraft | null {
|
||||
const { worktreeRoot } = menuHead;
|
||||
if (head?.worktreeRoot !== worktreeRoot || (menuHead.kind === 'branch' && menuHead.name === name) || !isCurrent()) return null;
|
||||
const text = gitDeleteBranchCommand(name);
|
||||
return text ? {
|
||||
text,
|
||||
send: (draft, signal) => sendCommand(scopeGitBranchDraft(worktreeRoot, draft), signal),
|
||||
} : null;
|
||||
async switchBranch(worktreeRoot: string, name: string, signal: AbortSignal): Promise<'sent' | 'busy' | 'unavailable'> {
|
||||
const command = gitSwitchCommand(worktreeRoot, name);
|
||||
if (!command || !scope || !isCurrent()) return 'unavailable';
|
||||
try {
|
||||
await scope.controller.sendLocalCommand(command, scope.cwd, signal);
|
||||
return 'sent';
|
||||
} catch (error) {
|
||||
return error instanceof DirectoryPickerError && error.code === 'busy' ? 'busy' : 'unavailable';
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { GitBranchCommandDraft } from './useComposeGitBranch';
|
||||
|
||||
type DraftStatus = 'ready' | 'sending' | 'busy' | 'unavailable' | 'singleLine';
|
||||
|
||||
type DraftSnapshot = {
|
||||
text: string;
|
||||
selectionStart: number;
|
||||
selectionEnd: number;
|
||||
};
|
||||
|
||||
export function useGitBranchDraft(sessionId: string, restore: (snapshot: DraftSnapshot) => void) {
|
||||
const staged = useRef<{ draft: GitBranchCommandDraft; previous: DraftSnapshot; request?: AbortController } | null>(null);
|
||||
const [status, setStatus] = useState<DraftStatus | null>(null);
|
||||
const getDraft = useCallback(() => staged.current?.draft ?? null, []);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
const current = staged.current;
|
||||
if (!current) return;
|
||||
staged.current = null;
|
||||
current.request?.abort();
|
||||
restore(current.previous);
|
||||
}, [restore]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setStatus(null);
|
||||
return clear;
|
||||
}, [sessionId, clear]);
|
||||
|
||||
const stage = useCallback((draft: GitBranchCommandDraft, previous: DraftSnapshot) => {
|
||||
if (staged.current) return false;
|
||||
staged.current = { draft, previous };
|
||||
setStatus('ready');
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
clear();
|
||||
setStatus(null);
|
||||
}, [clear]);
|
||||
|
||||
const send = useCallback(async (text: string) => {
|
||||
const current = staged.current;
|
||||
if (!current || current.request || !text.trim()) return;
|
||||
// The command goes directly to the shell prompt, followed by Enter.
|
||||
if (Array.from(text).some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
|
||||
setStatus('singleLine');
|
||||
return;
|
||||
}
|
||||
const request = new AbortController();
|
||||
current.request = request;
|
||||
setStatus('sending');
|
||||
const result = await current.draft.send(text, request.signal);
|
||||
if (staged.current !== current || request.signal.aborted) return;
|
||||
current.request = undefined;
|
||||
if (result === 'sent') cancel();
|
||||
else setStatus(result);
|
||||
}, [cancel]);
|
||||
|
||||
return { status, getDraft, stage, cancel, send };
|
||||
}
|
||||
@@ -57,40 +57,6 @@ async function mountSessionState(t: test.TestContext) {
|
||||
return () => latestState;
|
||||
}
|
||||
|
||||
test('converting a standalone tab keeps the live session, tab position and focus', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
let first = '';
|
||||
let target = '';
|
||||
let last = '';
|
||||
await act(async () => {
|
||||
first = getState().createLocalTerminal();
|
||||
target = getState().createLocalTerminal({ shellName: 'Build shell' });
|
||||
last = getState().createLocalTerminal();
|
||||
});
|
||||
await act(async () => { getState().updateSessionStatus(target, 'connected'); });
|
||||
const before = getState().sessions;
|
||||
await act(async () => {
|
||||
getState().convertSessionToWorkspace(target);
|
||||
getState().convertSessionToWorkspace(target);
|
||||
});
|
||||
assert.equal(getState().workspaces.length, 1);
|
||||
const [workspace] = getState().workspaces;
|
||||
assert.equal(workspace.root.type, 'pane');
|
||||
assert.equal(workspace.root.sessionId, target);
|
||||
assert.equal(workspace.focusedSessionId, target);
|
||||
assert.deepEqual(getState().sessions, before.map(session =>
|
||||
session.id === target ? { ...session, workspaceId: workspace.id } : session));
|
||||
assert.deepEqual(getState().orderedTabs, [first, workspace.id, last]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
|
||||
|
||||
// A reordered editor tab must keep its place alongside terminal tabs.
|
||||
const editor = 'editor:test';
|
||||
await act(async () => { getState().reorderTabs(editor, last, 'before', [editor]); });
|
||||
await act(async () => { getState().convertSessionToWorkspace(last); });
|
||||
const secondWorkspace = getState().workspaces[1];
|
||||
assert.deepEqual(getState().getOrderedWorkTabs([editor]), [first, workspace.id, editor, secondWorkspace.id]);
|
||||
});
|
||||
|
||||
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
|
||||
@@ -1503,30 +1503,6 @@ export const useSessionState = ({
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const convertSessionToWorkspace = useCallback((sessionId: string) => {
|
||||
const standaloneIds = orphanSessionsRef.current.map(session => session.id);
|
||||
const workspace = createWorkspaceFromSessionIds([sessionId], {
|
||||
title: DEFAULT_WORKSPACE_TITLE,
|
||||
autoTitle: true,
|
||||
viewMode: 'focus',
|
||||
});
|
||||
|
||||
setSessions(prev => {
|
||||
const source = prev.find(session => session.id === sessionId);
|
||||
if (!source || source.workspaceId || source.hiddenFromTabs) return prev;
|
||||
|
||||
setWorkspaces(current => addWorkspaceIfMissing(current, workspace));
|
||||
setTabOrder(current => {
|
||||
if (current.includes(workspace.id)) return current;
|
||||
// Unreordered terminal tabs may only have an implicit position.
|
||||
const order = current.includes(sessionId) ? current : [...new Set([...current, ...standaloneIds])];
|
||||
return order.map(id => id === sessionId ? workspace.id : id);
|
||||
});
|
||||
setActiveTabId(workspace.id);
|
||||
return prev.map(session => session === source ? { ...session, workspaceId: workspace.id } : session);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Copy a session - creates a new session with the same host connection
|
||||
const copySession = useCallback((sessionId: string, options?: {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
@@ -1818,7 +1794,6 @@ export const useSessionState = ({
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
removeSessionFromWorkspace,
|
||||
|
||||
@@ -62,7 +62,6 @@ interface AIChatPanelContentProps {
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
@@ -177,7 +176,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
@@ -576,7 +574,6 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={onSendWithGrokMode}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
|
||||
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
|
||||
const handleSend = useCallback(async (
|
||||
textOverride?: string,
|
||||
options?: { includeDraftAttachments?: boolean; chooseGrokMode?: boolean },
|
||||
options?: { includeDraftAttachments?: boolean },
|
||||
) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
@@ -1964,7 +1964,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
scopeType,
|
||||
scopeTargetId,
|
||||
existingSessionId: existingExternalSessionId,
|
||||
chooseGrokMode: options?.chooseGrokMode,
|
||||
updateExternalSessionId: updateSessionExternalSessionId,
|
||||
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
|
||||
terminalSessions,
|
||||
@@ -2190,10 +2189,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
return registerGrantPersister((rule) => { addGrant(rule); });
|
||||
}, [addGrant]);
|
||||
|
||||
const handleSendWithGrokMode = useCallback((text: string) => {
|
||||
void handleSend(text, { includeDraftAttachments: true, chooseGrokMode: true });
|
||||
}, [handleSend]);
|
||||
|
||||
const handleSendQuickPrompt = useCallback((promptText: string) => {
|
||||
void handleSend(promptText, { includeDraftAttachments: true });
|
||||
}, [handleSend]);
|
||||
@@ -2659,7 +2654,6 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={getExternalAgentSdkBackend(currentAgentConfig ?? undefined) === 'grok' && currentAgentConfig?.grokRuntime !== 'streaming-json' ? handleSendWithGrokMode : undefined}
|
||||
handleCompact={handleCompact}
|
||||
onRenameSession={handleRenameSession}
|
||||
onRenameActiveChat={handleRenameSlashCommand}
|
||||
|
||||
@@ -383,8 +383,8 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
|
||||
active
|
||||
? "bg-primary/12 text-primary"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60",
|
||||
? "bg-primary/12 text-primary border border-primary/25"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
+16
-12
@@ -802,13 +802,6 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
? 'select'
|
||||
: 'connect';
|
||||
|
||||
const activation = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
@@ -844,11 +837,17 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
if (!ids) e.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
if (activation === 'toggle-multi') {
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (activation === 'select') {
|
||||
if (action === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -857,11 +856,17 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
if (activation === 'toggle-multi') {
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (activation === 'select') {
|
||||
if (action === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -975,7 +980,6 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<HostTreeHostContextMenuContent
|
||||
enterConnects={activation === 'connect'}
|
||||
host={host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
|
||||
@@ -624,55 +624,13 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<VaultPageHeader>
|
||||
<div className="flex-1 min-w-0 flex flex-wrap items-center gap-2">
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<VaultHeaderSearch
|
||||
placeholder={t("knownHosts.search.placeholder")}
|
||||
className="flex-1 min-w-[160px] max-w-xs"
|
||||
className="flex-1 max-w-xs"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex h-10 shrink-0 items-center rounded-md bg-secondary/70 p-1 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* View Mode Toggle */}
|
||||
@@ -762,6 +720,52 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
)}
|
||||
</VaultPageHeader>
|
||||
|
||||
{/* Segmented Tab Strip: SSH Host Keys | Remote Desktop Certificates */}
|
||||
<div className="px-4 py-2 border-b border-border/50 bg-background/60 shrink-0">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex items-center rounded-lg bg-secondary/70 p-0.5 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<ScrollArea className="flex-1">
|
||||
{activeTab === "certs" ? (
|
||||
|
||||
@@ -712,7 +712,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{hostRow}</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem shortcut={isSelected ? "Enter" : undefined} onClick={() => onSelect(host)}>
|
||||
<ContextMenuItem onClick={() => onSelect(host)}>
|
||||
{t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onEditHost(host)}>
|
||||
|
||||
+31
-48
@@ -1,7 +1,6 @@
|
||||
import { Folder, FolderLock, Lock, Menu, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import { Folder, FolderLock, Lock, Menu, MoreHorizontal, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { activeTabStore, fromEditorTabId, isEditorTabId, toEditorTabId } from '../application/state/activeTabStore';
|
||||
import { applySessionPresentation } from '../application/state/sessionPresentationStore';
|
||||
import { topTabsSessionsEqual } from '../domain/topTabsSessionsEqual';
|
||||
import { isHostTreeWorkTabSurface } from '../application/app/workTabSurface';
|
||||
import { buildTabShortcutNumberById } from '../application/app/tabShortcutTargets';
|
||||
@@ -36,8 +35,6 @@ import { GlobalSftpTransferCenter } from './GlobalSftpTransferCenter';
|
||||
import { TopTabsQuickControls } from './TopTabsQuickControls';
|
||||
import {
|
||||
ActiveTabAutoScroller,
|
||||
formatSessionTopTabLabel,
|
||||
resolveWorkspaceTopTabLabel,
|
||||
EditorTopTab,
|
||||
LogViewTopTab,
|
||||
PluginViewTopTab,
|
||||
@@ -56,7 +53,6 @@ import {
|
||||
scheduleAfterInstantThemeSwitch,
|
||||
scheduleChromeLayoutAnimation,
|
||||
} from '../application/state/useActiveChromeTheme';
|
||||
import { TopTabOverflowMenu, type OverflowTab } from './top-tabs/TopTabOverflowMenu';
|
||||
import { useTopTabLifecycleAnimations } from './top-tabs/useTopTabLifecycleAnimations';
|
||||
|
||||
// Helper styles for Electron drag regions (use type assertion to include non-standard WebkitAppRegion)
|
||||
@@ -195,7 +191,6 @@ interface TopTabsProps {
|
||||
onCopySession: (sessionId: string) => void;
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onRenameWorkspace: (workspaceId: string) => void;
|
||||
@@ -254,7 +249,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
onRenameWorkspace,
|
||||
onCopyWorkspace,
|
||||
@@ -862,42 +856,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
}).filter(Boolean);
|
||||
}, [orderedTabs, editorTabMap, pluginViewTabMap, orphanSessionMap, workspaceMap, logViewMap, workspacePaneCounts]);
|
||||
|
||||
const getOverflowTabs = (): OverflowTab[] => {
|
||||
const tabs: OverflowTab[] = [{ id: 'vault', label: 'Vaults' }];
|
||||
if (showSftpTab) tabs.push({ id: 'sftp', label: 'SFTP' });
|
||||
for (const item of orderedTabItems) {
|
||||
if (!item) continue;
|
||||
const { id } = item;
|
||||
switch (item.type) {
|
||||
case 'session':
|
||||
tabs.push({ id, label: formatSessionTopTabLabel(applySessionPresentation(item.session), dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'workspace':
|
||||
tabs.push({ id, label: resolveWorkspaceTopTabLabel(item.workspace, workspaceTabSessions.get(id)?.sessions ?? [], dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'editor': {
|
||||
const editor = item.editorTab;
|
||||
tabs.push({
|
||||
id,
|
||||
label: (editorTabFileNameCounts.get(editor.fileName) ?? 0) > 1 ? editor.remotePath : editor.fileName,
|
||||
activate: editor.placement === 'window' ? () => onFocusEditorWindowTab?.(editor.id) : undefined,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'pluginView':
|
||||
tabs.push({ id, label: item.pluginViewTab.title });
|
||||
break;
|
||||
case 'logView': {
|
||||
const { protocol, hostname } = item.logView.log;
|
||||
const host = protocol === 'local' || hostname === 'localhost' ? t('tabs.logLocal') : hostname;
|
||||
tabs.push({ id, label: `${t('tabs.logPrefix')} ${host}` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return tabs;
|
||||
};
|
||||
|
||||
// Bulk-close menu items shared by session and workspace context menus.
|
||||
// Anchor is the tab the user right-clicked on (matches VSCode/JetBrains UX).
|
||||
const renderBulkCloseItems = useCallback((anchorId: string) => {
|
||||
@@ -1034,7 +992,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession={onDuplicateSession}
|
||||
onCopySessionToNewWindow={onCopySessionToNewWindow}
|
||||
onMoveSessionToNewWindow={onMoveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={onConvertSessionToWorkspace}
|
||||
onEditHost={onEditHost}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
dynamicTabTitleMode={dynamicTabTitleMode}
|
||||
@@ -1253,11 +1210,17 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
)}
|
||||
|
||||
<div className="relative min-w-0 flex-1 flex app-drag" style={dragRegionStyle}>
|
||||
{/* Left fade mask */}
|
||||
{canScrollLeft && (
|
||||
<div
|
||||
className="absolute left-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to right, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Scrollable container */}
|
||||
<div
|
||||
ref={tabsContainerRef}
|
||||
data-fade-left={canScrollLeft || undefined}
|
||||
data-fade-right={canScrollRight || undefined}
|
||||
className="top-tab-scroll-viewport min-w-0 flex items-end gap-0 overflow-x-auto scrollbar-none app-no-drag max-w-full"
|
||||
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none', ...noDragRegionStyle }}
|
||||
onClick={handleScrollableTabClick}
|
||||
@@ -1292,6 +1255,14 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* Keep unused space and the drag handle outside the scroll viewport's exclusion. */}
|
||||
<div className="flex-1 app-drag" style={dragRegionStyle} />
|
||||
<div className="min-w-[20px] h-7 app-drag flex-shrink-0 self-end" style={dragRegionStyle} />
|
||||
|
||||
{/* Right fade mask */}
|
||||
{canScrollRight && (
|
||||
<div
|
||||
className="absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to left, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -1299,7 +1270,20 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* More tabs button - only when overflowing */}
|
||||
{hasOverflow && (
|
||||
<div className="contents" data-section="top-tabs-toolbar-actions">
|
||||
<TopTabOverflowMenu getTabs={getOverflowTabs} onOpenQuickSwitcher={onOpenQuickSwitcher} />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 flex-shrink-0 app-no-drag self-end rounded-none"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
onClick={onOpenQuickSwitcher}
|
||||
>
|
||||
<MoreHorizontal size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('topTabs.moreTabs')}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1407,7 +1391,6 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onCopySession === next.onCopySession &&
|
||||
prev.onDuplicateSession === next.onDuplicateSession &&
|
||||
prev.onCopySessionToNewWindow === next.onCopySessionToNewWindow &&
|
||||
prev.onConvertSessionToWorkspace === next.onConvertSessionToWorkspace &&
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
|
||||
@@ -323,6 +323,18 @@ interface VaultViewProps {
|
||||
};
|
||||
}
|
||||
|
||||
function downloadHostExport(content: string, type: string, filename: string) {
|
||||
const blob = new Blob([content], { type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
hosts,
|
||||
keys,
|
||||
@@ -929,15 +941,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `hosts_export_${new Date().toISOString().slice(0, 10)}.csv`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
downloadHostExport(csv, "text/csv;charset=utf-8;", `hosts_export_${new Date().toISOString().slice(0, 10)}.csv`);
|
||||
|
||||
if (unreadablePassphraseCount > 0) {
|
||||
toast.warning(
|
||||
@@ -967,6 +971,21 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
}
|
||||
}, [hosts, keys, proxyProfiles, identities, groupConfigs, t]);
|
||||
|
||||
const handleExportSshConfig = useCallback(async () => {
|
||||
try {
|
||||
const { exportVaultSshConfig } = await import("../domain/vaultSshConfigExport");
|
||||
const { text, skippedCount } = exportVaultSshConfig(hosts, groupConfigs, identities, keys, proxyProfileIdSet);
|
||||
if (!text) {
|
||||
toast.warning(t("vault.hosts.export.sshEmpty"));
|
||||
return;
|
||||
}
|
||||
downloadHostExport(text, "text/plain;charset=utf-8", "netcatty-ssh.conf");
|
||||
if (skippedCount) toast.warning(t("vault.hosts.export.sshSkipped", { count: skippedCount }));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : String(error), t("vault.hosts.export.sshFailed"));
|
||||
}
|
||||
}, [hosts, groupConfigs, identities, keys, proxyProfileIdSet, t]);
|
||||
|
||||
// Copy hostname/IP for cross-host paste without opening the editor
|
||||
const handleCopyHostname = useCallback(
|
||||
(host: Host) => {
|
||||
@@ -1686,6 +1705,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
|
||||
handleEditHost,
|
||||
handleEditTag,
|
||||
handleExportHosts,
|
||||
handleExportSshConfig,
|
||||
handleHostConnect,
|
||||
handleImportFileSelected,
|
||||
handleNewHost,
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
|
||||
test('a completed reply has file actions but a streaming reply does not', () => {
|
||||
const content = '```netcatty-file\n{"name":"report.md","content":"# Example content"}\n```';
|
||||
const render = (isAnimating: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en"><ChatFileReply content={content} isAnimating={isAnimating} /></I18nProvider>,
|
||||
);
|
||||
const completed = render(false);
|
||||
assert.match(completed, /data-chat-text-file/);
|
||||
assert.match(completed, /report\.md/);
|
||||
assert.match(completed, /Save as/);
|
||||
assert.match(completed, /Preview/);
|
||||
assert.doesNotMatch(completed, /# Example content/);
|
||||
assert.doesNotMatch(render(true), /data-chat-text-file/);
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Download, FileText } from 'lucide-react';
|
||||
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { saveDeliveredChatTextFile } from '../../application/state/chatTextFileDelivery';
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { splitChatTextFileOffers } from '../../domain/chatTextFileOffers';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
|
||||
const previewLimit = 32 * 1024;
|
||||
|
||||
function ChatFileOffer({ file }: { file: ChatTextFile }) {
|
||||
const { t } = useI18n();
|
||||
const [preview, setPreview] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [status, setStatus] = useState<'saved' | 'exists' | 'failed' | 'unavailable'>();
|
||||
const saveFile = async () => {
|
||||
setStatus(undefined);
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await saveDeliveredChatTextFile(file);
|
||||
if (result !== 'cancelled') setStatus(result);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="my-2 min-w-0 rounded-md border border-border bg-muted/35 px-3 py-2" data-chat-text-file>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 items-start gap-2 text-sm">
|
||||
<FileText size={16} aria-hidden="true" className="mt-0.5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0">
|
||||
<div className="break-all font-semibold">{file.name}</div>
|
||||
<div className="text-muted-foreground">{t('ai.chat.deliveredTextFile.source')}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="rounded px-1 py-0.5 text-sm underline focus-visible:outline-2 focus-visible:outline-ring"
|
||||
aria-expanded={preview} onClick={() => setPreview(value => !value)}
|
||||
>{t(`ai.chat.deliveredTextFile.${preview ? 'hidePreview' : 'preview'}`)}</button>
|
||||
<button type="button" className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-60"
|
||||
disabled={saving} onClick={() => { void saveFile(); }}
|
||||
><Download size={14} aria-hidden="true" />{t(`ai.chat.deliveredTextFile.${saving ? 'saving' : 'save'}`)}</button>
|
||||
</div>
|
||||
{status && <p role="status" className="mt-2 text-sm">{t(`ai.chat.deliveredTextFile.${status}`)}</p>}
|
||||
{preview && (
|
||||
<>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm border border-border bg-background px-2 py-1 font-mono text-xs">{file.content.slice(0, previewLimit)}</pre>
|
||||
{file.content.length > previewLimit && <p className="mt-1 text-sm text-muted-foreground">{t('ai.chat.deliveredTextFile.previewPartial')}</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatFileReply({ content, isAnimating }: { content: string; isAnimating?: boolean }) {
|
||||
const parsed = useMemo(() => isAnimating ? null : splitChatTextFileOffers(content), [content, isAnimating]);
|
||||
if (!parsed?.files.length) return <LazyMessageResponse isAnimating={isAnimating}>{content}</LazyMessageResponse>;
|
||||
return (
|
||||
<>
|
||||
{parsed.markdown.trim() && <LazyMessageResponse>{parsed.markdown}</LazyMessageResponse>}
|
||||
{parsed.files.map((file, index) => <ChatFileOffer key={`${index}:${file.name}`} file={file} />)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -263,7 +263,6 @@ interface ChatInputProps {
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean; protocol?: string }>;
|
||||
/** Explicit signal that the active tab/scope is a VNC or RDP remote desktop. */
|
||||
isRemoteDesktopContext?: boolean;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
/** Optional handler invoked when a remote desktop quick prompt chip is clicked. */
|
||||
onSendQuickPrompt?: (promptText: string) => void;
|
||||
/** Force-show remote desktop quick prompt chips (auto-shown when a remote screen image is attached). */
|
||||
@@ -343,7 +342,6 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
hosts = [],
|
||||
isRemoteDesktopContext = false,
|
||||
onSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
showRemoteScreenQuickPrompts,
|
||||
notes = [],
|
||||
onMentionNote,
|
||||
@@ -1691,22 +1689,6 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
<span className="flex-1 text-foreground/85">{t('ai.chat.menuMentionHost')}</span>
|
||||
{hosts.length > 0 && <ChevronRight size={10} className="text-muted-foreground/50" />}
|
||||
</button>
|
||||
{onSendWithGrokMode && (
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
disabled={composerDisabled || isStreaming || (!hasTextStore.get() && !hasTerminalSelectionAttachment && !hasImageAttachment)}
|
||||
onClick={() => {
|
||||
const text = readComposerText();
|
||||
closeAllMenus();
|
||||
onSendWithGrokMode(text);
|
||||
}}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 cursor-pointer whitespace-nowrap disabled:opacity-40"
|
||||
>
|
||||
<MessageSquare size={13} className="text-muted-foreground/60" />
|
||||
{t('ai.grok.chooseModeAndSend')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@@ -2044,7 +2026,6 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
|
||||
&& prev.onRemoveFile === next.onRemoveFile
|
||||
&& prev.hosts === next.hosts
|
||||
&& prev.isRemoteDesktopContext === next.isRemoteDesktopContext
|
||||
&& prev.onSendWithGrokMode === next.onSendWithGrokMode
|
||||
&& prev.onSendQuickPrompt === next.onSendQuickPrompt
|
||||
&& prev.showRemoteScreenQuickPrompts === next.showRemoteScreenQuickPrompts
|
||||
&& prev.notes === next.notes
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ConversationContent,
|
||||
ConversationScrollButton,
|
||||
} from '../ai-elements/conversation';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
import { Message, MessageContent } from '../ai-elements/messageShell';
|
||||
import { warmAiMarkdownRenderer } from './aiMarkdownWarmup';
|
||||
import { ToolCall } from '../ai-elements/tool-call';
|
||||
@@ -833,7 +833,9 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
: (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Markdown')}>
|
||||
<div data-ai-content="markdown">
|
||||
<ChatFileReply content={message.content} isAnimating={!!isThisStreaming} />
|
||||
<LazyMessageResponse isAnimating={!!isThisStreaming}>
|
||||
{message.content}
|
||||
</LazyMessageResponse>
|
||||
</div>
|
||||
</React.Profiler>
|
||||
)
|
||||
@@ -1034,7 +1036,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
))}
|
||||
{(Array.from(pendingCodebuddyElicitations.values()) as CodebuddyElicitation[])
|
||||
.filter((elicitation) => elicitation.chatSessionId === activeSessionId
|
||||
|| (!activeSessionId && !elicitation.request.source))
|
||||
|| (!activeSessionId && elicitation.request.source !== 'grok'))
|
||||
.map((elicitation) => (
|
||||
<CodebuddyElicitationCard
|
||||
key={`${elicitation.elicitationId}:${elicitation.requestInstanceId ?? 0}`}
|
||||
|
||||
@@ -57,8 +57,7 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const isGrokQuestion = elicitation.request.source === 'grok';
|
||||
const isNativeQuestion = Boolean(elicitation.request.source);
|
||||
const formValues = isNativeQuestion
|
||||
const formValues = isGrokQuestion
|
||||
? Object.fromEntries(Object.entries(values).map(([id, value]) =>
|
||||
[id, typeof value === 'string' ? value.trim() : value]))
|
||||
: values;
|
||||
@@ -97,11 +96,10 @@ 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(isGrokQuestion ? 'ai.grok.userQuestion.title'
|
||||
: elicitation.request.source === 'opencode-native' ? 'ai.opencode.userQuestion.title'
|
||||
: '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(isNativeQuestion
|
||||
{elicitation.request.message || t(isGrokQuestion
|
||||
? 'ai.grok.userQuestion.description' : 'ai.codebuddy.elicitation.description')}
|
||||
</div>
|
||||
</div>
|
||||
@@ -258,7 +256,7 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
{!isNativeQuestion && <Button
|
||||
{!isGrokQuestion && <Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={submitting}
|
||||
@@ -274,7 +272,7 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
buildCodebuddyElicitationContent(formValues, fields),
|
||||
)}
|
||||
>
|
||||
{t(isNativeQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
{t(isGrokQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -40,21 +40,6 @@ test('buildManagedAgentState removes stale managed agents when path detection fa
|
||||
assert.equal(state.defaultAgentId, 'catty');
|
||||
});
|
||||
|
||||
test('a temporary unavailable probe preserves the per-agent question preference', () => {
|
||||
for (const key of ['codex', 'codebuddy', 'opencode'] as const) {
|
||||
const id = `discovered_${key}`;
|
||||
const state = buildManagedAgentState([{
|
||||
id, name: key, command: key, enabled: true, sdkBackend: key, allowNativeUserQuestions: true,
|
||||
}], id, key, null);
|
||||
assert.equal(state.agents[0]?.available, false);
|
||||
assert.equal(state.agents[0]?.allowNativeUserQuestions, true);
|
||||
const recovered = buildManagedAgentState(state.agents, id, key, {
|
||||
available: true, path: key, version: '1.0',
|
||||
});
|
||||
assert.equal(recovered.agents[0]?.allowNativeUserQuestions, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('buildManagedAgentState keeps unrelated defaults when removing stale managed agents', () => {
|
||||
const agents: ExternalAgentConfig[] = [
|
||||
{
|
||||
|
||||
@@ -123,10 +123,9 @@ export const OpenHostBrowserMenuItem: React.FC<{ host: Host; onOpenBrowser?: (ho
|
||||
};
|
||||
|
||||
export const HostTreeHostContextMenuContent: React.FC<
|
||||
HostTreeHostContextMenuHandlers & { host: Host; enterConnects?: boolean }
|
||||
HostTreeHostContextMenuHandlers & { host: Host }
|
||||
> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
@@ -154,7 +153,7 @@ export const HostTreeHostContextMenuContent: React.FC<
|
||||
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem shortcut={enterConnects ? 'Enter' : undefined} onClick={() => onConnect(safeHost)}>
|
||||
<ContextMenuItem onClick={() => onConnect(safeHost)}>
|
||||
<Monitor className="mr-2 h-4 w-4" /> {t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<OpenDualPaneSftpMenuItem host={safeHost} />
|
||||
|
||||
@@ -766,12 +766,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
)));
|
||||
}, [setExternalAgents]);
|
||||
|
||||
const setNativeQuestions = useCallback((agentId: string, enabled: boolean) => {
|
||||
setExternalAgents(agents => agents.map(agent =>
|
||||
agent.id === agentId ? { ...agent, allowNativeUserQuestions: enabled } : agent));
|
||||
}, [setExternalAgents]);
|
||||
const opencodeQuestionAgent = externalAgents.find(agent => agent.id === "discovered_opencode");
|
||||
|
||||
const handleGrokRuntimeChange = useCallback((runtime: 'acp' | 'streaming-json') => {
|
||||
setExternalAgents((agents) => {
|
||||
const managedId = "discovered_grok";
|
||||
@@ -1167,15 +1161,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
appServerStatus={codexAppServerStatus}
|
||||
onAppServerRuntimeChange={handleCodexRuntimeChange}
|
||||
/>
|
||||
{codexRuntime === 'app-server' && codexManagedAgent && (
|
||||
<SettingCard>
|
||||
<SettingRow label={t('ai.agentQuestions.title')} description={t('ai.agentQuestions.codexDescription')}>
|
||||
<Toggle checked={codexManagedAgent.allowNativeUserQuestions === true}
|
||||
onChange={enabled => setNativeQuestions(codexManagedAgent.id, enabled)}
|
||||
ariaLabel={t('ai.agentQuestions.title')} />
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
@@ -1217,7 +1202,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
<SettingsSection
|
||||
anchorId="ai-agy"
|
||||
title={t('ai.agy.title')}
|
||||
leading={<AgentIconBadge agent={{ id: "agy", icon: "agy", name: "Antigravity CLI" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
|
||||
leading={<AgentIconBadge agent={{ id: "agy", icon: "google", name: "Antigravity CLI" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
|
||||
>
|
||||
<CopilotCliCard
|
||||
pathInfo={agyPathInfo}
|
||||
@@ -1259,16 +1244,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
onResetPath={() => void handleResetCustomPath("opencode")}
|
||||
i18nPrefix="ai.opencode"
|
||||
/>
|
||||
{opencodeQuestionAgent && opencodePathInfo?.available
|
||||
&& /(?:^|\s)v?1\.\d+\.\d+\b/i.test(opencodePathInfo.version ?? '') && (
|
||||
<SettingCard>
|
||||
<SettingRow label={t('ai.agentQuestions.title')} description={t('ai.agentQuestions.description')}>
|
||||
<Toggle checked={opencodeQuestionAgent.allowNativeUserQuestions === true}
|
||||
onChange={enabled => setNativeQuestions(opencodeQuestionAgent.id, enabled)}
|
||||
ariaLabel={t('ai.agentQuestions.title')} />
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
@@ -1311,15 +1286,6 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
advancedOptions={codebuddyAdvancedOptions}
|
||||
onAdvancedOptionsChange={updateCodebuddyAdvancedOptions}
|
||||
/>
|
||||
{codebuddyManagedAgent && (
|
||||
<SettingCard>
|
||||
<SettingRow label={t('ai.agentQuestions.title')} description={t('ai.agentQuestions.description')}>
|
||||
<Toggle checked={codebuddyManagedAgent.allowNativeUserQuestions === true}
|
||||
onChange={enabled => setNativeQuestions(codebuddyManagedAgent.id, enabled)}
|
||||
ariaLabel={t('ai.agentQuestions.title')} />
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
)}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
|
||||
@@ -59,13 +59,6 @@ export function buildManagedAgentState(
|
||||
defaultAgentId,
|
||||
};
|
||||
}
|
||||
if (existingManaged?.allowNativeUserQuestions !== undefined
|
||||
&& (agentKey === "codex" || agentKey === "codebuddy" || agentKey === "opencode")) {
|
||||
return {
|
||||
agents: prevAgents.map((agent) => agent.id === managedId ? { ...agent, available: false } : agent),
|
||||
defaultAgentId,
|
||||
};
|
||||
}
|
||||
if (agentKey === "cursor" && (existingManaged?.apiKey || existingManaged?.cursorAuthMode === "cli-login")) {
|
||||
const defaults = AGENT_DEFAULTS[agentKey];
|
||||
const {
|
||||
|
||||
@@ -245,7 +245,7 @@ export const AGENT_DEFAULTS: Record<string, Omit<ExternalAgentConfig, "id" | "co
|
||||
agy: {
|
||||
name: "Antigravity CLI",
|
||||
args: [],
|
||||
icon: "agy",
|
||||
icon: "google",
|
||||
sdkBackend: "agy",
|
||||
},
|
||||
mimo: {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { AppWindow, Archive, ArrowDown, ArrowRight, ArrowUp, ChevronDown, ClipboardCopy, Code2, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderPlus, Loader2, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Unplug, Upload } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { BoundMenuShortcut } from '../ui/BoundMenuShortcut';
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
@@ -319,15 +318,13 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
}, [filesByName, pane.connection?.id, pane.connection?.currentPath]);
|
||||
|
||||
const renderRow = useCallback(
|
||||
(entry: SftpFileEntry, index: number) => {
|
||||
const selected = pane.selectedFiles.has(entry.name);
|
||||
const keyboardTargetsEntry = isPaneFocused && selected && pane.selectedFiles.size === 1;
|
||||
return <ContextMenu>
|
||||
(entry: SftpFileEntry, index: number) => (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger>
|
||||
<SftpFileRow
|
||||
entry={entry}
|
||||
index={index}
|
||||
isSelected={selected}
|
||||
isSelected={pane.selectedFiles.has(entry.name)}
|
||||
showSelectionHighlight={isPaneFocused}
|
||||
isDragOver={dragOverEntry === entry.name}
|
||||
columnWidths={columnWidths}
|
||||
@@ -348,7 +345,6 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
{isNavigableDirectory(entry) ? (
|
||||
<>
|
||||
<Folder size={14} className="mr-2" /> {t("sftp.context.open")}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpOpen" whenDisabled="Enter" />}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -360,7 +356,6 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
{isNavigableDirectory(entry) && (
|
||||
<ContextMenuItem onClick={() => onNavigateTo(joinPath(pane.connection.currentPath, entry.name))}>
|
||||
<ArrowRight size={14} className="mr-2" /> {t("sftp.context.navigateTo")}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpNavigateTo" />}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{!isLocal && onOpenInExternalEditor && (
|
||||
@@ -493,7 +488,6 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
})()}
|
||||
<ContextMenuItem onClick={() => openRenameDialog(joinPath(pane.connection?.currentPath ?? "", entry.name))}>
|
||||
<Pencil size={14} className="mr-2" /> {t("common.rename")}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpRename" />}
|
||||
</ContextMenuItem>
|
||||
{onEditPermissions && pane.connection && !pane.connection.isLocal && (
|
||||
<ContextMenuItem onClick={() => onEditPermissions(entry)}>
|
||||
@@ -512,16 +506,13 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} className="mr-2" /> {t("action.delete")}
|
||||
{isPaneFocused && selected && <BoundMenuShortcut action="sftpDelete" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onClick={onRefresh}>
|
||||
<RefreshCw size={14} className="mr-2" /> {t("common.refresh")}
|
||||
{isPaneFocused && <BoundMenuShortcut action="sftpRefresh" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => setShowNewFolderDialog(true)}>
|
||||
<FolderPlus size={14} className="mr-2" /> {t("sftp.newFolder")}
|
||||
{isPaneFocused && <BoundMenuShortcut action="sftpNewFolder" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => setShowNewFileDialog(true)}>
|
||||
<FilePlus size={14} className="mr-2" /> {t("sftp.newFile")}
|
||||
@@ -550,8 +541,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
)}
|
||||
</ContextMenu>;
|
||||
},
|
||||
</ContextMenu>
|
||||
),
|
||||
[
|
||||
columnWidths,
|
||||
visibleColumns,
|
||||
@@ -827,11 +818,9 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={onRefresh}>
|
||||
<RefreshCw size={14} className="mr-2" />{t("sftp.context.refresh")}
|
||||
{isPaneFocused && <BoundMenuShortcut action="sftpRefresh" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => setShowNewFolderDialog(true)}>
|
||||
<FolderPlus size={14} className="mr-2" />{t("sftp.newFolder")}
|
||||
{isPaneFocused && <BoundMenuShortcut action="sftpNewFolder" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => {
|
||||
const defaultName = getNextUntitledName(pane.files.map(f => f.name));
|
||||
|
||||
@@ -48,7 +48,6 @@ export const getSftpTreeEntryOpenAction = (
|
||||
export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
|
||||
pane,
|
||||
side,
|
||||
isPaneFocused = true,
|
||||
onPrepareSelection,
|
||||
onLoadChildren,
|
||||
onMoveEntriesToPath,
|
||||
@@ -955,11 +954,7 @@ export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
|
||||
handleNodeDragLeave,
|
||||
handleNodeContextMenu,
|
||||
});
|
||||
const keyboardSelectionContainsTarget = isPaneFocused && contextTarget != null && selectedPaths.has(contextTarget.entryPath);
|
||||
const contextMenuContent = useSftpPaneTreeContextMenu({
|
||||
isPaneFocused,
|
||||
keyboardSelectionContainsTarget,
|
||||
keyboardTargetsEntry: keyboardSelectionContainsTarget && selectedPaths.size === 1,
|
||||
contextTarget,
|
||||
pane,
|
||||
toggleExpand,
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { SftpTreeFolderDoubleClickBehavior } from '../../domain/sftpTreeFol
|
||||
export interface SftpPaneTreeViewProps {
|
||||
pane: SftpPane;
|
||||
side: 'left' | 'right';
|
||||
isPaneFocused?: boolean;
|
||||
onPrepareSelection: () => void;
|
||||
onLoadChildren: (path: string) => Promise<SftpFileEntry[]>;
|
||||
onMoveEntriesToPath: (sourcePaths: string[], targetPath: string) => Promise<void>;
|
||||
|
||||
@@ -43,7 +43,6 @@ function installSftpDom() {
|
||||
installGlobal("Element", win.Element);
|
||||
installGlobal("SVGElement", win.SVGElement);
|
||||
installGlobal("Node", win.Node);
|
||||
installGlobal("DOMRect", win.DOMRect);
|
||||
installGlobal("NodeFilter", win.NodeFilter);
|
||||
installGlobal("MutationObserver", win.MutationObserver);
|
||||
installGlobal("CustomEvent", win.CustomEvent);
|
||||
@@ -536,76 +535,3 @@ test("SftpPaneView preserves null activeTabId fallbacks and SftpSidePanel 0-arg
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("SFTP list and tree menus show file shortcuts and keep basic navigation when hotkeys are disabled", async () => {
|
||||
const env = installSftpDom();
|
||||
const { act } = await import("react");
|
||||
const { createRoot } = await import("react-dom/client");
|
||||
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
|
||||
const { TooltipProvider } = await import("../ui/tooltip.tsx");
|
||||
const { SftpContextProvider } = await import("./SftpContext.tsx");
|
||||
const { SftpPaneView } = await import("./SftpPaneView.tsx");
|
||||
const { getTerminalSettingsSnapshot, publishTerminalSettingsSnapshot } = await import("../../application/state/terminalSettingsStore.ts");
|
||||
const { DEFAULT_KEY_BINDINGS } = await import("../../domain/models/keyBindings.ts");
|
||||
const previous = getTerminalSettingsSnapshot();
|
||||
const callbacks = createNoopCallbacks();
|
||||
const root = createRoot(env.window.document.getElementById("root")!);
|
||||
|
||||
try {
|
||||
const keyBindings = DEFAULT_KEY_BINDINGS.map((binding) =>
|
||||
binding.action === "sftpOpen" ? { ...binding, pc: "Ctrl + O" } : binding,
|
||||
);
|
||||
for (const [mode, type, name, canOpen, selected] of [
|
||||
["list", "file", "readme.txt", false, true],
|
||||
["list", "directory", "docs", true, true],
|
||||
["list", "directory", "other", false, false],
|
||||
["tree", "file", "readme.txt", true, true],
|
||||
["tree", "file", "other.txt", false, false],
|
||||
] as const) {
|
||||
const pane = createTrackedPane(mode + name, new Map(), { selectedFile: selected ? name : "another.txt" });
|
||||
pane.files = [{ ...pane.files[0], type, name }];
|
||||
await act(async () => {
|
||||
publishTerminalSettingsSnapshot({ ...previous, hotkeyScheme: "pc", keyBindings });
|
||||
root.render(
|
||||
<I18nProvider locale="en">
|
||||
<TooltipProvider>
|
||||
<SftpContextProvider hosts={[]} updateHosts={() => {}} draggedFiles={null}
|
||||
dragCallbacks={{ onDragStart() {}, onDragEnd() {} }} leftCallbacks={callbacks} rightCallbacks={callbacks}>
|
||||
<SftpPaneView key={pane.id} pane={pane} side="left" dialogActionScopeId="menu-test"
|
||||
forceActive isPaneFocused sftpDefaultViewMode={mode} showHeader={false} showEmptyHeader={false} />
|
||||
</SftpContextProvider>
|
||||
</TooltipProvider>
|
||||
</I18nProvider>,
|
||||
);
|
||||
});
|
||||
const row = env.window.document.querySelector(`[data-entry-name="${name}"]`);
|
||||
assert.ok(row, mode);
|
||||
if (mode === "tree" && selected) {
|
||||
await act(async () => (row as HTMLElement).click());
|
||||
}
|
||||
await act(async () => {
|
||||
row.dispatchEvent(new env.window.MouseEvent("contextmenu", { bubbles: true, button: 2 }));
|
||||
});
|
||||
const items = Array.from(env.window.document.querySelectorAll('[role="menuitem"]'));
|
||||
const hint = (label: string) => {
|
||||
const item = items.find((entry) => entry.textContent?.trimStart().startsWith(label));
|
||||
assert.ok(item, label);
|
||||
return item.querySelector("span.ml-auto")?.textContent;
|
||||
};
|
||||
assert.equal(hint("Open"), canOpen ? "Ctrl+O" : undefined, pane.id);
|
||||
assert.equal(hint("Rename"), selected ? "F2" : undefined, mode);
|
||||
assert.equal(hint("Delete"), selected ? "Delete" : undefined, mode);
|
||||
assert.equal(hint("Refresh"), mode === "list" ? "F5" : undefined, mode);
|
||||
assert.equal(hint("Copy file path"), undefined, mode);
|
||||
await act(async () => publishTerminalSettingsSnapshot({ ...previous, hotkeyScheme: "disabled" }));
|
||||
assert.equal(hint("Open"), canOpen ? "Enter" : undefined, pane.id);
|
||||
assert.equal(hint("Rename"), undefined, mode);
|
||||
}
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
// Radix restores menu focus on the next tick using the installed DOM globals.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
publishTerminalSettingsSnapshot(previous);
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -664,7 +664,6 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
data-section="terminal-sftp-tree"
|
||||
>
|
||||
<SftpPaneTreeView
|
||||
isPaneFocused={effectiveIsPaneFocused}
|
||||
pane={pane}
|
||||
side={side}
|
||||
onPrepareSelection={callbacks.onPrepareSelection}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { AppWindow, Archive, ArrowRight, ArrowUp, ClipboardCopy, Code2, Copy, CopyPlus, Download, Edit2, ExternalLink, FilePlus, Folder, FolderInput, FolderPlus, Pencil, RefreshCw, Shield, Terminal, TerminalSquare, Trash2, Upload } from 'lucide-react';
|
||||
import { BoundMenuShortcut } from '../ui/BoundMenuShortcut';
|
||||
import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from '../ui/context-menu';
|
||||
import { getParentPath } from '../../application/state/sftp/utils';
|
||||
import { isKnownBinaryFile } from '../../lib/sftpFileUtils';
|
||||
@@ -35,7 +34,6 @@ function downloadRoots(paths: string[], entries: ReadonlyMap<string, SftpFileEnt
|
||||
|
||||
export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps) {
|
||||
const {
|
||||
isPaneFocused, keyboardSelectionContainsTarget, keyboardTargetsEntry,
|
||||
contextTarget, pane, toggleExpand, stableOnOpenEntry, stableOnRefresh, getActionPaths, toTransferSources,
|
||||
executeMoveAction, triggerUploadPicker, onUploadExternalFolder, onInsertPathToTerminal, onCdInTerminal, uploadEnabled, folderUploadEnabled,
|
||||
setMoveTargetPaths, setMoveToPath, setMoveToError, setMoveToSuggestions, setMoveToSuggestionIndex,
|
||||
@@ -56,8 +54,6 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
// could recurse into its own output.
|
||||
const isParentEntry = isSftpTreeParentEntry(entry);
|
||||
|
||||
const createDirectory = isDir ? entryPath : getParentPath(entryPath);
|
||||
|
||||
const handleOpen = () => {
|
||||
if (isDir) void toggleExpand(entry, entryPath);
|
||||
else stableOnOpenEntry(entry, entryPath);
|
||||
@@ -112,12 +108,10 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
{isDir
|
||||
? <><Folder size={14} className="mr-2" />{tRef.current('sftp.context.open')}</>
|
||||
: <><ExternalLink size={14} className="mr-2" />{tRef.current('sftp.context.open')}</>}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpOpen" whenDisabled="Enter" />}
|
||||
</ContextMenuItem>
|
||||
{isDir && (
|
||||
<ContextMenuItem onClick={() => onNavigateToRef.current(entryPath)}>
|
||||
<ArrowRight size={14} className="mr-2" />{tRef.current('sftp.context.navigateTo')}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpNavigateTo" />}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{!isLocal && !isParentEntry && onOpenInExternalEditorRef?.current && (
|
||||
@@ -206,7 +200,6 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => openRenameDialogRef.current(entryPath)}>
|
||||
<Pencil size={14} className="mr-2" />{tRef.current('common.rename')}
|
||||
{keyboardTargetsEntry && <BoundMenuShortcut action="sftpRename" />}
|
||||
</ContextMenuItem>
|
||||
{onEditPermissionsRef.current && !isLocal && (
|
||||
<ContextMenuItem onClick={() => onEditPermissionsRef.current?.(entry, entryPath)}>
|
||||
@@ -218,17 +211,15 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
onClick={handleDelete}
|
||||
>
|
||||
<Trash2 size={14} className="mr-2" />{tRef.current('action.delete')}
|
||||
{keyboardSelectionContainsTarget && <BoundMenuShortcut action="sftpDelete" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onClick={stableOnRefresh}>
|
||||
<RefreshCw size={14} className="mr-2" />{tRef.current('common.refresh')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => openNewFolderDialogRef.current(createDirectory)}>
|
||||
<ContextMenuItem onClick={() => openNewFolderDialogRef.current(isDir ? entryPath : getParentPath(entryPath))}>
|
||||
<FolderPlus size={14} className="mr-2" />{tRef.current('sftp.newFolder')}
|
||||
{isPaneFocused && createDirectory === pane.connection?.currentPath && <BoundMenuShortcut action="sftpNewFolder" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => openNewFileDialogRef.current(createDirectory)}>
|
||||
<ContextMenuItem onClick={() => openNewFileDialogRef.current(isDir ? entryPath : getParentPath(entryPath))}>
|
||||
<FilePlus size={14} className="mr-2" />{tRef.current('sftp.newFile')}
|
||||
</ContextMenuItem>
|
||||
{uploadEnabled && (
|
||||
@@ -252,11 +243,7 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
</ContextMenuContent>
|
||||
);
|
||||
}, [
|
||||
isPaneFocused,
|
||||
keyboardSelectionContainsTarget,
|
||||
keyboardTargetsEntry,
|
||||
contextTarget,
|
||||
pane.connection?.currentPath,
|
||||
pane.connection?.isLocal,
|
||||
pane.connection?.id,
|
||||
toggleExpand,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { Check, ChevronDown, GitBranch, LoaderCircle, Trash2 } from 'lucide-react';
|
||||
import { Check, ChevronDown, GitBranch, LoaderCircle } from 'lucide-react';
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { useComposeGitBranch, type GitBranchCommandDraft } from '../../application/state/useComposeGitBranch';
|
||||
import type { TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { useComposeGitBranch } from '../../application/state/useComposeGitBranch';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
||||
import type { ComposeBarTheme } from './TerminalComposeBar';
|
||||
|
||||
@@ -11,7 +10,6 @@ type Menu = {
|
||||
scope: ReturnType<typeof useComposeGitBranch>['scope'];
|
||||
root: string;
|
||||
branches: readonly string[];
|
||||
head?: TerminalGitHead;
|
||||
status: 'loading' | 'ready' | 'sending' | 'busy' | 'unavailable';
|
||||
};
|
||||
|
||||
@@ -19,10 +17,8 @@ const chipClass = 'flex h-6 min-w-0 max-w-[min(180px,35%)] shrink items-center g
|
||||
const branchRowHeight = 32;
|
||||
const branchViewportHeight = branchRowHeight * 7;
|
||||
|
||||
export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftCommand, draftPending }: {
|
||||
export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
|
||||
sessionId: string; theme: ComposeBarTheme; onReturnFocus: () => void;
|
||||
onDraftCommand: (draft: GitBranchCommandDraft) => boolean;
|
||||
draftPending: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const model = useComposeGitBranch(sessionId);
|
||||
@@ -67,7 +63,7 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftC
|
||||
return <div data-compose-git-branch role="group" aria-label={label} title={label} className={chipClass} style={chipStyle}>{chipContent}</div>;
|
||||
}
|
||||
|
||||
const currentBranch = current?.head?.kind === 'branch' ? current.head.name : null;
|
||||
const currentBranch = head.kind === 'branch' ? head.name : null;
|
||||
const canSelect = current?.status === 'ready' || current?.status === 'busy';
|
||||
|
||||
function closeMenu() {
|
||||
@@ -75,12 +71,6 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftC
|
||||
setMenu(null);
|
||||
}
|
||||
|
||||
function draftDeletion(name: string) {
|
||||
if (!current?.head || !canSelect || submission.current || draftPending) return;
|
||||
const draft = model.deleteBranchDraft(current.head, name);
|
||||
if (draft && onDraftCommand(draft)) closeMenu();
|
||||
}
|
||||
|
||||
async function openMenu() {
|
||||
if (!head) return;
|
||||
outside.current = false;
|
||||
@@ -91,7 +81,7 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftC
|
||||
setMenu(pending);
|
||||
const result = await model.list(head.worktreeRoot);
|
||||
setMenu(value => value !== pending ? value : result.kind === 'branches'
|
||||
? { ...pending, status: 'ready', head: result.head, branches: result.branches }
|
||||
? { ...pending, status: 'ready', branches: result.branches }
|
||||
: { ...pending, status: result.kind });
|
||||
}
|
||||
|
||||
@@ -150,45 +140,27 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftC
|
||||
if (viewport.current) viewport.current.scrollTop = 0;
|
||||
}}
|
||||
role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls={listId}
|
||||
aria-haspopup="grid" aria-activedescendant={filtered[selected] ? `${listId}-${selected}` : undefined}
|
||||
aria-activedescendant={filtered[selected] ? `${listId}-${selected}` : undefined}
|
||||
aria-label={t('terminal.gitBranch.search')} placeholder={t('terminal.gitBranch.search')}
|
||||
className="w-full bg-transparent text-xs outline-none placeholder:opacity-60"
|
||||
onCompositionStart={() => { composing.current = true; }}
|
||||
onCompositionEnd={() => { composing.current = false; }} />
|
||||
</div>
|
||||
<div ref={viewport} id={listId} role="grid" aria-label={t('terminal.gitBranch.branches')}
|
||||
aria-rowcount={filtered.length} aria-colcount={2}
|
||||
<div ref={viewport} id={listId} role="listbox" aria-label={t('terminal.gitBranch.branches')}
|
||||
className="overflow-y-auto overscroll-contain" style={{ maxHeight: branchViewportHeight }}
|
||||
aria-busy={current?.status === 'loading' || current?.status === 'sending'}>
|
||||
<div role="presentation" style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map(({ index, start, size }) => {
|
||||
const name = filtered[index];
|
||||
return (
|
||||
<div key={name} role="row" aria-rowindex={index + 1}
|
||||
className="absolute inset-x-0 flex items-center pr-2 font-mono text-xs"
|
||||
style={{ top: start, height: size, backgroundColor: index === selected ? theme.chipHoverBg : undefined }}>
|
||||
<div id={`${listId}-${index}`} role="gridcell" aria-selected={name === currentBranch}
|
||||
aria-disabled={!canSelect} title={name}
|
||||
className="flex h-full min-w-0 flex-1 items-center gap-2 px-3"
|
||||
style={{ cursor: canSelect ? 'pointer' : undefined }}
|
||||
onPointerMove={() => {
|
||||
if (search.current === document.activeElement) setActive(index);
|
||||
}} onMouseDown={event => event.preventDefault()}
|
||||
onClick={() => { void choose(name); }}>
|
||||
<span className="w-3 shrink-0" aria-hidden="true">{name === currentBranch && <Check size={12} />}</span>
|
||||
<span className="min-w-0 truncate" dir="auto">{name}</span>
|
||||
</div>
|
||||
<div role="gridcell" className="w-6 shrink-0">
|
||||
{name !== currentBranch && (
|
||||
<button type="button" disabled={!canSelect || draftPending} tabIndex={index === selected ? 0 : -1}
|
||||
className="flex size-6 items-center justify-center rounded opacity-70 hover:opacity-100 focus-visible:outline focus-visible:outline-1 disabled:opacity-30"
|
||||
aria-label={t('terminal.gitBranch.draftDelete', { value: name })}
|
||||
title={t('terminal.gitBranch.draftDelete', { value: name })}
|
||||
onFocus={() => setActive(index)} onClick={() => draftDeletion(name)}>
|
||||
<Trash2 size={12} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div key={name} id={`${listId}-${index}`} role="option" aria-selected={name === currentBranch}
|
||||
aria-posinset={index + 1} aria-setsize={filtered.length} aria-disabled={!canSelect} title={name}
|
||||
className="absolute inset-x-0 flex items-center gap-2 px-3 py-1 font-mono text-xs"
|
||||
style={{ top: start, height: size, backgroundColor: index === selected ? theme.chipHoverBg : undefined, cursor: canSelect ? 'pointer' : undefined }}
|
||||
onPointerMove={() => setActive(index)} onMouseDown={event => event.preventDefault()}
|
||||
onClick={() => { void choose(name); }}>
|
||||
<span className="w-3 shrink-0" aria-hidden="true">{name === currentBranch && <Check size={12} />}</span>
|
||||
<span className="min-w-0 truncate" dir="auto">{name}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act } from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
|
||||
test('Git deletion drafts wait for Enter and send only to the original terminal', async t => {
|
||||
const dom = new JSDOM('<div id="root"></div>', { pretendToBeVisual: true, url: 'http://localhost' });
|
||||
const win = dom.window;
|
||||
const globals = { window: win, document: win.document, localStorage: win.localStorage,
|
||||
Element: win.Element, HTMLElement: win.HTMLElement, Node: win.Node, NodeFilter: win.NodeFilter,
|
||||
CustomEvent: win.CustomEvent, MutationObserver: win.MutationObserver,
|
||||
getComputedStyle: win.getComputedStyle.bind(win), requestAnimationFrame: win.requestAnimationFrame.bind(win),
|
||||
cancelAnimationFrame: win.cancelAnimationFrame.bind(win), IS_REACT_ACT_ENVIRONMENT: true };
|
||||
const originals = Object.keys(globals).map(name => [name, Object.getOwnPropertyDescriptor(globalThis, name)] as const);
|
||||
for (const [name, value] of Object.entries(globals)) {
|
||||
Object.defineProperty(globalThis, name, { configurable: true, value });
|
||||
}
|
||||
// JSDOM has no layout. Supply a visible scroll viewport for the virtualizer.
|
||||
Object.defineProperties(win.HTMLElement.prototype, {
|
||||
offsetHeight: { get: () => 224 }, offsetWidth: { get: () => 360 },
|
||||
attachEvent: { value() {} }, detachEvent: { value() {} },
|
||||
});
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { scopeGitBranchDraft } = await import('../../domain/terminalGitHead');
|
||||
const { I18nProvider } = await import('../../application/i18n/I18nProvider');
|
||||
const { TooltipProvider } = await import('../ui/tooltip');
|
||||
const { TerminalComposeBar } = await import('./TerminalComposeBar');
|
||||
const { createTerminalDirectoryController } = await import('../../application/state/terminalDirectoryController');
|
||||
const { registerTerminalDirectory } = await import('../../application/state/terminalDirectoryRegistry');
|
||||
const { terminalCwdStore } = await import('../../application/state/terminalCwdStore');
|
||||
const id = 'git-delete-draft';
|
||||
const head = { kind: 'branch', name: 'main', worktreeRoot: '/repo' } as const;
|
||||
let menuHead: { kind: 'branch'; name: string; worktreeRoot: string } = head;
|
||||
Object.defineProperty(win, 'netcatty', { value: {
|
||||
readLocalSessionGitHead: async () => head,
|
||||
listLocalSessionGitBranches: async () => ({ kind: 'branches', head: menuHead, branches: ['main', 'topic'] }),
|
||||
} });
|
||||
let ready = true;
|
||||
let liveCwd = '/repo';
|
||||
let pendingCwd: Promise<string> | undefined;
|
||||
const ptyWrites: string[] = [];
|
||||
const sent: string[] = [];
|
||||
const unregister = registerTerminalDirectory(id, createTerminalDirectoryController({
|
||||
sessionId: id, localPosixSessionId: 'local', isCurrent: () => true, isReady: () => ready,
|
||||
io: { cwd: async () => pendingCwd ?? liveCwd, list: async () => ({ entries: [], home: null }),
|
||||
realpath: async value => value, write: value => ptyWrites.push(value) },
|
||||
publish: cwd => terminalCwdStore.setCwd(id, cwd, 'backend-strict'),
|
||||
}));
|
||||
terminalCwdStore.setCwd(id, '/repo', 'osc7');
|
||||
const root = createRoot(win.document.querySelector('#root')!);
|
||||
t.after(async () => {
|
||||
await act(async () => root.unmount());
|
||||
unregister();
|
||||
terminalCwdStore.setCwd(id, null);
|
||||
win.close();
|
||||
for (const [name, descriptor] of originals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, name, descriptor);
|
||||
else Reflect.deleteProperty(globalThis, name);
|
||||
}
|
||||
});
|
||||
const render = (sessionId: string) => <I18nProvider locale="en"><TooltipProvider><TerminalComposeBar
|
||||
sessionId={sessionId} composeSendToAll onClose={() => {}} onSend={text => { sent.push(text); }} />
|
||||
</TooltipProvider></I18nProvider>;
|
||||
await act(async () => root.render(render(id)));
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 200)); });
|
||||
const textarea = win.document.querySelector('textarea')!;
|
||||
textarea.value = 'keep this draft';
|
||||
textarea.setSelectionRange(5, 9);
|
||||
const stage = async (branch = 'topic', checkedOut = 'main') => {
|
||||
const chip = win.document.querySelector<HTMLButtonElement>('button[data-compose-git-branch]');
|
||||
assert.ok(chip);
|
||||
await act(async () => chip.click());
|
||||
const action = win.document.querySelector<HTMLButtonElement>(`[aria-label="Draft deletion of ${branch}"]`);
|
||||
assert.ok(action);
|
||||
assert.equal(win.document.querySelector(`[aria-label="Draft deletion of ${checkedOut}"]`), null);
|
||||
assert.equal(win.document.querySelector(`[role="gridcell"][title="${checkedOut}"]`)?.getAttribute('aria-selected'), 'true');
|
||||
await act(async () => {
|
||||
action.focus();
|
||||
action.click();
|
||||
});
|
||||
assert.equal(textarea.value, `git branch -d -- '${branch}'`);
|
||||
assert.equal(win.document.activeElement === textarea, true, 'focus goes to the draft as soon as the menu closes');
|
||||
};
|
||||
const press = (key: string, repeat = false) => act(async () => {
|
||||
win.document.activeElement?.dispatchEvent(new win.KeyboardEvent('keydown', { key, repeat, bubbles: true, cancelable: true }));
|
||||
});
|
||||
await stage();
|
||||
assert.deepEqual(ptyWrites, []);
|
||||
ready = false;
|
||||
await press('Enter');
|
||||
assert.deepEqual(ptyWrites, []);
|
||||
assert.match(win.document.querySelector('[role="status"]')?.textContent ?? '', /empty shell prompt/);
|
||||
await press('Escape');
|
||||
assert.equal(textarea.value, 'keep this draft');
|
||||
assert.deepEqual([textarea.selectionStart, textarea.selectionEnd], [5, 9]);
|
||||
|
||||
ready = true;
|
||||
await stage();
|
||||
const draft = textarea.value;
|
||||
textarea.value = draft + '\necho extra';
|
||||
await press('Enter');
|
||||
assert.deepEqual(ptyWrites, []);
|
||||
const edited = draft.replace('-d', '-D');
|
||||
textarea.value = edited;
|
||||
await press('Enter');
|
||||
assert.deepEqual(ptyWrites, [scopeGitBranchDraft('/repo', edited) + '\r']);
|
||||
assert.deepEqual(sent, []);
|
||||
assert.equal(textarea.value, 'keep this draft');
|
||||
await press('Enter', true);
|
||||
assert.deepEqual(sent, []);
|
||||
|
||||
await stage();
|
||||
let resolveCwd!: (path: string) => void;
|
||||
pendingCwd = new Promise(resolve => { resolveCwd = resolve; });
|
||||
await press('Enter');
|
||||
assert.equal(textarea.readOnly, true);
|
||||
await press('Escape');
|
||||
await act(async () => resolveCwd('/repo'));
|
||||
pendingCwd = undefined;
|
||||
assert.equal(ptyWrites.length, 1);
|
||||
assert.equal(textarea.value, 'keep this draft');
|
||||
|
||||
// A separate process changed HEAD while the terminal was idle.
|
||||
menuHead = { ...head, name: 'topic' };
|
||||
await stage('main', 'topic');
|
||||
liveCwd = '/other';
|
||||
await press('Enter');
|
||||
assert.equal(ptyWrites.length, 1);
|
||||
assert.match(textarea.value, /branch -d/);
|
||||
await act(async () => root.render(render('different-session')));
|
||||
assert.equal(textarea.value, 'keep this draft');
|
||||
assert.deepEqual(sent, []);
|
||||
});
|
||||
@@ -6,9 +6,7 @@ import { ComposeDirectoryPicker } from './ComposeDirectoryPicker';
|
||||
* user-resizable height, and terminal-matched chrome.
|
||||
*/
|
||||
import { GripHorizontal, Pin, Plus, Radio, Search, X } from 'lucide-react';
|
||||
import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { GitBranchCommandDraft } from '../../application/state/useComposeGitBranch';
|
||||
import { useGitBranchDraft } from '../../application/state/useGitBranchDraft';
|
||||
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
|
||||
import { useComposeBarHistory } from '../../application/state/useComposeBarHistory';
|
||||
import { canNavigateComposeBarHistory } from '../../domain/composeBarHistory';
|
||||
@@ -395,33 +393,10 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
const { t } = useI18n();
|
||||
const { readClipboardText, writeClipboardText } = useClipboardBackend();
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const branchDraftEnter = useRef(false);
|
||||
const restoreDraft = useCallback((draft: string) => {
|
||||
if (textareaRef.current) textareaRef.current.value = draft;
|
||||
}, []);
|
||||
const { prepareRecord, navigate, reset } = useComposeBarHistory(sessionId, restoreDraft);
|
||||
const restoreBranchDraft = useCallback((snapshot: { text: string; selectionStart: number; selectionEnd: number }) => {
|
||||
const el = textareaRef.current;
|
||||
if (el) {
|
||||
el.value = snapshot.text;
|
||||
el.setSelectionRange(snapshot.selectionStart, snapshot.selectionEnd);
|
||||
}
|
||||
}, []);
|
||||
const { status: branchDraftStatus, getDraft: getBranchDraft, stage: stageDraft, cancel: cancelBranchDraft, send: sendBranchDraft } =
|
||||
useGitBranchDraft(sessionId, restoreBranchDraft);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (branchDraftStatus === 'ready') textareaRef.current?.focus({ preventScroll: true });
|
||||
}, [branchDraftStatus]);
|
||||
|
||||
const stageBranchCommand = useCallback((draft: GitBranchCommandDraft) => {
|
||||
const el = textareaRef.current;
|
||||
if (!el || !stageDraft(draft, { text: el.value, selectionStart: el.selectionStart, selectionEnd: el.selectionEnd })) return false;
|
||||
reset();
|
||||
el.value = draft.text;
|
||||
el.setSelectionRange(el.value.length, el.value.length);
|
||||
return true;
|
||||
}, [reset, stageDraft]);
|
||||
const isComposingRef = useRef(false);
|
||||
const resizeCleanupRef = useRef<(() => void) | null>(null);
|
||||
const [barHeight, setBarHeight, persistBarHeight] = useComposeBarHeight();
|
||||
@@ -511,14 +486,12 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
}
|
||||
const start = textarea.selectionStart;
|
||||
const end = textarea.selectionEnd;
|
||||
const draft = getBranchDraft();
|
||||
const canEdit = () => textareaRef.current === textarea && getBranchDraft() === draft && !textarea.readOnly;
|
||||
try {
|
||||
if (action === 'paste') {
|
||||
let text: string | undefined;
|
||||
try { text = await readClipboardText(); } catch { /* Use browser clipboard. */ }
|
||||
if (typeof text !== 'string') text = await navigator.clipboard.readText();
|
||||
if (!text || !canEdit()) return;
|
||||
if (!text) return;
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('insertText', false, text)) {
|
||||
textarea.setRangeText(text, start, end, 'end');
|
||||
@@ -534,7 +507,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
if (!wroteToBridge) {
|
||||
await navigator.clipboard.writeText(selectedText);
|
||||
}
|
||||
if (action === 'cut' && canEdit()) {
|
||||
if (action === 'cut') {
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('delete')) {
|
||||
textarea.setRangeText('', start, end, 'end');
|
||||
@@ -545,7 +518,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
} catch (error) {
|
||||
console.error('Compose bar clipboard action failed', error);
|
||||
}
|
||||
}, [getBranchDraft, readClipboardText, reset, writeClipboardText]);
|
||||
}, [readClipboardText, reset, writeClipboardText]);
|
||||
|
||||
const snippetsById = useMemo(
|
||||
() => mergeComposeBarSnippetMap(snippets),
|
||||
@@ -713,12 +686,12 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const insertCommand = useCallback((command: string) => {
|
||||
const el = textareaRef.current;
|
||||
if (!el || getBranchDraft()) return;
|
||||
if (!el) return;
|
||||
reset();
|
||||
const prefix = el.value && !el.value.endsWith('\n') ? '\n' : '';
|
||||
el.value = el.value ? `${el.value}${prefix}${command}` : command;
|
||||
el.focus();
|
||||
}, [getBranchDraft, reset]);
|
||||
}, [reset]);
|
||||
|
||||
const handleSnippetActivate = useCallback(async (snippet: Snippet, sendImmediately: boolean) => {
|
||||
if (sendImmediately) {
|
||||
@@ -738,24 +711,6 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isComposingRef.current || e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) return;
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
if (e.repeat && (getBranchDraft() || branchDraftEnter.current)) {
|
||||
// A held Enter can outlast the draft and reach the restored text.
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
branchDraftEnter.current = Boolean(getBranchDraft());
|
||||
}
|
||||
if (getBranchDraft()) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void sendBranchDraft(e.currentTarget.value);
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
cancelBranchDraft();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') &&
|
||||
!e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||
const el = e.currentTarget;
|
||||
@@ -788,7 +743,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
}, [cancelBranchDraft, getBranchDraft, handleSend, navigate, onClose, sendBranchDraft, sessionId]);
|
||||
}, [handleSend, navigate, onClose, sessionId]);
|
||||
|
||||
const handleReturnFocus = useCallback(() => {
|
||||
textareaRef.current?.focus({ preventScroll: true });
|
||||
@@ -870,8 +825,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
theme={theme}
|
||||
onReturnFocus={handleReturnFocus}
|
||||
/>
|
||||
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme}
|
||||
onReturnFocus={handleReturnFocus} onDraftCommand={stageBranchCommand} draftPending={branchDraftStatus !== null} />
|
||||
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme} onReturnFocus={handleReturnFocus} />
|
||||
{pinnedSnippets.length > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
@@ -965,7 +919,6 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
)}
|
||||
style={{ color: theme.resolvedFg }}
|
||||
placeholder={t('terminal.composeBar.placeholder')}
|
||||
readOnly={branchDraftStatus === 'sending'}
|
||||
onKeyDown={handleKeyDown}
|
||||
onInput={reset}
|
||||
onCompositionStart={() => { isComposingRef.current = true; }}
|
||||
@@ -997,14 +950,6 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
<TooltipContent>{t('terminal.composeBar.close')}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{branchDraftStatus && branchDraftStatus !== 'sending' && (
|
||||
<p role="status" className="shrink-0 px-2 text-[11px]" style={{ color: theme.mutedFg }}>
|
||||
{t(branchDraftStatus === 'busy' ? 'terminal.directory.busy'
|
||||
: branchDraftStatus === 'unavailable' ? 'terminal.gitBranch.draftUnavailable'
|
||||
: branchDraftStatus === 'singleLine' ? 'terminal.gitBranch.draftSingleLine'
|
||||
: 'terminal.gitBranch.draftHint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{broadcastMenuAnchor && (
|
||||
|
||||
@@ -114,7 +114,7 @@ test('split menu keeps custom shortcuts aligned with the matching split actions'
|
||||
|
||||
await openMenu();
|
||||
const horizontalItem = findMenuItem('水平分屏');
|
||||
assert.match(horizontalItem.textContent ?? '', /水平分屏\s*⌘H/);
|
||||
assert.match(horizontalItem.textContent ?? '', /水平分屏\s*⌘ H/);
|
||||
const horizontalDivider = horizontalItem.querySelector('svg line');
|
||||
assert.ok(horizontalDivider);
|
||||
assert.equal(horizontalDivider.getAttribute('y1'), horizontalDivider.getAttribute('y2'));
|
||||
@@ -123,7 +123,7 @@ test('split menu keeps custom shortcuts aligned with the matching split actions'
|
||||
|
||||
await openMenu();
|
||||
const verticalItem = findMenuItem('垂直分屏');
|
||||
assert.match(verticalItem.textContent ?? '', /垂直分屏\s*⌘V/);
|
||||
assert.match(verticalItem.textContent ?? '', /垂直分屏\s*⌘ V/);
|
||||
const verticalDivider = verticalItem.querySelector('svg line');
|
||||
assert.ok(verticalDivider);
|
||||
assert.equal(verticalDivider.getAttribute('x1'), verticalDivider.getAttribute('x2'));
|
||||
|
||||
@@ -29,9 +29,6 @@ import {
|
||||
ContextMenuShortcut,
|
||||
ContextMenuTrigger,
|
||||
} from '../ui/context-menu';
|
||||
import { useSessionSnapshotField } from '../../application/state/sessionSnapshotStore';
|
||||
import { collectSessionIds } from '../../domain/workspace';
|
||||
import { getMenuShortcut } from '../../domain/activeKeyBindings';
|
||||
import { installRightClickLongPress } from './runtime/rightClickLongPress';
|
||||
import { isMiddleClickContextMenuEvent, isMouseTrackingActive } from './runtime/middleClickBehavior';
|
||||
import { isHistoryPreviewContextMenuTarget } from './runtime/terminalHistoryScrollOverride';
|
||||
@@ -39,14 +36,6 @@ import { collectOwnedPluginMenus, comparePluginMenus, usePluginContributions } f
|
||||
import { buildTerminalPluginContributionContext } from '../../application/state/pluginContributionContexts';
|
||||
import { PluginContributionIcon } from '../plugins/PluginContributionIcon';
|
||||
|
||||
function PaneCloseShortcut({ workspaceId, shortcut }: { workspaceId?: string; shortcut?: string }) {
|
||||
const workspaces = useSessionSnapshotField('workspaces');
|
||||
const workspace = workspaces.find((item) => item.id === workspaceId);
|
||||
// Closing the final pane via the keyboard also closes its workspace.
|
||||
if (!workspace || collectSessionIds(workspace.root).length < 2) return null;
|
||||
return <ContextMenuShortcut>{shortcut}</ContextMenuShortcut>;
|
||||
}
|
||||
|
||||
export interface TerminalContextMenuProps {
|
||||
children: React.ReactNode;
|
||||
sessionId: string;
|
||||
@@ -294,6 +283,7 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
const pluginMenus = collectOwnedPluginMenus(pluginContributions.snapshot.plugins)
|
||||
.filter((menu) => menu.location === 'terminal/context' && menu.visible)
|
||||
.sort(comparePluginMenus);
|
||||
const isMac = hotkeyScheme === 'mac';
|
||||
// Tracks the .workspace-pane whose context menu is currently open so we can
|
||||
// keep its `:focus-within`-driven opacity stable while focus is in the
|
||||
// menu portal (otherwise the pane dims for the menu's lifetime).
|
||||
@@ -309,7 +299,23 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
}
|
||||
}, []);
|
||||
|
||||
const shortcut = (action: string) => getMenuShortcut(action, hotkeyScheme, keyBindings ?? []);
|
||||
// Helper to get shortcut from keyBindings and format for display
|
||||
const getShortcut = (bindingId: string): string => {
|
||||
const binding = keyBindings?.find(b => b.id === bindingId);
|
||||
if (!binding) return '';
|
||||
const key = isMac ? binding.mac : binding.pc;
|
||||
if (!key || key === 'Disabled') return '';
|
||||
// Replace " + " with space for cleaner display (e.g., "⌘ + Shift + D" → "⌘ Shift D")
|
||||
return key.replace(/\s*\+\s*/g, ' ').trim();
|
||||
};
|
||||
|
||||
const copyShortcut = getShortcut('copy');
|
||||
const pasteShortcut = getShortcut('paste');
|
||||
const pasteSelectionShortcut = getShortcut('paste-selection');
|
||||
const selectAllShortcut = getShortcut('select-all');
|
||||
const splitHShortcut = getShortcut('split-horizontal');
|
||||
const splitVShortcut = getShortcut('split-vertical');
|
||||
const clearShortcut = getShortcut('clear-buffer');
|
||||
|
||||
const terminalMouseTrackingMode = getMouseTrackingMode?.();
|
||||
|
||||
@@ -401,13 +407,15 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
forceMenuInAlternateScreen: showContextMenuOverFullscreenApps,
|
||||
}) && (
|
||||
<ContextMenuContent className="w-max">
|
||||
<ContextMenuItem shortcut={shortcut('copy')} onClick={onCopy} disabled={!hasSelection}>
|
||||
<ContextMenuItem onClick={onCopy} disabled={!hasSelection}>
|
||||
<Copy size={14} className="mr-2" />
|
||||
{t('terminal.menu.copy')}
|
||||
<ContextMenuShortcut>{copyShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem shortcut={shortcut('paste')} onClick={onPaste}>
|
||||
<ContextMenuItem onClick={onPaste}>
|
||||
<ClipboardPaste size={14} className="mr-2" />
|
||||
{t('terminal.menu.paste')}
|
||||
<ContextMenuShortcut>{pasteShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
{shouldShowUploadClipboardImageContextMenuAction(onUploadClipboardImage) && (
|
||||
<ContextMenuItem onClick={onUploadClipboardImage}>
|
||||
@@ -422,14 +430,16 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onPasteSelection && (
|
||||
<ContextMenuItem shortcut={shortcut('pasteSelection')} onClick={onPasteSelection} disabled={!hasSelection}>
|
||||
<ContextMenuItem onClick={onPasteSelection} disabled={!hasSelection}>
|
||||
<ClipboardPaste size={14} className="mr-2" />
|
||||
{t('terminal.menu.pasteSelection')}
|
||||
<ContextMenuShortcut>{pasteSelectionShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem shortcut={shortcut('selectAll')} onClick={onSelectAll}>
|
||||
<ContextMenuItem onClick={onSelectAll}>
|
||||
<TerminalIcon size={14} className="mr-2" />
|
||||
{t('terminal.menu.selectAll')}
|
||||
<ContextMenuShortcut>{selectAllShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
{onOpenSftp && (
|
||||
<>
|
||||
@@ -478,13 +488,15 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
|
||||
<ContextMenuSeparator />
|
||||
|
||||
<ContextMenuItem shortcut={shortcut('splitHorizontal')} onClick={onSplitHorizontal}>
|
||||
<ContextMenuItem onClick={onSplitHorizontal}>
|
||||
<SplitSquareVertical size={14} className="mr-2" />
|
||||
{t('terminal.menu.splitHorizontal')}
|
||||
<ContextMenuShortcut>{splitHShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem shortcut={shortcut('splitVertical')} onClick={onSplitVertical}>
|
||||
<ContextMenuItem onClick={onSplitVertical}>
|
||||
<SplitSquareHorizontal size={14} className="mr-2" />
|
||||
{t('terminal.menu.splitVertical')}
|
||||
<ContextMenuShortcut>{splitVShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuSeparator />
|
||||
@@ -495,9 +507,10 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
{t('terminal.menu.saveScreen')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem shortcut={shortcut('clearBuffer')} onClick={onClear}>
|
||||
<ContextMenuItem onClick={onClear}>
|
||||
<Trash2 size={14} className="mr-2" />
|
||||
{t('terminal.menu.clearBuffer')}
|
||||
<ContextMenuShortcut>{clearShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
|
||||
{onRename && (
|
||||
@@ -549,7 +562,6 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
>
|
||||
<Trash2 size={14} className="mr-2" />
|
||||
{t('terminal.menu.closeTerminal')}
|
||||
<PaneCloseShortcut workspaceId={workspaceId} shortcut={shortcut('closeSession')} />
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -63,7 +63,6 @@ type WorkspaceFocusSessionRowProps = {
|
||||
session: TerminalSession;
|
||||
host: Host | undefined;
|
||||
isSelected: boolean;
|
||||
hasSiblingPane: boolean;
|
||||
isRenaming: boolean;
|
||||
renameValue: string;
|
||||
onStartRename: (sessionId: string) => void;
|
||||
@@ -91,7 +90,6 @@ const WorkspaceFocusSessionRow = memo<WorkspaceFocusSessionRowProps>(({
|
||||
session,
|
||||
host,
|
||||
isSelected,
|
||||
hasSiblingPane,
|
||||
isRenaming,
|
||||
renameValue,
|
||||
onStartRename,
|
||||
@@ -220,7 +218,6 @@ const WorkspaceFocusSessionRow = memo<WorkspaceFocusSessionRowProps>(({
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<SessionTabContextMenuContent
|
||||
closeShortcutAction={isSelected && hasSiblingPane ? 'closeSession' : undefined}
|
||||
sessionId={session.id}
|
||||
onCloseSession={onCloseSession}
|
||||
onCopySession={onCopySession}
|
||||
@@ -238,7 +235,6 @@ const WorkspaceFocusSessionRow = memo<WorkspaceFocusSessionRowProps>(({
|
||||
}, (prev, next) => (
|
||||
prev.session === next.session
|
||||
&& prev.host === next.host
|
||||
&& prev.hasSiblingPane === next.hasSiblingPane
|
||||
&& prev.isSelected === next.isSelected
|
||||
&& prev.isRenaming === next.isRenaming
|
||||
&& prev.renameValue === next.renameValue
|
||||
@@ -654,7 +650,6 @@ const TerminalFocusSidebarInner: React.FC<TerminalFocusSidebarProps> = ({
|
||||
key={session.id}
|
||||
session={session}
|
||||
host={sessionHostsMap.get(session.id)}
|
||||
hasSiblingPane={workspaceSessions.length > 1}
|
||||
isSelected={session.id === focusedSessionId}
|
||||
isRenaming={sidebarRenameSessionId === session.id}
|
||||
renameValue={sidebarRenameValue}
|
||||
|
||||
@@ -580,7 +580,6 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
</ContextMenuTrigger>
|
||||
{menuActions ? (
|
||||
<HostTreeHostContextMenuContent
|
||||
enterConnects={!isInlineEditing}
|
||||
host={row.host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
@@ -594,7 +593,7 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
/>
|
||||
) : (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem shortcut={isInlineEditing ? undefined : 'Enter'} onClick={() => onConnect(row.host)}>
|
||||
<ContextMenuItem onClick={() => onConnect(row.host)}>
|
||||
<Server className="mr-2 h-4 w-4" /> {t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onEditHost?.(row.host)}>
|
||||
|
||||
@@ -2,20 +2,17 @@ import React from 'react';
|
||||
|
||||
import type { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import type { Host, TerminalSession } from '../../types';
|
||||
import { BoundMenuShortcut } from '../ui/BoundMenuShortcut';
|
||||
import { ContextMenuContent, ContextMenuItem } from '../ui/context-menu';
|
||||
|
||||
type TranslateFn = ReturnType<typeof useI18n>['t'];
|
||||
|
||||
interface SessionTabContextMenuContentProps {
|
||||
sessionId: string;
|
||||
closeShortcutAction?: 'closeTab' | 'closeSession';
|
||||
onCloseSession: (sessionId: string) => void;
|
||||
onCopySession?: (sessionId: string) => void;
|
||||
/** Duplicate the session with a brand-new connection (fresh auth, e.g. a new bastion login). */
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow?: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
/** Move this live session into its own window (no reconnect). */
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onDetachSession?: (sessionId: string) => void;
|
||||
@@ -32,13 +29,11 @@ interface SessionTabContextMenuContentProps {
|
||||
|
||||
export function SessionTabContextMenuContent({
|
||||
sessionId,
|
||||
closeShortcutAction,
|
||||
onCloseSession,
|
||||
onCopySession,
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onDetachSession,
|
||||
onReconnectSession,
|
||||
sessionStatus,
|
||||
@@ -61,11 +56,6 @@ export function SessionTabContextMenuContent({
|
||||
{t('tabs.copyTabToNewWindow')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onConvertSessionToWorkspace && (
|
||||
<ContextMenuItem onClick={() => onConvertSessionToWorkspace(sessionId)}>
|
||||
{t('tabs.convertToWorkspace')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onMoveSessionToNewWindow && (
|
||||
<ContextMenuItem
|
||||
disabled={sessionStatus !== 'connected'}
|
||||
@@ -100,7 +90,6 @@ export function SessionTabContextMenuContent({
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem className="text-destructive" onClick={() => onCloseSession(sessionId)}>
|
||||
{t('common.close')}
|
||||
{closeShortcutAction && <BoundMenuShortcut action={closeShortcutAction} />}
|
||||
</ContextMenuItem>
|
||||
{renderBulkCloseItems?.(sessionId)}
|
||||
</ContextMenuContent>
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { useTrackShortcutModifierHeld } from '../../application/state/useShortcutModifierHeld';
|
||||
import { createDomRenderer, dispatchDomEvent, installDomEnvironment } from '../test-support/renderReactDom';
|
||||
|
||||
test('the original tab icon stays mounted while its shortcut number is shown', async () => {
|
||||
const dom = installDomEnvironment();
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
try {
|
||||
const { TabIconSlot } = await import('./TopTabItems');
|
||||
function Tab() {
|
||||
useTrackShortcutModifierHeld('⌘ + [1...9]', 'mac');
|
||||
return <TabIconSlot shortcutNumber={3}><img alt="Shell" width={16} height={16} /></TabIconSlot>;
|
||||
}
|
||||
|
||||
await renderer.render(<Tab />);
|
||||
const icon = renderer.container.querySelector('img');
|
||||
assert.ok(icon);
|
||||
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent('keydown', { key: 'Meta', metaKey: true }));
|
||||
assert.equal(renderer.container.textContent, '3');
|
||||
assert.equal(renderer.container.querySelector('img'), icon);
|
||||
|
||||
await dispatchDomEvent(dom.window, new dom.window.KeyboardEvent('keyup', { key: 'Meta' }));
|
||||
assert.equal(renderer.container.textContent, '');
|
||||
assert.equal(renderer.container.querySelector('img'), icon);
|
||||
} finally {
|
||||
await renderer.unmount();
|
||||
dom.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -36,7 +36,6 @@ import { Host, TerminalSession, Workspace } from '../../types';
|
||||
import { DISTRO_LOGOS, DISTRO_COLORS } from '../DistroAvatar';
|
||||
import { getShellIconPath, isMonochromeShellIcon } from '../../lib/useDiscoveredShells';
|
||||
import { handleTabCloseButtonMouseDown, handleTabDragThresholdDrag, handleTabDragThresholdDragStart, handleTabDragThresholdMouseDown, handleTabDragThresholdRelease, handleTabMiddleClickClose } from '../../lib/tabInteractions';
|
||||
import { BoundMenuShortcut } from '../ui/BoundMenuShortcut';
|
||||
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuTrigger } from '../ui/context-menu';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
|
||||
import { SessionTabContextMenuContent } from './SessionTabContextMenuContent';
|
||||
@@ -381,7 +380,7 @@ type RenderBulkCloseItems = (anchorId: string) => React.ReactNode;
|
||||
/** 1-9 badge aligned with Cmd/Ctrl+[1...9] tab switching. */
|
||||
export const TabShortcutNumberBadge: React.FC<{ number: number }> = memo(({ number }) => (
|
||||
<span
|
||||
className="absolute inline-flex h-3.5 min-w-3.5 shrink-0 items-center justify-center rounded px-0.5 font-mono text-[10px] font-semibold leading-none tabular-nums"
|
||||
className="inline-flex h-3.5 min-w-3.5 shrink-0 items-center justify-center rounded px-0.5 font-mono text-[10px] font-semibold leading-none tabular-nums"
|
||||
style={{
|
||||
color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))',
|
||||
backgroundColor: 'color-mix(in srgb, var(--top-tabs-fg, hsl(var(--foreground))) 12%, transparent)',
|
||||
@@ -402,15 +401,8 @@ export const TabIconSlot: React.FC<{ shortcutNumber?: number; children: React.Re
|
||||
children,
|
||||
}) => {
|
||||
const held = useShortcutModifierHeldValue();
|
||||
if (shortcutNumber == null) return <>{children}</>;
|
||||
|
||||
return (
|
||||
<div className="relative inline-flex shrink-0 items-center justify-center">
|
||||
{/* The original icon sets the slot size even while the badge covers it. */}
|
||||
<div className={cn('flex', held && 'invisible')}>{children}</div>
|
||||
{held && <TabShortcutNumberBadge number={shortcutNumber} />}
|
||||
</div>
|
||||
);
|
||||
if (shortcutNumber != null && held) return <TabShortcutNumberBadge number={shortcutNumber} />;
|
||||
return <>{children}</>;
|
||||
};
|
||||
|
||||
const TOP_TAB_COMFORT_EDGE_RATIO = 0.22;
|
||||
@@ -634,10 +626,7 @@ export const PluginViewTopTab: React.FC<PluginViewTopTabProps> = memo(({
|
||||
<TooltipContent>{tab.pluginName}</TooltipContent>
|
||||
</Tooltip>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onClose(tab.id)}>
|
||||
{t('common.close')}
|
||||
{isActive && <BoundMenuShortcut action="closeTab" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onClose(tab.id)}>{t('common.close')}</ContextMenuItem>
|
||||
{renderBulkCloseItems(tab.id)}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
@@ -811,7 +800,6 @@ export const EditorTopTab: React.FC<EditorTopTabProps> = memo(({
|
||||
<ContextMenuItem onClick={() => onRequestCloseEditorTab(editorTab.id)}>
|
||||
<X size={14} className="mr-2" />
|
||||
{t('sftp.editor.close')}
|
||||
{isActive && !isDetached && <BoundMenuShortcut action="closeTab" />}
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
@@ -837,7 +825,6 @@ interface SessionTopTabProps {
|
||||
onCopySession: (sessionId: string) => void;
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
renderBulkCloseItems: RenderBulkCloseItems;
|
||||
@@ -867,7 +854,6 @@ export const SessionTopTab: React.FC<SessionTopTabProps> = memo(({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
renderBulkCloseItems,
|
||||
dynamicTabTitleMode,
|
||||
@@ -1006,13 +992,11 @@ export const SessionTopTab: React.FC<SessionTopTabProps> = memo(({
|
||||
<ContextMenu>
|
||||
{tabTrigger}
|
||||
<SessionTabContextMenuContent
|
||||
closeShortcutAction={isActive ? 'closeTab' : undefined}
|
||||
sessionId={session.id}
|
||||
onCloseSession={onCloseSession}
|
||||
onCopySession={onCopySession}
|
||||
onDuplicateSession={onDuplicateSession}
|
||||
onCopySessionToNewWindow={onCopySessionToNewWindow}
|
||||
onConvertSessionToWorkspace={onConvertSessionToWorkspace}
|
||||
onMoveSessionToNewWindow={
|
||||
(isPluginHostProtocol(session.protocol) || session.protocol?.startsWith('plugin:'))
|
||||
? undefined
|
||||
@@ -1219,7 +1203,6 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
|
||||
{onRequestAddToWorkspace && (
|
||||
<ContextMenuItem onClick={() => onRequestAddToWorkspace(workspace.id)}>
|
||||
{t('tabs.addSessionToWorkspace')}
|
||||
{isActive && <BoundMenuShortcut action="addSessionToWorkspace" />}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onDetachSessionFromWorkspace && detachSessions.map((session) => (
|
||||
@@ -1237,7 +1220,6 @@ export const WorkspaceTopTab: React.FC<WorkspaceTopTabProps> = memo(({
|
||||
)}
|
||||
<ContextMenuItem className="text-destructive" onClick={() => onCloseWorkspace(workspace.id)}>
|
||||
{t('common.close')}
|
||||
{isActive && <BoundMenuShortcut action="closeTab" />}
|
||||
</ContextMenuItem>
|
||||
{renderBulkCloseItems(workspace.id)}
|
||||
</ContextMenuContent>
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { activeTabStore } from '../../application/state/activeTabStore';
|
||||
import { createDomRenderer, dispatchDomEvent, installDomEnvironment } from '../test-support/renderReactDom';
|
||||
import { TopTabOverflowMenu } from './TopTabOverflowMenu';
|
||||
|
||||
test('overflow menu selects an existing tab, focuses detached editors and retains the quick switcher', async t => {
|
||||
const dom = installDomEnvironment();
|
||||
t.after(dom.cleanup);
|
||||
const oldElement = Object.getOwnPropertyDescriptor(globalThis, 'Element');
|
||||
const oldRaf = Object.getOwnPropertyDescriptor(globalThis, 'requestAnimationFrame');
|
||||
Object.defineProperty(globalThis, 'Element', { configurable: true, value: dom.window.Element });
|
||||
Object.defineProperty(globalThis, 'requestAnimationFrame', {
|
||||
configurable: true, value: (callback: FrameRequestCallback) => setTimeout(() => callback(0), 0),
|
||||
});
|
||||
t.after(() => {
|
||||
if (oldElement) Object.defineProperty(globalThis, 'Element', oldElement);
|
||||
else Reflect.deleteProperty(globalThis, 'Element');
|
||||
if (oldRaf) Object.defineProperty(globalThis, 'requestAnimationFrame', oldRaf);
|
||||
else Reflect.deleteProperty(globalThis, 'requestAnimationFrame');
|
||||
});
|
||||
const renderer = await createDomRenderer(dom.document);
|
||||
const previous = activeTabStore.getActiveTabId();
|
||||
let focused = 0;
|
||||
let openedSwitcher = 0;
|
||||
const tabs = [
|
||||
{ id: 'vault', label: 'Vaults' },
|
||||
{ id: 's1', label: 'Test SSH' },
|
||||
{ id: 'editor:1', label: 'Detached editor', activate: () => { focused++; } },
|
||||
];
|
||||
const click = (selector: string) => {
|
||||
const element = dom.document.querySelector(selector);
|
||||
assert.ok(element, selector);
|
||||
return dispatchDomEvent(element, new dom.window.MouseEvent('click', { bubbles: true }));
|
||||
};
|
||||
try {
|
||||
activeTabStore.setActiveTabId('vault');
|
||||
await renderer.render(<I18nProvider locale="en">
|
||||
<TopTabOverflowMenu getTabs={() => tabs} onOpenQuickSwitcher={() => { openedSwitcher++; }} />
|
||||
</I18nProvider>);
|
||||
const trigger = 'button[aria-haspopup="menu"]';
|
||||
await click(trigger);
|
||||
const options = [...dom.document.querySelectorAll('[role="menuitemradio"]')];
|
||||
assert.deepEqual(options.map(option => option.textContent), tabs.map(tab => tab.label));
|
||||
assert.equal(options[0].getAttribute('aria-checked'), 'true');
|
||||
await click('[title="Test SSH"]');
|
||||
assert.equal(activeTabStore.getActiveTabId(), 's1');
|
||||
assert.equal(dom.document.querySelector('[role="menu"]'), null);
|
||||
|
||||
await click(trigger);
|
||||
await click('[title="Detached editor"]');
|
||||
assert.equal(focused, 1);
|
||||
assert.equal(activeTabStore.getActiveTabId(), 's1');
|
||||
|
||||
await click(trigger);
|
||||
await click('[role="menuitem"]');
|
||||
assert.equal(openedSwitcher, 1);
|
||||
assert.equal(dom.document.querySelector('[role="menu"]'), null);
|
||||
} finally {
|
||||
await renderer.unmount();
|
||||
activeTabStore.setActiveTabId(previous);
|
||||
}
|
||||
});
|
||||
@@ -1,73 +0,0 @@
|
||||
import { Check, MoreVertical, Plus } from 'lucide-react';
|
||||
import React, { useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { activeTabStore, useActiveTabId } from '../../application/state/activeTabStore';
|
||||
import { useSessionPresentationVersion } from '../../application/state/sessionPresentationStore';
|
||||
import { Button } from '../ui/button';
|
||||
import { Dropdown, DropdownContent, DropdownTrigger } from '../ui/dropdown';
|
||||
|
||||
export interface OverflowTab {
|
||||
id: string;
|
||||
label: string;
|
||||
activate?: () => void;
|
||||
}
|
||||
|
||||
const itemClass = 'flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-foreground/10 focus-visible:bg-foreground/10';
|
||||
|
||||
function TabChoices({ getTabs, onClose }: { getTabs: () => OverflowTab[]; onClose: () => void }) {
|
||||
const activeId = useActiveTabId();
|
||||
useSessionPresentationVersion();
|
||||
return getTabs().map(({ id, label, activate }) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
role="menuitemradio"
|
||||
aria-checked={id === activeId}
|
||||
className={itemClass}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
if (activate) activate();
|
||||
else activeTabStore.setActiveTabId(id);
|
||||
}}
|
||||
>
|
||||
<span className="w-4 shrink-0">{id === activeId && <Check size={14} />}</span>
|
||||
<span className="truncate" title={label}>{label}</span>
|
||||
</button>
|
||||
));
|
||||
}
|
||||
|
||||
export function TopTabOverflowMenu({ getTabs, onOpenQuickSwitcher }: {
|
||||
getTabs: () => OverflowTab[];
|
||||
onOpenQuickSwitcher: () => void;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<Dropdown open={open} onOpenChange={setOpen}>
|
||||
<DropdownTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-5 flex-shrink-0 app-no-drag self-end top-tab-utility-btn"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
aria-haspopup="menu"
|
||||
data-state={open ? 'open' : 'closed'}
|
||||
aria-expanded={open}
|
||||
aria-label={t('topTabs.moreTabs')}
|
||||
title={t('topTabs.moreTabs')}
|
||||
>
|
||||
<MoreVertical size={14} />
|
||||
</Button>
|
||||
</DropdownTrigger>
|
||||
<DropdownContent align="end" keyboardNavigation className="app-no-drag w-64 max-h-[65vh] overflow-y-auto">
|
||||
<TabChoices getTabs={getTabs} onClose={() => setOpen(false)} />
|
||||
<button type="button" role="menuitem" className={`${itemClass} mt-1 border-t`} onClick={() => {
|
||||
setOpen(false);
|
||||
onOpenQuickSwitcher();
|
||||
}}>
|
||||
<Plus size={14} />{t('topTabs.openQuickSwitcher')}
|
||||
</button>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
@@ -58,12 +58,6 @@ test('WorkspaceTopTab context menu invokes onRequestAddToWorkspace for the works
|
||||
const { WorkspaceTopTab } = await import('./TopTabItems.tsx');
|
||||
const { topTabsAreEqual } = await import('../TopTabs.tsx');
|
||||
|
||||
const { getTerminalSettingsSnapshot, publishTerminalSettingsSnapshot } = await import('../../application/state/terminalSettingsStore.ts');
|
||||
const { DEFAULT_KEY_BINDINGS } = await import('../../domain/models/keyBindings.ts');
|
||||
const { activeTabStore } = await import('../../application/state/activeTabStore.ts');
|
||||
const previousActiveTab = activeTabStore.getActiveTabId();
|
||||
const previousSettings = getTerminalSettingsSnapshot();
|
||||
|
||||
const rootNode = window.document.getElementById('root');
|
||||
assert.ok(rootNode);
|
||||
const root = createRoot(rootNode);
|
||||
@@ -131,23 +125,10 @@ test('WorkspaceTopTab context menu invokes onRequestAddToWorkspace for the works
|
||||
);
|
||||
});
|
||||
|
||||
publishTerminalSettingsSnapshot({ ...previousSettings, hotkeyScheme: 'mac', keyBindings: DEFAULT_KEY_BINDINGS });
|
||||
await openTabMenu();
|
||||
const addMenuItem = Array.from(window.document.querySelectorAll('[role="menuitem"]'))
|
||||
.find((item): item is HTMLElement => (item as Element).textContent?.includes('Add Session to Workspace') ?? false);
|
||||
assert.ok(addMenuItem, 'Add Session to Workspace menu item should render');
|
||||
assert.equal(addMenuItem.querySelector('span'), null, 'inactive workspace');
|
||||
await act(async () => {
|
||||
activeTabStore.setActiveTabId(workspace.id);
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
assert.equal(addMenuItem.querySelector('span')?.textContent, '⌘N');
|
||||
await act(async () => publishTerminalSettingsSnapshot({
|
||||
...previousSettings, hotkeyScheme: 'pc', keyBindings: DEFAULT_KEY_BINDINGS,
|
||||
}));
|
||||
assert.equal(addMenuItem.querySelector('span')?.textContent, 'Ctrl+N');
|
||||
await act(async () => publishTerminalSettingsSnapshot({ ...previousSettings, hotkeyScheme: 'disabled' }));
|
||||
assert.equal(addMenuItem.querySelector('span'), null);
|
||||
|
||||
await act(async () => {
|
||||
addMenuItem.click();
|
||||
@@ -182,8 +163,6 @@ test('WorkspaceTopTab context menu invokes onRequestAddToWorkspace for the works
|
||||
root.unmount();
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
});
|
||||
activeTabStore.setActiveTabId(previousActiveTab);
|
||||
publishTerminalSettingsSnapshot(previousSettings);
|
||||
dom.window.close();
|
||||
for (const [key, descriptor] of previousGlobals) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
import { useTerminalSettingsStore } from '../../application/state/terminalSettingsStore';
|
||||
import { getMenuShortcut } from '../../domain/activeKeyBindings';
|
||||
import { ContextMenuShortcut } from './context-menu';
|
||||
|
||||
export function BoundMenuShortcut({ action, whenDisabled }: { action: string; whenDisabled?: string }) {
|
||||
const { hotkeyScheme, keyBindings } = useTerminalSettingsStore();
|
||||
const label = hotkeyScheme === 'disabled' ? whenDisabled : getMenuShortcut(action, hotkeyScheme, keyBindings);
|
||||
return <ContextMenuShortcut>{label}</ContextMenuShortcut>;
|
||||
}
|
||||
@@ -147,9 +147,8 @@ const ContextMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
shortcut?: string;
|
||||
}
|
||||
>(({ className, inset, shortcut, children, ...props }, ref) => (
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
@@ -158,14 +157,7 @@ const ContextMenuItem = React.forwardRef<
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{shortcut ? (
|
||||
<>
|
||||
{children}
|
||||
<ContextMenuShortcut>{shortcut}</ContextMenuShortcut>
|
||||
</>
|
||||
) : children}
|
||||
</ContextMenuPrimitive.Item>
|
||||
/>
|
||||
));
|
||||
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
|
||||
|
||||
@@ -247,20 +239,16 @@ ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
|
||||
|
||||
const ContextMenuShortcut = ({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLSpanElement>) => {
|
||||
if (!children) return null;
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"ml-auto shrink-0 whitespace-nowrap pl-4 text-xs text-muted-foreground",
|
||||
"ml-auto shrink-0 pl-4 text-xs tracking-widest text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
/>
|
||||
);
|
||||
};
|
||||
ContextMenuShortcut.displayName = "ContextMenuShortcut";
|
||||
|
||||
@@ -195,7 +195,7 @@ const CertItem = memo<CertItemProps>(({
|
||||
|
||||
const menuContent = (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem shortcut="Enter" onClick={() => onInspect(cert)}>
|
||||
<ContextMenuItem onClick={() => onInspect(cert)}>
|
||||
<Eye className="mr-2 h-4 w-4" />
|
||||
{t("knownHosts.certs.action.inspect")}
|
||||
</ContextMenuItem>
|
||||
|
||||
@@ -38,7 +38,6 @@ export interface VaultHostCardPrimitives {
|
||||
}
|
||||
|
||||
export interface VaultHostContextMenuProps {
|
||||
enterConnects?: boolean;
|
||||
host: Host;
|
||||
section: VaultHostCardSection;
|
||||
primitives: Pick<
|
||||
@@ -67,7 +66,6 @@ export interface VaultHostContextMenuProps {
|
||||
|
||||
export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
section,
|
||||
primitives,
|
||||
t,
|
||||
@@ -98,7 +96,7 @@ export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem shortcut={enterConnects ? "Enter" : undefined} onClick={() => onConnect(host)}>
|
||||
<ContextMenuItem onClick={() => onConnect(host)}>
|
||||
<Plug className="mr-2 h-4 w-4" /> {t("vault.hosts.connect")}
|
||||
</ContextMenuItem>
|
||||
<OpenDualPaneSftpMenuItem host={host} />
|
||||
@@ -137,7 +135,6 @@ export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
};
|
||||
|
||||
export interface VaultHostCardProps {
|
||||
enterConnects?: boolean;
|
||||
host: Host;
|
||||
section: VaultHostCardSection;
|
||||
gridItemKey: string;
|
||||
@@ -170,7 +167,6 @@ export interface VaultHostCardProps {
|
||||
|
||||
export const VaultHostCard: React.FC<VaultHostCardProps> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
section,
|
||||
gridItemKey,
|
||||
viewMode,
|
||||
@@ -304,7 +300,6 @@ export const VaultHostCard: React.FC<VaultHostCardProps> = ({
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<VaultHostContextMenu
|
||||
enterConnects={enterConnects}
|
||||
host={host}
|
||||
section={section}
|
||||
primitives={primitives}
|
||||
|
||||
@@ -399,7 +399,6 @@ export function VaultHostListSection({ ctx }: { ctx: VaultHostListSectionContext
|
||||
getEffectiveHostDistro={getEffectiveHostDistro}
|
||||
renderEditButton={renderHostEditButton}
|
||||
onDragStart={handleHostDragStart}
|
||||
enterConnects={!isMultiSelectMode && (hostClickBehavior === "connect" || focusedHostId === host.id)}
|
||||
onActivate={activateHost}
|
||||
onConnect={handleHostConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
|
||||
@@ -26,7 +26,6 @@ test("nested VaultPageHeader action groups wrap so controls stay visible at narr
|
||||
|
||||
const knownHostsHeader = knownHostsSource.match(/<VaultPageHeader>[\s\S]*?<\/VaultPageHeader>/)?.[0] ?? "";
|
||||
assert.ok(knownHostsHeader, "expected VaultPageHeader in KnownHostsManager.tsx");
|
||||
assert.match(knownHostsHeader, /role="tablist"/);
|
||||
assert.match(
|
||||
knownHostsHeader,
|
||||
/<div className="[^"]*flex-wrap[^"]*">\s*<Button[\s\S]*?knownHosts\.action\.scanSystem/,
|
||||
|
||||
@@ -319,6 +319,7 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
handleEditHost,
|
||||
handleEditTag,
|
||||
handleExportHosts,
|
||||
handleExportSshConfig,
|
||||
handleHostConnect,
|
||||
handleImportFileSelected,
|
||||
handleNewHost,
|
||||
@@ -1173,6 +1174,16 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
</span>
|
||||
{t("vault.hosts.export")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="group justify-start gap-2.5"
|
||||
onClick={handleExportSshConfig}
|
||||
>
|
||||
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-sky-500/12 text-sky-500 group-hover:bg-current/15 group-hover:text-current">
|
||||
<Download size={13} />
|
||||
</span>
|
||||
{t("vault.hosts.export.sshConfig")}
|
||||
</Button>
|
||||
</DropdownContent>
|
||||
</Dropdown>
|
||||
</div>
|
||||
|
||||
@@ -27,17 +27,14 @@ interview actions are out of scope for this adapter.
|
||||
| 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 | Native `item/tool/requestUserInput` is already routed. The per-agent opt-in enables `features.default_mode_request_user_input` for its conversation threads without changing sandbox or approval rules. Codex SDK is unchanged. |
|
||||
| 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 MCP elicitation is unchanged. The separate per-agent opt-in exposes only native `AskUserQuestion`; the driver uses its typed answer callback before tool approval logic, including in Auto and Observer. |
|
||||
| GitHub Copilot SDK | SDK offers `onUserInputRequest` for `ask_user`; the current driver does not register it. Local CLI 1.0.117 reported protocol 4 while both the pinned SDK 1.0.0 and the separately tested 1.0.34 supported protocol 3. Fix transport compatibility before enabling a question adapter. |
|
||||
| OpenCode 1.x | Optional native questions use the local sidecar's `question.asked` and reply/reject APIs. The driver probes the API before sending a prompt, routes only the current session, and does not change edit, shell, or network policies. Verified with CLI 1.19.6. |
|
||||
| OpenCode 2.x | Not enabled by this change. It has a separate transport adapter and needs separate validation. |
|
||||
| Cursor CLI, MiMo | This change does not wire or verify a native question path. Inspect the specific runtime before advertising support. |
|
||||
| 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. |
|
||||
|
||||
The new per-agent settings default off. They affect optional native questions, not
|
||||
plan approvals or tool grants. No public MCP capability is added. A future optional
|
||||
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.
|
||||
@@ -1,27 +1,12 @@
|
||||
# Terminal Compose Bar
|
||||
|
||||
[Compose Bar 设计](compose-bar.md) · [PR 开发顺序](pr-roadmap.md)
|
||||
- [Compose Bar 设计](compose-bar.md)
|
||||
- [PR 开发顺序](pr-roadmap.md)
|
||||
|
||||
## 已实现的 Chip
|
||||
|
||||
| 终端环境 | [Directory Picker](chips/directory-picker/README.md) | [Git Branch](chips/git-branch.md) |
|
||||
| --- | --- | --- |
|
||||
| macOS 本地 Zsh、Bash、sh | 浏览、切换 | 展示、搜索、切换、删除草稿 |
|
||||
| Linux 本地 Bash、sh | 浏览、切换 | 展示、搜索、切换、删除草稿 |
|
||||
| Windows PowerShell 5.1/7 | FileSystem 目录浏览、切换 | 待适配 |
|
||||
| Windows CMD | 盘符路径浏览、切换 | 待适配 |
|
||||
| Windows Git Bash | Windows 盘符映射下浏览、切换 | 待适配 |
|
||||
| Windows WSL Bash | Linux 目录与挂载盘浏览、切换 | 待适配 |
|
||||
| Windows Cygwin Bash | Cygwin 路径浏览、切换 | 待适配 |
|
||||
| Unix SSH | 符合条件的会话通过同一连接的 SFTP 浏览,并在原 shell 切换 | 待适配 |
|
||||
| GNU Screen、tmux | 待接入活动窗口的 cwd 和空提示符 | 待目录层接入后适配 |
|
||||
|
||||
其他本地 POSIX shell 的浏览取决于 cwd 识别,命令操作还需要识别空提示符。各类路径与启动方式的细节见 [Directory Picker 跨平台设计](chips/directory-picker/cross-platform.md)。
|
||||
|
||||
## 下一批 Chip
|
||||
|
||||
| Chip | 状态 | 首版范围 |
|
||||
| --- | --- | --- |
|
||||
| [Git Changes](chips/git-changes.md) | 调研完成,待实现 | 本地 macOS/Linux,显示未提交变更摘要 |
|
||||
| [Pull Request](chips/pull-request.md) | 调研完成,待实现 | 本地 macOS/Linux,查询当前 GitHub 分支关联的开放 PR |
|
||||
| [Node Version](chips/node-version.md) | 调研完成,待实现 | 本地 macOS/Linux,从当前交互 shell 读取实际 Node 版本 |
|
||||
| Chip | 完成度 |
|
||||
| --- | --- |
|
||||
| [Directory Picker](chips/directory-picker/README.md) | 已支持本地 macOS/Linux、符合条件的 Unix SSH,以及 Windows 的 PowerShell、CMD、Git Bash、WSL Bash 和 Cygwin Bash。 |
|
||||
| [Git Branch](chips/git-branch.md) | 本地 macOS/Linux 的分支展示已合入,搜索与切换待提交。 |
|
||||
| [Git Changes](chips/git-changes.md) | 已完成初步调研,首版为只读变更摘要。 |
|
||||
| [Pull Request](chips/pull-request.md) | 已完成初步调研,首版为关联 GitHub PR 查看。 |
|
||||
| [Node Version](chips/node-version.md) | 已完成初步调研,首版为当前 shell 的版本展示。 |
|
||||
@@ -5,7 +5,7 @@
|
||||
- 显示当前终端 cwd,支持当前层搜索、父级和子目录导航、目录链接、隐藏目录及刷新。
|
||||
- 本地覆盖 macOS/Linux 直接 shell,以及 Windows PowerShell 5.1/7 的 FileSystem、CMD 盘符路径、Git Bash 盘符映射、WSL Bash 和 Cygwin Bash。Unix SSH 使用同一认证会话的 SFTP 列出目录。
|
||||
- 共用目录控制器绑定会话和 cwd 版本,在终端空闲时向原 shell 发送目录切换命令,再用实际 cwd 确认。
|
||||
- macOS Bash 和 sh 的系统登录提示符 `主机名:目录 用户名$` 供目录和分支操作共用。
|
||||
- **随本轮待提交**。识别 macOS Bash 和 sh 的系统登录提示符 `主机名:目录 用户名$`,供目录和分支操作共用。
|
||||
|
||||
## 待完成
|
||||
|
||||
@@ -16,4 +16,4 @@
|
||||
| Git Bash/WSL/Cygwin | 验证 Git Bash 共享路径和虚拟挂载,补充 WSL 2、其他发行版与 shell 的覆盖验证,补齐 Cygwin 自定义挂载前缀和共享路径。 |
|
||||
| 嵌套 shell 与远程 | GNU Screen 先绑定活动窗口及内层 shell 的 cwd,再判断该窗口的空提示符。tmux、su/sudo、容器和其他远程传输分别明确 shell 与文件系统映射。 |
|
||||
|
||||
[Chip 兼容矩阵](../../README.md#已实现的-chip) · [跨平台设计](cross-platform.md) · [交互示意](demo.html) · [PR 开发顺序](../../pr-roadmap.md)
|
||||
[跨平台设计](cross-platform.md) · [交互示意](demo.html) · [PR 开发顺序](../../pr-roadmap.md)
|
||||
@@ -1,14 +1,13 @@
|
||||
# Git Branch
|
||||
|
||||
## 已实现
|
||||
## 已完成
|
||||
|
||||
- 本地 macOS/Linux 的直接 shell 显示当前分支,detached HEAD 显示短哈希,初始分支显示分支名。
|
||||
- 菜单支持搜索本地分支和键盘选择,并按本次查询的 HEAD 标记当前分支。切换命令绑定菜单所在的工作树,终端显示 Git 原生结果,chip 根据实际 HEAD 刷新。
|
||||
- 其他本地分支的删除按钮填入 `git branch -d -- '分支名'` 并将焦点交给输入区。回车在原会话执行草稿,并将 Git 绑定到菜单读取的工作树。终端显示 Git 的删除结果。发送或取消后恢复原草稿。
|
||||
- **已合入**。本地 macOS/Linux 的直接 shell 显示当前分支,detached HEAD 显示短哈希,初始分支显示分支名。
|
||||
- **本轮待提交**。菜单支持搜索本地分支和键盘选择。选择后向当前终端发送 `git switch`,关闭菜单并保留草稿。终端显示命令和 Git 原生结果,chip 随活动重读实际 HEAD。目录控制器在发送前确认当前会话、目录和空提示符。
|
||||
|
||||
## 待完成
|
||||
|
||||
- Windows 按 PowerShell/CMD、Git Bash、WSL Bash、Cygwin Bash 分别适配 Git 与工作树路径。Unix SSH 在原会话中获取 Git 状态和分支。GNU Screen 依赖目录层先绑定活动窗口与内层 shell。
|
||||
- 新建分支先确定起点和创建后是否切换,再设计命令草稿。远程分支先明确跟踪分支的展示和检出规则。
|
||||
- Windows 和 SSH 分别确认 Git 的可执行文件、工作树路径和会话身份。GNU Screen 依赖目录层先绑定活动窗口与内层 shell。
|
||||
- 远程分支与新建分支分别调研命令范围和菜单交互。
|
||||
|
||||
[Chip 兼容矩阵](../README.md#已实现的-chip) · [PR 开发顺序](../pr-roadmap.md)
|
||||
[PR 开发顺序](../pr-roadmap.md)
|
||||
@@ -10,5 +10,4 @@ Compose Bar 位于终端下方。顶栏先显示当前会话的 Context Chips,
|
||||
- 文件系统、Git 和 shell 集成由 `infrastructure/services/` 与 Electron bridge 提供。`components/terminal/` 负责布局、菜单、焦点和主题。
|
||||
- 目录和 Git Branch 共用已确认的工作目录。操作绑定当前终端,发送前确认会话、目录和空提示符,保留撰写栏草稿。
|
||||
- 命令类 chip 在原终端执行操作,终端显示命令和原生输出。chip 根据实际状态刷新。菜单提示用于数据读取和发送前的状态。
|
||||
- 删除分支等需要用户确认的操作先在输入区生成独立草稿。发送沿用会话和提示符检查,完成或取消后恢复原草稿。
|
||||
- Git Changes 计划复用工作树身份,详情接入现有终端侧栏。Pull Request 单独处理远程身份和查询状态。Node Version 从当前交互 shell 获取运行时信息。
|
||||
@@ -1,34 +1,18 @@
|
||||
# PR 开发顺序
|
||||
|
||||
当前覆盖范围见 [Chip 兼容矩阵](README.md#已实现的-chip)。Git Branch 已实现分支展示、搜索、切换和删除草稿。
|
||||
|
||||
## 下一批 Chip
|
||||
|
||||
| 顺序 | PR | 交付范围 |
|
||||
| --- | --- | --- |
|
||||
| 1 | [Git Changes 只读摘要](chips/git-changes.md) | 复用本地 Git 工作树识别,交付改动文件数、增删行和刷新规则。 |
|
||||
| 2 | [Pull Request 查询](chips/pull-request.md) | 根据仓库、remote 和分支查找关联的开放 GitHub PR,显示编号并提供打开入口。 |
|
||||
| 3 | [Node Version 只读展示](chips/node-version.md) | 读取当前交互 shell 实际使用的 Node 版本,处理 cwd 和 PATH 变化。 |
|
||||
| 1 | [Git Branch 搜索与切换](chips/git-branch.md) | 当前开发分支。覆盖本地 macOS/Linux 的直接 shell。选择后向当前终端发送 `git switch`,按实际 HEAD 更新。 |
|
||||
| 2 | [Git Changes 只读摘要](chips/git-changes.md) | 复用工作树识别,先确定并交付改动文件数、增删行和刷新规则。 |
|
||||
| 3 | [Pull Request 查询](chips/pull-request.md) | 根据仓库、remote 和分支查找关联的开放 GitHub PR,显示编号并提供打开入口。 |
|
||||
| 4 | [Node Version 只读展示](chips/node-version.md) | 读取当前 shell 实际使用的 Node 版本,处理 cwd 和 PATH 变化。 |
|
||||
|
||||
## 兼容性 PR
|
||||
## 独立 PR 待排期
|
||||
|
||||
兼容性按会话环境独立提交,可与下一批 Chip 并行推进。每个 Git Branch 适配先确认可执行文件、工作树路径和会话身份,再接入分支读取、切换和删除草稿。
|
||||
|
||||
| PR | 范围与依赖 |
|
||||
| 工作 | 交付范围 |
|
||||
| --- | --- |
|
||||
| Windows 原生 Git Branch | PowerShell、CMD。复用 Windows 目录控制器,验证 Git 查找、路径与各 shell 的命令引用。 |
|
||||
| Git Bash 的 Git Branch | 绑定 Git for Windows 安装及原 Bash,处理 MSYS 与 Win32 路径。 |
|
||||
| WSL Bash 的 Git Branch | 在同一发行版和用户下读取工作树与分支,使用原 Bash 的路径语义。 |
|
||||
| Cygwin Bash 的 Git Branch | 在同一 Cygwin 安装下定位 Git 与工作树,使用原 Bash 的路径语义。 |
|
||||
| GNU Screen 的 Directory Picker | 识别活动窗口、内层 shell 和空提示符,再接通目录读取与切换。 |
|
||||
| GNU Screen 的 Git Branch | 复用 Screen 的目录接入,绑定分支读取和发送目标。tmux 按同样依赖另行评估。 |
|
||||
| Unix SSH 的 Git Branch | 在同一认证会话中读取 Git 状态,并把操作送往原 shell。 |
|
||||
|
||||
Directory Picker 的 POSIX 位置上报、路径边界和传输扩展按 shell 或传输拆分。详见 [Directory Picker 待完成](chips/directory-picker/README.md#待完成)。
|
||||
|
||||
## 功能扩展 PR
|
||||
|
||||
- Git Branch 切换命令简化。确认原 shell 的 Git 目标与菜单使用同一工作树后,发送 `git switch --no-guess -- '分支名'`,保留 Git 原生反馈。
|
||||
- Git Branch 新建与远程分支分别设计起点选择和跟踪分支检出。
|
||||
- Git Changes 摘要稳定后接入终端侧栏,提供文件列表和只读 diff。
|
||||
- Node Version 先验证 nvm 的版本列表和原 shell 切换,再评估其他管理器。
|
||||
| Windows Git Branch | 先验证 PowerShell 和 CMD 的 Git 执行环境,再单独验证 Git Bash、WSL 和 Cygwin 的路径与 Git 上下文。 |
|
||||
| GNU Screen | 先识别活动窗口和内层 shell,接通目录读取与切换,再复用 Git Branch 的工作树读取和命令入口。tmux 按相同边界单独评估。 |
|
||||
| Git Changes 详情 | 在统计口径稳定后接入终端侧栏,提供文件列表和只读 diff。 |
|
||||
| Node 版本切换 | 先验证 nvm 的列表读取和原 shell 切换,其余管理器分别评估。 |
|
||||
| 目录兼容与远程扩展 | 按 shell 或传输拆分。详见 [Directory Picker 待完成](chips/directory-picker/README.md#待完成) 和 [Git Branch 待完成](chips/git-branch.md#待完成)。 |
|
||||
@@ -3,7 +3,6 @@ import test from 'node:test';
|
||||
|
||||
import {
|
||||
findActiveSystemShortcutConflict,
|
||||
getMenuShortcut,
|
||||
listActiveSystemBindings,
|
||||
} from './activeKeyBindings.ts';
|
||||
import { DEFAULT_KEY_BINDINGS, type KeyBinding } from './models/keyBindings.ts';
|
||||
@@ -67,23 +66,3 @@ test('a Disabled individual binding is not a conflict', () => {
|
||||
assert.equal(findActiveSystemShortcutConflict('Ctrl + 1', 'pc', bindings), null);
|
||||
assert.equal(findActiveSystemShortcutConflict('Ctrl + B', 'pc', bindings)?.id, 'broadcast');
|
||||
});
|
||||
|
||||
test('menu hints follow the selected scheme and use compact platform chords', () => {
|
||||
assert.equal(getMenuShortcut('closeSession', 'mac', DEFAULT_KEY_BINDINGS), '⇧⌘W');
|
||||
assert.equal(getMenuShortcut('closeSession', 'pc', DEFAULT_KEY_BINDINGS), 'Ctrl+Shift+W');
|
||||
assert.equal(getMenuShortcut('sftpRename', 'mac', DEFAULT_KEY_BINDINGS), 'F2');
|
||||
assert.equal(getMenuShortcut('sftpRefresh', 'pc', DEFAULT_KEY_BINDINGS), 'F5');
|
||||
assert.equal(getMenuShortcut('sftpRefresh', 'disabled', DEFAULT_KEY_BINDINGS), undefined);
|
||||
assert.equal(getMenuShortcut('openHosts', 'mac', DEFAULT_KEY_BINDINGS), undefined);
|
||||
assert.equal(getMenuShortcut('closeTab', 'pc', []), undefined);
|
||||
});
|
||||
|
||||
test('menu hints use an enabled secondary binding when the primary is unset', () => {
|
||||
const primary = DEFAULT_KEY_BINDINGS.find((binding) => binding.action === 'closeTab')!;
|
||||
const bindings = [
|
||||
{ ...primary, mac: 'Disabled', pc: '' },
|
||||
{ ...primary, id: 'extra-close-tab', extraOf: primary.id, mac: '⌘ + ⌥ + Z', pc: 'Ctrl + F4' },
|
||||
];
|
||||
assert.equal(getMenuShortcut('closeTab', 'mac', bindings), '⌥⌘Z');
|
||||
assert.equal(getMenuShortcut('closeTab', 'pc', bindings), 'Ctrl+F4');
|
||||
});
|
||||
@@ -35,30 +35,6 @@ export const listActiveSystemBindings = (
|
||||
});
|
||||
};
|
||||
|
||||
const MAC_MODIFIERS: Record<string, string> = { Ctrl: '⌃', Alt: '⌥', Shift: '⇧', Cmd: '⌘' };
|
||||
const MAC_MODIFIER_ORDER = ['⌃', '⌥', '⇧', '⌘'];
|
||||
|
||||
// Use the first enabled chord, including user-added alternatives when the
|
||||
// primary binding is disabled. macOS menu modifiers follow native glyph order.
|
||||
export function getMenuShortcut(
|
||||
action: string,
|
||||
scheme: HotkeyScheme,
|
||||
bindings: readonly KeyBinding[],
|
||||
): string | undefined {
|
||||
if (scheme === 'disabled') return undefined;
|
||||
const binding = bindings.find((entry) => (
|
||||
entry.action === action && entry[scheme] && entry[scheme] !== 'Disabled'
|
||||
));
|
||||
if (!binding) return undefined;
|
||||
|
||||
const parts = binding[scheme].split(/\s*\+\s*/);
|
||||
if (scheme === 'pc') return parts.join('+');
|
||||
const key = parts.pop() ?? '';
|
||||
const modifiers = parts.map((part) => MAC_MODIFIERS[part] ?? part);
|
||||
modifiers.sort((a, b) => MAC_MODIFIER_ORDER.indexOf(a) - MAC_MODIFIER_ORDER.indexOf(b));
|
||||
return modifiers.join('') + key;
|
||||
}
|
||||
|
||||
export const findActiveSystemShortcutConflict = (
|
||||
key: string,
|
||||
hotkeyScheme: HotkeyScheme,
|
||||
|
||||
@@ -11,7 +11,6 @@ export type AgentIconKey =
|
||||
| 'codex'
|
||||
| 'claude'
|
||||
| 'anthropic'
|
||||
| 'agy'
|
||||
| 'gemini'
|
||||
| 'google'
|
||||
| 'ollama'
|
||||
@@ -24,7 +23,6 @@ export type AgentIconKey =
|
||||
| 'codebuddy'
|
||||
| 'grok'
|
||||
| 'mimo'
|
||||
| 'qoder'
|
||||
| 'terminal'
|
||||
| 'plus';
|
||||
|
||||
@@ -70,11 +68,6 @@ export const AGENT_ICON_VISUALS: Record<AgentIconKey, AgentIconVisual> = {
|
||||
badgeClassName: 'border-orange-500/22 bg-orange-500/12',
|
||||
imageClassName: 'object-contain dark:brightness-0 dark:invert',
|
||||
},
|
||||
agy: {
|
||||
src: '/ai/agents/agy.svg',
|
||||
badgeClassName: 'border-sky-500/22 bg-sky-500/12',
|
||||
imageClassName: 'object-contain dark:brightness-0 dark:invert',
|
||||
},
|
||||
gemini: {
|
||||
src: '/ai/agents/gemini.svg',
|
||||
badgeClassName: 'border-sky-500/22 bg-sky-500/12',
|
||||
@@ -130,11 +123,6 @@ export const AGENT_ICON_VISUALS: Record<AgentIconKey, AgentIconVisual> = {
|
||||
badgeClassName: 'border-zinc-500/22 bg-zinc-500/12',
|
||||
imageClassName: 'object-contain dark:brightness-0 dark:invert opacity-90',
|
||||
},
|
||||
qoder: {
|
||||
src: '/ai/agents/qoder.svg',
|
||||
badgeClassName: 'border-violet-500/22 bg-violet-500/12',
|
||||
imageClassName: 'object-contain dark:brightness-0 dark:invert opacity-90',
|
||||
},
|
||||
mimo: {
|
||||
src: '/ai/agents/mimo.svg',
|
||||
badgeClassName: 'border-orange-500/22 bg-orange-500/12',
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export type ChatTextFile = { name: string; content: string };
|
||||
export function chatTextFileExtension(name: string): string;
|
||||
export function validateChatTextFile(value: unknown): ChatTextFile | null;
|
||||
@@ -1,20 +0,0 @@
|
||||
const maxTextBytes = 256 * 1024;
|
||||
const textExtensions = new Set(['txt', 'md', 'csv', 'tsv', 'json']);
|
||||
|
||||
export function chatTextFileExtension(name) {
|
||||
return name.slice(name.lastIndexOf('.') + 1).toLowerCase();
|
||||
}
|
||||
|
||||
/** Never treat a model-supplied file name as a path. Keep contents as text. */
|
||||
export function validateChatTextFile(value) {
|
||||
if (!value || typeof value !== 'object' || Object.keys(value).length !== 2
|
||||
|| !Object.hasOwn(value, 'name') || !Object.hasOwn(value, 'content')) return null;
|
||||
const { name, content } = value;
|
||||
if (typeof name !== 'string' || name.length > 128 || name !== name.trim()
|
||||
|| name.startsWith('.') || !name.includes('.') || /[/\\:<>"|?*\p{Cc}\p{Cf}]/u.test(name)
|
||||
|| /^(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:[ .]|$)/i.test(name)
|
||||
|| !textExtensions.has(chatTextFileExtension(name))) return null;
|
||||
if (typeof content !== 'string' || content.length > maxTextBytes || content.includes('\0')
|
||||
|| new globalThis.TextEncoder().encode(content).byteLength > maxTextBytes) return null;
|
||||
return { name, content };
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { splitChatTextFileOffers } from './chatTextFileOffers';
|
||||
|
||||
const offer = (name: string, content: string) => '```netcatty-file\n' + JSON.stringify({ name, content }) + '\n```';
|
||||
|
||||
test('only complete top-level text file offers are removed from display markdown', () => {
|
||||
const report = offer('report.md', '# Report\nRésumé\n');
|
||||
const rows = Array.from({ length: 138 }, (_, i) => `${i + 1},checked`).join('\n');
|
||||
const result = splitChatTextFileOffers(`Here are both files:\n\n${report}\n\n${offer('核对表.csv', rows)}`);
|
||||
assert.equal(result.markdown.trim(), 'Here are both files:');
|
||||
assert.deepEqual(result.files, [
|
||||
{ name: 'report.md', content: '# Report\nRésumé\n' }, { name: '核对表.csv', content: rows },
|
||||
]);
|
||||
});
|
||||
|
||||
test('unclosed, nested, invalid and disguised file offers stay literal', () => {
|
||||
const valid = offer('notes.txt', 'hi');
|
||||
for (const markdown of [valid.slice(0, -3), `~~~~example\n${valid}\n~~~~`,
|
||||
offer('../notes.txt', 'hi'), offer('report.exe', 'hi'), offer('CON.txt', 'hi'), offer('report.txt', '\0'),
|
||||
'```netcatty-file\n{"name":"report.md","path":"D:/private/report.md"}\n```']) {
|
||||
assert.deepEqual(splitChatTextFileOffers(markdown), { markdown, files: [] });
|
||||
}
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { validateChatTextFile, type ChatTextFile } from './chatTextFile.shared.mjs';
|
||||
|
||||
const offerLabel = 'netcatty-file';
|
||||
const maxOffers = 4;
|
||||
// JSON-escaped text can take up to six characters per input byte.
|
||||
const maxEncodedOffer = 6 * 256 * 1024 + 1024;
|
||||
const fence = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)\r?\n?$/;
|
||||
|
||||
export function splitChatTextFileOffers(source: string): { markdown: string; files: ChatTextFile[] } {
|
||||
if (!source.includes(offerLabel)) return { markdown: source, files: [] };
|
||||
const lines = source.split(/(?<=\n)/);
|
||||
const files: ChatTextFile[] = [];
|
||||
const output: string[] = [];
|
||||
let open: { start: number; marker: string; offer: boolean } | undefined;
|
||||
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
const match = fence.exec(line);
|
||||
if (!open) {
|
||||
if (!match || (match[1][0] === '`' && match[2].includes('`'))) {
|
||||
output.push(line);
|
||||
continue;
|
||||
}
|
||||
open = { start: index, marker: match[1], offer: match[2].trim() === offerLabel };
|
||||
} else if (match && match[1][0] === open.marker[0] && match[1].length >= open.marker.length && !match[2].trim()) {
|
||||
const block = lines.slice(open.start + 1, index);
|
||||
// A JSON object is the single wire shape. Reject incomplete or malformed
|
||||
// offers by leaving the original Markdown visible instead of hiding it.
|
||||
let file: ChatTextFile | null = null;
|
||||
if (open.offer && files.length < maxOffers && block.length === 1 && block[0].length <= maxEncodedOffer) {
|
||||
try { file = validateChatTextFile(JSON.parse(block[0])); } catch { /* Keep literal Markdown. */ }
|
||||
}
|
||||
if (file) { files.push(file); output.push('\n'); }
|
||||
else output.push(lines.slice(open.start, index + 1).join(''));
|
||||
open = undefined;
|
||||
}
|
||||
}
|
||||
if (open) output.push(lines.slice(open.start).join(''));
|
||||
return { markdown: output.join(''), files };
|
||||
}
|
||||
@@ -21,7 +21,6 @@ test('inferCodingCliProviderFromOutput detects other CLI banners', () => {
|
||||
assert.equal(inferCodingCliProviderFromOutput('Welcome to Claude Code'), 'claude');
|
||||
assert.equal(inferCodingCliProviderFromOutput('GitHub Copilot CLI'), 'copilot');
|
||||
assert.equal(inferCodingCliProviderFromOutput('Factory Droid ready'), 'droid');
|
||||
assert.equal(inferCodingCliProviderFromOutput('+ Welcome to Qoder CLI'), 'qoder');
|
||||
assert.equal(
|
||||
inferCodingCliProviderFromOutput(
|
||||
'█▀▀█ █▀▀█ █▀▀█ █▀▀▄ █▀▀▀ █▀▀█ █▀▀█ █▀▀█\n'
|
||||
@@ -56,10 +55,6 @@ test('inferCodingCliProviderFromOutput ignores coding CLI installer and package
|
||||
inferCodingCliProviderFromOutput('updated opencode-ai@1.2.3'),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(
|
||||
inferCodingCliProviderFromOutput('Install Qoder CLI: curl -fsSL https://qoder.com/install | bash'),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test('createCodingCliOutputScanner ignores split installer output', () => {
|
||||
@@ -181,22 +176,3 @@ test('stripTerminalControlSequences removes ANSI color codes', () => {
|
||||
const stripped = stripTerminalControlSequences('\x1b[1mOpenAI Codex\x1b[0m');
|
||||
assert.equal(stripped, 'OpenAI Codex');
|
||||
});
|
||||
|
||||
test('Antigravity startup banners survive chunk boundaries and exclude ordinary shell output', () => {
|
||||
const scanner = createCodingCliOutputScanner();
|
||||
assert.equal(scanner.feed('shell$ agy\r\n \x1b[1mWelcome to the Anti'), undefined);
|
||||
assert.equal(scanner.feed('gravity CLI. You are currently not signed in.\x1b[0m'), 'agy');
|
||||
assert.equal(inferCodingCliProviderFromOutput('│ Antigravity CLI 1.5.23 │'), 'agy');
|
||||
assert.equal(inferCodingCliProviderFromOutput('$ echo "Welcome to the Antigravity CLI"'), undefined);
|
||||
assert.equal(inferCodingCliProviderFromOutput('Installing Antigravity CLI 1.5.23'), undefined);
|
||||
assert.equal(inferCodingCliProviderFromOutput('Antigravity CLI 1.5.23 installed successfully'), undefined);
|
||||
assert.equal(inferCodingCliProviderFromOutput('Antigravity CLI installation complete'), undefined);
|
||||
});
|
||||
|
||||
test('Antigravity version headers wait for a terminator when the version ends a chunk', () => {
|
||||
const scanner = createCodingCliOutputScanner();
|
||||
assert.equal(scanner.feed('Antigravity CLI 1.5.23'), undefined);
|
||||
assert.equal(scanner.feed(' installed successfully\r\n'), undefined);
|
||||
assert.equal(scanner.feed('Antigravity CLI 1.5.23'), undefined);
|
||||
assert.equal(scanner.feed('\r\n'), 'agy');
|
||||
});
|
||||
@@ -95,12 +95,6 @@ const OUTPUT_SIGNATURES: readonly OutputSignature[] = [
|
||||
id: 'copilot',
|
||||
test: (text) => /GitHub Copilot/i.test(text),
|
||||
},
|
||||
{
|
||||
id: 'agy',
|
||||
// The default TUI has no OSC title. Match the welcome or versioned header
|
||||
// at the start of a terminal line so installer prose and echo commands stay shell output.
|
||||
test: (text) => /^[ \t│]*(?:Welcome to the Antigravity CLI\b|Antigravity CLI[ \t]+v?\d+\.\d+\.\d+(?=[ \t]*[\r\n│|·]))/im.test(text),
|
||||
},
|
||||
{
|
||||
id: 'gemini',
|
||||
test: (text) => /Gemini CLI/i.test(text),
|
||||
@@ -122,12 +116,6 @@ const OUTPUT_SIGNATURES: readonly OutputSignature[] = [
|
||||
id: 'kimi',
|
||||
test: (text) => /\bMoonshot\b/i.test(text) || /\bKimi\b/i.test(text),
|
||||
},
|
||||
{
|
||||
id: 'qoder',
|
||||
// Qoder's TUI prints this banner on startup. Installer output and npm
|
||||
// listings only ever mention the product name, so anchor on the banner.
|
||||
test: (text) => /\bWelcome to Qoder CLI\b/i.test(text),
|
||||
},
|
||||
] as const;
|
||||
|
||||
const OUTPUT_SCAN_BUFFER_LIMIT = 8192;
|
||||
|
||||
@@ -18,12 +18,6 @@ test('matchCodingCliProviderFromCommand resolves known CLIs', () => {
|
||||
assert.equal(matchCodingCliProviderFromCommand('factory')?.id, 'droid');
|
||||
assert.equal(matchCodingCliProviderFromCommand('grok')?.id, 'grok');
|
||||
assert.equal(matchCodingCliProviderFromCommand('C:\\\\Tools\\\\grok.exe')?.id, 'grok');
|
||||
assert.equal(matchCodingCliProviderFromCommand('qoder')?.id, 'qoder');
|
||||
assert.equal(matchCodingCliProviderFromCommand('/usr/local/bin/qoder --acp')?.id, 'qoder');
|
||||
assert.equal(matchCodingCliProviderFromCommand('/usr/local/bin/qodercli --resume previous')?.id, 'qoder');
|
||||
assert.equal(matchCodingCliProviderFromCommand('qodercli.cmd')?.id, 'qoder');
|
||||
assert.equal(matchCodingCliProviderFromCommand('qodercn')?.id, 'qoder');
|
||||
assert.equal(matchCodingCliProviderFromCommand('qoderclicn')?.id, 'qoder');
|
||||
});
|
||||
|
||||
test('matchCodingCliProviderFromTitle detects Claude Code and Codex titles', () => {
|
||||
@@ -43,10 +37,6 @@ test('matchCodingCliProviderFromTitle detects Claude Code and Codex titles', ()
|
||||
matchCodingCliProviderFromTitle('Factory Droid · auth flow')?.id,
|
||||
'droid',
|
||||
);
|
||||
assert.equal(
|
||||
matchCodingCliProviderFromTitle('Qoder CLI · netcatty')?.id,
|
||||
'qoder',
|
||||
);
|
||||
assert.equal(
|
||||
matchCodingCliProviderFromTitle('android@pixel:~'),
|
||||
undefined,
|
||||
@@ -98,15 +88,3 @@ test('resolveSessionCodingCliProvider keeps sticky provider when title is only a
|
||||
'codex',
|
||||
);
|
||||
});
|
||||
|
||||
test('Antigravity launch commands use the Antigravity icon in terminal tabs', () => {
|
||||
for (const command of ['agy', 'agy --continue', '/usr/local/bin/agy', 'C:\\Tools\\agy.exe']) {
|
||||
assert.equal(matchCodingCliProviderFromCommand(command)?.iconKey, 'agy');
|
||||
}
|
||||
assert.equal(matchCodingCliProviderFromCommand('legacy'), undefined);
|
||||
assert.equal(matchCodingCliProviderFromTitle('user@host: /tmp/agy-project'), undefined);
|
||||
assert.equal(matchCodingCliProviderFromTitle('✳ Claude Code · fix agy detection')?.id, 'claude');
|
||||
assert.equal(matchCodingCliProviderFromTitle('⠋ codex · antigravity')?.id, 'codex');
|
||||
assert.equal(matchCodingCliProviderFromTitle('Grok Build · fix agy detection')?.id, 'grok');
|
||||
assert.equal(matchCodingCliProviderFromTitle('fix agy detection'), undefined);
|
||||
});
|
||||
@@ -65,8 +65,6 @@ export function matchCodingCliProviderFromTitle(title: string): CodingCliProvide
|
||||
});
|
||||
|
||||
for (const provider of ranked) {
|
||||
// Antigravity titles are identified above by their brand prefix or official script.
|
||||
if (provider.id === 'agy') continue;
|
||||
const hints = [
|
||||
...(provider.titleHints ?? []),
|
||||
provider.label,
|
||||
|
||||
@@ -4,7 +4,6 @@ export type CodingCliProviderId =
|
||||
| 'claude'
|
||||
| 'codex'
|
||||
| 'opencode'
|
||||
| 'agy'
|
||||
| 'gemini'
|
||||
| 'kimi'
|
||||
| 'droid'
|
||||
@@ -12,8 +11,7 @@ export type CodingCliProviderId =
|
||||
| 'cursor'
|
||||
| 'codebuddy'
|
||||
| 'grok'
|
||||
| 'mimo'
|
||||
| 'qoder';
|
||||
| 'mimo';
|
||||
|
||||
export type CodingCliProvider = {
|
||||
id: CodingCliProviderId;
|
||||
@@ -53,13 +51,6 @@ export const CODING_CLI_PROVIDERS: readonly CodingCliProvider[] = [
|
||||
titleHints: ['opencode'],
|
||||
iconKey: 'opencode',
|
||||
},
|
||||
{
|
||||
id: 'agy',
|
||||
label: 'Antigravity CLI',
|
||||
command: 'agy',
|
||||
titleHints: ['antigravity'],
|
||||
iconKey: 'agy',
|
||||
},
|
||||
{
|
||||
id: 'gemini',
|
||||
label: 'Gemini CLI',
|
||||
@@ -118,15 +109,6 @@ export const CODING_CLI_PROVIDERS: readonly CodingCliProvider[] = [
|
||||
titleHints: ['mimo code', 'mimocode', 'mimo'],
|
||||
iconKey: 'mimo',
|
||||
},
|
||||
{
|
||||
id: 'qoder',
|
||||
label: 'Qoder CLI',
|
||||
command: 'qoder',
|
||||
// The npm package exposes qodercli directly and regional builds use CN aliases.
|
||||
aliases: ['qodercli', 'qodercn', 'qoderclicn'],
|
||||
titleHints: ['qoder cli', 'qoder'],
|
||||
iconKey: 'qoder',
|
||||
},
|
||||
] as const;
|
||||
|
||||
const PROVIDER_BY_ID = new Map(
|
||||
|
||||
@@ -78,17 +78,3 @@ test('titleHasBrailleSpinner recognizes Codex frames', () => {
|
||||
assert.equal(titleHasBrailleSpinner('⠇ my-app'), true);
|
||||
assert.equal(titleHasBrailleSpinner('my-app'), false);
|
||||
});
|
||||
|
||||
test('Antigravity branded titles and the official title script report agent activity', () => {
|
||||
assert.equal(inferCodingCliProviderFromTitleSignals('Antigravity CLI · Project'), 'agy');
|
||||
assert.equal(inferCodingCliProviderFromTitleSignals('agy · Project'), 'agy');
|
||||
assert.equal(inferCodingCliProviderFromTitleSignals('🛠️ tool_use | codex'), 'agy');
|
||||
assert.equal(inferCodingCliProviderFromTitleSignals('strategy'), undefined);
|
||||
assert.equal(shouldClearCodingCliProviderForTitle('🛠️ tool_use | project', 'agy'), false);
|
||||
assert.equal(shouldClearCodingCliProviderForTitle('user@host: /tmp/agy-project', 'agy'), true);
|
||||
assert.equal(resolveCodingCliActivityPhase('🚀 initializing | project', 'agy'), 'busy');
|
||||
assert.equal(resolveCodingCliActivityPhase('🛠️ tool_use | waiting', 'agy'), 'busy');
|
||||
assert.equal(resolveCodingCliActivityPhase('😴 idle | working', 'agy'), 'idle');
|
||||
assert.equal(resolveCodingCliActivityPhase('agy · waiting for approval', 'agy'), 'waiting');
|
||||
assert.equal(resolveCodingCliActivityPhase('tool_use', 'codex'), 'idle');
|
||||
});
|
||||
@@ -9,10 +9,6 @@ const BRAILLE_SPINNER_RE = /^[\s⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏✳✴✶✻✽❋
|
||||
const ACTION_REQUIRED_PREFIX_RE = /^\[\s*[!.]\s*\]\s*(?:Action Required\s*)?/iu;
|
||||
const LEADING_SEPARATOR_RE = /^[\s·•….]+/u;
|
||||
|
||||
// Google ships a title script with these exact emoji/state pairs. Match the
|
||||
// status before inspecting the workspace name, which could itself be "codex".
|
||||
const AGY_SCRIPT_STATE_RE = /^(?:🚀 initializing|😴 idle|🤔 thinking|🏃 working|🛠️? tool_use)\s*\|/u;
|
||||
|
||||
const CLAUDE_MARKERS = ['claude code', 'claude', 'anthropic'] as const;
|
||||
const CODEX_STATUS_WORDS = ['working', 'thinking', 'ready', 'waiting'] as const;
|
||||
const BUSY_STATUS_WORDS = ['working', 'thinking', 'running', 'compacting', 'generating'] as const;
|
||||
@@ -49,10 +45,6 @@ export function inferCodingCliProviderFromTitleSignals(title: string): CodingCli
|
||||
const raw = title.trim();
|
||||
if (!raw) return undefined;
|
||||
|
||||
if (AGY_SCRIPT_STATE_RE.test(raw)) return 'agy';
|
||||
if (!isShellPathTitle(raw) && /^(?:antigravity(?: cli)?|agy)(?:$|\s*[·|:]\s|\s+[-–—]\s)/iu.test(raw)) {
|
||||
return 'agy';
|
||||
}
|
||||
if (titleIncludesPhrase(raw, 'claude code') || raw.includes('✳') || titleIncludesPhrase(raw, 'claude')) {
|
||||
return 'claude';
|
||||
}
|
||||
@@ -60,7 +52,6 @@ export function inferCodingCliProviderFromTitleSignals(title: string): CodingCli
|
||||
if (titleIncludesPhrase(raw, 'codex') || titleIncludesPhrase(raw, 'chatgpt')) return 'codex';
|
||||
if (titleIncludesPhrase(raw, 'github copilot') || titleIncludesPhrase(raw, 'copilot')) return 'copilot';
|
||||
if (titleIncludesPhrase(raw, 'codebuddy')) return 'codebuddy';
|
||||
if (titleIncludesPhrase(raw, 'qoder')) return 'qoder';
|
||||
if (titleIncludesPhrase(raw, 'gemini')) return 'gemini';
|
||||
if (titleIncludesPhrase(raw, 'moonshot') || titleIncludesPhrase(raw, 'kimi')) return 'kimi';
|
||||
if (titleIncludesPhrase(raw, 'factory droid') || titleIncludesPhrase(raw, 'factory ai')) return 'droid';
|
||||
@@ -88,18 +79,10 @@ export function resolveCodingCliActivityPhase(
|
||||
|
||||
const normalized = normalizeCodingCliTitle(raw).toLowerCase();
|
||||
|
||||
if (providerId === 'agy' && AGY_SCRIPT_STATE_RE.test(normalized)) {
|
||||
return normalized.startsWith('😴 idle') ? 'idle' : 'busy';
|
||||
}
|
||||
|
||||
if (WAITING_STATUS_WORDS.some((word) => titleIncludesPhrase(normalized, word))) {
|
||||
return 'waiting';
|
||||
}
|
||||
|
||||
if (providerId === 'agy' && ['tool_use', 'initializing'].some(word => titleIncludesPhrase(normalized, word))) {
|
||||
return 'busy';
|
||||
}
|
||||
|
||||
if (titleHasBrailleSpinner(raw) || raw.includes('✳')) {
|
||||
return 'busy';
|
||||
}
|
||||
@@ -116,11 +99,7 @@ export function resolveCodingCliActivityPhase(
|
||||
}
|
||||
|
||||
const SHELL_TITLE_RE = /^(?:bash|zsh|fish|pwsh|powershell|sh|nu|xonsh|cmd)(?:\s|$|[(@])/i;
|
||||
const SHELL_PATH_TITLE_RE = /^(?:(?:[^@\s:]+@)?[^:\s]+:[ \t]*)?(?:~(?:\/|$)|\/|[A-Za-z]:[\\/])/;
|
||||
|
||||
function isShellPathTitle(title: string): boolean {
|
||||
return SHELL_PATH_TITLE_RE.test(title.trim());
|
||||
}
|
||||
const SHELL_PATH_TITLE_RE = /^(?:(?:[^@\s:]+@)?[^:\s]+:)?(?:~(?:\/|$)|\/|[A-Za-z]:[\\/])/;
|
||||
|
||||
/** Whether a shell-reported title no longer reflects an active coding CLI session. */
|
||||
export function shouldClearCodingCliProviderForTitle(
|
||||
@@ -134,7 +113,7 @@ export function shouldClearCodingCliProviderForTitle(
|
||||
if (inferredId === providerId) return false;
|
||||
if (inferredId) return true;
|
||||
if (SHELL_TITLE_RE.test(trimmed)) return true;
|
||||
if (isShellPathTitle(trimmed)) return true;
|
||||
if (SHELL_PATH_TITLE_RE.test(trimmed)) return true;
|
||||
|
||||
// Ambiguous titles (e.g. Codex project names) may still be an active agent session.
|
||||
return false;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import test from 'node:test';
|
||||
import { getTempFilePath } from '../electron/bridges/tempDirBridge.cjs';
|
||||
import { gitDeleteBranchCommand, gitSwitchCommand, scopeGitBranchDraft } from './terminalGitHead';
|
||||
import { gitSwitchCommand } from './terminalGitHead';
|
||||
|
||||
test('the branch command stays inside the selected worktree with another repository in the shell environment', {
|
||||
skip: process.platform !== 'darwin' && process.platform !== 'linux',
|
||||
@@ -35,46 +35,3 @@ test('the branch command stays inside the selected worktree with another reposit
|
||||
assert.equal(git(selected, 'branch', '--show-current'), 'main');
|
||||
assert.equal(git(other, 'branch', '--show-current'), 'main');
|
||||
});
|
||||
|
||||
test('branch deletion stays in the selected worktree and applies Git deletion checks', {
|
||||
skip: process.platform !== 'darwin' && process.platform !== 'linux',
|
||||
}, t => {
|
||||
const fixture = realpathSync(mkdtempSync(getTempFilePath('git-delete-')));
|
||||
t.after(() => rmSync(fixture, { recursive: true, force: true }));
|
||||
const selected = path.join(fixture, "selected repo's worktree");
|
||||
const other = path.join(fixture, 'other');
|
||||
const merged = "topic/it's-merged";
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8' }).trim();
|
||||
const commit = (cwd: string) => git(cwd, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid',
|
||||
'-c', 'commit.gpgSign=false', 'commit', '--quiet', '--allow-empty', '-m', 'fixture');
|
||||
for (const repo of [selected, other]) {
|
||||
mkdirSync(repo);
|
||||
git(repo, 'init', '--quiet', '--initial-branch=main');
|
||||
commit(repo);
|
||||
git(repo, 'branch', merged);
|
||||
}
|
||||
git(selected, 'switch', '--quiet', '-c', 'unmerged');
|
||||
commit(selected);
|
||||
git(selected, 'switch', '--quiet', 'main');
|
||||
const linked = path.join(fixture, 'linked');
|
||||
git(selected, 'worktree', 'add', '--quiet', '-b', 'occupied', linked);
|
||||
const deleteBranch = (branch: string, worktree = selected, force = false) => {
|
||||
const draft = gitDeleteBranchCommand(branch);
|
||||
assert.ok(draft);
|
||||
const text = scopeGitBranchDraft(worktree, force ? draft.replace(' -d ', ' -D ') : draft);
|
||||
assert.ok(text);
|
||||
return execFileSync('/bin/sh', ['-c', text], {
|
||||
cwd: worktree, stdio: 'pipe',
|
||||
env: { ...process.env, GIT_DIR: path.join(other, '.git'), GIT_WORK_TREE: other, GIT_COMMON_DIR: path.join(other, '.git') },
|
||||
});
|
||||
};
|
||||
assert.throws(() => deleteBranch('main'), /checked out|used by worktree/);
|
||||
assert.throws(() => deleteBranch('unmerged'), /not fully merged/);
|
||||
assert.throws(() => deleteBranch('occupied'), /checked out|used by worktree/);
|
||||
deleteBranch(merged, linked);
|
||||
assert.deepEqual(git(selected, 'branch', '--format=%(refname:short)').split('\n'), ['main', 'occupied', 'unmerged']);
|
||||
assert.equal(git(other, 'branch', '--list', merged), merged);
|
||||
deleteBranch('unmerged', selected, true);
|
||||
assert.equal(git(selected, 'branch', '--list', 'unmerged'), '');
|
||||
});
|
||||
@@ -9,37 +9,15 @@ export type TerminalGitHeadResult = TerminalGitHead | Readonly<{ kind: 'outside-
|
||||
export type TerminalGitBranchesResult = Readonly<{ kind: 'unavailable' }>
|
||||
| Readonly<{ kind: 'branches'; head: TerminalGitHead; branches: readonly string[] }>;
|
||||
|
||||
function quoteBranchName(name: string): string | null {
|
||||
export function gitSwitchCommand(worktreeRoot: string, name: string): string | null {
|
||||
// Ref names can contain shell metacharacters, including single quotes.
|
||||
if (!isAbsoluteDirectoryPath(worktreeRoot, 'posix')) return null;
|
||||
if (!name || name.startsWith('-') || name.includes('\\')
|
||||
|| Array.from(name).some(char => char.charCodeAt(0) <= 32 || char.charCodeAt(0) === 127)) return null;
|
||||
return quoteShellArgument(name);
|
||||
}
|
||||
|
||||
// Escaping backslashes outside single quotes also works in fish.
|
||||
function quoteShellArgument(value: string): string {
|
||||
return "'" + value.replace(/[\\']/g, char => "'\\" + char + "'") + "'";
|
||||
}
|
||||
|
||||
const clearGitRepositoryOverrides = 'vars=$(git rev-parse --local-env-vars) && unset $vars';
|
||||
|
||||
export function gitSwitchCommand(worktreeRoot: string, name: string): string | null {
|
||||
if (!isAbsoluteDirectoryPath(worktreeRoot, 'posix')) return null;
|
||||
const branch = quoteBranchName(name);
|
||||
if (!branch) return null;
|
||||
// Clear the shell's Git repository overrides in a child process, then pin
|
||||
// both Git paths. A missing worktree must not fall back to a parent repo.
|
||||
const script = `${clearGitRepositoryOverrides} && exec git -C "$1" --git-dir=.git --work-tree=. switch --no-guess -- "$2"`;
|
||||
return `/bin/sh -c '${script}' sh ${quoteShellArgument(worktreeRoot)} ${branch}`;
|
||||
}
|
||||
|
||||
export function gitDeleteBranchCommand(name: string): string | null {
|
||||
const branch = quoteBranchName(name);
|
||||
return branch ? `git branch -d -- ${branch}` : null;
|
||||
}
|
||||
|
||||
export function scopeGitBranchDraft(worktreeRoot: string, text: string): string | null {
|
||||
if (!isAbsoluteDirectoryPath(worktreeRoot, 'posix')) return null;
|
||||
// Keep the edited command intact and scope Git in its child shell.
|
||||
const script = `${clearGitRepositoryOverrides} && export GIT_DIR="$1/.git" GIT_WORK_TREE="$1" && exec /bin/sh -c "$2"`;
|
||||
return `/bin/sh -c '${script}' sh ${quoteShellArgument(worktreeRoot)} ${quoteShellArgument(text)}`;
|
||||
const script = 'vars=$(git rev-parse --local-env-vars) && unset $vars && exec git -C "$1" --git-dir=.git --work-tree=. switch --no-guess -- "$2"';
|
||||
// Escaping backslashes outside single quotes also works in fish.
|
||||
const quote = (value: string) => "'" + value.replace(/[\\']/g, char => "'\\" + char + "'") + "'";
|
||||
return `/bin/sh -c '${script}' sh ${quote(worktreeRoot)} ${quote(name)}`;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { getActiveGlobalDefaultProxyProfileId, publishActiveGlobalDefaultProxyProfileId } from "./globalDefaultProxy";
|
||||
import type { Host, Identity, SSHKey } from "./models";
|
||||
import { importVaultHostsFromText } from "./vaultImport";
|
||||
import { exportVaultSshConfig } from "./vaultSshConfigExport";
|
||||
|
||||
const host = (id: string, fields: Partial<Host> = {}): Host => ({
|
||||
id, label: id, hostname: id + ".test", username: "", tags: [], os: "linux", ...fields,
|
||||
});
|
||||
|
||||
test("OpenSSH export resolves group credentials, preserves jump aliases, and round trips without secrets", () => {
|
||||
const identity: Identity = { id: "admin", label: "Admin", username: "deploy", keyId: "k", authMethod: "key", created: 0 };
|
||||
const key: SSHKey = { id: "k", label: "Key", type: "ED25519", category: "key", source: "reference",
|
||||
filePath: "/keys/dev key", privateKey: "PRIVATE-DATA", passphrase: "KEY-SECRET", created: 0 };
|
||||
const hosts = [host("a", { label: "Edge", password: "HOST-SECRET" }), host("b", { label: "E dge" }),
|
||||
host("c", { label: "Edge-2" }), host("app", { group: "Work", hostChain: { hostIds: ["b"] }, useKeychain: true })];
|
||||
const { text, skippedCount } = exportVaultSshConfig(hosts, [{ path: "Work", identityId: "admin", port: 2202 }], [identity], [key]);
|
||||
assert.equal(skippedCount, 0);
|
||||
assert.match(text, /Host Edge-3\n\s+HostName b\.test/);
|
||||
assert.match(text, /ProxyJump Edge-3/);
|
||||
assert.match(text, /^IgnoreUnknown UseKeychain/);
|
||||
assert.doesNotMatch(text, /PRIVATE-DATA|KEY-SECRET|HOST-SECRET/);
|
||||
const imported = importVaultHostsFromText("ssh_config", text);
|
||||
const app = imported.hosts.find(entry => entry.hostname === "app.test");
|
||||
assert.equal(app?.port, 2202);
|
||||
assert.equal(app?.username, "deploy");
|
||||
assert.deepEqual(app?.identityFilePaths, ["/keys/dev key"]);
|
||||
assert.equal(imported.hosts.length, 4);
|
||||
});
|
||||
|
||||
test("excludes non-SSH transports, unsupported routes and their dependants", () => {
|
||||
const chain = (id: string, hop: string): Host => host(id, { hostChain: { hostIds: [hop] } });
|
||||
const dual = host("dual", { protocol: "telnet", port: 23, protocols: [{ protocol: "ssh", enabled: true, port: 2266 }] });
|
||||
const { text, skippedCount } = exportVaultSshConfig([host("serial", { protocol: "serial" }),
|
||||
host("proxy", { proxyProfileId: "proxy" }), chain("via", "proxy"), chain("nested", "via"),
|
||||
chain("loop", "loop"), chain("missing", "gone"), dual], [], [], []);
|
||||
assert.equal(skippedCount, 6);
|
||||
assert.equal(text, "Host dual\n HostName dual.test\n Port 2266\n");
|
||||
assert.equal(exportVaultSshConfig([host("local", { protocol: "local" })], [], [], []).text, "");
|
||||
});
|
||||
|
||||
test("a global proxy applies to exported routes, unless this host explicitly connects directly", (t) => {
|
||||
const previous = getActiveGlobalDefaultProxyProfileId();
|
||||
t.after(() => publishActiveGlobalDefaultProxyProfileId(previous));
|
||||
publishActiveGlobalDefaultProxyProfileId("global");
|
||||
const hosts = [host("routed"), host("direct", { directProxy: true })];
|
||||
const { text, skippedCount } = exportVaultSshConfig(hosts, [], [], [], new Set(["global"]));
|
||||
assert.equal(skippedCount, 1);
|
||||
assert.match(text, /^Host direct$/m);
|
||||
assert.doesNotMatch(text, /routed/);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { applyGroupDefaults, resolveGroupDefaults } from "./groupConfig";
|
||||
import type { GroupConfig, Host, Identity, SSHKey } from "./models";
|
||||
import { getHostEnabledProtocols } from "./remoteDesktop";
|
||||
import { resolveHostAuth } from "./sshAuth";
|
||||
import { serializeHostsToSshConfig, toSafeSshHostAlias } from "./sshConfigSerializer";
|
||||
import { canServeAsSshJumpHost } from "./terminalProtocol";
|
||||
|
||||
export function exportVaultSshConfig(
|
||||
hosts: Host[],
|
||||
groupConfigs: GroupConfig[],
|
||||
identities: Identity[],
|
||||
keys: SSHKey[],
|
||||
validProxyProfileIds?: ReadonlySet<string>,
|
||||
) {
|
||||
const inheritance = { validProxyProfileIds };
|
||||
const candidates = hosts.map(host => {
|
||||
const defaults = host.group ? resolveGroupDefaults(host.group, groupConfigs, inheritance) : {};
|
||||
return applyGroupDefaults(host, defaults, inheritance);
|
||||
}).filter(host => getHostEnabledProtocols(host).includes("ssh") && !host.proxyConfig && !host.proxyProfileId);
|
||||
|
||||
// A missing or unrepresentable jump must not turn a routed connection into a direct one.
|
||||
const byId = new Map(candidates.map(host => [host.id, host]));
|
||||
const routeAvailable = new Map<string, boolean>();
|
||||
function hasCompleteRoute(id: string): boolean {
|
||||
if (routeAvailable.has(id)) return routeAvailable.get(id)!;
|
||||
const host = byId.get(id);
|
||||
routeAvailable.set(id, false); // Break cycles.
|
||||
const available = !!host && (host.hostChain?.hostIds ?? []).every(hasCompleteRoute);
|
||||
routeAvailable.set(id, available);
|
||||
return available;
|
||||
}
|
||||
|
||||
const exportable = candidates.filter(host => hasCompleteRoute(host.id));
|
||||
// Some otherwise literal Host patterns (such as "server(prod)") cannot be used as ssh CLI arguments.
|
||||
const labels = exportable.map(host => {
|
||||
const label = host.label || host.hostname;
|
||||
const alias = toSafeSshHostAlias(label, host.hostname);
|
||||
return /^[\p{L}\p{N}._+-]+$/u.test(alias) ? label : alias.replace(/[^\p{L}\p{N}._+-]/gu, "_");
|
||||
});
|
||||
const reserved = new Set(labels.map(label => toSafeSshHostAlias(label, "").toLowerCase()));
|
||||
const used = new Set<string>();
|
||||
const entries = exportable.map((host, index) => {
|
||||
let label = labels[index];
|
||||
let alias = toSafeSshHostAlias(label, host.hostname).toLowerCase();
|
||||
if (used.has(alias)) {
|
||||
// OpenSSH uses the first matching Host block. Preserve literal aliases already in the vault.
|
||||
let suffix = 2;
|
||||
do {
|
||||
label = `${labels[index]}-${suffix++}`;
|
||||
alias = toSafeSshHostAlias(label, host.hostname).toLowerCase();
|
||||
} while (reserved.has(alias) || used.has(alias));
|
||||
}
|
||||
used.add(alias);
|
||||
const { username, identityFilePath, authMethod } = resolveHostAuth({ host, identities, keys });
|
||||
return {
|
||||
...host,
|
||||
label,
|
||||
username,
|
||||
protocol: "ssh" as const,
|
||||
port: canServeAsSshJumpHost(host)
|
||||
? host.port
|
||||
: host.protocols?.find(entry => entry.protocol === "ssh" && entry.enabled)?.port ?? 22,
|
||||
identityFilePaths: authMethod === "password"
|
||||
? undefined
|
||||
: identityFilePath ? [identityFilePath] : host.identityFilePaths,
|
||||
};
|
||||
});
|
||||
const preamble = entries.some(host => host.useKeychain !== undefined) ? "IgnoreUnknown UseKeychain\n\n" : "";
|
||||
return {
|
||||
text: entries.length ? preamble + serializeHostsToSshConfig(entries) : "",
|
||||
skippedCount: hosts.length - entries.length,
|
||||
};
|
||||
}
|
||||
@@ -118,7 +118,6 @@ module.exports = {
|
||||
'domain/systemManager/containerRuntime.shared.cjs',
|
||||
'domain/singleChannelSshBanner.shared.cjs',
|
||||
'domain/sshServerVendor.mjs',
|
||||
'domain/chatTextFile.shared.mjs',
|
||||
// sshAuthHelper.cjs requires this at load. TypeScript under domain/
|
||||
// is excluded below, so the shared TOTP runtime must be listed.
|
||||
'domain/totp.shared.cjs',
|
||||
|
||||
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