mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-12-04 08:42:31 +00:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34b7df42fb | ||
|
|
d3f328090b | ||
|
|
4501e92e55 | ||
|
|
95b9db74f7 | ||
|
|
a343cf1d8c | ||
|
|
81ecaeb75a | ||
|
|
328bd83cc9 | ||
|
|
bdd393225c | ||
|
|
0d22a31bab | ||
|
|
ae2e3e0d0d | ||
|
|
1c4545f006 | ||
|
|
b664f51731 | ||
|
|
51c317667c | ||
|
|
569b05e7fa | ||
|
|
180a1427be | ||
|
|
5c4c7e3fa8 | ||
|
|
1c41aad9ff | ||
|
|
516314f8ef | ||
|
|
43dd7a43b3 | ||
|
|
0a389e760e | ||
|
|
897c3e23e6 |
No files matched your search
@@ -166,6 +166,7 @@ If you regularly work with a fleet of servers, Netcatty is built for speed and f
|
||||
- **Fast search** — locate hosts and groups quickly
|
||||
|
||||
### 🖥️ Terminal Workspaces
|
||||
- Right-click a standalone terminal tab and choose **Convert to Workspace** to keep your running shell as the first pane.
|
||||
- **Split panes** — horizontal and vertical splits for multi-tasking
|
||||
- **Session management** — run multiple connections side-by-side
|
||||
- **Save current screen** — right-click a terminal to save the visible final text, without replaying keystrokes or overwritten output; scroll first to save an earlier screen.
|
||||
|
||||
@@ -274,7 +274,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
const {
|
||||
addShellHistoryEntry, clearAllCommandHistory, removeShellHistoryEntry, addSessionToWorkspace, addToWorkspaceDialog, appendHostToWorkspace, appendLocalTerminalToWorkspace, moveWorkspacePane,
|
||||
clearAndRemoveSource, clearAndRemoveSources, closeLogView, closeSession, closeTabsBatch, closeWorkspace, commitPluginImporterData, commitVaultImportTransaction, commitVaultGroupMutation, copySessionToNewWindowWithCurrentShell, moveSessionToNewWindow, copySessionWithCurrentShell, duplicateSessionWithCurrentShell, copyWorkspaceWithCurrentShell,
|
||||
convertKnownHostToHost, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
convertKnownHostToHost, convertSessionToWorkspace, createWorkspaceFromSessions, createWorkspaceFromTargets, createWorkspaceWithHosts,
|
||||
customGroups, currentTerminalTheme, deepLinkHostDraft, draggingSessionId, effectiveKnownHosts, editorTabs, editorWordWrap, emptyVaultConflict,
|
||||
followAppTerminalTheme,
|
||||
groupConfigs, handleAddKnownHost, handleConnectSerial, handleConnectToHost, handleConnectRemoteDesktop, handleOpenSystemRemoteDesktop, handleCreateLocalTerminal, handleDefaultTerminalThemeChange, handleDeleteHost,
|
||||
@@ -569,6 +569,7 @@ function AppViewInner({ domains }: AppViewProps) {
|
||||
tabDoubleClickBehavior={terminalSettings.tabDoubleClickBehavior}
|
||||
onCopySessionToNewWindow={copySessionToNewWindowWithCurrentShell}
|
||||
onMoveSessionToNewWindow={moveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={convertSessionToWorkspace}
|
||||
onEditHost={handleEditHostFromOverlay}
|
||||
onRenameWorkspace={startWorkspaceRename}
|
||||
onCopyWorkspace={copyWorkspaceWithCurrentShell}
|
||||
|
||||
@@ -131,6 +131,7 @@ export function ChromeHost() {
|
||||
sessionRenameTarget: session.sessionRenameTarget,
|
||||
setActiveTabId: sessionActions?.setActiveTabId,
|
||||
startSessionRename: sessionActions?.startSessionRename,
|
||||
convertSessionToWorkspace: sessionActions?.convertSessionToWorkspace,
|
||||
renameSessionInline: sessionActions?.renameSessionInline,
|
||||
startWorkspaceRename: sessionActions?.startWorkspaceRename,
|
||||
submitSessionRename: sessionActions?.submitSessionRename,
|
||||
|
||||
@@ -59,6 +59,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -148,6 +149,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
clearSessionFontSizeOverride,
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
appendHostToWorkspace,
|
||||
@@ -197,6 +199,7 @@ export function SessionPublisher({ persistSessionRestore, children }: SessionPub
|
||||
createSerialSession,
|
||||
createSessionFromCloneSource,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceWithHosts,
|
||||
getOrderedWorkTabs,
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const enAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Choose Grok mode and send…',
|
||||
'ai.chat.iterationLimitReached': 'Tool-loop limit ({limit} iterations) reached. You can continue in this chat. Running terminal jobs are not stopped.',
|
||||
'ai.chat.continue': 'Continue',
|
||||
'ai.chat.attachmentContentUnavailable': 'Content not available on this device',
|
||||
'ai.chat.deliveredTextFile.source': 'Text included in this reply',
|
||||
'ai.chat.deliveredTextFile.preview': 'Preview',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Hide preview',
|
||||
'ai.chat.deliveredTextFile.save': 'Save as',
|
||||
'ai.chat.deliveredTextFile.saving': 'Saving…',
|
||||
'ai.chat.deliveredTextFile.saved': 'File saved',
|
||||
'ai.chat.deliveredTextFile.exists': 'That file exists. Choose another name.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Could not save this file.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Saving is not available in this window.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Preview is shortened. Saving keeps the full file.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent Settings',
|
||||
'ai.chat.preparing': 'Preparing…',
|
||||
@@ -344,6 +355,10 @@ 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.',
|
||||
|
||||
@@ -10,6 +10,10 @@ 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',
|
||||
@@ -713,6 +717,7 @@ export const enTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicate Session',
|
||||
'tabs.copyTabToNewWindow': 'Copy Tab to New Window',
|
||||
'tabs.copyTabToNewWindowFailed': 'Failed to open tab in a new window',
|
||||
'tabs.convertToWorkspace': 'Convert to Workspace',
|
||||
'tabs.moveTabToNewWindow': 'Move Tab to New Window',
|
||||
'tabs.moveTabToNewWindowFailed': 'Failed to move tab to a new window',
|
||||
'tabs.closeOthers': 'Close Others',
|
||||
|
||||
@@ -882,7 +882,7 @@ export const enVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Agent Socket',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Leave empty to use SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Only Use Configured Keys',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Do not try unrelated keys currently loaded in the agent',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Match agent keys to public keys configured for this host. To use agent keys without a local public key, choose Automatic authentication and leave this off.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'System SSH agent is unavailable',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Start or unlock your SSH agent, or provide its socket path above.',
|
||||
'hostDetails.keys.search': 'Search keys...',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const esAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Elegir el modo de Grok y enviar…',
|
||||
'ai.chat.iterationLimitReached': 'Se alcanzó el límite del bucle de herramientas ({limit} iteraciones). Puedes continuar en este chat. Las tareas de terminal en ejecución no se detienen.',
|
||||
'ai.chat.continue': 'Continuar',
|
||||
'ai.chat.attachmentContentUnavailable': 'Contenido no disponible en este dispositivo',
|
||||
'ai.chat.deliveredTextFile.source': 'Texto incluido en esta respuesta',
|
||||
'ai.chat.deliveredTextFile.preview': 'Vista previa',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Ocultar vista previa',
|
||||
'ai.chat.deliveredTextFile.save': 'Guardar como',
|
||||
'ai.chat.deliveredTextFile.saving': 'Guardando…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Archivo guardado',
|
||||
'ai.chat.deliveredTextFile.exists': 'El archivo ya existe. Elige otro nombre.',
|
||||
'ai.chat.deliveredTextFile.failed': 'No se pudo guardar el archivo.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'No se puede guardar en esta ventana.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'La vista previa está abreviada. Se guarda el archivo completo.',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Configuración del agente',
|
||||
'ai.chat.preparing': 'Preparando…',
|
||||
@@ -344,6 +355,10 @@ 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.',
|
||||
|
||||
@@ -10,6 +10,10 @@ 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',
|
||||
@@ -715,6 +719,7 @@ export const esTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Duplicar sesión',
|
||||
'tabs.copyTabToNewWindow': 'Copiar pestaña a una nueva ventana',
|
||||
'tabs.copyTabToNewWindowFailed': 'No se pudo abrir la pestaña en una nueva ventana',
|
||||
'tabs.convertToWorkspace': 'Convertir en espacio de trabajo',
|
||||
'tabs.moveTabToNewWindow': 'Mover pestaña a una nueva ventana',
|
||||
'tabs.moveTabToNewWindowFailed': 'No se pudo mover la pestaña a una nueva ventana',
|
||||
'tabs.closeOthers': 'Cerrar las demás',
|
||||
|
||||
@@ -878,7 +878,7 @@ export const esVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Socket del agente',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Déjalo vacío para usar SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Usar solo las claves configuradas',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'No intentar con claves no relacionadas actualmente cargadas en el agente',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Usa las claves del agente que coincidan con las claves públicas configuradas para este host. Para usar el agente sin una clave pública local, elige la autenticación automática y desactiva esta opción.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'El agente SSH del sistema no está disponible',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Inicia o desbloquea tu agente SSH, o proporciona la ruta de su socket arriba.',
|
||||
'hostDetails.keys.search': 'Buscar claves...',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const ruAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': 'Выбрать режим Grok и отправить…',
|
||||
'ai.chat.iterationLimitReached': 'Достигнут лимит цикла инструментов ({limit} итераций). Можно продолжить в этом чате. Запущенные задачи терминала не останавливаются.',
|
||||
'ai.chat.continue': 'Продолжить',
|
||||
'ai.chat.attachmentContentUnavailable': 'Содержимое недоступно на этом устройстве',
|
||||
'ai.chat.deliveredTextFile.source': 'Текст включён в ответ',
|
||||
'ai.chat.deliveredTextFile.preview': 'Предпросмотр',
|
||||
'ai.chat.deliveredTextFile.hidePreview': 'Скрыть предпросмотр',
|
||||
'ai.chat.deliveredTextFile.save': 'Сохранить как',
|
||||
'ai.chat.deliveredTextFile.saving': 'Сохранение…',
|
||||
'ai.chat.deliveredTextFile.saved': 'Файл сохранён',
|
||||
'ai.chat.deliveredTextFile.exists': 'Файл уже существует. Выберите другое имя.',
|
||||
'ai.chat.deliveredTextFile.failed': 'Не удалось сохранить файл.',
|
||||
'ai.chat.deliveredTextFile.unavailable': 'Сохранение недоступно в этом окне.',
|
||||
'ai.chat.deliveredTextFile.previewPartial': 'Предпросмотр сокращён. Файл сохранится полностью.',
|
||||
'ai.chat.contextUsage': 'Контекст: {used} / {max} токенов',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Настройки агента',
|
||||
@@ -302,6 +313,10 @@ 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,6 +10,10 @@ 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': 'Каталоги',
|
||||
@@ -728,6 +732,7 @@ export const ruTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': 'Дублировать сессию',
|
||||
'tabs.copyTabToNewWindow': 'Копировать вкладку в новое окно',
|
||||
'tabs.copyTabToNewWindowFailed': 'Не удалось открыть вкладку в новом окне',
|
||||
'tabs.convertToWorkspace': 'Преобразовать в рабочую область',
|
||||
'tabs.moveTabToNewWindow': 'Переместить вкладку в новое окно',
|
||||
'tabs.moveTabToNewWindowFailed': 'Не удалось переместить вкладку в новое окно',
|
||||
'tabs.closeOthers': 'Закрыть остальные',
|
||||
|
||||
@@ -924,7 +924,7 @@ export const ruVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': 'Сокет агента',
|
||||
'hostDetails.systemSshAgent.socket.desc': 'Оставьте пустым, чтобы использовать SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': 'Только настроенные ключи',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Не пробовать другие ключи, загруженные в агент',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': 'Использовать ключи агента, соответствующие открытым ключам этого хоста. Чтобы использовать агент без локального открытого ключа, выберите автоматическую аутентификацию и отключите эту настройку.',
|
||||
'hostDetails.systemSshAgent.notRunning': 'Системный SSH-агент недоступен',
|
||||
'hostDetails.systemSshAgent.notRunningHint': 'Запустите или разблокируйте SSH-агент либо укажите путь к его сокету выше.',
|
||||
'hostDetails.keys.search': 'Поиск ключей...',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhCNAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '选择 Grok 模式并发送…',
|
||||
'ai.chat.iterationLimitReached': '已达到工具循环上限({limit} 次迭代)。你可以在此对话中继续,正在运行的终端任务不会停止。',
|
||||
'ai.chat.continue': '继续',
|
||||
'ai.chat.attachmentContentUnavailable': '附件内容未保留在此设备',
|
||||
'ai.chat.deliveredTextFile.source': '文件正文已包含在回复中',
|
||||
'ai.chat.deliveredTextFile.preview': '预览',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起预览',
|
||||
'ai.chat.deliveredTextFile.save': '另存为',
|
||||
'ai.chat.deliveredTextFile.saving': '正在保存…',
|
||||
'ai.chat.deliveredTextFile.saved': '文件已保存',
|
||||
'ai.chat.deliveredTextFile.exists': '文件已存在,请另选名称。',
|
||||
'ai.chat.deliveredTextFile.failed': '无法保存该文件。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此窗口不支持保存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '预览已截短,保存时保留完整文件。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 设置',
|
||||
'ai.chat.preparing': '准备中…',
|
||||
@@ -344,6 +355,10 @@ 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 路径。',
|
||||
|
||||
@@ -10,6 +10,10 @@ 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': '目录',
|
||||
@@ -817,6 +821,7 @@ export const zhCNTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '复制会话',
|
||||
'tabs.copyTabToNewWindow': '复制标签页到新窗口',
|
||||
'tabs.copyTabToNewWindowFailed': '无法在新窗口打开标签页',
|
||||
'tabs.convertToWorkspace': '转为工作区',
|
||||
'tabs.moveTabToNewWindow': '移动标签页到新窗口',
|
||||
'tabs.moveTabToNewWindowFailed': '无法将标签页移动到新窗口',
|
||||
'tabs.closeOthers': '关闭其他标签',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhCNVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理地址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空时使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '仅使用已配置的密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不尝试代理中其他无关密钥',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '只尝试与此主机已配置公钥匹配的代理密钥。如需使用代理中的密钥且本地没有公钥,请将认证方式设为“自动选择”,并关闭此选项。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系统 SSH 密钥服务不可用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '请启动或解锁密钥服务,或者在上方填写它的地址。',
|
||||
'hostDetails.keys.search': '搜索密钥…',
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import type { Messages } from '../types';
|
||||
|
||||
export const zhTWAiMessages: Messages = {
|
||||
'ai.grok.chooseModeAndSend': '選擇 Grok 模式並傳送…',
|
||||
'ai.chat.iterationLimitReached': '已達到工具迴圈上限({limit} 次迭代)。你可以在此對話中繼續,正在執行的終端工作不會停止。',
|
||||
'ai.chat.continue': '繼續',
|
||||
'ai.chat.attachmentContentUnavailable': '附件內容未保留在此裝置',
|
||||
'ai.chat.deliveredTextFile.source': '檔案正文已包含在回覆中',
|
||||
'ai.chat.deliveredTextFile.preview': '預覽',
|
||||
'ai.chat.deliveredTextFile.hidePreview': '收起預覽',
|
||||
'ai.chat.deliveredTextFile.save': '另存為',
|
||||
'ai.chat.deliveredTextFile.saving': '正在儲存…',
|
||||
'ai.chat.deliveredTextFile.saved': '檔案已儲存',
|
||||
'ai.chat.deliveredTextFile.exists': '檔案已存在,請另選名稱。',
|
||||
'ai.chat.deliveredTextFile.failed': '無法儲存此檔案。',
|
||||
'ai.chat.deliveredTextFile.unavailable': '此視窗不支援儲存。',
|
||||
'ai.chat.deliveredTextFile.previewPartial': '預覽已截短,儲存時保留完整檔案。',
|
||||
// AI Settings
|
||||
'ai.agentSettings': 'Agent 設定',
|
||||
'ai.chat.preparing': '準備中…',
|
||||
@@ -344,6 +355,10 @@ 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 路徑。',
|
||||
|
||||
@@ -10,6 +10,10 @@ 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': '目錄',
|
||||
@@ -817,6 +821,7 @@ export const zhTWTerminalMessages: Messages = {
|
||||
'tabs.duplicateSession': '複製工作階段',
|
||||
'tabs.copyTabToNewWindow': '複製分頁到新視窗',
|
||||
'tabs.copyTabToNewWindowFailed': '無法在新視窗開啟分頁',
|
||||
'tabs.convertToWorkspace': '轉為工作區',
|
||||
'tabs.moveTabToNewWindow': '移動分頁到新視窗',
|
||||
'tabs.moveTabToNewWindowFailed': '無法將分頁移動到新視窗',
|
||||
'tabs.closeOthers': '關閉其他分頁',
|
||||
|
||||
@@ -309,7 +309,7 @@ export const zhTWVaultMessages: Messages = {
|
||||
'hostDetails.systemSshAgent.socket': '代理位址',
|
||||
'hostDetails.systemSshAgent.socket.desc': '留空時使用 SSH_AUTH_SOCK',
|
||||
'hostDetails.systemSshAgent.identitiesOnly': '僅使用已設定的金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '不嘗試代理中其他無關金鑰',
|
||||
'hostDetails.systemSshAgent.identitiesOnly.desc': '僅嘗試與此主機已設定公鑰相符的代理程式金鑰。若要使用代理程式中的金鑰且本機沒有公鑰,請將驗證方式設為「自動選擇」並關閉此選項。',
|
||||
'hostDetails.systemSshAgent.notRunning': '系統 SSH 金鑰服務無法使用',
|
||||
'hostDetails.systemSshAgent.notRunningHint': '請啟動或解鎖金鑰服務,或在上方填寫其位址。',
|
||||
'hostDetails.keys.search': '搜尋金鑰…',
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
|
||||
export async function saveDeliveredChatTextFile(file: ChatTextFile): Promise<
|
||||
'saved' | 'cancelled' | 'exists' | 'failed' | 'unavailable'
|
||||
> {
|
||||
const bridge = netcattyBridge.get();
|
||||
if (!bridge?.aiChatSaveTextFile) return 'unavailable';
|
||||
try {
|
||||
const { status } = await bridge.aiChatSaveTextFile(file);
|
||||
return status === 'invalid' ? 'failed' : status;
|
||||
} catch {
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,7 @@ test('session actions register and unregister', () => {
|
||||
clearSessionFontSizeOverride: noop,
|
||||
createWorkspaceWithHosts: noop,
|
||||
createWorkspaceFromSessions: noop,
|
||||
convertSessionToWorkspace: noop,
|
||||
addSessionToWorkspace: noop,
|
||||
appendHostToWorkspace: noop,
|
||||
appendHostToWorkspaceConfirmed: noop,
|
||||
|
||||
@@ -57,6 +57,7 @@ export type SessionSnapshotActions = Pick<
|
||||
| 'clearSessionFontSizeOverride'
|
||||
| 'createWorkspaceWithHosts'
|
||||
| 'createWorkspaceFromSessions'
|
||||
| 'convertSessionToWorkspace'
|
||||
| 'addSessionToWorkspace'
|
||||
| 'moveWorkspacePane'
|
||||
| 'appendHostToWorkspace'
|
||||
|
||||
@@ -139,6 +139,7 @@ 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 { gitSwitchCommand, type TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { gitDeleteBranchCommand, gitSwitchCommand, scopeGitBranchDraft, type TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { getTerminalDirectory, subscribeTerminalDirectories, subscribeTerminalDirectoryRefresh } from './terminalDirectoryRegistry';
|
||||
import type { TerminalDirectoryController } from './terminalDirectoryController';
|
||||
@@ -9,6 +9,13 @@ 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;
|
||||
@@ -71,6 +78,16 @@ 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,
|
||||
@@ -84,15 +101,17 @@ export function useComposeGitBranch(sessionId: string) {
|
||||
} catch { /* The menu displays the unavailable state. */ }
|
||||
return { kind: 'unavailable' } as const;
|
||||
},
|
||||
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';
|
||||
}
|
||||
switchBranch(worktreeRoot: string, name: string, signal: AbortSignal) {
|
||||
return sendCommand(gitSwitchCommand(worktreeRoot, name), signal);
|
||||
},
|
||||
deleteBranchDraft(menuHead: TerminalGitHead, name: string): GitBranchCommandDraft | null {
|
||||
const { worktreeRoot } = menuHead;
|
||||
if (head?.worktreeRoot !== worktreeRoot || (menuHead.kind === 'branch' && menuHead.name === name) || !isCurrent()) return null;
|
||||
const text = gitDeleteBranchCommand(name);
|
||||
return text ? {
|
||||
text,
|
||||
send: (draft, signal) => sendCommand(scopeGitBranchDraft(worktreeRoot, draft), signal),
|
||||
} : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { GitBranchCommandDraft } from './useComposeGitBranch';
|
||||
|
||||
type DraftStatus = 'ready' | 'sending' | 'busy' | 'unavailable' | 'singleLine';
|
||||
|
||||
type DraftSnapshot = {
|
||||
text: string;
|
||||
selectionStart: number;
|
||||
selectionEnd: number;
|
||||
};
|
||||
|
||||
export function useGitBranchDraft(sessionId: string, restore: (snapshot: DraftSnapshot) => void) {
|
||||
const staged = useRef<{ draft: GitBranchCommandDraft; previous: DraftSnapshot; request?: AbortController } | null>(null);
|
||||
const [status, setStatus] = useState<DraftStatus | null>(null);
|
||||
const getDraft = useCallback(() => staged.current?.draft ?? null, []);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
const current = staged.current;
|
||||
if (!current) return;
|
||||
staged.current = null;
|
||||
current.request?.abort();
|
||||
restore(current.previous);
|
||||
}, [restore]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setStatus(null);
|
||||
return clear;
|
||||
}, [sessionId, clear]);
|
||||
|
||||
const stage = useCallback((draft: GitBranchCommandDraft, previous: DraftSnapshot) => {
|
||||
if (staged.current) return false;
|
||||
staged.current = { draft, previous };
|
||||
setStatus('ready');
|
||||
return true;
|
||||
}, []);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
clear();
|
||||
setStatus(null);
|
||||
}, [clear]);
|
||||
|
||||
const send = useCallback(async (text: string) => {
|
||||
const current = staged.current;
|
||||
if (!current || current.request || !text.trim()) return;
|
||||
// The command goes directly to the shell prompt, followed by Enter.
|
||||
if (Array.from(text).some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127)) {
|
||||
setStatus('singleLine');
|
||||
return;
|
||||
}
|
||||
const request = new AbortController();
|
||||
current.request = request;
|
||||
setStatus('sending');
|
||||
const result = await current.draft.send(text, request.signal);
|
||||
if (staged.current !== current || request.signal.aborted) return;
|
||||
current.request = undefined;
|
||||
if (result === 'sent') cancel();
|
||||
else setStatus(result);
|
||||
}, [cancel]);
|
||||
|
||||
return { status, getDraft, stage, cancel, send };
|
||||
}
|
||||
@@ -57,6 +57,40 @@ async function mountSessionState(t: test.TestContext) {
|
||||
return () => latestState;
|
||||
}
|
||||
|
||||
test('converting a standalone tab keeps the live session, tab position and focus', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
let first = '';
|
||||
let target = '';
|
||||
let last = '';
|
||||
await act(async () => {
|
||||
first = getState().createLocalTerminal();
|
||||
target = getState().createLocalTerminal({ shellName: 'Build shell' });
|
||||
last = getState().createLocalTerminal();
|
||||
});
|
||||
await act(async () => { getState().updateSessionStatus(target, 'connected'); });
|
||||
const before = getState().sessions;
|
||||
await act(async () => {
|
||||
getState().convertSessionToWorkspace(target);
|
||||
getState().convertSessionToWorkspace(target);
|
||||
});
|
||||
assert.equal(getState().workspaces.length, 1);
|
||||
const [workspace] = getState().workspaces;
|
||||
assert.equal(workspace.root.type, 'pane');
|
||||
assert.equal(workspace.root.sessionId, target);
|
||||
assert.equal(workspace.focusedSessionId, target);
|
||||
assert.deepEqual(getState().sessions, before.map(session =>
|
||||
session.id === target ? { ...session, workspaceId: workspace.id } : session));
|
||||
assert.deepEqual(getState().orderedTabs, [first, workspace.id, last]);
|
||||
assert.equal(activeTabStore.getActiveTabId(), workspace.id);
|
||||
|
||||
// A reordered editor tab must keep its place alongside terminal tabs.
|
||||
const editor = 'editor:test';
|
||||
await act(async () => { getState().reorderTabs(editor, last, 'before', [editor]); });
|
||||
await act(async () => { getState().convertSessionToWorkspace(last); });
|
||||
const secondWorkspace = getState().workspaces[1];
|
||||
assert.deepEqual(getState().getOrderedWorkTabs([editor]), [first, workspace.id, editor, secondWorkspace.id]);
|
||||
});
|
||||
|
||||
test('useSessionState issue #4249 scenario 1: repeated close focuses C -> B -> A -> vault', async (t) => {
|
||||
const getState = await mountSessionState(t);
|
||||
|
||||
|
||||
@@ -1503,6 +1503,30 @@ export const useSessionState = ({
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
const convertSessionToWorkspace = useCallback((sessionId: string) => {
|
||||
const standaloneIds = orphanSessionsRef.current.map(session => session.id);
|
||||
const workspace = createWorkspaceFromSessionIds([sessionId], {
|
||||
title: DEFAULT_WORKSPACE_TITLE,
|
||||
autoTitle: true,
|
||||
viewMode: 'focus',
|
||||
});
|
||||
|
||||
setSessions(prev => {
|
||||
const source = prev.find(session => session.id === sessionId);
|
||||
if (!source || source.workspaceId || source.hiddenFromTabs) return prev;
|
||||
|
||||
setWorkspaces(current => addWorkspaceIfMissing(current, workspace));
|
||||
setTabOrder(current => {
|
||||
if (current.includes(workspace.id)) return current;
|
||||
// Unreordered terminal tabs may only have an implicit position.
|
||||
const order = current.includes(sessionId) ? current : [...new Set([...current, ...standaloneIds])];
|
||||
return order.map(id => id === sessionId ? workspace.id : id);
|
||||
});
|
||||
setActiveTabId(workspace.id);
|
||||
return prev.map(session => session === source ? { ...session, workspaceId: workspace.id } : session);
|
||||
});
|
||||
}, [setActiveTabId]);
|
||||
|
||||
// Copy a session - creates a new session with the same host connection
|
||||
const copySession = useCallback((sessionId: string, options?: {
|
||||
localShellType?: TerminalSession['shellType'];
|
||||
@@ -1794,6 +1818,7 @@ export const useSessionState = ({
|
||||
createWorkspaceWithHosts,
|
||||
createWorkspaceFromTargets,
|
||||
createWorkspaceFromSessions,
|
||||
convertSessionToWorkspace,
|
||||
addSessionToWorkspace,
|
||||
moveWorkspacePane,
|
||||
removeSessionFromWorkspace,
|
||||
|
||||
@@ -62,6 +62,7 @@ interface AIChatPanelContentProps {
|
||||
inputValueRevision?: number;
|
||||
setInputValue: (value: string) => void;
|
||||
handleSend: (textOverride?: string) => void;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
handleSendQuickPrompt?: (promptText: string) => void;
|
||||
handleCompact: () => void;
|
||||
/** Rename a chat by id (history drawer edit affordance). Panel action, never agent content. */
|
||||
@@ -176,6 +177,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
setInputValue,
|
||||
handleSend,
|
||||
handleSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
handleCompact,
|
||||
onRenameSession,
|
||||
onRenameActiveChat,
|
||||
@@ -574,6 +576,7 @@ export const AIChatPanelContent: React.FC<AIChatPanelContentProps> = ({
|
||||
onChange={setInputValue}
|
||||
onSend={handleSend}
|
||||
onSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={onSendWithGrokMode}
|
||||
onCompact={handleCompact}
|
||||
onRenameSession={onRenameActiveChat}
|
||||
onListChats={onListChats}
|
||||
|
||||
@@ -1739,7 +1739,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
|
||||
const handleSend = useCallback(async (
|
||||
textOverride?: string,
|
||||
options?: { includeDraftAttachments?: boolean },
|
||||
options?: { includeDraftAttachments?: boolean; chooseGrokMode?: boolean },
|
||||
) => {
|
||||
const draft = currentDraftRef.current;
|
||||
const currentPanelView = panelViewRef.current;
|
||||
@@ -1964,6 +1964,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
scopeType,
|
||||
scopeTargetId,
|
||||
existingSessionId: existingExternalSessionId,
|
||||
chooseGrokMode: options?.chooseGrokMode,
|
||||
updateExternalSessionId: updateSessionExternalSessionId,
|
||||
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
|
||||
terminalSessions,
|
||||
@@ -2189,6 +2190,10 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
return registerGrantPersister((rule) => { addGrant(rule); });
|
||||
}, [addGrant]);
|
||||
|
||||
const handleSendWithGrokMode = useCallback((text: string) => {
|
||||
void handleSend(text, { includeDraftAttachments: true, chooseGrokMode: true });
|
||||
}, [handleSend]);
|
||||
|
||||
const handleSendQuickPrompt = useCallback((promptText: string) => {
|
||||
void handleSend(promptText, { includeDraftAttachments: true });
|
||||
}, [handleSend]);
|
||||
@@ -2654,6 +2659,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setInputValue={setInputValue}
|
||||
handleSend={handleSend}
|
||||
handleSendQuickPrompt={handleSendQuickPrompt}
|
||||
onSendWithGrokMode={getExternalAgentSdkBackend(currentAgentConfig ?? undefined) === 'grok' && currentAgentConfig?.grokRuntime !== 'streaming-json' ? handleSendWithGrokMode : undefined}
|
||||
handleCompact={handleCompact}
|
||||
onRenameSession={handleRenameSession}
|
||||
onRenameActiveChat={handleRenameSlashCommand}
|
||||
|
||||
@@ -383,8 +383,8 @@ const ConnectionLogsManager: React.FC<ConnectionLogsManagerProps> = ({
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium transition-colors cursor-pointer",
|
||||
active
|
||||
? "bg-primary/12 text-primary border border-primary/25"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60 border border-transparent",
|
||||
? "bg-primary/12 text-primary"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-secondary/60",
|
||||
)}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
+12
-16
@@ -802,6 +802,13 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
? 'select'
|
||||
: 'connect';
|
||||
|
||||
const activation = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
|
||||
return (
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>
|
||||
@@ -837,17 +844,11 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
if (!ids) e.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
if (activation === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (action === 'select') {
|
||||
if (activation === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -856,17 +857,11 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return;
|
||||
event.preventDefault();
|
||||
const action = resolveHostActivateAction({
|
||||
behavior: normalizedHostClickBehavior,
|
||||
isMultiSelectMode: Boolean(isMultiSelectMode),
|
||||
focusedHostId,
|
||||
hostId: host.id,
|
||||
});
|
||||
if (action === 'toggle-multi') {
|
||||
if (activation === 'toggle-multi') {
|
||||
toggleHostSelection?.(host.id);
|
||||
return;
|
||||
}
|
||||
if (action === 'select') {
|
||||
if (activation === 'select') {
|
||||
onFocusHost?.(host.id);
|
||||
return;
|
||||
}
|
||||
@@ -980,6 +975,7 @@ const HostTreeItem: React.FC<HostTreeItemProps> = ({
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<HostTreeHostContextMenuContent
|
||||
enterConnects={activation === 'connect'}
|
||||
host={host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
|
||||
@@ -624,13 +624,55 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<VaultPageHeader>
|
||||
<div className="flex-1 min-w-0 flex items-center gap-2">
|
||||
<div className="flex-1 min-w-0 flex flex-wrap items-center gap-2">
|
||||
<VaultHeaderSearch
|
||||
placeholder={t("knownHosts.search.placeholder")}
|
||||
className="flex-1 max-w-xs"
|
||||
className="flex-1 min-w-[160px] max-w-xs"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex h-10 shrink-0 items-center rounded-md bg-secondary/70 p-1 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex h-full items-center gap-1.5 rounded-sm px-2.5 text-xs font-medium whitespace-nowrap transition-all cursor-pointer",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{/* View Mode Toggle */}
|
||||
@@ -720,52 +762,6 @@ const KnownHostsManager: React.FC<KnownHostsManagerProps> = ({
|
||||
)}
|
||||
</VaultPageHeader>
|
||||
|
||||
{/* Segmented Tab Strip: SSH Host Keys | Remote Desktop Certificates */}
|
||||
<div className="px-4 py-2 border-b border-border/50 bg-background/60 shrink-0">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={t("vault.nav.knownHosts")}
|
||||
className="inline-flex items-center rounded-lg bg-secondary/70 p-0.5 gap-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "ssh"}
|
||||
data-known-hosts-tab="ssh"
|
||||
onClick={() => setActiveTab("ssh")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "ssh"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.ssh")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{filteredHosts.length}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={activeTab === "certs"}
|
||||
data-known-hosts-tab="certs"
|
||||
onClick={() => setActiveTab("certs")}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-all",
|
||||
activeTab === "certs"
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<span>{t("knownHosts.tabs.remoteDesktopCerts")}</span>
|
||||
<span className="rounded-full bg-secondary px-1.5 py-0 text-[10px] tabular-nums text-muted-foreground">
|
||||
{remoteCerts.length}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<ScrollArea className="flex-1">
|
||||
{activeTab === "certs" ? (
|
||||
|
||||
@@ -712,7 +712,7 @@ const QuickSwitcherInner: React.FC<QuickSwitcherProps> = ({
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger asChild>{hostRow}</ContextMenuTrigger>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onSelect(host)}>
|
||||
<ContextMenuItem shortcut={isSelected ? "Enter" : undefined} onClick={() => onSelect(host)}>
|
||||
{t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onEditHost(host)}>
|
||||
|
||||
+48
-31
@@ -1,6 +1,7 @@
|
||||
import { Folder, FolderLock, Lock, Menu, MoreHorizontal, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import { Folder, FolderLock, Lock, Menu, Plus, Settings, Sparkles } from 'lucide-react';
|
||||
import React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
|
||||
import { activeTabStore, fromEditorTabId, isEditorTabId, toEditorTabId } from '../application/state/activeTabStore';
|
||||
import { applySessionPresentation } from '../application/state/sessionPresentationStore';
|
||||
import { topTabsSessionsEqual } from '../domain/topTabsSessionsEqual';
|
||||
import { isHostTreeWorkTabSurface } from '../application/app/workTabSurface';
|
||||
import { buildTabShortcutNumberById } from '../application/app/tabShortcutTargets';
|
||||
@@ -35,6 +36,8 @@ import { GlobalSftpTransferCenter } from './GlobalSftpTransferCenter';
|
||||
import { TopTabsQuickControls } from './TopTabsQuickControls';
|
||||
import {
|
||||
ActiveTabAutoScroller,
|
||||
formatSessionTopTabLabel,
|
||||
resolveWorkspaceTopTabLabel,
|
||||
EditorTopTab,
|
||||
LogViewTopTab,
|
||||
PluginViewTopTab,
|
||||
@@ -53,6 +56,7 @@ import {
|
||||
scheduleAfterInstantThemeSwitch,
|
||||
scheduleChromeLayoutAnimation,
|
||||
} from '../application/state/useActiveChromeTheme';
|
||||
import { TopTabOverflowMenu, type OverflowTab } from './top-tabs/TopTabOverflowMenu';
|
||||
import { useTopTabLifecycleAnimations } from './top-tabs/useTopTabLifecycleAnimations';
|
||||
|
||||
// Helper styles for Electron drag regions (use type assertion to include non-standard WebkitAppRegion)
|
||||
@@ -191,6 +195,7 @@ interface TopTabsProps {
|
||||
onCopySession: (sessionId: string) => void;
|
||||
onDuplicateSession?: (sessionId: string) => void;
|
||||
onCopySessionToNewWindow: (sessionId: string) => void;
|
||||
onConvertSessionToWorkspace?: (sessionId: string) => void;
|
||||
onMoveSessionToNewWindow?: (sessionId: string) => void;
|
||||
onEditHost?: (host: Host) => void;
|
||||
onRenameWorkspace: (workspaceId: string) => void;
|
||||
@@ -249,6 +254,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
onRenameWorkspace,
|
||||
onCopyWorkspace,
|
||||
@@ -856,6 +862,42 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
}).filter(Boolean);
|
||||
}, [orderedTabs, editorTabMap, pluginViewTabMap, orphanSessionMap, workspaceMap, logViewMap, workspacePaneCounts]);
|
||||
|
||||
const getOverflowTabs = (): OverflowTab[] => {
|
||||
const tabs: OverflowTab[] = [{ id: 'vault', label: 'Vaults' }];
|
||||
if (showSftpTab) tabs.push({ id: 'sftp', label: 'SFTP' });
|
||||
for (const item of orderedTabItems) {
|
||||
if (!item) continue;
|
||||
const { id } = item;
|
||||
switch (item.type) {
|
||||
case 'session':
|
||||
tabs.push({ id, label: formatSessionTopTabLabel(applySessionPresentation(item.session), dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'workspace':
|
||||
tabs.push({ id, label: resolveWorkspaceTopTabLabel(item.workspace, workspaceTabSessions.get(id)?.sessions ?? [], dynamicTabTitleMode) });
|
||||
break;
|
||||
case 'editor': {
|
||||
const editor = item.editorTab;
|
||||
tabs.push({
|
||||
id,
|
||||
label: (editorTabFileNameCounts.get(editor.fileName) ?? 0) > 1 ? editor.remotePath : editor.fileName,
|
||||
activate: editor.placement === 'window' ? () => onFocusEditorWindowTab?.(editor.id) : undefined,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'pluginView':
|
||||
tabs.push({ id, label: item.pluginViewTab.title });
|
||||
break;
|
||||
case 'logView': {
|
||||
const { protocol, hostname } = item.logView.log;
|
||||
const host = protocol === 'local' || hostname === 'localhost' ? t('tabs.logLocal') : hostname;
|
||||
tabs.push({ id, label: `${t('tabs.logPrefix')} ${host}` });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return tabs;
|
||||
};
|
||||
|
||||
// Bulk-close menu items shared by session and workspace context menus.
|
||||
// Anchor is the tab the user right-clicked on (matches VSCode/JetBrains UX).
|
||||
const renderBulkCloseItems = useCallback((anchorId: string) => {
|
||||
@@ -992,6 +1034,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
onDuplicateSession={onDuplicateSession}
|
||||
onCopySessionToNewWindow={onCopySessionToNewWindow}
|
||||
onMoveSessionToNewWindow={onMoveSessionToNewWindow}
|
||||
onConvertSessionToWorkspace={onConvertSessionToWorkspace}
|
||||
onEditHost={onEditHost}
|
||||
renderBulkCloseItems={renderBulkCloseItems}
|
||||
dynamicTabTitleMode={dynamicTabTitleMode}
|
||||
@@ -1210,17 +1253,11 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
)}
|
||||
|
||||
<div className="relative min-w-0 flex-1 flex app-drag" style={dragRegionStyle}>
|
||||
{/* Left fade mask */}
|
||||
{canScrollLeft && (
|
||||
<div
|
||||
className="absolute left-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to right, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Scrollable container */}
|
||||
<div
|
||||
ref={tabsContainerRef}
|
||||
data-fade-left={canScrollLeft || undefined}
|
||||
data-fade-right={canScrollRight || undefined}
|
||||
className="top-tab-scroll-viewport min-w-0 flex items-end gap-0 overflow-x-auto scrollbar-none app-no-drag max-w-full"
|
||||
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none', ...noDragRegionStyle }}
|
||||
onClick={handleScrollableTabClick}
|
||||
@@ -1255,14 +1292,6 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* Keep unused space and the drag handle outside the scroll viewport's exclusion. */}
|
||||
<div className="flex-1 app-drag" style={dragRegionStyle} />
|
||||
<div className="min-w-[20px] h-7 app-drag flex-shrink-0 self-end" style={dragRegionStyle} />
|
||||
|
||||
{/* Right fade mask */}
|
||||
{canScrollRight && (
|
||||
<div
|
||||
className="absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10"
|
||||
style={{ background: 'linear-gradient(to left, var(--top-tabs-bg, hsl(var(--secondary))), transparent)' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -1270,20 +1299,7 @@ const TopTabsInner: React.FC<TopTabsProps> = ({
|
||||
{/* More tabs button - only when overflowing */}
|
||||
{hasOverflow && (
|
||||
<div className="contents" data-section="top-tabs-toolbar-actions">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7 flex-shrink-0 app-no-drag self-end rounded-none"
|
||||
style={{ color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))' }}
|
||||
onClick={onOpenQuickSwitcher}
|
||||
>
|
||||
<MoreHorizontal size={14} />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{t('topTabs.moreTabs')}</TooltipContent>
|
||||
</Tooltip>
|
||||
<TopTabOverflowMenu getTabs={getOverflowTabs} onOpenQuickSwitcher={onOpenQuickSwitcher} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1391,6 +1407,7 @@ export const topTabsAreEqual = (prev: TopTabsProps, next: TopTabsProps): boolean
|
||||
prev.onCopySession === next.onCopySession &&
|
||||
prev.onDuplicateSession === next.onDuplicateSession &&
|
||||
prev.onCopySessionToNewWindow === next.onCopySessionToNewWindow &&
|
||||
prev.onConvertSessionToWorkspace === next.onConvertSessionToWorkspace &&
|
||||
prev.onMoveSessionToNewWindow === next.onMoveSessionToNewWindow &&
|
||||
prev.onEditHost === next.onEditHost &&
|
||||
prev.onAppendHostToWorkspace === next.onAppendHostToWorkspace &&
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { I18nProvider } from '../../application/i18n/I18nProvider';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
|
||||
test('a completed reply has file actions but a streaming reply does not', () => {
|
||||
const content = '```netcatty-file\n{"name":"report.md","content":"# Example content"}\n```';
|
||||
const render = (isAnimating: boolean) => renderToStaticMarkup(
|
||||
<I18nProvider locale="en"><ChatFileReply content={content} isAnimating={isAnimating} /></I18nProvider>,
|
||||
);
|
||||
const completed = render(false);
|
||||
assert.match(completed, /data-chat-text-file/);
|
||||
assert.match(completed, /report\.md/);
|
||||
assert.match(completed, /Save as/);
|
||||
assert.match(completed, /Preview/);
|
||||
assert.doesNotMatch(completed, /# Example content/);
|
||||
assert.doesNotMatch(render(true), /data-chat-text-file/);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Download, FileText } from 'lucide-react';
|
||||
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { saveDeliveredChatTextFile } from '../../application/state/chatTextFileDelivery';
|
||||
import type { ChatTextFile } from '../../domain/chatTextFile.shared.mjs';
|
||||
import { splitChatTextFileOffers } from '../../domain/chatTextFileOffers';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
|
||||
const previewLimit = 32 * 1024;
|
||||
|
||||
function ChatFileOffer({ file }: { file: ChatTextFile }) {
|
||||
const { t } = useI18n();
|
||||
const [preview, setPreview] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [status, setStatus] = useState<'saved' | 'exists' | 'failed' | 'unavailable'>();
|
||||
const saveFile = async () => {
|
||||
setStatus(undefined);
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await saveDeliveredChatTextFile(file);
|
||||
if (result !== 'cancelled') setStatus(result);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="my-2 min-w-0 rounded-md border border-border bg-muted/35 px-3 py-2" data-chat-text-file>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="flex min-w-0 flex-1 items-start gap-2 text-sm">
|
||||
<FileText size={16} aria-hidden="true" className="mt-0.5 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0">
|
||||
<div className="break-all font-semibold">{file.name}</div>
|
||||
<div className="text-muted-foreground">{t('ai.chat.deliveredTextFile.source')}</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="rounded px-1 py-0.5 text-sm underline focus-visible:outline-2 focus-visible:outline-ring"
|
||||
aria-expanded={preview} onClick={() => setPreview(value => !value)}
|
||||
>{t(`ai.chat.deliveredTextFile.${preview ? 'hidePreview' : 'preview'}`)}</button>
|
||||
<button type="button" className="inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-60"
|
||||
disabled={saving} onClick={() => { void saveFile(); }}
|
||||
><Download size={14} aria-hidden="true" />{t(`ai.chat.deliveredTextFile.${saving ? 'saving' : 'save'}`)}</button>
|
||||
</div>
|
||||
{status && <p role="status" className="mt-2 text-sm">{t(`ai.chat.deliveredTextFile.${status}`)}</p>}
|
||||
{preview && (
|
||||
<>
|
||||
<pre className="mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm border border-border bg-background px-2 py-1 font-mono text-xs">{file.content.slice(0, previewLimit)}</pre>
|
||||
{file.content.length > previewLimit && <p className="mt-1 text-sm text-muted-foreground">{t('ai.chat.deliveredTextFile.previewPartial')}</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatFileReply({ content, isAnimating }: { content: string; isAnimating?: boolean }) {
|
||||
const parsed = useMemo(() => isAnimating ? null : splitChatTextFileOffers(content), [content, isAnimating]);
|
||||
if (!parsed?.files.length) return <LazyMessageResponse isAnimating={isAnimating}>{content}</LazyMessageResponse>;
|
||||
return (
|
||||
<>
|
||||
{parsed.markdown.trim() && <LazyMessageResponse>{parsed.markdown}</LazyMessageResponse>}
|
||||
{parsed.files.map((file, index) => <ChatFileOffer key={`${index}:${file.name}`} file={file} />)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -263,6 +263,7 @@ interface ChatInputProps {
|
||||
hosts?: Array<{ sessionId: string; hostname: string; label: string; connected: boolean; protocol?: string }>;
|
||||
/** Explicit signal that the active tab/scope is a VNC or RDP remote desktop. */
|
||||
isRemoteDesktopContext?: boolean;
|
||||
onSendWithGrokMode?: (text: string) => void;
|
||||
/** Optional handler invoked when a remote desktop quick prompt chip is clicked. */
|
||||
onSendQuickPrompt?: (promptText: string) => void;
|
||||
/** Force-show remote desktop quick prompt chips (auto-shown when a remote screen image is attached). */
|
||||
@@ -342,6 +343,7 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
hosts = [],
|
||||
isRemoteDesktopContext = false,
|
||||
onSendQuickPrompt,
|
||||
onSendWithGrokMode,
|
||||
showRemoteScreenQuickPrompts,
|
||||
notes = [],
|
||||
onMentionNote,
|
||||
@@ -1689,6 +1691,22 @@ const ChatInput: React.FC<ChatInputProps> = ({
|
||||
<span className="flex-1 text-foreground/85">{t('ai.chat.menuMentionHost')}</span>
|
||||
{hosts.length > 0 && <ChevronRight size={10} className="text-muted-foreground/50" />}
|
||||
</button>
|
||||
{onSendWithGrokMode && (
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
disabled={composerDisabled || isStreaming || (!hasTextStore.get() && !hasTerminalSelectionAttachment && !hasImageAttachment)}
|
||||
onClick={() => {
|
||||
const text = readComposerText();
|
||||
closeAllMenus();
|
||||
onSendWithGrokMode(text);
|
||||
}}
|
||||
className="w-full flex items-center gap-2.5 px-3 py-1.5 text-left text-[12px] hover:bg-muted/30 cursor-pointer whitespace-nowrap disabled:opacity-40"
|
||||
>
|
||||
<MessageSquare size={13} className="text-muted-foreground/60" />
|
||||
{t('ai.grok.chooseModeAndSend')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
role="menuitem"
|
||||
@@ -2026,6 +2044,7 @@ function chatInputPropsAreEqual(prev: ChatInputProps, next: ChatInputProps): boo
|
||||
&& prev.onRemoveFile === next.onRemoveFile
|
||||
&& prev.hosts === next.hosts
|
||||
&& prev.isRemoteDesktopContext === next.isRemoteDesktopContext
|
||||
&& prev.onSendWithGrokMode === next.onSendWithGrokMode
|
||||
&& prev.onSendQuickPrompt === next.onSendQuickPrompt
|
||||
&& prev.showRemoteScreenQuickPrompts === next.showRemoteScreenQuickPrompts
|
||||
&& prev.notes === next.notes
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ConversationContent,
|
||||
ConversationScrollButton,
|
||||
} from '../ai-elements/conversation';
|
||||
import { LazyMessageResponse } from '../ai-elements/LazyMessageResponse';
|
||||
import { ChatFileReply } from './ChatFileReply';
|
||||
import { Message, MessageContent } from '../ai-elements/messageShell';
|
||||
import { warmAiMarkdownRenderer } from './aiMarkdownWarmup';
|
||||
import { ToolCall } from '../ai-elements/tool-call';
|
||||
@@ -833,9 +833,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
: (
|
||||
<React.Profiler {...getAIPanelProfilerProps('AIChatPanel.Markdown')}>
|
||||
<div data-ai-content="markdown">
|
||||
<LazyMessageResponse isAnimating={!!isThisStreaming}>
|
||||
{message.content}
|
||||
</LazyMessageResponse>
|
||||
<ChatFileReply content={message.content} isAnimating={!!isThisStreaming} />
|
||||
</div>
|
||||
</React.Profiler>
|
||||
)
|
||||
@@ -1036,7 +1034,7 @@ const ChatMessageList: React.FC<ChatMessageListProps> = ({
|
||||
))}
|
||||
{(Array.from(pendingCodebuddyElicitations.values()) as CodebuddyElicitation[])
|
||||
.filter((elicitation) => elicitation.chatSessionId === activeSessionId
|
||||
|| (!activeSessionId && elicitation.request.source !== 'grok'))
|
||||
|| (!activeSessionId && !elicitation.request.source))
|
||||
.map((elicitation) => (
|
||||
<CodebuddyElicitationCard
|
||||
key={`${elicitation.elicitationId}:${elicitation.requestInstanceId ?? 0}`}
|
||||
|
||||
@@ -57,7 +57,8 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const isGrokQuestion = elicitation.request.source === 'grok';
|
||||
const formValues = isGrokQuestion
|
||||
const isNativeQuestion = Boolean(elicitation.request.source);
|
||||
const formValues = isNativeQuestion
|
||||
? Object.fromEntries(Object.entries(values).map(([id, value]) =>
|
||||
[id, typeof value === 'string' ? value.trim() : value]))
|
||||
: values;
|
||||
@@ -96,10 +97,11 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
<div className="flex items-start gap-2">
|
||||
<MessageCircleQuestion size={16} className="mt-0.5 shrink-0 text-blue-500" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t(isGrokQuestion
|
||||
? 'ai.grok.userQuestion.title' : 'ai.codebuddy.elicitation.title')}</div>
|
||||
<div className="text-sm font-medium">{t(isGrokQuestion ? 'ai.grok.userQuestion.title'
|
||||
: elicitation.request.source === 'opencode-native' ? 'ai.opencode.userQuestion.title'
|
||||
: 'ai.codebuddy.elicitation.title')}</div>
|
||||
<div className="text-xs text-muted-foreground leading-5">
|
||||
{elicitation.request.message || t(isGrokQuestion
|
||||
{elicitation.request.message || t(isNativeQuestion
|
||||
? 'ai.grok.userQuestion.description' : 'ai.codebuddy.elicitation.description')}
|
||||
</div>
|
||||
</div>
|
||||
@@ -256,7 +258,7 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
{!isGrokQuestion && <Button
|
||||
{!isNativeQuestion && <Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={submitting}
|
||||
@@ -272,7 +274,7 @@ export const CodebuddyElicitationCard: React.FC<{
|
||||
buildCodebuddyElicitationContent(formValues, fields),
|
||||
)}
|
||||
>
|
||||
{t(isGrokQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
{t(isNativeQuestion ? 'ai.grok.userQuestion.submit' : 'ai.codebuddy.elicitation.accept')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -40,6 +40,21 @@ test('buildManagedAgentState removes stale managed agents when path detection fa
|
||||
assert.equal(state.defaultAgentId, 'catty');
|
||||
});
|
||||
|
||||
test('a temporary unavailable probe preserves the per-agent question preference', () => {
|
||||
for (const key of ['codex', 'codebuddy', 'opencode'] as const) {
|
||||
const id = `discovered_${key}`;
|
||||
const state = buildManagedAgentState([{
|
||||
id, name: key, command: key, enabled: true, sdkBackend: key, allowNativeUserQuestions: true,
|
||||
}], id, key, null);
|
||||
assert.equal(state.agents[0]?.available, false);
|
||||
assert.equal(state.agents[0]?.allowNativeUserQuestions, true);
|
||||
const recovered = buildManagedAgentState(state.agents, id, key, {
|
||||
available: true, path: key, version: '1.0',
|
||||
});
|
||||
assert.equal(recovered.agents[0]?.allowNativeUserQuestions, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('buildManagedAgentState keeps unrelated defaults when removing stale managed agents', () => {
|
||||
const agents: ExternalAgentConfig[] = [
|
||||
{
|
||||
|
||||
@@ -123,9 +123,10 @@ export const OpenHostBrowserMenuItem: React.FC<{ host: Host; onOpenBrowser?: (ho
|
||||
};
|
||||
|
||||
export const HostTreeHostContextMenuContent: React.FC<
|
||||
HostTreeHostContextMenuHandlers & { host: Host }
|
||||
HostTreeHostContextMenuHandlers & { host: Host; enterConnects?: boolean }
|
||||
> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
onConnect,
|
||||
onConnectRemoteDesktop,
|
||||
onOpenSystemRemoteDesktop,
|
||||
@@ -153,7 +154,7 @@ export const HostTreeHostContextMenuContent: React.FC<
|
||||
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onConnect(safeHost)}>
|
||||
<ContextMenuItem shortcut={enterConnects ? 'Enter' : undefined} onClick={() => onConnect(safeHost)}>
|
||||
<Monitor className="mr-2 h-4 w-4" /> {t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<OpenDualPaneSftpMenuItem host={safeHost} />
|
||||
|
||||
@@ -766,6 +766,12 @@ 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";
|
||||
@@ -1161,6 +1167,15 @@ 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
|
||||
@@ -1202,7 +1217,7 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
<SettingsSection
|
||||
anchorId="ai-agy"
|
||||
title={t('ai.agy.title')}
|
||||
leading={<AgentIconBadge agent={{ id: "agy", icon: "google", name: "Antigravity CLI" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
|
||||
leading={<AgentIconBadge agent={{ id: "agy", icon: "agy", name: "Antigravity CLI" }} variant="plain" className="h-5 w-5 text-muted-foreground/90" />}
|
||||
>
|
||||
<CopilotCliCard
|
||||
pathInfo={agyPathInfo}
|
||||
@@ -1244,6 +1259,16 @@ 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
|
||||
@@ -1286,6 +1311,15 @@ 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,6 +59,13 @@ 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: "google",
|
||||
icon: "agy",
|
||||
sdkBackend: "agy",
|
||||
},
|
||||
mimo: {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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,
|
||||
@@ -318,13 +319,15 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
}, [filesByName, pane.connection?.id, pane.connection?.currentPath]);
|
||||
|
||||
const renderRow = useCallback(
|
||||
(entry: SftpFileEntry, index: number) => (
|
||||
<ContextMenu>
|
||||
(entry: SftpFileEntry, index: number) => {
|
||||
const selected = pane.selectedFiles.has(entry.name);
|
||||
const keyboardTargetsEntry = isPaneFocused && selected && pane.selectedFiles.size === 1;
|
||||
return <ContextMenu>
|
||||
<ContextMenuTrigger>
|
||||
<SftpFileRow
|
||||
entry={entry}
|
||||
index={index}
|
||||
isSelected={pane.selectedFiles.has(entry.name)}
|
||||
isSelected={selected}
|
||||
showSelectionHighlight={isPaneFocused}
|
||||
isDragOver={dragOverEntry === entry.name}
|
||||
columnWidths={columnWidths}
|
||||
@@ -345,6 +348,7 @@ 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" />}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
@@ -356,6 +360,7 @@ 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 && (
|
||||
@@ -488,6 +493,7 @@ 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)}>
|
||||
@@ -506,13 +512,16 @@ 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")}
|
||||
@@ -541,8 +550,8 @@ export const SftpPaneFileList: React.FC<SftpPaneFileListProps> = React.memo(({
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
)}
|
||||
</ContextMenu>
|
||||
),
|
||||
</ContextMenu>;
|
||||
},
|
||||
[
|
||||
columnWidths,
|
||||
visibleColumns,
|
||||
@@ -818,9 +827,11 @@ 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,6 +48,7 @@ export const getSftpTreeEntryOpenAction = (
|
||||
export const SftpPaneTreeView = React.memo<SftpPaneTreeViewProps>(({
|
||||
pane,
|
||||
side,
|
||||
isPaneFocused = true,
|
||||
onPrepareSelection,
|
||||
onLoadChildren,
|
||||
onMoveEntriesToPath,
|
||||
@@ -954,7 +955,11 @@ 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,6 +7,7 @@ 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,6 +43,7 @@ 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);
|
||||
@@ -535,3 +536,76 @@ 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,6 +664,7 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
|
||||
data-section="terminal-sftp-tree"
|
||||
>
|
||||
<SftpPaneTreeView
|
||||
isPaneFocused={effectiveIsPaneFocused}
|
||||
pane={pane}
|
||||
side={side}
|
||||
onPrepareSelection={callbacks.onPrepareSelection}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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';
|
||||
@@ -34,6 +35,7 @@ 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,
|
||||
@@ -54,6 +56,8 @@ 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);
|
||||
@@ -108,10 +112,12 @@ 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 && (
|
||||
@@ -200,6 +206,7 @@ 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)}>
|
||||
@@ -211,15 +218,17 @@ 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(isDir ? entryPath : getParentPath(entryPath))}>
|
||||
<ContextMenuItem onClick={() => openNewFolderDialogRef.current(createDirectory)}>
|
||||
<FolderPlus size={14} className="mr-2" />{tRef.current('sftp.newFolder')}
|
||||
{isPaneFocused && createDirectory === pane.connection?.currentPath && <BoundMenuShortcut action="sftpNewFolder" />}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => openNewFileDialogRef.current(isDir ? entryPath : getParentPath(entryPath))}>
|
||||
<ContextMenuItem onClick={() => openNewFileDialogRef.current(createDirectory)}>
|
||||
<FilePlus size={14} className="mr-2" />{tRef.current('sftp.newFile')}
|
||||
</ContextMenuItem>
|
||||
{uploadEnabled && (
|
||||
@@ -243,7 +252,11 @@ export function useSftpPaneTreeContextMenu(props: SftpPaneTreeContextMenuProps)
|
||||
</ContextMenuContent>
|
||||
);
|
||||
}, [
|
||||
isPaneFocused,
|
||||
keyboardSelectionContainsTarget,
|
||||
keyboardTargetsEntry,
|
||||
contextTarget,
|
||||
pane.connection?.currentPath,
|
||||
pane.connection?.isLocal,
|
||||
pane.connection?.id,
|
||||
toggleExpand,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { Check, ChevronDown, GitBranch, LoaderCircle } from 'lucide-react';
|
||||
import { Check, ChevronDown, GitBranch, LoaderCircle, Trash2 } from 'lucide-react';
|
||||
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../../application/i18n/I18nProvider';
|
||||
import { useComposeGitBranch } from '../../application/state/useComposeGitBranch';
|
||||
import { useComposeGitBranch, type GitBranchCommandDraft } from '../../application/state/useComposeGitBranch';
|
||||
import type { TerminalGitHead } from '../../domain/terminalGitHead';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
|
||||
import type { ComposeBarTheme } from './TerminalComposeBar';
|
||||
|
||||
@@ -10,6 +11,7 @@ type Menu = {
|
||||
scope: ReturnType<typeof useComposeGitBranch>['scope'];
|
||||
root: string;
|
||||
branches: readonly string[];
|
||||
head?: TerminalGitHead;
|
||||
status: 'loading' | 'ready' | 'sending' | 'busy' | 'unavailable';
|
||||
};
|
||||
|
||||
@@ -17,8 +19,10 @@ 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 }: {
|
||||
export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus, onDraftCommand, draftPending }: {
|
||||
sessionId: string; theme: ComposeBarTheme; onReturnFocus: () => void;
|
||||
onDraftCommand: (draft: GitBranchCommandDraft) => boolean;
|
||||
draftPending: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const model = useComposeGitBranch(sessionId);
|
||||
@@ -63,7 +67,7 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
|
||||
return <div data-compose-git-branch role="group" aria-label={label} title={label} className={chipClass} style={chipStyle}>{chipContent}</div>;
|
||||
}
|
||||
|
||||
const currentBranch = head.kind === 'branch' ? head.name : null;
|
||||
const currentBranch = current?.head?.kind === 'branch' ? current.head.name : null;
|
||||
const canSelect = current?.status === 'ready' || current?.status === 'busy';
|
||||
|
||||
function closeMenu() {
|
||||
@@ -71,6 +75,12 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
|
||||
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;
|
||||
@@ -81,7 +91,7 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
|
||||
setMenu(pending);
|
||||
const result = await model.list(head.worktreeRoot);
|
||||
setMenu(value => value !== pending ? value : result.kind === 'branches'
|
||||
? { ...pending, status: 'ready', branches: result.branches }
|
||||
? { ...pending, status: 'ready', head: result.head, branches: result.branches }
|
||||
: { ...pending, status: result.kind });
|
||||
}
|
||||
|
||||
@@ -140,27 +150,45 @@ export function ComposeGitBranchChip({ sessionId, theme, onReturnFocus }: {
|
||||
if (viewport.current) viewport.current.scrollTop = 0;
|
||||
}}
|
||||
role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls={listId}
|
||||
aria-activedescendant={filtered[selected] ? `${listId}-${selected}` : undefined}
|
||||
aria-haspopup="grid" 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="listbox" aria-label={t('terminal.gitBranch.branches')}
|
||||
<div ref={viewport} id={listId} role="grid" aria-label={t('terminal.gitBranch.branches')}
|
||||
aria-rowcount={filtered.length} aria-colcount={2}
|
||||
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} 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 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>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
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,7 +6,9 @@ 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, useMemo, useRef, useState } from '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 { terminalReconnectRegistry } from '../../application/state/terminalReconnectRegistry';
|
||||
import { useComposeBarHistory } from '../../application/state/useComposeBarHistory';
|
||||
import { canNavigateComposeBarHistory } from '../../domain/composeBarHistory';
|
||||
@@ -393,10 +395,33 @@ 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();
|
||||
@@ -486,12 +511,14 @@ 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) return;
|
||||
if (!text || !canEdit()) return;
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('insertText', false, text)) {
|
||||
textarea.setRangeText(text, start, end, 'end');
|
||||
@@ -507,7 +534,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
if (!wroteToBridge) {
|
||||
await navigator.clipboard.writeText(selectedText);
|
||||
}
|
||||
if (action === 'cut') {
|
||||
if (action === 'cut' && canEdit()) {
|
||||
textarea.setSelectionRange(start, end);
|
||||
if (!document.execCommand('delete')) {
|
||||
textarea.setRangeText('', start, end, 'end');
|
||||
@@ -518,7 +545,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
} catch (error) {
|
||||
console.error('Compose bar clipboard action failed', error);
|
||||
}
|
||||
}, [readClipboardText, reset, writeClipboardText]);
|
||||
}, [getBranchDraft, readClipboardText, reset, writeClipboardText]);
|
||||
|
||||
const snippetsById = useMemo(
|
||||
() => mergeComposeBarSnippetMap(snippets),
|
||||
@@ -686,12 +713,12 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
|
||||
const insertCommand = useCallback((command: string) => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
if (!el || getBranchDraft()) return;
|
||||
reset();
|
||||
const prefix = el.value && !el.value.endsWith('\n') ? '\n' : '';
|
||||
el.value = el.value ? `${el.value}${prefix}${command}` : command;
|
||||
el.focus();
|
||||
}, [reset]);
|
||||
}, [getBranchDraft, reset]);
|
||||
|
||||
const handleSnippetActivate = useCallback(async (snippet: Snippet, sendImmediately: boolean) => {
|
||||
if (sendImmediately) {
|
||||
@@ -711,6 +738,24 @@ 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;
|
||||
@@ -743,7 +788,7 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
}, [handleSend, navigate, onClose, sessionId]);
|
||||
}, [cancelBranchDraft, getBranchDraft, handleSend, navigate, onClose, sendBranchDraft, sessionId]);
|
||||
|
||||
const handleReturnFocus = useCallback(() => {
|
||||
textareaRef.current?.focus({ preventScroll: true });
|
||||
@@ -825,7 +870,8 @@ export const TerminalComposeBar: React.FC<TerminalComposeBarProps> = ({
|
||||
theme={theme}
|
||||
onReturnFocus={handleReturnFocus}
|
||||
/>
|
||||
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme} onReturnFocus={handleReturnFocus} />
|
||||
<ComposeGitBranchChip key={`git-${sessionId}`} sessionId={sessionId} theme={theme}
|
||||
onReturnFocus={handleReturnFocus} onDraftCommand={stageBranchCommand} draftPending={branchDraftStatus !== null} />
|
||||
{pinnedSnippets.length > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
@@ -919,6 +965,7 @@ 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; }}
|
||||
@@ -950,6 +997,14 @@ 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,6 +29,9 @@ 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';
|
||||
@@ -36,6 +39,14 @@ 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;
|
||||
@@ -283,7 +294,6 @@ 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).
|
||||
@@ -299,23 +309,7 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 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 shortcut = (action: string) => getMenuShortcut(action, hotkeyScheme, keyBindings ?? []);
|
||||
|
||||
const terminalMouseTrackingMode = getMouseTrackingMode?.();
|
||||
|
||||
@@ -407,15 +401,13 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
forceMenuInAlternateScreen: showContextMenuOverFullscreenApps,
|
||||
}) && (
|
||||
<ContextMenuContent className="w-max">
|
||||
<ContextMenuItem onClick={onCopy} disabled={!hasSelection}>
|
||||
<ContextMenuItem shortcut={shortcut('copy')} onClick={onCopy} disabled={!hasSelection}>
|
||||
<Copy size={14} className="mr-2" />
|
||||
{t('terminal.menu.copy')}
|
||||
<ContextMenuShortcut>{copyShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={onPaste}>
|
||||
<ContextMenuItem shortcut={shortcut('paste')} onClick={onPaste}>
|
||||
<ClipboardPaste size={14} className="mr-2" />
|
||||
{t('terminal.menu.paste')}
|
||||
<ContextMenuShortcut>{pasteShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
{shouldShowUploadClipboardImageContextMenuAction(onUploadClipboardImage) && (
|
||||
<ContextMenuItem onClick={onUploadClipboardImage}>
|
||||
@@ -430,16 +422,14 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onPasteSelection && (
|
||||
<ContextMenuItem onClick={onPasteSelection} disabled={!hasSelection}>
|
||||
<ContextMenuItem shortcut={shortcut('pasteSelection')} onClick={onPasteSelection} disabled={!hasSelection}>
|
||||
<ClipboardPaste size={14} className="mr-2" />
|
||||
{t('terminal.menu.pasteSelection')}
|
||||
<ContextMenuShortcut>{pasteSelectionShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem onClick={onSelectAll}>
|
||||
<ContextMenuItem shortcut={shortcut('selectAll')} onClick={onSelectAll}>
|
||||
<TerminalIcon size={14} className="mr-2" />
|
||||
{t('terminal.menu.selectAll')}
|
||||
<ContextMenuShortcut>{selectAllShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
{onOpenSftp && (
|
||||
<>
|
||||
@@ -488,15 +478,13 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
|
||||
<ContextMenuSeparator />
|
||||
|
||||
<ContextMenuItem onClick={onSplitHorizontal}>
|
||||
<ContextMenuItem shortcut={shortcut('splitHorizontal')} onClick={onSplitHorizontal}>
|
||||
<SplitSquareVertical size={14} className="mr-2" />
|
||||
{t('terminal.menu.splitHorizontal')}
|
||||
<ContextMenuShortcut>{splitHShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={onSplitVertical}>
|
||||
<ContextMenuItem shortcut={shortcut('splitVertical')} onClick={onSplitVertical}>
|
||||
<SplitSquareHorizontal size={14} className="mr-2" />
|
||||
{t('terminal.menu.splitVertical')}
|
||||
<ContextMenuShortcut>{splitVShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
|
||||
<ContextMenuSeparator />
|
||||
@@ -507,10 +495,9 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
{t('terminal.menu.saveScreen')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem onClick={onClear}>
|
||||
<ContextMenuItem shortcut={shortcut('clearBuffer')} onClick={onClear}>
|
||||
<Trash2 size={14} className="mr-2" />
|
||||
{t('terminal.menu.clearBuffer')}
|
||||
<ContextMenuShortcut>{clearShortcut}</ContextMenuShortcut>
|
||||
</ContextMenuItem>
|
||||
|
||||
{onRename && (
|
||||
@@ -562,6 +549,7 @@ export const TerminalContextMenu: React.FC<TerminalContextMenuProps> = ({
|
||||
>
|
||||
<Trash2 size={14} className="mr-2" />
|
||||
{t('terminal.menu.closeTerminal')}
|
||||
<PaneCloseShortcut workspaceId={workspaceId} shortcut={shortcut('closeSession')} />
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -63,6 +63,7 @@ type WorkspaceFocusSessionRowProps = {
|
||||
session: TerminalSession;
|
||||
host: Host | undefined;
|
||||
isSelected: boolean;
|
||||
hasSiblingPane: boolean;
|
||||
isRenaming: boolean;
|
||||
renameValue: string;
|
||||
onStartRename: (sessionId: string) => void;
|
||||
@@ -90,6 +91,7 @@ const WorkspaceFocusSessionRow = memo<WorkspaceFocusSessionRowProps>(({
|
||||
session,
|
||||
host,
|
||||
isSelected,
|
||||
hasSiblingPane,
|
||||
isRenaming,
|
||||
renameValue,
|
||||
onStartRename,
|
||||
@@ -218,6 +220,7 @@ const WorkspaceFocusSessionRow = memo<WorkspaceFocusSessionRowProps>(({
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<SessionTabContextMenuContent
|
||||
closeShortcutAction={isSelected && hasSiblingPane ? 'closeSession' : undefined}
|
||||
sessionId={session.id}
|
||||
onCloseSession={onCloseSession}
|
||||
onCopySession={onCopySession}
|
||||
@@ -235,6 +238,7 @@ 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
|
||||
@@ -650,6 +654,7 @@ 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,6 +580,7 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
</ContextMenuTrigger>
|
||||
{menuActions ? (
|
||||
<HostTreeHostContextMenuContent
|
||||
enterConnects={!isInlineEditing}
|
||||
host={row.host}
|
||||
onConnect={onConnect}
|
||||
onConnectRemoteDesktop={onConnectRemoteDesktop}
|
||||
@@ -593,7 +594,7 @@ const HostTreeFlatRowItem = memo<HostTreeFlatRowProps>(({
|
||||
/>
|
||||
) : (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onConnect(row.host)}>
|
||||
<ContextMenuItem shortcut={isInlineEditing ? undefined : 'Enter'} onClick={() => onConnect(row.host)}>
|
||||
<Server className="mr-2 h-4 w-4" /> {t('vault.hosts.connect')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onEditHost?.(row.host)}>
|
||||
|
||||
@@ -2,17 +2,20 @@ 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;
|
||||
@@ -29,11 +32,13 @@ interface SessionTabContextMenuContentProps {
|
||||
|
||||
export function SessionTabContextMenuContent({
|
||||
sessionId,
|
||||
closeShortcutAction,
|
||||
onCloseSession,
|
||||
onCopySession,
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onDetachSession,
|
||||
onReconnectSession,
|
||||
sessionStatus,
|
||||
@@ -56,6 +61,11 @@ export function SessionTabContextMenuContent({
|
||||
{t('tabs.copyTabToNewWindow')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onConvertSessionToWorkspace && (
|
||||
<ContextMenuItem onClick={() => onConvertSessionToWorkspace(sessionId)}>
|
||||
{t('tabs.convertToWorkspace')}
|
||||
</ContextMenuItem>
|
||||
)}
|
||||
{onMoveSessionToNewWindow && (
|
||||
<ContextMenuItem
|
||||
disabled={sessionStatus !== 'connected'}
|
||||
@@ -90,6 +100,7 @@ export function SessionTabContextMenuContent({
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem className="text-destructive" onClick={() => onCloseSession(sessionId)}>
|
||||
{t('common.close')}
|
||||
{closeShortcutAction && <BoundMenuShortcut action={closeShortcutAction} />}
|
||||
</ContextMenuItem>
|
||||
{renderBulkCloseItems?.(sessionId)}
|
||||
</ContextMenuContent>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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,6 +36,7 @@ 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';
|
||||
@@ -380,7 +381,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="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="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"
|
||||
style={{
|
||||
color: 'var(--top-tabs-muted, hsl(var(--muted-foreground)))',
|
||||
backgroundColor: 'color-mix(in srgb, var(--top-tabs-fg, hsl(var(--foreground))) 12%, transparent)',
|
||||
@@ -401,8 +402,15 @@ export const TabIconSlot: React.FC<{ shortcutNumber?: number; children: React.Re
|
||||
children,
|
||||
}) => {
|
||||
const held = useShortcutModifierHeldValue();
|
||||
if (shortcutNumber != null && held) return <TabShortcutNumberBadge number={shortcutNumber} />;
|
||||
return <>{children}</>;
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
const TOP_TAB_COMFORT_EDGE_RATIO = 0.22;
|
||||
@@ -626,7 +634,10 @@ export const PluginViewTopTab: React.FC<PluginViewTopTabProps> = memo(({
|
||||
<TooltipContent>{tab.pluginName}</TooltipContent>
|
||||
</Tooltip>
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onClose(tab.id)}>{t('common.close')}</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onClose(tab.id)}>
|
||||
{t('common.close')}
|
||||
{isActive && <BoundMenuShortcut action="closeTab" />}
|
||||
</ContextMenuItem>
|
||||
{renderBulkCloseItems(tab.id)}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
@@ -800,6 +811,7 @@ 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>
|
||||
@@ -825,6 +837,7 @@ 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;
|
||||
@@ -854,6 +867,7 @@ export const SessionTopTab: React.FC<SessionTopTabProps> = memo(({
|
||||
onDuplicateSession,
|
||||
onCopySessionToNewWindow,
|
||||
onMoveSessionToNewWindow,
|
||||
onConvertSessionToWorkspace,
|
||||
onEditHost,
|
||||
renderBulkCloseItems,
|
||||
dynamicTabTitleMode,
|
||||
@@ -992,11 +1006,13 @@ 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
|
||||
@@ -1203,6 +1219,7 @@ 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) => (
|
||||
@@ -1220,6 +1237,7 @@ 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>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
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,6 +58,12 @@ 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);
|
||||
@@ -125,10 +131,23 @@ 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();
|
||||
@@ -163,6 +182,8 @@ 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);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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,8 +147,9 @@ const ContextMenuItem = React.forwardRef<
|
||||
React.ElementRef<typeof ContextMenuPrimitive.Item>,
|
||||
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
shortcut?: string;
|
||||
}
|
||||
>(({ className, inset, ...props }, ref) => (
|
||||
>(({ className, inset, shortcut, children, ...props }, ref) => (
|
||||
<ContextMenuPrimitive.Item
|
||||
ref={ref}
|
||||
className={cn(
|
||||
@@ -157,7 +158,14 @@ const ContextMenuItem = React.forwardRef<
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
>
|
||||
{shortcut ? (
|
||||
<>
|
||||
{children}
|
||||
<ContextMenuShortcut>{shortcut}</ContextMenuShortcut>
|
||||
</>
|
||||
) : children}
|
||||
</ContextMenuPrimitive.Item>
|
||||
));
|
||||
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
|
||||
|
||||
@@ -239,16 +247,20 @@ 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 pl-4 text-xs tracking-widest text-muted-foreground",
|
||||
"ml-auto shrink-0 whitespace-nowrap pl-4 text-xs text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
ContextMenuShortcut.displayName = "ContextMenuShortcut";
|
||||
|
||||
@@ -195,7 +195,7 @@ const CertItem = memo<CertItemProps>(({
|
||||
|
||||
const menuContent = (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onInspect(cert)}>
|
||||
<ContextMenuItem shortcut="Enter" onClick={() => onInspect(cert)}>
|
||||
<Eye className="mr-2 h-4 w-4" />
|
||||
{t("knownHosts.certs.action.inspect")}
|
||||
</ContextMenuItem>
|
||||
|
||||
@@ -38,6 +38,7 @@ export interface VaultHostCardPrimitives {
|
||||
}
|
||||
|
||||
export interface VaultHostContextMenuProps {
|
||||
enterConnects?: boolean;
|
||||
host: Host;
|
||||
section: VaultHostCardSection;
|
||||
primitives: Pick<
|
||||
@@ -66,6 +67,7 @@ export interface VaultHostContextMenuProps {
|
||||
|
||||
export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
section,
|
||||
primitives,
|
||||
t,
|
||||
@@ -96,7 +98,7 @@ export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
|
||||
return (
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => onConnect(host)}>
|
||||
<ContextMenuItem shortcut={enterConnects ? "Enter" : undefined} onClick={() => onConnect(host)}>
|
||||
<Plug className="mr-2 h-4 w-4" /> {t("vault.hosts.connect")}
|
||||
</ContextMenuItem>
|
||||
<OpenDualPaneSftpMenuItem host={host} />
|
||||
@@ -135,6 +137,7 @@ export const VaultHostContextMenu: React.FC<VaultHostContextMenuProps> = ({
|
||||
};
|
||||
|
||||
export interface VaultHostCardProps {
|
||||
enterConnects?: boolean;
|
||||
host: Host;
|
||||
section: VaultHostCardSection;
|
||||
gridItemKey: string;
|
||||
@@ -167,6 +170,7 @@ export interface VaultHostCardProps {
|
||||
|
||||
export const VaultHostCard: React.FC<VaultHostCardProps> = ({
|
||||
host,
|
||||
enterConnects,
|
||||
section,
|
||||
gridItemKey,
|
||||
viewMode,
|
||||
@@ -300,6 +304,7 @@ export const VaultHostCard: React.FC<VaultHostCardProps> = ({
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
<VaultHostContextMenu
|
||||
enterConnects={enterConnects}
|
||||
host={host}
|
||||
section={section}
|
||||
primitives={primitives}
|
||||
|
||||
@@ -399,6 +399,7 @@ 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,6 +26,7 @@ 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/,
|
||||
|
||||
@@ -27,14 +27,17 @@ 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 | 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 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 SDK | Do not assume App Server support applies to the SDK path. No equivalent reverse request is wired here. |
|
||||
| Claude Agent SDK | Native `AskUserQuestion` input and SDK tool callbacks exist. Netcatty currently disallows this tool in the Claude UI driver; a separate adapter must own its answer path before removing the block. |
|
||||
| CodeBuddy | Existing SDK MCP elicitation is already wired to this form. That does not enable its separate native `AskUserQuestion` tool. |
|
||||
| GitHub Copilot SDK | SDK offers `onUserInputRequest` for `ask_user`; the current driver does not register it. A separate adapter is needed. |
|
||||
| Cursor CLI, OpenCode, MiMo | This change does not wire or verify a native question path. Inspect the specific runtime before advertising support. |
|
||||
| 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. |
|
||||
|
||||
No public MCP capability or configuration is added. A future optional
|
||||
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
|
||||
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,12 +1,27 @@
|
||||
# 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) | 已支持本地 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 的版本展示。 |
|
||||
## 已实现的 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 版本 |
|
||||
@@ -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 与文件系统映射。 |
|
||||
|
||||
[跨平台设计](cross-platform.md) · [交互示意](demo.html) · [PR 开发顺序](../../pr-roadmap.md)
|
||||
[Chip 兼容矩阵](../../README.md#已实现的-chip) · [跨平台设计](cross-platform.md) · [交互示意](demo.html) · [PR 开发顺序](../../pr-roadmap.md)
|
||||
@@ -1,13 +1,14 @@
|
||||
# Git Branch
|
||||
|
||||
## 已完成
|
||||
## 已实现
|
||||
|
||||
- **已合入**。本地 macOS/Linux 的直接 shell 显示当前分支,detached HEAD 显示短哈希,初始分支显示分支名。
|
||||
- **本轮待提交**。菜单支持搜索本地分支和键盘选择。选择后向当前终端发送 `git switch`,关闭菜单并保留草稿。终端显示命令和 Git 原生结果,chip 随活动重读实际 HEAD。目录控制器在发送前确认当前会话、目录和空提示符。
|
||||
- 本地 macOS/Linux 的直接 shell 显示当前分支,detached HEAD 显示短哈希,初始分支显示分支名。
|
||||
- 菜单支持搜索本地分支和键盘选择,并按本次查询的 HEAD 标记当前分支。切换命令绑定菜单所在的工作树,终端显示 Git 原生结果,chip 根据实际 HEAD 刷新。
|
||||
- 其他本地分支的删除按钮填入 `git branch -d -- '分支名'` 并将焦点交给输入区。回车在原会话执行草稿,并将 Git 绑定到菜单读取的工作树。终端显示 Git 的删除结果。发送或取消后恢复原草稿。
|
||||
|
||||
## 待完成
|
||||
|
||||
- Windows 和 SSH 分别确认 Git 的可执行文件、工作树路径和会话身份。GNU Screen 依赖目录层先绑定活动窗口与内层 shell。
|
||||
- 远程分支与新建分支分别调研命令范围和菜单交互。
|
||||
- Windows 按 PowerShell/CMD、Git Bash、WSL Bash、Cygwin Bash 分别适配 Git 与工作树路径。Unix SSH 在原会话中获取 Git 状态和分支。GNU Screen 依赖目录层先绑定活动窗口与内层 shell。
|
||||
- 新建分支先确定起点和创建后是否切换,再设计命令草稿。远程分支先明确跟踪分支的展示和检出规则。
|
||||
|
||||
[PR 开发顺序](../pr-roadmap.md)
|
||||
[Chip 兼容矩阵](../README.md#已实现的-chip) · [PR 开发顺序](../pr-roadmap.md)
|
||||
@@ -10,4 +10,5 @@ Compose Bar 位于终端下方。顶栏先显示当前会话的 Context Chips,
|
||||
- 文件系统、Git 和 shell 集成由 `infrastructure/services/` 与 Electron bridge 提供。`components/terminal/` 负责布局、菜单、焦点和主题。
|
||||
- 目录和 Git Branch 共用已确认的工作目录。操作绑定当前终端,发送前确认会话、目录和空提示符,保留撰写栏草稿。
|
||||
- 命令类 chip 在原终端执行操作,终端显示命令和原生输出。chip 根据实际状态刷新。菜单提示用于数据读取和发送前的状态。
|
||||
- 删除分支等需要用户确认的操作先在输入区生成独立草稿。发送沿用会话和提示符检查,完成或取消后恢复原草稿。
|
||||
- Git Changes 计划复用工作树身份,详情接入现有终端侧栏。Pull Request 单独处理远程身份和查询状态。Node Version 从当前交互 shell 获取运行时信息。
|
||||
@@ -1,18 +1,34 @@
|
||||
# PR 开发顺序
|
||||
|
||||
当前覆盖范围见 [Chip 兼容矩阵](README.md#已实现的-chip)。Git Branch 已实现分支展示、搜索、切换和删除草稿。
|
||||
|
||||
## 下一批 Chip
|
||||
|
||||
| 顺序 | PR | 交付范围 |
|
||||
| --- | --- | --- |
|
||||
| 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 变化。 |
|
||||
| 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 变化。 |
|
||||
|
||||
## 独立 PR 待排期
|
||||
## 兼容性 PR
|
||||
|
||||
| 工作 | 交付范围 |
|
||||
兼容性按会话环境独立提交,可与下一批 Chip 并行推进。每个 Git Branch 适配先确认可执行文件、工作树路径和会话身份,再接入分支读取、切换和删除草稿。
|
||||
|
||||
| PR | 范围与依赖 |
|
||||
| --- | --- |
|
||||
| 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#待完成)。 |
|
||||
| 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 切换,再评估其他管理器。
|
||||
@@ -3,6 +3,7 @@ import test from 'node:test';
|
||||
|
||||
import {
|
||||
findActiveSystemShortcutConflict,
|
||||
getMenuShortcut,
|
||||
listActiveSystemBindings,
|
||||
} from './activeKeyBindings.ts';
|
||||
import { DEFAULT_KEY_BINDINGS, type KeyBinding } from './models/keyBindings.ts';
|
||||
@@ -66,3 +67,23 @@ 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,6 +35,30 @@ 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,6 +11,7 @@ export type AgentIconKey =
|
||||
| 'codex'
|
||||
| 'claude'
|
||||
| 'anthropic'
|
||||
| 'agy'
|
||||
| 'gemini'
|
||||
| 'google'
|
||||
| 'ollama'
|
||||
@@ -23,6 +24,7 @@ export type AgentIconKey =
|
||||
| 'codebuddy'
|
||||
| 'grok'
|
||||
| 'mimo'
|
||||
| 'qoder'
|
||||
| 'terminal'
|
||||
| 'plus';
|
||||
|
||||
@@ -68,6 +70,11 @@ 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',
|
||||
@@ -123,6 +130,11 @@ 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',
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export type ChatTextFile = { name: string; content: string };
|
||||
export function chatTextFileExtension(name: string): string;
|
||||
export function validateChatTextFile(value: unknown): ChatTextFile | null;
|
||||
@@ -0,0 +1,20 @@
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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: [] });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
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,6 +21,7 @@ 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'
|
||||
@@ -55,6 +56,10 @@ 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', () => {
|
||||
@@ -176,3 +181,22 @@ 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,6 +95,12 @@ 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),
|
||||
@@ -116,6 +122,12 @@ 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,6 +18,12 @@ 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', () => {
|
||||
@@ -37,6 +43,10 @@ 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,
|
||||
@@ -88,3 +98,15 @@ 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,6 +65,8 @@ 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,6 +4,7 @@ export type CodingCliProviderId =
|
||||
| 'claude'
|
||||
| 'codex'
|
||||
| 'opencode'
|
||||
| 'agy'
|
||||
| 'gemini'
|
||||
| 'kimi'
|
||||
| 'droid'
|
||||
@@ -11,7 +12,8 @@ export type CodingCliProviderId =
|
||||
| 'cursor'
|
||||
| 'codebuddy'
|
||||
| 'grok'
|
||||
| 'mimo';
|
||||
| 'mimo'
|
||||
| 'qoder';
|
||||
|
||||
export type CodingCliProvider = {
|
||||
id: CodingCliProviderId;
|
||||
@@ -51,6 +53,13 @@ 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',
|
||||
@@ -109,6 +118,15 @@ 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,3 +78,17 @@ 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,6 +9,10 @@ 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;
|
||||
@@ -45,6 +49,10 @@ 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';
|
||||
}
|
||||
@@ -52,6 +60,7 @@ 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';
|
||||
@@ -79,10 +88,18 @@ 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';
|
||||
}
|
||||
@@ -99,7 +116,11 @@ 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]+:)?(?:~(?:\/|$)|\/|[A-Za-z]:[\\/])/;
|
||||
const SHELL_PATH_TITLE_RE = /^(?:(?:[^@\s:]+@)?[^:\s]+:[ \t]*)?(?:~(?:\/|$)|\/|[A-Za-z]:[\\/])/;
|
||||
|
||||
function isShellPathTitle(title: string): boolean {
|
||||
return SHELL_PATH_TITLE_RE.test(title.trim());
|
||||
}
|
||||
|
||||
/** Whether a shell-reported title no longer reflects an active coding CLI session. */
|
||||
export function shouldClearCodingCliProviderForTitle(
|
||||
@@ -113,7 +134,7 @@ export function shouldClearCodingCliProviderForTitle(
|
||||
if (inferredId === providerId) return false;
|
||||
if (inferredId) return true;
|
||||
if (SHELL_TITLE_RE.test(trimmed)) return true;
|
||||
if (SHELL_PATH_TITLE_RE.test(trimmed)) return true;
|
||||
if (isShellPathTitle(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 { gitSwitchCommand } from './terminalGitHead';
|
||||
import { gitDeleteBranchCommand, gitSwitchCommand, scopeGitBranchDraft } 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,3 +35,46 @@ 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,15 +9,37 @@ export type TerminalGitHeadResult = TerminalGitHead | Readonly<{ kind: 'outside-
|
||||
export type TerminalGitBranchesResult = Readonly<{ kind: 'unavailable' }>
|
||||
| Readonly<{ kind: 'branches'; head: TerminalGitHead; branches: readonly string[] }>;
|
||||
|
||||
export function gitSwitchCommand(worktreeRoot: string, name: string): string | null {
|
||||
// Ref names can contain shell metacharacters, including single quotes.
|
||||
if (!isAbsoluteDirectoryPath(worktreeRoot, 'posix')) return null;
|
||||
function quoteBranchName(name: string): string | 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 = '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)}`;
|
||||
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)}`;
|
||||
}
|
||||
@@ -118,6 +118,7 @@ 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',
|
||||
|
||||
@@ -278,3 +278,35 @@ test("terminal_execute tool description documents the unknown outcome and the re
|
||||
assert.match(description, /get_environment|terminal_read_context/);
|
||||
assert.match(description, /ask the user to confirm/);
|
||||
});
|
||||
|
||||
test("Starship SSH host and empty character rows admit a command together", async () => {
|
||||
const hostRow = "\x1b[31mroot\x1b[0m in 🌐 \x1b[32mdebian\x1b[0m in \x1b[36m~\x1b[0m";
|
||||
const prompt = hostRow + "\r\n\x1b[32m❯\x1b[0m ";
|
||||
for (const [output, extra, ready] of [
|
||||
[prompt, {}, true],
|
||||
[prompt + "x\b\x1b[K", {}, true],
|
||||
["❯ ", {}, false],
|
||||
["build finished\r\n❯ ", {}, false],
|
||||
[hostRow + "\r\n\r\n❯ ", {}, false],
|
||||
[prompt + "whoami", {}, false],
|
||||
[prompt + "whoami\x1b[6D", {}, false],
|
||||
[prompt + " ", {}, false],
|
||||
[prompt + "\r\nPassword: ", {}, false],
|
||||
["\x1b[?1049h" + prompt, {}, false],
|
||||
[prompt, { waitingForInput: true }, false],
|
||||
[prompt, { busy: true }, false],
|
||||
["\x1b]133;C\x07" + prompt, {}, false],
|
||||
]) {
|
||||
const session = makeSession(extra);
|
||||
trackSessionIdlePrompt(session, output);
|
||||
const pty = new TestPty();
|
||||
const result = await startPtyJob(pty, "echo OK", {
|
||||
shellKind: "posix",
|
||||
getReadyPrompt: () => readyPrompt(session),
|
||||
classifyReadiness: () => classifyShellReadiness(session),
|
||||
...SHORT_BUDGET,
|
||||
}).resultPromise;
|
||||
assert.equal(result.ok, ready, JSON.stringify([output, extra]));
|
||||
assert.equal(pty.writes.length, ready ? 1 : 0);
|
||||
}
|
||||
});
|
||||
@@ -189,6 +189,11 @@ const MACOS_ROOT_PROMPT_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]*:(?:~|\/|[^\s:#$>
|
||||
const POWERLEVEL10K_PROMPT_PATTERN =
|
||||
/^(?:[^\s@]+@[^\s:]+\s+)?[^\s❯][^❯\r\n]*\s+❯$/;
|
||||
|
||||
// Starship's SSH username, hostname and directory modules above its character.
|
||||
// Match the two adjacent rendered rows so a lone arrow cannot establish readiness.
|
||||
const STARSHIP_SSH_PROMPT_PATTERN =
|
||||
/(?:^|\n)([\w.-]+ in 🌐 [\w.-]+ in (?:~(?:\/[^\r\n]*)?|\/[^\r\n]*)\n❯ )$/u;
|
||||
|
||||
const POWERLINE_PROMPT_PATTERN =
|
||||
/^\s*(?:[\uE0B0-\uE0B7]\s*)*(?:[^\s@\uE0B0-\uE0B7]+@[^\s:\uE0B0-\uE0B7]+|(?:[\uE000-\uE0AF\uE0B8-\uF8FF]{1,4}\s*)?[A-Za-z0-9_.-]+\s*(?:[\uE0B0-\uE0B7]\s*)+[~/]|[~/])[^\r\n]*[\uE0B0-\uE0B7]$/;
|
||||
|
||||
@@ -533,6 +538,29 @@ function getFreshIdlePrompt(session) {
|
||||
return normalizedTail.endsWith(normalizedCached) ? cached : "";
|
||||
}
|
||||
|
||||
// A one-line Powerlevel10k prompt with user@host and a directory on the left.
|
||||
const POWERLINE_HOST_DIR = /^ *[\w.-]+@[\w.-]+ +\uE0B0 +[~/][^\uE0B0-\uE0B7\r\n]* +\uE0B0 $/u;
|
||||
const POWERLINE_STATUS_CLOCK = /^(?:\uE0B2 *)?(?:[✔✓]|[1-9]\d{0,2} ↵) +(?:[\uE0B2\uE0B3] *)?(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d *$/u;
|
||||
|
||||
// zle clears from the input cursor, moves right, paints RPROMPT and moves
|
||||
// back before enabling bracketed paste. Plain output or a clock-like buffer
|
||||
// to the right of an editing cursor does not establish that boundary.
|
||||
function getZlePowerlineIdlePrompt(tail, view) {
|
||||
if (!tail.endsWith("\x1b[?2004h")) return "";
|
||||
const unstyled = tail.replace(/\u001B\[[0-9;:]*m/g, "");
|
||||
const paint = /\u001B\[K\u001B\[([1-9]\d*)C([^\u001B\r\n]{1,80})\u001B\[([1-9]\d*)D\u001B\[\?2004h$/.exec(unstyled);
|
||||
if (!paint) return "";
|
||||
const [, advance, status, retreat] = paint;
|
||||
// All allowed status characters occupy a single terminal cell.
|
||||
if (!POWERLINE_STATUS_CLOCK.test(status) || Number(retreat) !== Number(advance) + status.length) return "";
|
||||
|
||||
const { renderCursorBoundScreenText } = require("../terminalLogSanitizer.cjs");
|
||||
const beforeRightPrompt = unstyled.slice(0, paint.index) + "\x1b[K";
|
||||
const screen = renderCursorBoundScreenText(beforeRightPrompt, view);
|
||||
const left = screen?.rawText.split("\n").pop() || "";
|
||||
return POWERLINE_HOST_DIR.test(left) ? left : "";
|
||||
}
|
||||
|
||||
// Readiness companion to getFreshIdlePrompt. PSReadLine echoes keys (including
|
||||
// the pending-input clear prefix) and then erases them with cursor-column +
|
||||
// ED/EL without appending a fresh copy of the prompt. stripAnsi removes the
|
||||
@@ -558,6 +586,11 @@ function getVisibleIdlePrompt(session) {
|
||||
// and lack of continuation are checked above before bypassing shape checks.
|
||||
return /\s$/.test(cursorLine) ? `${rightTrimmed} ` : rightTrimmed;
|
||||
}
|
||||
if (rightTrimmed === "❯") {
|
||||
if (session.busy || session.waitingForInput) return "";
|
||||
const screen = renderCursorBoundScreenText(visibleTail, view);
|
||||
return screen?.trimmedAboveText.match(STARSHIP_SSH_PROMPT_PATTERN)?.[1] || "";
|
||||
}
|
||||
if (KALI_PROMPT_MARKER_LINE_PATTERN.test(rightTrimmed)) {
|
||||
// After readline or zle erases input, verify the host and marker on the
|
||||
// current screen together. The bare marker alone cannot establish readiness.
|
||||
@@ -569,7 +602,8 @@ function getVisibleIdlePrompt(session) {
|
||||
&& !isDefaultPosixPromptLine(rightTrimmed)
|
||||
&& !isDefaultCmdPromptLine(rightTrimmed)
|
||||
) {
|
||||
return "";
|
||||
if (session.busy || session.waitingForInput) return "";
|
||||
return getZlePowerlineIdlePrompt(visibleTail, view);
|
||||
}
|
||||
// Keep one trailing space when the visible prompt has one. Erase-to-end
|
||||
// padding must not become part of the expected prompt.
|
||||
|
||||
@@ -1536,6 +1536,47 @@ test("visible idle prompt survives a PSReadLine erase that leaves the raw tail d
|
||||
assert.equal(getVisibleIdlePrompt(crHomed), prompt);
|
||||
});
|
||||
|
||||
test("zle's Powerline right prompt returns to the empty input cursor", () => {
|
||||
const left = " root@box ~/项目 ";
|
||||
for (const status of [" ✔ 11:47:04 ", " 1 ↵ 11:47:04 "]) {
|
||||
const session = {};
|
||||
const retreat = 40 + status.length;
|
||||
trackSessionIdlePrompt(session, left + "\x1b[K\x1b[40C\x1b[32m" + status);
|
||||
assert.equal(getVisibleIdlePrompt(session), "");
|
||||
trackSessionIdlePrompt(session, "\x1b[0m" + "\x1b[" + retreat + "D\x1b[?2004h");
|
||||
assert.equal(getVisibleIdlePrompt(session), left);
|
||||
trackSessionIdlePrompt(session, "some input\x1b[10D");
|
||||
assert.equal(getVisibleIdlePrompt(session), "");
|
||||
}
|
||||
});
|
||||
|
||||
test("printed clocks, partial right prompts, active programs and pending input remain unready", () => {
|
||||
const left = " root@box ~ ";
|
||||
const status = " ✔ 11:47:04 ";
|
||||
const paint = "\x1b[K\x1b[40C" + status + "\x1b[" + (40 + status.length) + "D\x1b[?2004h";
|
||||
for (const output of [
|
||||
left + " ".repeat(40) + status,
|
||||
left + paint.replace("40C", "39C"),
|
||||
left + paint.replace("11:47:04", "Password"),
|
||||
left + paint.replace("\x1b[?2004h", ""),
|
||||
"root# " + paint,
|
||||
left + "echo editing " + paint,
|
||||
left + paint + "\r\nPassword: ",
|
||||
"\x1b[?1049h" + left + paint,
|
||||
"\x1b]133;C\x07" + left + paint,
|
||||
left + "\r\nApplication menu\x1b[1A\x1b[" + (left.length + 1) + "G" + paint,
|
||||
]) {
|
||||
const session = {};
|
||||
trackSessionIdlePrompt(session, output);
|
||||
assert.equal(getVisibleIdlePrompt(session), "", JSON.stringify(output));
|
||||
assert.equal(getFreshIdlePrompt(session), "", JSON.stringify(output));
|
||||
}
|
||||
for (const session of [{ busy: true }, { waitingForInput: true }]) {
|
||||
trackSessionIdlePrompt(session, left + paint);
|
||||
assert.equal(getVisibleIdlePrompt(session), "");
|
||||
}
|
||||
});
|
||||
|
||||
test("visible idle prompt stays empty for pending input, a following line, and an unrecognized prompt", () => {
|
||||
const pending = {};
|
||||
trackSessionIdlePrompt(pending, "PS C:\\Users\\alice> Write-Output ok");
|
||||
|
||||
@@ -133,6 +133,7 @@ function getSkillsCliInvocation() {
|
||||
}
|
||||
|
||||
function buildExternalAgentSystemContext({ mode, chatSessionId, defaultTargetSession, userSkillsContext }) {
|
||||
const chatTextFileOfferGuidance = 'For a requested downloadable text file whose contents you already know or may read with existing permissions, you may emit a netcatty-file fenced block with a single JSON line containing name and content. Use only a basename ending in .txt, .md, .csv, .tsv or .json and at most 256 KiB of UTF-8 content, then close the fence. The user chooses whether to save it. Never share credentials or pretend an inaccessible path is an attachment. ';
|
||||
const userSkillsPreamble = userSkillsContext ? `${userSkillsContext}\n\n` : "";
|
||||
if (mode === "skills") {
|
||||
const { commandPrefix: cliCommandPrefix, launcherPath, usesLauncher } = getSkillsCliInvocation();
|
||||
@@ -198,6 +199,7 @@ function buildExternalAgentSystemContext({ mode, chatSessionId, defaultTargetSes
|
||||
`Do not spend time narrating intent before every CLI call for routine read-only checks. Execute the minimal command sequence and then report the result. ` +
|
||||
`Only after that confirmation step should you call \`${cliCommandPrefix} exec --session <id> --json -- <command>\` for command execution. ` +
|
||||
`If the user stops the run or asks to abort outstanding Netcatty work, use \`${cliCommandPrefix} cancel --json\`, and use \`resume\` to re-enable execs for that scope if needed. ` +
|
||||
`${chatTextFileOfferGuidance}` +
|
||||
`For serial/raw sessions and network device sessions (deviceType: network), commands are sent as-is without shell wrapping and exit codes are unavailable. Use vendor CLI commands directly.]`
|
||||
);
|
||||
}
|
||||
@@ -212,6 +214,7 @@ function buildExternalAgentSystemContext({ mode, chatSessionId, defaultTargetSes
|
||||
`Use terminal_execute only for commands likely to finish within about 60 seconds. ` +
|
||||
`For long-running commands such as builds, scans, follow/log streaming, watch commands, or anything likely to exceed 60 seconds on PTY-backed shell sessions, use terminal_start, then terminal_poll until completed is true. Reuse the returned nextOffset for the next poll. If terminal_poll reports outputTruncated=true, only the retained tail starting at outputBaseOffset is still available. Do not poll aggressively: wait at least about 30 seconds between polls, and increase the interval further when there is no new output, to avoid wasting tokens. As soon as completed is true, stop polling and analyze the result immediately. ` +
|
||||
`Use terminal_stop if you need to interrupt a started long-running command. Note: terminal_start requires a PTY-backed session; for sessions that only support exec-channel execution (no writable PTY), use terminal_execute instead. ` +
|
||||
`${chatTextFileOfferGuidance}` +
|
||||
`For serial/raw sessions and network device sessions (deviceType: network), commands are sent as-is without shell wrapping and exit codes are unavailable. Use vendor CLI commands directly.]`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ function resolveCodexPermissionConfig(permissionMode) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadConfig(injectedMcpServers) {
|
||||
function buildThreadConfig(injectedMcpServers, allowNativeUserQuestions) {
|
||||
return {
|
||||
// Netcatty already applies its Observer/Confirm/Auto policy inside the MCP
|
||||
// bridge. Tell Codex not to add a second MCP approval prompt: App Server
|
||||
@@ -84,6 +84,8 @@ function buildThreadConfig(injectedMcpServers) {
|
||||
defaultToolsApprovalMode: "approve",
|
||||
}),
|
||||
model_reasoning_summary: "concise",
|
||||
...(typeof allowNativeUserQuestions === "boolean"
|
||||
? { "features.default_mode_request_user_input": allowNativeUserQuestions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -252,6 +254,7 @@ class CodexAppServerRuntime {
|
||||
cwd,
|
||||
model,
|
||||
permissionMode,
|
||||
allowNativeUserQuestions,
|
||||
env,
|
||||
binPath,
|
||||
injectedMcpServers,
|
||||
@@ -279,7 +282,7 @@ class CodexAppServerRuntime {
|
||||
approvalPolicy: permission.approvalPolicy,
|
||||
approvalsReviewer: permission.approvalsReviewer,
|
||||
sandbox: permission.sandbox,
|
||||
config: buildThreadConfig(injectedMcpServers),
|
||||
config: buildThreadConfig(injectedMcpServers, allowNativeUserQuestions),
|
||||
};
|
||||
|
||||
assertSessionValid?.();
|
||||
|
||||
@@ -246,6 +246,26 @@ test("runtime delegates injected MCP approvals to Netcatty's policy gate", async
|
||||
await run;
|
||||
});
|
||||
|
||||
test("Codex App Server config opts into default mode questions without changing observer policy", async () => {
|
||||
let connection;
|
||||
const runtime = new CodexAppServerRuntime({
|
||||
connectionFactory: options => (connection = new FakeConnection(options)),
|
||||
});
|
||||
const turn = runtime.runTurn({
|
||||
requestId: "request-questions", chatSessionId: "questions", prompt: "ask",
|
||||
permissionMode: "observer", allowNativeUserQuestions: true, env: {}, binPath: "/bin/codex",
|
||||
injectedMcpServers: [], emitter: createEmitter(),
|
||||
});
|
||||
await waitFor(() => connection?.requests.some(request => request.method === "turn/start"));
|
||||
const thread = connection.requests.find(request => request.method === "thread/start").params;
|
||||
assert.equal(thread.config["features.default_mode_request_user_input"], true);
|
||||
assert.equal(thread.sandbox, "read-only");
|
||||
assert.equal(thread.approvalPolicy, "never");
|
||||
connection.notify({ method: "turn/completed",
|
||||
params: { threadId: "thread-1", turn: { id: "turn-1", status: "completed", error: null } } });
|
||||
await turn;
|
||||
});
|
||||
|
||||
test("runtime routes native approvals and request_user_input responses", async () => {
|
||||
let connection;
|
||||
let interaction;
|
||||
|
||||
@@ -142,8 +142,25 @@ async function createCodebuddySdkMcpServer(toolDefs) {
|
||||
* @param {Function} [args.requestApproval] (toolName, args, chatSessionId) => Promise<boolean>
|
||||
* @returns {Function} SDK CanUseTool handler: (toolName, input, options) => Promise<PermissionResult>
|
||||
*/
|
||||
function buildCodebuddyCanUseTool({ permissionMode, chatSessionId, requestApproval }) {
|
||||
return async (toolName, input, _options) => {
|
||||
function buildCodebuddyCanUseTool({ permissionMode, chatSessionId, requestApproval, requestUserForm, signal }) {
|
||||
return async (toolName, input, options) => {
|
||||
if (toolName === "AskUserQuestion") {
|
||||
if (typeof requestUserForm === "function") {
|
||||
try {
|
||||
const toolSignal = options?.signal;
|
||||
const answerSignal = signal && toolSignal ? AbortSignal.any([signal, toolSignal]) : signal || toolSignal;
|
||||
const { requestStructuredQuestion } = require("./structuredQuestion.cjs");
|
||||
const result = await requestStructuredQuestion(input?.questions,
|
||||
(form, validateContent) => requestUserForm(form, answerSignal, validateContent), "codebuddy-native");
|
||||
if (!answerSignal?.aborted && result.outcome === "accepted") {
|
||||
const answers = Object.fromEntries(Object.entries(result.answers).map(([question, labels]) =>
|
||||
[question, result.annotations?.[question]?.notes ?? labels.join(", ")]));
|
||||
return { behavior: "allow", updatedInput: { ...input, answers } };
|
||||
}
|
||||
} catch { /* Missing or failed UI is not an answer. */ }
|
||||
}
|
||||
return { behavior: "deny", message: "No answer was provided to AskUserQuestion." };
|
||||
}
|
||||
// Auto mode: confirm execution immediately without user interruption.
|
||||
if (permissionMode === "auto") {
|
||||
return { behavior: "allow" };
|
||||
@@ -248,7 +265,7 @@ function buildCodebuddyQueryOptions({
|
||||
systemPrompt, effort, maxTurns, maxBudgetUsd, fallbackModel,
|
||||
sandbox, agents, outputFormat, enableFileCheckpointing,
|
||||
traceId, parentSpanId, persistSession, sessionId, hooks,
|
||||
elicitation, canUseTool,
|
||||
elicitation, canUseTool, allowNativeUserQuestions = false,
|
||||
}) {
|
||||
const builtinTools = codebuddyBuiltinTools(toolIntegrationMode);
|
||||
const mcpMode = builtinTools.length === 0;
|
||||
@@ -269,8 +286,8 @@ function buildCodebuddyQueryOptions({
|
||||
mcpServers,
|
||||
...(mcpMode ? { strictMcpConfig: true } : {}),
|
||||
// Keep unrelated CLI built-ins disabled by default, including future tools.
|
||||
tools: builtinTools,
|
||||
disallowedTools: [...UI_DISALLOWED_TOOLS],
|
||||
tools: allowNativeUserQuestions ? [...builtinTools, "AskUserQuestion"] : builtinTools,
|
||||
disallowedTools: allowNativeUserQuestions ? [] : [...UI_DISALLOWED_TOOLS],
|
||||
// Keep the SDK isolated from user/project settings so local hooks, plugins,
|
||||
// or extra MCP servers cannot expand Netcatty's controlled tool boundary.
|
||||
settingSources: [],
|
||||
|
||||
@@ -40,9 +40,13 @@ const {
|
||||
spawnGrokProcess,
|
||||
} = require("./grokDriver.cjs");
|
||||
|
||||
const { chooseGrokSessionMode } = require("./grokSessionMode.cjs");
|
||||
|
||||
const GROK_ACP_ABORT_GRACE_MS = 1_500;
|
||||
const MAX_GROK_ACP_LINE_BYTES = 10 * 1024 * 1024;
|
||||
const MAX_GROK_ACP_STDERR_CHARS = 64 * 1024;
|
||||
const GROK_MCP_AUTH_HINT =
|
||||
"A remote MCP server requested authorization. Check the MCP servers configured for this Grok session. If the prompt stalls, stop the turn, authenticate or disable the server in Grok, then retry.";
|
||||
const ACP_PROTOCOL_VERSION = 1;
|
||||
// The outer SDK model-list request has a 10s deadline. Leave enough time for
|
||||
// the legacy `grok models` fallback when ACP initialize hangs.
|
||||
@@ -58,6 +62,13 @@ const GROK_REASONING_EFFORTS = new Set([
|
||||
"max",
|
||||
]);
|
||||
|
||||
function formatGrokAcpError(message, sawMcpAuthChallenge = false) {
|
||||
// RPC errors can repeat the challenge, including signed metadata URLs.
|
||||
if (/\bBearer[ \t]+resource_metadata[ \t]*=/i.test(String(message))) return GROK_MCP_AUTH_HINT;
|
||||
const detail = formatGrokErrorForUser(message);
|
||||
return sawMcpAuthChallenge ? `${detail}. ${GROK_MCP_AUTH_HINT}` : detail;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve absolute cwd for ACP session lifecycle (protocol requires absolute path).
|
||||
*/
|
||||
@@ -545,7 +556,7 @@ async function establishGrokAcpSession(rpc, {
|
||||
);
|
||||
const sessionId = created?.sessionId || created?.session_id;
|
||||
if (!sessionId) throw new Error("Grok ACP session/new did not return a sessionId");
|
||||
return { sessionId, method: "new" };
|
||||
return { sessionId, method: "new", modes: created?.modes };
|
||||
}
|
||||
if (method === "resume") {
|
||||
const result = await rpc.request(
|
||||
@@ -558,7 +569,7 @@ async function establishGrokAcpSession(rpc, {
|
||||
{ timeoutMs: 30_000 },
|
||||
);
|
||||
const sessionId = result?.sessionId || result?.session_id || resumeSessionId;
|
||||
return { sessionId, method: "resume" };
|
||||
return { sessionId, method: "resume", modes: result?.modes };
|
||||
}
|
||||
if (method === "load") {
|
||||
const result = await rpc.request(
|
||||
@@ -571,7 +582,7 @@ async function establishGrokAcpSession(rpc, {
|
||||
{ timeoutMs: 30_000 },
|
||||
);
|
||||
const sessionId = result?.sessionId || result?.session_id || resumeSessionId;
|
||||
return { sessionId, method: "load" };
|
||||
return { sessionId, method: "load", modes: result?.modes };
|
||||
}
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
@@ -698,7 +709,7 @@ function translateGrokAcpUpdate(update, emitter, state = {}) {
|
||||
case "error": {
|
||||
closeReasoning(state, emitter);
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(update.message || update.error || "Grok ACP turn failed"));
|
||||
emitter.emitError(formatGrokAcpError(update.message || update.error || "Grok ACP turn failed"));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -751,6 +762,13 @@ function handleGrokAcpMessage(message, { emitter, state, pending, onPromptComple
|
||||
}
|
||||
|
||||
if (method === "session/update" || method === "x.ai/session/update") {
|
||||
const modeUpdate = params.update;
|
||||
if (modeUpdate?.sessionUpdate === "current_mode_update" && params.sessionId
|
||||
&& params.sessionId === state.sessionId && typeof modeUpdate.currentModeId === "string") {
|
||||
state.observedMode = { sessionId: params.sessionId, id: modeUpdate.currentModeId };
|
||||
if (state.acceptUpdates) emitter.status?.(`Grok mode: ${modeUpdate.currentModeId}`);
|
||||
return;
|
||||
}
|
||||
// session/load may re-broadcast historical agent_message_chunk events for
|
||||
// client UI rebuild. Those must not be written into the *current* Netcatty
|
||||
// assistant bubble — only accept updates after session/prompt is in flight.
|
||||
@@ -917,6 +935,7 @@ async function runGrokAcpTurn({
|
||||
abortGraceMs = GROK_ACP_ABORT_GRACE_MS,
|
||||
forceKillImpl,
|
||||
requestUserForm,
|
||||
chooseGrokMode,
|
||||
// inject for tests: skip real spawn
|
||||
rpcClientFactory,
|
||||
assertSessionValid,
|
||||
@@ -967,6 +986,23 @@ async function runGrokAcpTurn({
|
||||
writeResponse: null,
|
||||
};
|
||||
|
||||
async function preparePrompt(client, established) {
|
||||
state.sessionId = established.sessionId;
|
||||
emitter.sessionId?.(established.sessionId);
|
||||
if (chooseGrokMode === true) {
|
||||
await chooseGrokSessionMode(client, established, {
|
||||
observedMode: state.observedMode?.sessionId === established.sessionId ? state.observedMode.id : undefined,
|
||||
permissionMode,
|
||||
requestUserForm,
|
||||
signal: planReviewSignal,
|
||||
assertSessionValid,
|
||||
});
|
||||
}
|
||||
return resolveGrokTurnPrompt({
|
||||
turnPrompt: prompt, historySeed, resumeSessionId, establishMethod: established.method,
|
||||
});
|
||||
}
|
||||
|
||||
// Test inject path: pure RPC loop without process
|
||||
if (typeof rpcClientFactory === "function") {
|
||||
const client = rpcClientFactory({ state, emitter });
|
||||
@@ -983,14 +1019,7 @@ async function runGrokAcpTurn({
|
||||
assertSessionValid,
|
||||
agentCapabilities: parseGrokAcpAgentCapabilities(initResult),
|
||||
});
|
||||
state.sessionId = established.sessionId;
|
||||
emitter.sessionId?.(established.sessionId);
|
||||
const effectivePrompt = resolveGrokTurnPrompt({
|
||||
turnPrompt: prompt,
|
||||
historySeed,
|
||||
resumeSessionId,
|
||||
establishMethod: established.method,
|
||||
});
|
||||
const effectivePrompt = await preparePrompt(client, established);
|
||||
// Only accept updates for this turn's prompt (not session/load replay).
|
||||
state.acceptUpdates = true;
|
||||
assertSessionValid?.();
|
||||
@@ -1006,7 +1035,7 @@ async function runGrokAcpTurn({
|
||||
} catch (err) {
|
||||
if (!state.failed && !signal?.aborted) {
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
}
|
||||
}
|
||||
planReviewLifetime.abort();
|
||||
@@ -1023,11 +1052,13 @@ async function runGrokAcpTurn({
|
||||
detached: process.platform !== "win32",
|
||||
});
|
||||
} catch (err) {
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
return { sessionId: state.sessionId, runtime: "acp" };
|
||||
}
|
||||
|
||||
const stderrCollector = createBoundedTextCollector(MAX_GROK_ACP_STDERR_CHARS);
|
||||
let sawMcpAuthChallenge = false;
|
||||
let previousStderrTail = "";
|
||||
let settled = false;
|
||||
let abortGuard = null;
|
||||
/** @type {ReturnType<typeof createJsonRpcClient>|null} */
|
||||
@@ -1044,7 +1075,7 @@ async function runGrokAcpTurn({
|
||||
if (settled || state.failed || signal?.aborted || state.turnCompleted) return;
|
||||
if (isBenignStdinError(err)) return;
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
try { rpc?.rejectAll?.(err || new Error("Grok ACP stdin error")); } catch { /* ignore */ }
|
||||
};
|
||||
if (typeof child.stdin?.on === "function") {
|
||||
@@ -1128,7 +1159,7 @@ async function runGrokAcpTurn({
|
||||
} catch (err) {
|
||||
if (!state.failed) {
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
}
|
||||
}
|
||||
}, MAX_GROK_ACP_LINE_BYTES);
|
||||
@@ -1140,7 +1171,7 @@ async function runGrokAcpTurn({
|
||||
} catch (err) {
|
||||
if (!state.failed) {
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
}
|
||||
signalProcessTree(child, "SIGKILL", forceKillImpl);
|
||||
}
|
||||
@@ -1148,12 +1179,24 @@ async function runGrokAcpTurn({
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
if (signal?.aborted) return;
|
||||
stderrCollector.push(chunk);
|
||||
if (sawMcpAuthChallenge || state.failed || state.turnCompleted) return;
|
||||
// Grok's worker can log an OAuth challenge while the ACP child stays alive.
|
||||
// Keep enough overlap to recognize the diagnostic across pipe writes.
|
||||
const recent = previousStderrTail + chunk.toString();
|
||||
if (/\bAuthRequired\b[\s\S]{0,384}?\bBearer[ \t]+resource_metadata[ \t]*=/i.test(recent)) {
|
||||
sawMcpAuthChallenge = true;
|
||||
previousStderrTail = "";
|
||||
emitter.warning?.("grok-mcp-authorization", GROK_MCP_AUTH_HINT);
|
||||
} else {
|
||||
previousStderrTail = recent.slice(-512);
|
||||
}
|
||||
});
|
||||
|
||||
const closePromise = new Promise((resolve) => {
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
planReviewLifetime.abort();
|
||||
abortGuard?.clearTimer();
|
||||
if (!signal?.aborted) {
|
||||
try { lineBuffer.flush(); } catch { /* ignore */ }
|
||||
@@ -1163,7 +1206,7 @@ async function runGrokAcpTurn({
|
||||
child.on("error", (err) => {
|
||||
if (!state.failed && !signal?.aborted) {
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(err?.message || String(err)));
|
||||
emitter.emitError(formatGrokAcpError(err?.message || String(err)));
|
||||
}
|
||||
rpc.rejectAll(err || new Error("Grok ACP process error"));
|
||||
finish();
|
||||
@@ -1178,7 +1221,9 @@ async function runGrokAcpTurn({
|
||||
? `exited with code ${code}`
|
||||
: (exitSignal ? `terminated by signal ${exitSignal}` : "exited before the turn completed");
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser(stderr || `Grok ACP ${detail}`));
|
||||
emitter.emitError(sawMcpAuthChallenge
|
||||
? `Grok ACP ${detail}. ${GROK_MCP_AUTH_HINT}`
|
||||
: formatGrokAcpError(stderr || `Grok ACP ${detail}`));
|
||||
}
|
||||
// Unblock any in-flight RPC (initialize/prompt) so await rejects into catch.
|
||||
rpc.rejectAll(new Error("Grok ACP process closed"));
|
||||
@@ -1223,14 +1268,7 @@ async function runGrokAcpTurn({
|
||||
assertSessionValid,
|
||||
agentCapabilities: parseGrokAcpAgentCapabilities(initResult),
|
||||
});
|
||||
state.sessionId = established.sessionId;
|
||||
emitter.sessionId?.(established.sessionId);
|
||||
const effectivePrompt = resolveGrokTurnPrompt({
|
||||
turnPrompt: prompt,
|
||||
historySeed,
|
||||
resumeSessionId,
|
||||
establishMethod: established.method,
|
||||
});
|
||||
const effectivePrompt = await preparePrompt(rpc, established);
|
||||
|
||||
// Accept streamed updates only for this turn's prompt (not session/load replay).
|
||||
state.acceptUpdates = true;
|
||||
@@ -1249,9 +1287,9 @@ async function runGrokAcpTurn({
|
||||
state.failed = true;
|
||||
const message = err?.message || String(err);
|
||||
const stderr = stderrCollector.text().trim();
|
||||
emitter.emitError(formatGrokErrorForUser(
|
||||
stderr && !message.includes(stderr) ? `${message} (${stderr})` : message,
|
||||
));
|
||||
const detail = !sawMcpAuthChallenge && stderr && !message.includes(stderr)
|
||||
? `${message} (${stderr})` : message;
|
||||
emitter.emitError(formatGrokAcpError(detail, sawMcpAuthChallenge));
|
||||
}
|
||||
} finally {
|
||||
planReviewLifetime.abort();
|
||||
@@ -1276,7 +1314,7 @@ async function runGrokAcpTurn({
|
||||
emitter.emitDone();
|
||||
} else {
|
||||
state.failed = true;
|
||||
emitter.emitError(formatGrokErrorForUser("Grok ACP ended before the turn completed"));
|
||||
emitter.emitError(formatGrokAcpError("Grok ACP ended before the turn completed"));
|
||||
}
|
||||
|
||||
return { sessionId: state.sessionId, runtime: "acp" };
|
||||
|
||||
Loaded 100 of 146 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user