From 8ebbf3db10d1921edd548e4dd604a9cb2e9ad231 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:28:10 -0800 Subject: [PATCH] perf: remove unused dashboard launch projection --- .../dashboard/build-dashboard-snapshot.ts | 18 --- .../dashboard-chat-program-acquisition.ts | 41 ----- .../dashboard-worktree-launch-options.ts | 153 ------------------ .../dashboard/useDashboardPopoutBridge.ts | 25 +-- .../dashboard/useLiveDashboardSnapshot.ts | 40 +---- .../ai-vault/panel/AiVaultPanel.tsx | 2 + .../use-ai-vault-resume-catalogs.test.tsx | 138 ++++++++++++++++ .../use-ai-vault-resume-catalogs.ts | 75 +++++++++ 8 files changed, 226 insertions(+), 266 deletions(-) delete mode 100644 src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts delete mode 100644 src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts create mode 100644 src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.ts diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts index bd8c099b15d..3bcaa52e3a1 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts @@ -1,6 +1,5 @@ import { agentVerdictDisplayMark } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { StructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-tab-name' -import type { AgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import type { AppState } from '@/store/types' import { DASHBOARD_MAX_MAP_WORKSPACES, @@ -42,10 +41,6 @@ import { rowConversationName, rowTask } from './dashboard-card-labels' -import { - buildDashboardWorktreeLaunchOptions, - type DashboardLaunchDetectionState -} from './dashboard-worktree-launch-options' import { buildDashboardSnapshotFilterOptions } from './dashboard-snapshot-filter-options' import { groupSubagentsByParentPaneKey } from './dashboard-subagent-cards' import { selectDashboardOrchestration } from './dashboard-orchestration-selection' @@ -71,7 +66,6 @@ export type DashboardSnapshotState = Pick< DashboardCardContextState & Partial< DashboardCardTerminalInputState & - DashboardLaunchDetectionState & Pick< AppState, | 'runtimeEnvironments' @@ -89,7 +83,6 @@ export function buildDashboardSnapshot( state: DashboardSnapshotInput, now: number, options: { - launchRouteStore?: AgentLaunchRouteView includeCardDetails?: boolean includeFilterOptions?: boolean /** Cache only row derivation; review/host/status inputs still require fresh card assembly. */ @@ -274,17 +267,6 @@ export function buildDashboardSnapshot( ...(workspaces ? { workspaces } : {}), showIdle, filterOptions, - // Count-only callers offer no launcher; skip host-detection lookups for sidebar rebuilds. - ...(includeCardDetails - ? { - launchableAgentsByWorktreeId: buildDashboardWorktreeLaunchOptions( - state, - cards, - workspaces, - options.launchRouteStore - ) - } - : {}), repoIconsByRepoId } } diff --git a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts b/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts deleted file mode 100644 index b3f8308d39c..00000000000 --- a/src/renderer/src/components/dashboard/dashboard-chat-program-acquisition.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { AppState } from '@/store/types' -import { holdChatProgramFacts } from '@/lib/host-chat-program-acquisition' -import { resolveChatProgramContext } from '@/lib/host-chat-program' -import { - selectAgentLaunchRouteView, - worktreeLaunchWorkspace -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { DASHBOARD_MAX_LAUNCH_WORKTREES } from '../../../../shared/dashboard-snapshot' -import { collectActiveDashboardWorkspaces } from './dashboard-snapshot-workspaces' - -/** Publishers reconcile one hold per represented execution resource before building payloads. */ -export function createDashboardChatProgramHolds() { - const held = new Map void>() - return { - reconcile(state: AppState): void { - const next = new Set() - const routeStore = selectAgentLaunchRouteView(state) - const shown = collectActiveDashboardWorkspaces(state, false) - for (const { worktree } of shown.slice(0, DASHBOARD_MAX_LAUNCH_WORKTREES)) { - const context = resolveChatProgramContext(routeStore, worktreeLaunchWorkspace(worktree.id)) - const key = context.revision - next.add(key) - if (!held.has(key)) { - // A new hold can notify synchronously and re-enter this reconcile: reserve its key first. - held.set(key, () => {}) - held.set(key, holdChatProgramFacts(context).release) - } - } - for (const [key, release] of held) { - if (!next.has(key)) { - release() - held.delete(key) - } - } - }, - release(): void { - held.forEach((release) => release()) - held.clear() - } - } -} diff --git a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts b/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts deleted file mode 100644 index b274999aa7d..00000000000 --- a/src/renderer/src/components/dashboard/dashboard-worktree-launch-options.ts +++ /dev/null @@ -1,153 +0,0 @@ -import type { AppState } from '@/store/types' -import { parseExecutionHostId } from '../../../../shared/execution-host' -import { - DASHBOARD_MAX_LAUNCH_WORKTREES, - type DashboardCard, - type DashboardWorkspace -} from '../../../../shared/dashboard-snapshot' -import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' -import { - filterEnabledTuiAgents, - TUI_AGENT_AUTO_PICK_ORDER -} from '../../../../shared/agent-launch/catalog/tui-agent-selection' -import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import { parseWorkspaceKey } from '../../../../shared/workspace-scope' -import { getRuntimeAgentInventoryKey } from '@/store/slices/agent-inventory/runtime-agent-inventory-key' -import { - worktreeLaunchWorkspace, - type AgentLaunchRouteView -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import { agentsOfferedForLaunch } from '@/lib/host-chat-program' -import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' - -export type DashboardLaunchDetectionState = Pick< - AppState, - | 'detectedAgentIds' - | 'folderWorkspaces' - | 'projectGroups' - | 'remoteDetectedAgentIds' - | 'runtimeDetectedAgentIds' -> - -type DashboardLaunchOptionState = Pick & - Partial - -type DashboardLaunchCatalog = { - foldersById: Map - groupsById: Map - reposById: Map - worktreesByRepoAndId: Map> -} - -function buildDashboardLaunchCatalog(state: DashboardLaunchOptionState): DashboardLaunchCatalog { - return { - foldersById: new Map((state.folderWorkspaces ?? []).map((folder) => [folder.id, folder])), - groupsById: new Map((state.projectGroups ?? []).map((group) => [group.id, group])), - reposById: new Map((state.repos ?? []).map((repo) => [repo.id, repo])), - worktreesByRepoAndId: new Map( - Object.entries(selectWorktreesByRepo(state) ?? {}).map(([repoId, worktrees]) => [ - repoId, - new Map(worktrees.map((worktree) => [worktree.id, worktree])) - ]) - ) - } -} - -// Why the host-default fallback: a card can render before any launch surface probed its workspace. -function runtimeAgentsForWorkspace( - state: DashboardLaunchOptionState, - environmentId: string, - worktreeId: string -): readonly TuiAgent[] { - const agents = state.runtimeDetectedAgentIds - return ( - agents?.[getRuntimeAgentInventoryKey(environmentId, worktreeId)] ?? - agents?.[environmentId] ?? - [] - ) -} - -function detectedAgentsForWorktree( - state: DashboardLaunchOptionState, - worktreeId: string, - repoId: string, - catalog: DashboardLaunchCatalog -): readonly TuiAgent[] { - const workspaceScope = parseWorkspaceKey(worktreeId) - if (workspaceScope?.type === 'folder') { - const folder = catalog.foldersById.get(workspaceScope.folderWorkspaceId) - const group = folder ? catalog.groupsById.get(folder.projectGroupId) : undefined - const host = parseExecutionHostId(group?.executionHostId) - if (host?.kind === 'runtime') { - return runtimeAgentsForWorkspace(state, host.environmentId, worktreeId) - } - const connectionId = folder?.connectionId ?? group?.connectionId - return connectionId ? (state.remoteDetectedAgentIds?.[connectionId] ?? []) : [] - } - - const worktree = catalog.worktreesByRepoAndId.get(repoId)?.get(worktreeId) - const repo = catalog.reposById.get(worktree?.repoId ?? repoId) - const host = parseExecutionHostId(worktree?.hostId ?? repo?.executionHostId) - if (host?.kind === 'runtime') { - return runtimeAgentsForWorkspace(state, host.environmentId, worktreeId) - } - const connectionId = host?.kind === 'ssh' ? host.targetId : repo?.connectionId - return connectionId - ? (state.remoteDetectedAgentIds?.[connectionId] ?? []) - : (state.detectedAgentIds ?? []) -} - -/** Host-detected choices, agents that open as a chat there, and providers proven to run there. */ -export function buildDashboardWorktreeLaunchOptions( - state: DashboardLaunchOptionState, - cards: readonly DashboardCard[], - workspaces: readonly DashboardWorkspace[] = [], - launchRouteStore?: AgentLaunchRouteView -): Record { - const catalog = buildDashboardLaunchCatalog(state) - const cardsByWorktreeId = new Map() - const repoIdByWorktreeId = new Map( - workspaces.map((workspace) => [workspace.worktreeId, workspace.repoId]) - ) - for (const card of cards) { - repoIdByWorktreeId.set(card.worktreeId, card.repoId) - const existing = cardsByWorktreeId.get(card.worktreeId) - if (existing) { - existing.push(card) - } else { - cardsByWorktreeId.set(card.worktreeId, [card]) - } - } - - const result: Record = {} - let worktreeCount = 0 - for (const [worktreeId, repoId] of repoIdByWorktreeId) { - // Bound launch options before validation would reject the entire snapshot. - if (worktreeCount >= DASHBOARD_MAX_LAUNCH_WORKTREES) { - break - } - worktreeCount += 1 - const worktreeCards = cardsByWorktreeId.get(worktreeId) ?? [] - const detected = detectedAgentsForWorktree(state, worktreeId, repoId, catalog) - const available = new Set( - launchRouteStore - ? agentsOfferedForLaunch(launchRouteStore, worktreeLaunchWorkspace(worktreeId), detected) - : detected - ) - for (const card of worktreeCards) { - if (isTuiAgent(card.agentType)) { - available.add(card.agentType) - } - } - const enabled = filterEnabledTuiAgents( - TUI_AGENT_AUTO_PICK_ORDER.filter((agent) => available.has(agent)), - state.settings?.disabledTuiAgents - ) - const preferred = state.settings?.defaultTuiAgent - result[worktreeId] = - preferred && preferred !== 'blank' && enabled.includes(preferred) - ? [preferred, ...enabled.filter((agent) => agent !== preferred)] - : enabled - } - return result -} diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index 17247a60c28..1bd53b4ff5a 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -1,4 +1,3 @@ -import { createDashboardChatProgramHolds } from './dashboard-chat-program-acquisition' import { useEffect } from 'react' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' @@ -6,12 +5,6 @@ import { subscribeStructuredChatTabNames, getStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' -import { subscribeChatProgramFacts } from '@/lib/host-chat-program' -import { - type AgentLaunchRouteView, - agentLaunchRouteInputsChanged, - selectAgentLaunchRouteView -} from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { revealDashboardAgent } from './reveal-dashboard-agent' import type { RepoIcon } from '../../../../shared/repo-icon' import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot' @@ -36,16 +29,15 @@ export function repoIconsUnchanged( return nextIds.every((id) => id in previous && next[id] === previous[id]) } -type DashboardSnapshotWatchState = DashboardSnapshotState & - Pick & - AgentLaunchRouteView +type DashboardSnapshotWatchState = DashboardSnapshotState & Pick export function dashboardSnapshotInputsChanged( state: DashboardSnapshotWatchState, previousState: DashboardSnapshotWatchState ): boolean { return ( - agentLaunchRouteInputsChanged(state, previousState) || + state.activeWorktreeId !== previousState.activeWorktreeId || + state.activeWorkspaceExecutionHostId !== previousState.activeWorkspaceExecutionHostId || state.repos !== previousState.repos || selectWorktreesByRepo(state) !== selectWorktreesByRepo(previousState) || state.tabsByWorktree !== previousState.tabsByWorktree || @@ -62,9 +54,6 @@ export function dashboardSnapshotInputsChanged( // Why: settings controls idle visibility and generated conversation names. state.settings !== previousState.settings || state.workspaceStatuses !== previousState.workspaceStatuses || - state.detectedAgentIds !== previousState.detectedAgentIds || - state.remoteDetectedAgentIds !== previousState.remoteDetectedAgentIds || - state.runtimeDetectedAgentIds !== previousState.runtimeDetectedAgentIds || // Relay live hooks directly; rebuild snapshots for host-profile changes too, since idle boards may have no later event to correct stale byte routing. state.sshConnectionStates !== previousState.sshConnectionStates || state.sshStateByEnvironment !== previousState.sshStateByEnvironment || @@ -92,12 +81,9 @@ export function watchSnapshotInputs(onChanged: () => void): () => void { onChanged() } }) - // Launch options also read host chat facts held outside the store. - const unsubscribeChatFacts = subscribeChatProgramFacts(onChanged) return () => { stopNames() unsubscribeStore() - unsubscribeChatFacts() } } @@ -128,7 +114,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { } let open = false let disposed = false - const chatOwners = createDashboardChatProgramHolds() let unsubscribeStore: (() => void) | null = null let trailingTimer: ReturnType | null = null let lastPublishAt = 0 @@ -139,12 +124,10 @@ export function useDashboardPopoutBridge(enabled: boolean): void { const publishNow = (withIcons: boolean): void => { lastPublishAt = Date.now() const state = useAppStore.getState() - chatOwners.reconcile(state) const snapshot = buildDashboardSnapshot( { ...state, chatNames: getStructuredChatTabNames() }, lastPublishAt, { - launchRouteStore: selectAgentLaunchRouteView(state), rowsCache, rowsGeneration: state.agentStatusEpoch } @@ -210,7 +193,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { } publishNow(true) } else { - chatOwners.release() unsubscribeStore?.() unsubscribeStore = null if (trailingTimer) { @@ -236,7 +218,6 @@ export function useDashboardPopoutBridge(enabled: boolean): void { return () => { disposed = true - chatOwners.release() offOpenChanged?.() offRequested?.() unsubscribeStore?.() diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index bb2225f0e39..481ae3e6d2d 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -1,13 +1,9 @@ -import { watchSnapshotInputs } from './useDashboardPopoutBridge' -import { createDashboardChatProgramHolds } from './dashboard-chat-program-acquisition' -import { useEffect, useMemo, useRef } from 'react' +import { useMemo, useRef } from 'react' import { useAppStore } from '@/store' import { useStructuredChatTabNames } from '@/runtime/native-chat/naming/structured-chat-name-observation' import type { DashboardSnapshot } from '../../../../shared/dashboard-snapshot' import { buildDashboardSnapshot } from './build-dashboard-snapshot' -import { useChatProgramFactsVersion } from '@/lib/host-chat-program-acquisition' import { createWorktreeAgentRowsCache } from './worktree-agent-rows-cache' -import { selectAgentLaunchRouteView } from '@/lib/agent-session/launch/routing/agent-launch-route-input' import { selectDetectedWorktreesByRepo, selectFolderWorkspaces, @@ -53,25 +49,11 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { const runtimeEnvironmentCatalogHydrated = useAppStore((s) => s.runtimeEnvironmentCatalogHydrated) const removedRuntimeEnvironmentIds = useAppStore((s) => s.removedRuntimeEnvironmentIds) const paneForegroundAgentByPaneKey = useAppStore((s) => s.paneForegroundAgentByPaneKey) - const detectedAgentIds = useAppStore((s) => s.detectedAgentIds) - const remoteDetectedAgentIds = useAppStore((s) => s.remoteDetectedAgentIds) - const runtimeDetectedAgentIds = useAppStore((s) => s.runtimeDetectedAgentIds) // Freshness can change buckets without map writes; the epoch invalidates stale-decay memos. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) const chatNames = useStructuredChatTabNames() - // Why: launch options read only this view, so any route input change rebuilds them. - const launchRouteStore = useAppStore(selectAgentLaunchRouteView) - useEffect(() => { - const holds = createDashboardChatProgramHolds() - const reconcile = (): void => holds.reconcile(useAppStore.getState()) - const stopWatching = watchSnapshotInputs(reconcile) - reconcile() - return () => { - stopWatching() - holds.release() - } - }, []) - const chatProgramFactsVersion = useChatProgramFactsVersion() + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const activeWorkspaceExecutionHostId = useAppStore((s) => s.activeWorkspaceExecutionHostId) return useMemo( // Read the clock when the freshness epoch invalidates this memo, matching row derivation. @@ -79,8 +61,8 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { buildDashboardSnapshot( { chatNames, - activeWorktreeId: launchRouteStore.activeWorktreeId, - activeWorkspaceExecutionHostId: launchRouteStore.activeWorkspaceExecutionHostId, + activeWorktreeId, + activeWorkspaceExecutionHostId, repos, worktreesByRepo, tabsByWorktree, @@ -109,15 +91,12 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { runtimeEnvironmentCatalogHydrated, removedRuntimeEnvironmentIds, paneForegroundAgentByPaneKey, - detectedAgentIds, - remoteDetectedAgentIds, - runtimeDetectedAgentIds, // Read launch identity non-reactively because Shift+Enter routing does not depend on it; match the bridge gate. agentLaunchConfigByPaneKey: useAppStore.getState().agentLaunchConfigByPaneKey }, Date.now(), // Reuse unchanged worktree rows while assembling cards fresh from current review/host/status slices. - { rowsCache: rowsCacheRef.current, rowsGeneration: agentStatusEpoch, launchRouteStore } + { rowsCache: rowsCacheRef.current, rowsGeneration: agentStatusEpoch } ), // eslint-disable-next-line react-hooks/exhaustive-deps [ @@ -149,12 +128,9 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { runtimeEnvironmentCatalogHydrated, removedRuntimeEnvironmentIds, paneForegroundAgentByPaneKey, - detectedAgentIds, - remoteDetectedAgentIds, - runtimeDetectedAgentIds, chatNames, - chatProgramFactsVersion, - launchRouteStore, + activeWorktreeId, + activeWorkspaceExecutionHostId, agentStatusEpoch ] ) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx b/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx index c7cb212c32f..b45c616e831 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx +++ b/src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanel.tsx @@ -38,6 +38,7 @@ import { useAiVaultPanelSearch } from '../search/use-ai-vault-search' import { useAiVaultPanelSearchSessions } from '../search/ai-vault-search-session' import { aiVaultSearchScopeIdentity } from '../search/ai-vault-search-scope-identity' import { AiVaultPanelSearch } from '../search/AiVaultPanelSearch' +import { useAiVaultResumeCatalogs } from '../session-actions/use-ai-vault-resume-catalogs' import { useAiVaultPanelSessionResume } from '../session-actions/use-ai-vault-panel-session-resume' import { AiVaultScanProgressStrip } from '../scanning/AiVaultScanProgressStrip' import { useAiVaultScanProgress } from '../scanning/ai-vault-scan-progress-store' @@ -108,6 +109,7 @@ export default function AiVaultPanel({ } = usePersistedAiVaultViewOptions(initialAgents) const { executionHostScope, onExecutionHostScopeChange, hostScopeOptions } = useAiVaultPanelHostScope(activeWorktreeId ?? null, resumeTargetState) + useAiVaultResumeCatalogs(executionHostScope) const activeWorktreePath = activeWorktree?.path ?? null // Why: AI Vault ownership is cwd-based, so we must consider live worktrees across all repos. const activeWorktreePaths = useMemo( diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.test.tsx new file mode 100644 index 00000000000..c56ee626e1b --- /dev/null +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.test.tsx @@ -0,0 +1,138 @@ +// @vitest-environment happy-dom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' +import { resetHostStructuredAgentsForTests } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../../../shared/agent-session/agent-session-runtime-capabilities' +import { + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY +} from '../../../../../../shared/agent-session/structured-agent-session-surface-capabilities' +import type { AiVaultSession } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' +import { makeRepo, makeWorktree } from '../../../worktree-jump/worktree-jump-palette-test-fixtures' +import type { GlobalSettings } from '../../../../../../shared/global-settings-types' +import { AiVaultSessionSurfaceSwitchMenuItems } from '../session-list/AiVaultSessionSurfaceSwitchMenuItems' +import { useAiVaultPanelSessionResume } from './use-ai-vault-panel-session-resume' +import { useAiVaultResumeCatalogs } from './use-ai-vault-resume-catalogs' + +const rpc = vi.hoisted(() => vi.fn()) +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc })) + +const initial = useAppStore.getInitialState() +const localWorkspace = makeWorktree('local-workspace', 'Local', { path: '/repo/local' }) +const pairedWorkspace = makeWorktree('paired-workspace', 'Old server', { + repoId: 'paired-repo', + path: '/srv/remote', + hostId: 'runtime:old-server' +}) +const session = { + id: 'local:opencode:session-1', + executionHostId: 'local', + agent: 'opencode', + sessionId: 'session-1', + cwd: '/repo/local', + filePath: '/home/test/.local/share/opencode/session/session-1.json', + messageCount: 2, + previewMessages: [{ role: 'user', text: 'Continue this task' }], + subagent: null +} as AiVaultSession +const sessions = [session] +const worktrees = [localWorkspace, pairedWorkspace] + +function HistoryActions({ + acquire, + onResume +}: { + acquire: boolean + onResume: (id: string) => void +}) { + const state = useAppStore.getState() + const resume = useAiVaultPanelSessionResume({ + sessions, + repos: state.repos, + allWorktrees: worktrees, + workspaceId: 'paired-workspace', + resumeTargetState: state + }) + const target = resume.getSessionResumeInChat(session) + return ( + <> + {acquire ? : null} + + Session actions + + onResume(target.workspaceId) : undefined} + /> + + + + ) +} + +function HistoryCatalog() { + useAiVaultResumeCatalogs('local') + return null +} + +beforeEach(() => { + resetHostStructuredAgentsForTests() + setLocalRuntimeCapabilitiesForTests([ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_REGISTERED_AGENTS_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RESUME_HISTORY_RUNTIME_CAPABILITY + ]) + useAppStore.setState({ + ...initial, + settings: { + ...initial.settings, + agentDefaultSurface: 'terminal', + nativeChatProviders: {} + } as GlobalSettings, + repos: [ + { ...makeRepo(), path: '/repo', displayName: 'Local' }, + { ...makeRepo(), id: 'paired-repo', path: '/srv', executionHostId: 'runtime:old-server' } + ], + worktreesByRepo: { 'repo-1': [localWorkspace], 'paired-repo': [pairedWorkspace] }, + activeWorktreeId: 'paired-workspace', + activeWorkspaceExecutionHostId: 'runtime:old-server' + }) +}) + +afterEach(() => { + cleanup() + useAppStore.setState(initial, true) + resetHostStructuredAgentsForTests() + setLocalRuntimeCapabilitiesForTests(null) + vi.clearAllMocks() +}) + +it('offers cold local History resume in its own workspace while an old paired workspace is active', async () => { + let answer!: (value: unknown) => void + rpc.mockImplementation( + () => + new Promise((resolve) => { + answer = resolve + }) + ) + const onResume = vi.fn() + const view = render() + expect(screen.queryByRole('menuitem', { name: 'Resume in New Chat' })).toBeNull() + + view.rerender() + await act(async () => { + await Promise.resolve() + answer({ agents: [{ agent: 'opencode', capabilities: {} }] }) + }) + fireEvent.click(await screen.findByRole('menuitem', { name: 'Resume in New Chat' })) + expect(onResume).toHaveBeenCalledWith('local-workspace') +}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.ts new file mode 100644 index 00000000000..dcdc56b71c4 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/use-ai-vault-resume-catalogs.ts @@ -0,0 +1,75 @@ +import { useEffect } from 'react' +import { useAppStore } from '@/store/index' +import { + ALL_EXECUTION_HOSTS_SCOPE, + LOCAL_EXECUTION_HOST_ID, + parseRoutableExecutionHostId, + toRuntimeExecutionHostId, + type ExecutionHostScope +} from '../../../../../../shared/execution-host' +import { lastVerifiedRuntimeStatus } from '../../../../../../shared/remote-runtime/host-status/runtime-host-status' +import { loadHostStructuredAgents } from '@/runtime/native-chat/agent-catalogs/host-structured-agents' +import { + ensureLocalRuntimeCapabilities, + subscribeLocalRuntimeCapabilitiesKnown +} from '@/runtime/hosts/capabilities/local-runtime-capabilities' + +/** Resume eligibility needs the recording host's catalog even when new agents default to terminals. */ +export function useAiVaultResumeCatalogs(scope: ExecutionHostScope): void { + useEffect(() => { + let disposed = false + const host = parseRoutableExecutionHostId(scope) + const all = scope === ALL_EXECUTION_HOSTS_SCOPE + const local = all || host?.kind === 'local' + const loadLocal = (capabilities: readonly string[] | null): void => { + if (!disposed) { + void loadHostStructuredAgents(LOCAL_EXECUTION_HOST_ID, capabilities, null) + } + } + const stopLocal = local ? subscribeLocalRuntimeCapabilitiesKnown(loadLocal) : undefined + if (local) { + void ensureLocalRuntimeCapabilities().then(loadLocal) + } + const loadRuntime = (environmentId: string): void => { + const status = lastVerifiedRuntimeStatus( + useAppStore.getState().runtimeStatusByEnvironmentId.get(environmentId) + ) + if (!disposed && status) { + void loadHostStructuredAgents( + toRuntimeExecutionHostId(environmentId), + status.capabilities, + status.runtimeId + ) + } + } + const loadRuntimes = (): void => { + if (all) { + for (const environment of useAppStore.getState().runtimeEnvironments) { + loadRuntime(environment.id) + } + } else if (host?.kind === 'runtime') { + loadRuntime(host.environmentId) + } + } + const stopStore = + all || host?.kind === 'runtime' + ? useAppStore.subscribe((state, previous) => { + const changed = all + ? state.runtimeEnvironments !== previous.runtimeEnvironments || + state.runtimeStatusByEnvironmentId !== previous.runtimeStatusByEnvironmentId + : host?.kind === 'runtime' && + state.runtimeStatusByEnvironmentId.get(host.environmentId) !== + previous.runtimeStatusByEnvironmentId.get(host.environmentId) + if (changed) { + loadRuntimes() + } + }) + : undefined + loadRuntimes() + return () => { + disposed = true + stopLocal?.() + stopStore?.() + } + }, [scope]) +}