From b64c36fd40fe1d3ea3bbf7a328d0f8dc1ca82772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:29:32 +0800 Subject: [PATCH] feat(ui): inline compose directory picker and streamline AI session history UX (#4356) * feat(ui): inline compose directory picker and streamline AI session history UX * fix(ai): exclude workspace members and hidden terminals from active-elsewhere jump targets * fix(ai): clear non-AI magnification overlay when jumping to an active chat tab --- application/i18n/locales/en/ai.ts | 4 +- application/i18n/locales/es/ai.ts | 4 +- application/i18n/locales/ru/ai.ts | 4 +- application/i18n/locales/zh-CN/ai.ts | 4 +- application/i18n/locales/zh-TW/ai.ts | 4 +- application/state/useComposeBarHeight.ts | 4 +- .../AIChatSessionHistoryDrawer.test.tsx | 8 +-- components/AIChatSessionHistoryDrawer.tsx | 7 +-- components/AIChatSidePanel.tsx | 16 +++++ components/AIChatSidePanel.types.ts | 4 ++ components/TerminalLayer.tsx | 35 +++++++++++ .../ai/GlobalAIChatSessionManager.test.tsx | 58 +++++++++++++++++++ components/ai/GlobalAIChatSessionManager.tsx | 15 ++++- .../ai/globalSessionManagerRows.test.ts | 51 +++++++++++++++- components/ai/globalSessionManagerRows.ts | 50 +++++++++++++--- .../terminal/ComposeDirectoryPicker.tsx | 16 +++-- .../terminal/TerminalComposeBar.test.tsx | 3 + components/terminal/TerminalComposeBar.tsx | 28 +++++++-- .../terminalLayer/TerminalLayerSupport.tsx | 5 ++ .../terminalLayer/TerminalLayerTabBridge.tsx | 1 + .../terminalLayerSidePanelSlots.tsx | 2 + .../terminalLayer/terminalLayerViewMemo.ts | 1 + domain/aiPanelContextsEqual.ts | 4 ++ domain/buildAITerminalSessionInfo.ts | 4 ++ 24 files changed, 287 insertions(+), 45 deletions(-) diff --git a/application/i18n/locales/en/ai.ts b/application/i18n/locales/en/ai.ts index 52d8e69a8..960eed7a5 100644 --- a/application/i18n/locales/en/ai.ts +++ b/application/i18n/locales/en/ai.ts @@ -618,8 +618,8 @@ export const enAiMessages: Messages = { 'ai.chat.rebindUsage': 'Usage: /rebind ', 'ai.chat.rebindDone': 'Chat "{title}" rebound to this panel.', 'ai.chat.rebindUnavailable': 'No rebind target in this panel scope.', - 'ai.chat.managerScopeTab': 'Current', - 'ai.chat.managerAllChatsTab': 'All', + 'ai.chat.managerScopeTab': 'Current chats', + 'ai.chat.managerAllChatsTab': 'All chats', 'ai.chat.managerSearchPlaceholder': 'Search chat titles…', 'ai.chat.managerFilterAllAgents': 'All agents', 'ai.chat.managerMoreActions': 'More actions', diff --git a/application/i18n/locales/es/ai.ts b/application/i18n/locales/es/ai.ts index cfa2d58fb..ea2c70e2a 100644 --- a/application/i18n/locales/es/ai.ts +++ b/application/i18n/locales/es/ai.ts @@ -618,8 +618,8 @@ export const esAiMessages: Messages = { 'ai.chat.rebindUsage': 'Uso: /rebind ', 'ai.chat.rebindDone': 'Chat «{title}» reasociado a este panel.', 'ai.chat.rebindUnavailable': 'No hay destino de reasociación en el ámbito de este panel.', - 'ai.chat.managerScopeTab': 'Actual', - 'ai.chat.managerAllChatsTab': 'Todos', + 'ai.chat.managerScopeTab': 'Chats actuales', + 'ai.chat.managerAllChatsTab': 'Todos los chats', 'ai.chat.managerSearchPlaceholder': 'Buscar títulos de chats…', 'ai.chat.managerFilterAllAgents': 'Todos los agentes', 'ai.chat.managerMoreActions': 'Más acciones', diff --git a/application/i18n/locales/ru/ai.ts b/application/i18n/locales/ru/ai.ts index 36067f38b..02e476919 100644 --- a/application/i18n/locales/ru/ai.ts +++ b/application/i18n/locales/ru/ai.ts @@ -557,8 +557,8 @@ export const ruAiMessages: Messages = { 'ai.chat.rebindUsage': 'Использование: /rebind <номер из /chats>', 'ai.chat.rebindDone': 'Чат «{title}» привязан к этой панели.', 'ai.chat.rebindUnavailable': 'В области этой панели нет цели для привязки.', - 'ai.chat.managerScopeTab': 'Текущие', - 'ai.chat.managerAllChatsTab': 'Все', + 'ai.chat.managerScopeTab': 'Текущие чаты', + 'ai.chat.managerAllChatsTab': 'Все чаты', 'ai.chat.managerSearchPlaceholder': 'Поиск по названиям чатов…', 'ai.chat.managerFilterAllAgents': 'Все агенты', 'ai.chat.managerMoreActions': 'Ещё действия', diff --git a/application/i18n/locales/zh-CN/ai.ts b/application/i18n/locales/zh-CN/ai.ts index 60b972e79..3d3485890 100644 --- a/application/i18n/locales/zh-CN/ai.ts +++ b/application/i18n/locales/zh-CN/ai.ts @@ -618,8 +618,8 @@ export const zhCNAiMessages: Messages = { 'ai.chat.rebindUsage': '用法:/rebind <序号>', 'ai.chat.rebindDone': '聊天“{title}”已重绑到此面板。', 'ai.chat.rebindUnavailable': '当前面板范围内没有可用的重绑目标。', - 'ai.chat.managerScopeTab': '当前', - 'ai.chat.managerAllChatsTab': '全部', + 'ai.chat.managerScopeTab': '当前会话', + 'ai.chat.managerAllChatsTab': '全部会话', 'ai.chat.managerSearchPlaceholder': '搜索会话标题…', 'ai.chat.managerFilterAllAgents': '全部 Agent', 'ai.chat.managerMoreActions': '更多操作', diff --git a/application/i18n/locales/zh-TW/ai.ts b/application/i18n/locales/zh-TW/ai.ts index a722cc8a1..0230e5731 100644 --- a/application/i18n/locales/zh-TW/ai.ts +++ b/application/i18n/locales/zh-TW/ai.ts @@ -617,8 +617,8 @@ export const zhTWAiMessages: Messages = { 'ai.chat.rebindUsage': '用法:/rebind <序號>', 'ai.chat.rebindDone': '聊天「{title}」已重新綁定到此面板。', 'ai.chat.rebindUnavailable': '目前面板範圍內沒有可用的重新綁定目標。', - 'ai.chat.managerScopeTab': '目前', - 'ai.chat.managerAllChatsTab': '全部', + 'ai.chat.managerScopeTab': '目前會話', + 'ai.chat.managerAllChatsTab': '全部會話', 'ai.chat.managerSearchPlaceholder': '搜尋會話標題…', 'ai.chat.managerFilterAllAgents': '全部 Agent', 'ai.chat.managerMoreActions': '更多操作', diff --git a/application/state/useComposeBarHeight.ts b/application/state/useComposeBarHeight.ts index 8f89c6dd4..4f06377ae 100644 --- a/application/state/useComposeBarHeight.ts +++ b/application/state/useComposeBarHeight.ts @@ -2,8 +2,8 @@ import { useCallback } from 'react'; import { STORAGE_KEY_COMPOSE_BAR_HEIGHT } from '../../infrastructure/config/storageKeys'; import { useStoredNumber } from './useStoredNumber'; -export const COMPOSE_BAR_HEIGHT_DEFAULT = 144; -export const COMPOSE_BAR_HEIGHT_MIN = 104; +export const COMPOSE_BAR_HEIGHT_DEFAULT = 120; +export const COMPOSE_BAR_HEIGHT_MIN = 72; export const COMPOSE_BAR_HEIGHT_MAX = 360; const HEIGHT_CLAMP = { min: COMPOSE_BAR_HEIGHT_MIN, max: COMPOSE_BAR_HEIGHT_MAX }; diff --git a/components/AIChatSessionHistoryDrawer.test.tsx b/components/AIChatSessionHistoryDrawer.test.tsx index 726681a15..424592cfd 100644 --- a/components/AIChatSessionHistoryDrawer.test.tsx +++ b/components/AIChatSessionHistoryDrawer.test.tsx @@ -94,9 +94,6 @@ test("history drawer filters, pages, clears and explains the bounded search in e await enterQuery("[](){}"); assert.equal(rows().length, 0); assert.match(renderer.container.textContent ?? "", /No matches in titles or recent retained content/); - assert.match(renderer.container.textContent ?? "", /prioritizing newer messages and entries/); - assert.match(renderer.container.textContent ?? "", /only a limited portion at the beginning is searched/); - assert.match(renderer.container.textContent ?? "", /not full-text search/); await click(renderer.container.querySelector("input")?.parentElement?.querySelector("button")); assert.equal(renderer.container.querySelector("input")?.value, ""); assert.equal(rows().length, 80); @@ -113,13 +110,12 @@ test("history drawer filters, pages, clears and explains the bounded search in e await enterQuery("no-such-content"); const messages = getLoadedLocaleMessages(locale)!; const input = renderer.container.querySelector("input")!; - const hint = dom.document.getElementById(input.getAttribute("aria-describedby")!); - for (const key of ["ai.chat.searchSessions", "ai.chat.searchSessionsHint", "ai.chat.noMatchingSessions"]) { + for (const key of ["ai.chat.searchSessions", "ai.chat.noMatchingSessions"]) { assert.ok(messages[key], `${locale} is missing ${key}`); } assert.equal(input.placeholder, messages["ai.chat.searchSessions"]); assert.equal(input.getAttribute("aria-label"), messages["ai.chat.searchSessions"]); - assert.equal(hint?.textContent, messages["ai.chat.searchSessionsHint"]); + assert.equal(input.getAttribute("aria-describedby"), null); assert.ok(renderer.container.textContent?.includes(messages["ai.chat.noMatchingSessions"])); await render([], locale); assert.ok(renderer.container.textContent?.includes(messages["ai.chat.noSessions"])); diff --git a/components/AIChatSessionHistoryDrawer.tsx b/components/AIChatSessionHistoryDrawer.tsx index c203fbfe8..f57da1431 100644 --- a/components/AIChatSessionHistoryDrawer.tsx +++ b/components/AIChatSessionHistoryDrawer.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useId, useRef, useState } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { Download, MoreHorizontal, Pencil, Search, Trash2, Upload, X } from 'lucide-react'; import type { AISession } from '../infrastructure/ai/types'; import { useI18n } from '../application/i18n/I18nProvider'; @@ -57,7 +57,6 @@ export const SessionHistoryDrawer: React.FC = ({ const [renamingSessionId, setRenamingSessionId] = useState(null); const [renameDraft, setRenameDraft] = useState(''); const renameInputRef = useRef(null); - const searchHintId = useId(); const searchInputRef = useRef(null); const { filteredSessions, isSearching } = useSessionHistorySearch( sessions, @@ -201,7 +200,6 @@ export const SessionHistoryDrawer: React.FC = ({ maxLength={MAX_SEARCH_QUERY_LENGTH} placeholder={t('ai.chat.searchSessions')} aria-label={t('ai.chat.searchSessions')} - aria-describedby={searchHintId} onChange={(event) => setSearchQuery(truncateQueryForMatch(event.target.value))} className="h-8 pl-8 pr-7 text-[12px]" /> @@ -219,9 +217,6 @@ export const SessionHistoryDrawer: React.FC = ({ )} -

- {t('ai.chat.searchSessionsHint')} -

{isSearching && ( diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index e0cd2ced4..236257fda 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -329,6 +329,7 @@ const AIChatSidePanelActive: React.FC = ({ scopeLabel, focusedSessionId, onSetWorkspaceAnchorChat, + onFocusAIScopeTarget, workspaces = [], terminalSessions = [], appTerminalSessions, @@ -2322,6 +2323,17 @@ const AIChatSidePanelActive: React.FC = ({ workspaces, ]); + const handleManagerFocusScope = useCallback((target: { + type: 'terminal' | 'workspace'; + targetId: string; + }): boolean => { + const focused = onFocusAIScopeTarget?.(target) ?? false; + if (focused) { + setShowHistory(false); + } + return focused; + }, [onFocusAIScopeTarget]); + const handleManagerRebind = useCallback(async (sessionId: string, target: GlobalManagerScopeTarget) => { if (!rebindSessionScope) return; // A rebinding while a turn streams into the chat corrupts streaming state @@ -2397,6 +2409,7 @@ const AIChatSidePanelActive: React.FC = ({ externalAgents={externalAgents} rebindTargets={managerRebindTargets} onSelect={(sessionId) => { void handleManagerActivate(sessionId); }} + onFocusScope={onFocusAIScopeTarget ? handleManagerFocusScope : undefined} onRebind={handleManagerRebind} onRename={handleRenameSession} onDelete={(sessionId) => { void handleManagerDelete(sessionId); }} @@ -2414,10 +2427,12 @@ const AIChatSidePanelActive: React.FC = ({ externalAgents, managerRebindTargets, handleManagerActivate, + handleManagerFocusScope, handleManagerRebind, handleRenameSession, handleManagerDelete, handleManagerExport, + onFocusAIScopeTarget, ]); const handleAgentChange = useCallback((agentId: string) => { @@ -2632,6 +2647,7 @@ export function aiChatSidePanelPropsAreEqual( if (prev.onOpenVaultHost !== next.onOpenVaultHost) return false; if (prev.onOpenVaultSnippet !== next.onOpenVaultSnippet) return false; if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false; + if (prev.onFocusAIScopeTarget !== next.onFocusAIScopeTarget) return false; const scopeKey = `${prev.scopeType}:${prev.scopeTargetId ?? ''}`; if ( diff --git a/components/AIChatSidePanel.types.ts b/components/AIChatSidePanel.types.ts index 0f9a19f17..40046d717 100644 --- a/components/AIChatSidePanel.types.ts +++ b/components/AIChatSidePanel.types.ts @@ -112,6 +112,8 @@ export interface AIChatSidePanelProps { focusedSessionId?: string; /** Issue #4098 phase 2: pin the AI chat a workspace scope is anchored to. */ onSetWorkspaceAnchorChat?: (workspaceId: string, chatId: string | null) => void; + /** Focus an already-open terminal or workspace tab and ensure its AI side panel is visible. */ + onFocusAIScopeTarget?: (target: { type: 'terminal' | 'workspace'; targetId: string }) => boolean; /** Live workspaces (with their anchor chat and member host IDs), used for scope titles, anchor resolution, and explicit workspace rebinds. */ workspaces?: Array<{ id: string; title: string; anchorChatId?: string; hostIds?: string[] }>; /** All currently live terminal (and workspace) scope target ids. */ @@ -123,6 +125,8 @@ export interface AIChatSidePanelProps { hostname: string; label: string; connected: boolean; + workspaceId?: string; + hiddenFromTabs?: boolean; }>; // Terminal session context (from parent) diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index 8013315c2..9ae47461d 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -2097,6 +2097,40 @@ const TerminalLayerInner: React.FC = ({ handleSwitchSidePanelTab('ai'); }, [handleSwitchSidePanelTab]); + // Focus an already-open terminal or workspace hosting an active AI chat and + // ensure its AI side panel is visible, instead of moving/interrupting it. + const handleFocusAIScopeTarget = useCallback((target: { + type: 'terminal' | 'workspace'; + targetId: string; + }): boolean => { + let tabId: string | null = null; + if (target.type === 'workspace') { + const workspace = workspacesRef.current.find((candidate) => candidate.id === target.targetId); + if (!workspace) return false; + tabId = workspace.id; + } else { + const terminal = sessionsRef.current.find((candidate) => candidate.id === target.targetId); + // Reject hidden/popped-out terminals (no main-window tab) and workspace + // members (focused via their owning `workspace:` scope so the active + // chat shown in the workspace matches the clicked row). + if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false; + tabId = terminal.id; + } + setMagnifiedPane((current) => ( + current?.tabId === tabId + && !(current.target.kind === 'side-panel' && current.target.tool === 'ai') + ? null + : current + )); + activeTabStore.setActiveTabId(tabId); + if (prepareSidePanelTool(tabId, 'ai')) { + startTransition(() => { + selectSidePanelToolForTab(tabId, 'ai'); + }); + } + return true; + }, [prepareSidePanelTool, selectSidePanelToolForTab]); + const handleOpenSystem = useCallback(() => { handleSwitchSidePanelTab('system'); }, [handleSwitchSidePanelTab]); @@ -2715,6 +2749,7 @@ const TerminalLayerInner: React.FC = ({ handleOpenScripts, handleOpenTheme, handleOpenAI, + handleFocusAIScopeTarget, handleOpenSystem, handleOpenNotes, getActiveTerminalSessionId, diff --git a/components/ai/GlobalAIChatSessionManager.test.tsx b/components/ai/GlobalAIChatSessionManager.test.tsx index b77eed7fa..445edd6b2 100644 --- a/components/ai/GlobalAIChatSessionManager.test.tsx +++ b/components/ai/GlobalAIChatSessionManager.test.tsx @@ -48,6 +48,7 @@ function baseProps() { { type: "terminal" as const, targetId: "t-2", label: "core", hostIds: undefined as string[] | undefined }, ], onSelect: (_sessionId: string) => {}, + onFocusScope: undefined as ((_target: { type: "terminal" | "workspace"; targetId: string }) => boolean | void) | undefined, onRebind: (_sessionId: string, _target: { type: string; targetId: string; hostIds?: string[] }) => {}, onRename: undefined as ((_sessionId: string, _title: string) => void) | undefined, onDelete: (_sessionId: string) => {}, @@ -484,3 +485,60 @@ test("history drawer hosts the manager behind a current/all toggle", async () => dom.cleanup(); } }); + +test("clicking an active-elsewhere chat jumps to its open panel instead of moving it; past chats still open directly", async () => { + const dom = installDomEnvironment(); + try { + const props = baseProps(); + props.sessions = [ + makeSession({ id: "elsewhere-term", title: "Active in core", scope: { type: "terminal", targetId: "t-2" }, updatedAt: 300 }), + makeSession({ id: "elsewhere-ws", title: "Active in prod", scope: { type: "workspace", targetId: "w-1" }, updatedAt: 200 }), + makeSession({ id: "past-chat", title: "Closed host chat", scope: { type: "terminal", targetId: "t-gone", hostIds: ["h-old"] }, updatedAt: 100 }), + ]; + props.activeSessionIdMap = { + "terminal:t-2": "elsewhere-term", + "workspace:w-1": "elsewhere-ws", + }; + const selected: string[] = []; + const focused: Array<{ type: "terminal" | "workspace"; targetId: string }> = []; + props.onSelect = (id) => selected.push(id); + props.onFocusScope = (target) => { + focused.push(target); + return true; + }; + const renderer = await renderManager(dom, props); + + const byId = (id: string) => rows(renderer).find((row) => row.dataset.sessionId === id)!; + await dispatchDomEvent(byId("elsewhere-term"), new dom.window.MouseEvent("click", { bubbles: true })); + await dispatchDomEvent(byId("elsewhere-ws"), new dom.window.KeyboardEvent("keydown", { key: "Enter", bubbles: true })); + await dispatchDomEvent(byId("past-chat"), new dom.window.MouseEvent("click", { bubbles: true })); + + assert.deepEqual(focused, [ + { type: "terminal", targetId: "t-2" }, + { type: "workspace", targetId: "w-1" }, + ]); + assert.deepEqual(selected, ["past-chat"]); + } finally { + dom.cleanup(); + } +}); + +test("clicking an active-elsewhere chat falls back to opening locally when focusing the target panel fails", async () => { + const dom = installDomEnvironment(); + try { + const props = baseProps(); + props.sessions = [ + makeSession({ id: "elsewhere-term", title: "Active in core", scope: { type: "terminal", targetId: "t-2" } }), + ]; + props.activeSessionIdMap = { "terminal:t-2": "elsewhere-term" }; + const selected: string[] = []; + props.onSelect = (id) => selected.push(id); + props.onFocusScope = () => false; + const renderer = await renderManager(dom, props); + + await dispatchDomEvent(rows(renderer)[0], new dom.window.MouseEvent("click", { bubbles: true })); + assert.deepEqual(selected, ["elsewhere-term"]); + } finally { + dom.cleanup(); + } +}); diff --git a/components/ai/GlobalAIChatSessionManager.tsx b/components/ai/GlobalAIChatSessionManager.tsx index a0573360f..fee477365 100644 --- a/components/ai/GlobalAIChatSessionManager.tsx +++ b/components/ai/GlobalAIChatSessionManager.tsx @@ -51,6 +51,8 @@ interface GlobalAIChatSessionManagerProps { externalAgents: ExternalAgentConfig[]; rebindTargets: GlobalManagerScopeTarget[]; onSelect: (sessionId: string) => void; + /** Focus an already-open terminal or workspace hosting an active chat instead of moving it. */ + onFocusScope?: (target: { type: 'terminal' | 'workspace'; targetId: string }) => boolean | void; onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void; onRename?: (sessionId: string, title: string) => void; onDelete: (sessionId: string) => void; @@ -72,6 +74,7 @@ export const GlobalAIChatSessionManager: React.FC[number]) => { + if (row.isActiveElsewhere && row.activeElsewhereTarget && onFocusScope) { + const focused = onFocusScope(row.activeElsewhereTarget); + if (focused !== false) return; + } + onSelect(row.session.id); + }; + return (
@@ -264,13 +275,13 @@ export const GlobalAIChatSessionManager: React.FC { - if (!isRenaming && row.canActivate) onSelect(row.session.id); + if (!isRenaming && row.canActivate) activateRow(row); }} onKeyDown={(e) => { if (e.target !== e.currentTarget) return; if (!isRenaming && row.canActivate && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); - onSelect(row.session.id); + activateRow(row); } }} className={cn( diff --git a/components/ai/globalSessionManagerRows.test.ts b/components/ai/globalSessionManagerRows.test.ts index 976718b67..75cf29711 100644 --- a/components/ai/globalSessionManagerRows.test.ts +++ b/components/ai/globalSessionManagerRows.test.ts @@ -101,20 +101,69 @@ test("active marker distinguishes current panel active chat vs active elsewhere" input.sessions = [ baseSession({ id: "s-active-here", scope: { type: "terminal", targetId: "t-1" } }), baseSession({ id: "s-active-elsewhere", scope: { type: "terminal", targetId: "t-2" } }), + baseSession({ id: "s-active-workspace", scope: { type: "workspace", targetId: "w-1" } }), + baseSession({ id: "s-stale-active", scope: { type: "terminal", targetId: "t-dead" } }), baseSession({ id: "s-idle", scope: { type: "terminal", targetId: "t-1" } }), ]; - input.activeSessionIdMap = { "terminal:t-1": "s-active-here", "terminal:t-2": "s-active-elsewhere" }; + input.activeSessionIdMap = { + "terminal:t-1": "s-active-here", + "terminal:t-2": "s-active-elsewhere", + "workspace:w-1": "s-active-workspace", + "terminal:t-dead": "s-stale-active", + }; const rows = buildGlobalManagerRows(input); const byId = new Map(rows.map((row) => [row.session.id, row])); assert.equal(byId.get("s-active-here")!.scopeState, "active"); assert.equal(byId.get("s-active-here")!.isCurrentActive, true); assert.equal(byId.get("s-active-here")!.isActiveElsewhere, false); + assert.equal(byId.get("s-active-here")!.activeElsewhereTarget, null); assert.equal(byId.get("s-active-elsewhere")!.scopeState, "active"); assert.equal(byId.get("s-active-elsewhere")!.isCurrentActive, false); assert.equal(byId.get("s-active-elsewhere")!.isActiveElsewhere, true); + assert.deepEqual(byId.get("s-active-elsewhere")!.activeElsewhereTarget, { type: "terminal", targetId: "t-2" }); + assert.equal(byId.get("s-active-workspace")!.scopeState, "active"); + assert.equal(byId.get("s-active-workspace")!.isActiveElsewhere, true); + assert.deepEqual(byId.get("s-active-workspace")!.activeElsewhereTarget, { type: "workspace", targetId: "w-1" }); + // Stale active map entries for closed scopes must not mark a past chat as active elsewhere. + assert.equal(byId.get("s-stale-active")!.scopeState, "dangling"); + assert.equal(byId.get("s-stale-active")!.isActiveElsewhere, false); + assert.equal(byId.get("s-stale-active")!.activeElsewhereTarget, null); assert.equal(byId.get("s-idle")!.scopeState, "idle"); assert.equal(byId.get("s-idle")!.isCurrentActive, false); assert.equal(byId.get("s-idle")!.isActiveElsewhere, false); + assert.equal(byId.get("s-idle")!.activeElsewhereTarget, null); +}); + +test("workspace member and hidden terminal active pointers are not treated as jumpable elsewhere panels", () => { + const input = baseInput(); + input.terminalInfos = [ + ...input.terminalInfos, + { sessionId: "t-member", hostId: "h-3", label: "member", hostname: "member.example", connected: true, workspaceId: "w-1" }, + { sessionId: "t-hidden", hostId: "h-4", label: "popout", hostname: "popout.example", connected: true, hiddenFromTabs: true }, + ]; + input.sessions = [ + baseSession({ id: "s-ws-active", scope: { type: "workspace", targetId: "w-1" } }), + baseSession({ id: "s-member-retained", scope: { type: "terminal", targetId: "t-member" } }), + baseSession({ id: "s-hidden-active", scope: { type: "terminal", targetId: "t-hidden" } }), + ]; + input.activeSessionIdMap = { + "workspace:w-1": "s-ws-active", + "terminal:t-member": "s-member-retained", + "terminal:t-hidden": "s-hidden-active", + }; + const rows = buildGlobalManagerRows(input); + const byId = new Map(rows.map((row) => [row.session.id, row])); + + assert.equal(byId.get("s-ws-active")!.isActiveElsewhere, true); + assert.deepEqual(byId.get("s-ws-active")!.activeElsewhereTarget, { type: "workspace", targetId: "w-1" }); + + assert.equal(byId.get("s-member-retained")!.isActiveElsewhere, false); + assert.equal(byId.get("s-member-retained")!.activeElsewhereTarget, null); + assert.equal(byId.get("s-member-retained")!.scopeState, "idle"); + + assert.equal(byId.get("s-hidden-active")!.isActiveElsewhere, false); + assert.equal(byId.get("s-hidden-active")!.activeElsewhereTarget, null); + assert.equal(byId.get("s-hidden-active")!.scopeState, "idle"); }); test("rows sort by updatedAt descending and carry agent labels + counts", () => { diff --git a/components/ai/globalSessionManagerRows.ts b/components/ai/globalSessionManagerRows.ts index 8b3921249..1b05a9c99 100644 --- a/components/ai/globalSessionManagerRows.ts +++ b/components/ai/globalSessionManagerRows.ts @@ -20,6 +20,8 @@ export interface GlobalManagerTerminalInfo { label: string; hostname: string; connected: boolean; + workspaceId?: string; + hiddenFromTabs?: boolean; } export interface GlobalManagerHostInfo { @@ -50,9 +52,11 @@ export interface GlobalManagerRow { isCurrentActive: boolean; /** True when the chat is currently active in another open panel. */ isActiveElsewhere: boolean; + /** Live panel currently displaying this chat when `isActiveElsewhere` is true. */ + activeElsewhereTarget: { type: 'terminal' | 'workspace'; targetId: string } | null; /** - * Clicking the row opens the chat in the viewing panel: directly when it is - * already in scope, or by attaching it to the viewing panel automatically. + * Clicking the row jumps to the owning open panel when active elsewhere, or + * opens the chat in the viewing panel directly when in scope or historical. */ canActivate: boolean; messageCount: number; @@ -114,15 +118,39 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob hostNamesById.set(info.hostId, name); } } - const activeSessionIds = new Set( - Object.values(activeSessionIdMap).filter((id): id is string => Boolean(id)), - ); const currentScopeKey = currentScopeTargetId ? `${currentScopeType}:${currentScopeTargetId}` : null; const currentPanelActiveSessionId = currentScopeKey ? activeSessionIdMap[currentScopeKey] ?? null : null; + const activeElsewhereTargetBySessionId = new Map< + string, + { type: 'terminal' | 'workspace'; targetId: string } + >(); + for (const [scopeKey, activeChatId] of Object.entries(activeSessionIdMap)) { + if (!activeChatId || scopeKey === currentScopeKey) continue; + if (scopeKey.startsWith('workspace:')) { + const targetId = scopeKey.slice('workspace:'.length); + if (workspaceTitles.has(targetId) && !activeElsewhereTargetBySessionId.has(activeChatId)) { + activeElsewhereTargetBySessionId.set(activeChatId, { type: 'workspace', targetId }); + } + } else if (scopeKey.startsWith('terminal:')) { + const targetId = scopeKey.slice('terminal:'.length); + const terminal = liveTerminals.get(targetId); + // Only standalone, visible main-window terminal tabs own an independent + // AI side panel. Workspace members defer to their `workspace:` panel + // pointer, and hidden/popped-out terminals have no main-window tab. + if ( + terminal + && !terminal.workspaceId + && !terminal.hiddenFromTabs + && !activeElsewhereTargetBySessionId.has(activeChatId) + ) { + activeElsewhereTargetBySessionId.set(activeChatId, { type: 'terminal', targetId }); + } + } + } return sessions .map((session) => { @@ -158,7 +186,10 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob } const isCurrentActive = currentPanelActiveSessionId === session.id; - const isActiveElsewhere = !isCurrentActive && !isDangling && activeSessionIds.has(session.id); + const activeElsewhereTarget = !isCurrentActive + ? activeElsewhereTargetBySessionId.get(session.id) ?? null + : null; + const isActiveElsewhere = activeElsewhereTarget !== null; return { session, @@ -166,15 +197,16 @@ export function buildGlobalManagerRows(input: BuildGlobalManagerRowsInput): Glob agentId: session.agentId, agentLabel: resolveChatAgentLabel(session.agentId, externalAgents), scopeLabel, - scopeState: isDangling + scopeState: isDangling && !isActiveElsewhere ? 'dangling' - : activeSessionIds.has(session.id) + : isCurrentActive || isActiveElsewhere ? 'active' : 'idle', isCurrentView, isCurrentActive, isActiveElsewhere, - canActivate: Boolean(isCurrentView || currentScopeTargetId), + activeElsewhereTarget, + canActivate: Boolean(isCurrentView || currentScopeTargetId || isActiveElsewhere), messageCount: session.messages.length, } satisfies GlobalManagerRow; }) diff --git a/components/terminal/ComposeDirectoryPicker.tsx b/components/terminal/ComposeDirectoryPicker.tsx index 8d91c00a8..665d4fe1c 100644 --- a/components/terminal/ComposeDirectoryPicker.tsx +++ b/components/terminal/ComposeDirectoryPicker.tsx @@ -1,12 +1,12 @@ import { ArrowUp, ChevronDown, Folder, LoaderCircle, RefreshCw } from 'lucide-react'; -import { useEffect, useId, useRef, useState } from 'react'; +import { memo, useEffect, useId, useRef, useState } from 'react'; import { useI18n } from '../../application/i18n/I18nProvider'; import { useComposeDirectoryPicker } from '../../application/state/useComposeDirectoryPicker'; import { directoryDisplayName, directoryLabel } from '../../domain/directoryPicker'; import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'; import type { ComposeBarTheme } from './TerminalComposeBar'; -export function ComposeDirectoryPicker({ sessionId, theme, onReturnFocus }: { +export const ComposeDirectoryPicker = memo(function ComposeDirectoryPicker({ sessionId, theme, onReturnFocus }: { sessionId: string; theme: ComposeBarTheme; onReturnFocus: () => void; }) { const { t } = useI18n(); @@ -47,14 +47,20 @@ export function ComposeDirectoryPicker({ sessionId, theme, onReturnFocus }: {
); return ( -
+
{ if (value) outside.current = false; model.setOpen(value); }}>
); -} +}); diff --git a/components/terminal/TerminalComposeBar.test.tsx b/components/terminal/TerminalComposeBar.test.tsx index 9bace6db2..c73198b01 100644 --- a/components/terminal/TerminalComposeBar.test.tsx +++ b/components/terminal/TerminalComposeBar.test.tsx @@ -44,6 +44,9 @@ test('disabling Context Chips preserves the compose draft and stops extra cwd re let root!: ReactTestRenderer; await act(async () => { root = create(render(true), { createNodeMock: el => el.type === 'textarea' ? textarea : null }); }); assert.equal(probes, 1); + const topBar = root.root.findByProps({ 'data-compose-top-bar': true }); + assert.equal(topBar.findAllByProps({ 'aria-label': 'Context Chips' }).length, 1); + assert.equal(topBar.findAllByProps({ 'data-compose-snippet-strip': true }).length, 1); textarea.value = 'keep this draft'; textarea.selectionStart = 2; textarea.selectionEnd = 8; await act(async () => { root.update(render(false)); }); assert.equal(root.root.findAllByProps({ 'aria-label': 'Context Chips' }).length, 0); diff --git a/components/terminal/TerminalComposeBar.tsx b/components/terminal/TerminalComposeBar.tsx index f1cfbece3..cf5865d9e 100644 --- a/components/terminal/TerminalComposeBar.tsx +++ b/components/terminal/TerminalComposeBar.tsx @@ -740,6 +740,10 @@ export const TerminalComposeBar: React.FC = ({ } }, [handleSend, navigate, onClose, sessionId]); + const handleReturnFocus = useCallback(() => { + textareaRef.current?.focus({ preventScroll: true }); + }, []); + const handleResizeStart = useCallback((e: React.MouseEvent) => { e.preventDefault(); resizeCleanupRef.current?.(); @@ -804,9 +808,28 @@ export const TerminalComposeBar: React.FC = ({
+ {contextChipsEnabled && ( + <> + + {pinnedSnippets.length > 0 && ( +