diff --git a/config/scripts/mobile-web-app/mobile-web-app-project-conversations-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-project-conversations-render.test.mjs new file mode 100644 index 000000000000..fccd8a5ca9f7 --- /dev/null +++ b/config/scripts/mobile-web-app/mobile-web-app-project-conversations-render.test.mjs @@ -0,0 +1,397 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { chromium } from 'playwright-core' +import { buildMobileWebAppBundle } from '../build/mobile-web-app/build-mobile-web-app-bundle.mjs' +import { mobileWebAppDependenciesPresent } from './mobile-web-app-bundle-dependencies.mjs' +import { + createBundleServer, + installShellDouble, + readBridgeFaultGrant, + readBridgeProtocolVersion, + readShellCsp +} from './preview/mobile-web-app-render-harness.mjs' + +const HOST = { + id: 'conversation-host', + name: 'MacBook', + endpoint: 'ws://fixture', + lastConnected: 1 +} +const ROUTE = `/h/${HOST.id}` +const WORKSPACE = 'atlas::/projects/atlas' +const agent = (paneKey, taskTitle) => ({ + paneKey, + parentPaneKey: null, + state: 'done', + agentType: 'codex', + prompt: taskTitle, + taskTitle, + displayName: null, + lastAssistantMessage: 'Done', + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: 1792800000000, + updatedAt: 1792800000000 +}) +const workspace = (worktreeId, repoId, repo, path, branch, extra = {}) => ({ + worktreeId, + repoId, + repo, + path, + branch, + displayName: branch || repo, + hostId: 'local', + liveTerminalCount: 1, + hasAttachedPty: true, + unread: false, + isPinned: false, + isMainWorktree: true, + linkedPR: { number: 42, state: 'open' }, + agents: [], + ...extra +}) +const WORKSPACES = [ + workspace(WORKSPACE, 'atlas', 'Atlas', '/projects/atlas', 'master', { + agents: [agent('terminal:navigation', 'Clearer conversation navigation')] + }), + workspace( + 'atlas::/projects/atlas-fix', + 'atlas', + 'Atlas', + '/projects/atlas-fix', + 'feat/private-branch', + { + isMainWorktree: false, + linkedPR: { number: 57, state: 'merged' }, + agents: [agent('terminal:composer', 'Polish the message composer')] + } + ), + workspace('folder:notes', 'notes', 'Notes', '/documents/notes', '', { + workspaceKind: 'folder-workspace', + agents: [agent('terminal:notes', 'Organize the release notes')] + }) +] +const saved = (id, title, extra = {}) => ({ + id, + executionHostId: 'local', + agent: 'claude', + sessionId: id, + title, + cwd: '/projects/atlas', + branch: 'master', + model: 'recorded-model', + filePath: `/transcripts/${id}.jsonl`, + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '2026-10-24T12:00:00Z', + messageCount: 2, + totalTokens: 10, + previewMessages: [{ role: 'user', text: 'Review the plan', timestamp: null }], + ...extra +}) +const REPLIES = { + 'status.get': { + protocolVersion: 5, + minCompatibleMobileVersion: 1, + appVersion: '1.4.200', + platform: 'darwin', + capabilities: [ + 'aiVault.v1', + 'agent.launch.v2', + 'agent.launch.replay-required.v1', + 'agent-session.structured.reveal.v1' + ], + floatingWorkspaceEnabled: false + }, + 'worktree.ps': { worktrees: WORKSPACES }, + 'repo.list': { + repos: [{ id: 'atlas', displayName: 'Atlas', path: '/projects/atlas', connectionId: null }] + }, + 'settings.get': { settings: { defaultTuiAgent: 'codex' } }, + 'session.tabs.list': { tabs: [], snapshotVersion: 1, activeTabId: null, activeTabType: null }, + 'aiVault.listSessions': { + sessions: [ + saved('transcript', 'Review the onboarding plan'), + saved('empty', 'A saved empty conversation', { + source: 'structured-record', + filePath: '', + messageCount: 0, + previewMessages: [], + structuredSession: { sessionId: 'saved-empty', workspaceId: WORKSPACE } + }) + ], + issues: [], + includesStructuredSessions: true + }, + 'preflight.detectAgents': ['codex', 'claude'], + 'agent.launchReplay': { + worktreeId: WORKSPACE, + outcome: { kind: 'terminal', handle: 'terminal:new-chat' }, + receipt: { + mode: 'terminal', + preferred: 'terminal', + reason: 'user_default', + detail: 'Started a terminal agent.' + } + }, + 'agentSession.reveal': { ok: true, sessionId: 'saved-empty', workspaceId: WORKSPACE }, + 'worktree.activate': {} +} + +const describeRender = mobileWebAppDependenciesPresent() ? describe : describe.skip +let scratch, server, browser, origin, version, faultGrant +const proofDir = process.env.ORCA_CONVERSATION_PROOF_DIR + +beforeAll(async () => { + version = await readBridgeProtocolVersion() + faultGrant = await readBridgeFaultGrant() + scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-conversations-')) + const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') }) + const served = await createBundleServer({ outDir: built.outDir, cspHeader: await readShellCsp() }) + server = served.server + origin = served.origin + const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER + browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) }) + if (proofDir) { + await mkdir(proofDir, { recursive: true }) + } +}, 180_000) + +afterAll(async () => { + await browser?.close() + server?.close() + if (scratch) { + await rm(scratch, { recursive: true, force: true }) + } +}) + +async function open(replies = REPLIES, locale = 'ru-RU') { + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale }) + const errors = [] + page.on('pageerror', (error) => errors.push(error.message)) + await page.addInitScript(installShellDouble, { + version, + sessionId: 'conversation-render', + buildId: 'conversation-build', + route: { pathname: ROUTE }, + host: HOST, + storage: {}, + faultGrant, + grants: [faultGrant, 'navigate'], + pageRoutes: ['/h/[hostId]'], + replies + }) + await page.goto(origin) + await page.getByRole('button', { name: /^Clearer conversation navigation(?:\.|$)/ }).waitFor() + await page.getByRole('button', { name: 'A saved empty conversation', exact: true }).waitFor() + return { page, errors } +} + +async function proof(page, name) { + if (!proofDir) { + return + } + const cdp = await page.context().newCDPSession(page) + const shot = await cdp.send('Page.captureScreenshot', { + format: 'png', + captureBeyondViewport: false + }) + await writeFile(join(proofDir, `${name}.png`), Buffer.from(shot.data, 'base64')) + await cdp.detach() +} + +const requests = (page) => page.evaluate(() => globalThis.__orcaRenderCheckRequests) +const notifies = (page) => + page.evaluate(() => + globalThis.__orcaRenderCheckNotifies.filter((frame) => frame.name === 'navigate') + ) + +describeRender('the actual mobile project conversation list', () => { + it('opens a selected transcript with its preview expanded and no workspace badge', async () => { + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'ru-RU' }) + const errors = [] + page.on('pageerror', (error) => errors.push(error.message)) + await page.addInitScript(installShellDouble, { + version, + sessionId: 'selected-history', + buildId: 'conversation-build', + route: { + pathname: `${ROUTE}/agent-history/${encodeURIComponent(WORKSPACE)}`, + params: { name: 'Review the onboarding plan', conversationId: 'transcript' } + }, + host: HOST, + storage: {}, + faultGrant, + grants: [faultGrant, 'navigate'], + pageRoutes: ['/h/[hostId]/agent-history/[worktreeId]'], + replies: REPLIES + }) + await page.goto(origin) + await page.getByText('Review the plan', { exact: true }).last().waitFor() + const text = await page.locator('body').innerText() + expect(text).toContain('История разговоров') + expect(text).not.toMatch( + /A saved empty conversation|current worktree|master|PR #|PROJECTS\/ATLAS/ + ) + await proof(page, 'selected-transcript') + expect(errors).toEqual([]) + await page.close() + }, 60_000) + + it('groups chats directly under projects and reserves all git metadata for details', async () => { + const { page, errors } = await open() + const text = await page.locator('body').innerText() + expect(text).toContain('Проекты') + expect(text).toContain('Atlas') + expect(text).toContain('Notes') + expect(await page.getByTestId('conversation-row').count()).toBe(5) + expect(text).not.toMatch(/master|feat\/private-branch|PR #|\/projects\/|recorded-model/) + await proof(page, 'after-conversations') + await page + .getByRole('button', { + name: 'Детали разговора: Clearer conversation navigation', + exact: true + }) + .click() + await page.getByText('Ветка: master', { exact: false }).waitFor() + expect(await page.locator('body').innerText()).toContain('PR #42') + await proof(page, 'conversation-details') + expect(errors).toEqual([]) + await page.close() + }, 60_000) + + it('opens the selected pane and targets new chat creation at the project main workspace', async () => { + const { page, errors } = await open() + await page.getByRole('button', { name: /^Clearer conversation navigation(?:\.|$)/ }).click() + await expect + .poll(() => notifies(page)) + .toEqual([ + expect.objectContaining({ href: expect.stringContaining('paneKey=terminal%3Anavigation') }) + ]) + await page.getByRole('button', { name: 'Новый чат: Atlas', exact: true }).click() + await page.getByText('Выберите агента', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Codex', exact: true }).click() + await expect + .poll(async () => + (await requests(page)).filter((request) => request.method === 'agent.launchReplay') + ) + .toEqual([ + expect.objectContaining({ + params: expect.objectContaining({ + agent: 'codex', + target: { kind: 'existing', worktree: `id:${WORKSPACE}` } + }) + }) + ]) + await expect + .poll(() => notifies(page)) + .toEqual( + expect.arrayContaining([ + expect.objectContaining({ href: expect.stringContaining('paneKey=terminal%3Anew-chat') }) + ]) + ) + expect(errors).toEqual([]) + await page.close() + }, 60_000) + + it('reopens a durable empty conversation and routes a transcript to its specific history entry', async () => { + const { page, errors } = await open() + await page.getByRole('button', { name: 'A saved empty conversation', exact: true }).click() + await expect + .poll(async () => + (await requests(page)).filter((request) => request.method === 'agentSession.reveal') + ) + .toEqual([{ method: 'agentSession.reveal', params: { sessionId: 'saved-empty' } }]) + await expect + .poll(() => notifies(page)) + .toEqual([ + expect.objectContaining({ + href: expect.stringContaining('paneKey=structured-agent-session-saved-empty') + }) + ]) + await page.getByRole('button', { name: /^Review the onboarding plan(?:\.|$)/ }).click() + await expect + .poll(() => notifies(page)) + .toEqual( + expect.arrayContaining([ + expect.objectContaining({ href: expect.stringContaining('conversationId=transcript') }) + ]) + ) + expect(errors).toEqual([]) + await page.close() + }, 60_000) + + it('keeps old-host history honest and moves workspace navigation behind advanced settings', async () => { + const { page, errors } = await open({ + ...REPLIES, + 'aiVault.listSessions': { + ...REPLIES['aiVault.listSessions'], + includesStructuredSessions: undefined + } + }) + expect(await page.locator('body').innerText()).not.toMatch(/Обновите Orca|Этот хост показывает/) + await page.getByRole('button', { name: 'Другие действия', exact: true }).click() + await page.getByText('Дополнительно: рабочие каталоги', { exact: true }).click() + await page.getByText('К проектам', { exact: true }).waitFor() + await page.getByText('master', { exact: true }).first().waitFor() + await proof(page, 'before-workspaces-preserved') + await page.getByRole('button', { name: 'К проектам', exact: true }).click() + await page.getByRole('button', { name: /^Clearer conversation navigation(?:\.|$)/ }).waitFor() + expect(errors).toEqual([]) + await page.close() + }, 60_000) +}) + +describeRender('mobile history diagnostics', () => { + it('does not present informational record notices as missing chats or an upgrade requirement', async () => { + const { page, errors } = await open( + { + ...REPLIES, + 'aiVault.listSessions': { + ...REPLIES['aiVault.listSessions'], + issues: [{ kind: 'notice', message: 'Skipped 2 oversized transcript records.' }] + } + }, + 'en-US' + ) + await proof(page, 'history-notice') + const text = await page.locator('body').innerText() + expect(text).not.toMatch(/Some conversations|Could not refresh|Update Orca|This host lists/) + expect(await page.getByTestId('conversation-row').count()).toBe(5) + expect(errors).toEqual([]) + await page.close() + }, 60_000) + + it('keeps a real history failure visible with a working refresh button and no upgrade claim', async () => { + const { page, errors } = await open( + { + ...REPLIES, + 'aiVault.listSessions': { + ...REPLIES['aiVault.listSessions'], + issues: [{ kind: 'host', message: 'History source unavailable' }] + } + }, + 'en-US' + ) + await page.getByText('Could not refresh the full chat list.', { exact: true }).waitFor() + await proof(page, 'history-failure-retry') + expect(await page.locator('body').innerText()).not.toContain('Update Orca') + const before = (await requests(page)).filter( + (request) => request.method === 'aiVault.listSessions' + ).length + await page.getByRole('button', { name: 'Refresh', exact: true }).click() + await expect + .poll( + async () => + (await requests(page)).filter((request) => request.method === 'aiVault.listSessions') + .length + ) + .toBeGreaterThan(before) + expect(errors).toEqual([]) + await page.close() + }, 60_000) +}) diff --git a/mobile/README.md b/mobile/README.md index ce29f398bf6b..23843ff792ca 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -1,6 +1,14 @@ # Orca Mobile -React Native companion app for Orca. Monitor worktrees, view terminal output, and send commands from your phone. +React Native companion app for Orca. Open project conversations, view terminal output, and send commands from your phone. + +The host screen lists conversations directly under their projects. A project’s **New chat** action uses its main workspace (or its folder workspace), detects agents on that execution host, and launches through the existing agent API. Workspace management remains under **More options → Advanced: workspaces**. Branches, paths and linked pull requests appear in conversation details. + +Open agent panes, persisted session tabs and saved transcripts are separate sources. The optional `includeStructuredSessions` mode of `aiVault.listSessions` adds durable Orca records, including closed chats with no provider transcript; only a host that actually read its record catalog answers `includesStructuredSessions: true`. Older hosts keep serving open tabs and transcript history, with a visible coverage notice. The list is bounded to the history API’s 500-session recency window. Reopening a saved Orca chat uses its recorded session identity; transcript history retains the existing preview and explicit resume flow. + +Project and conversation identities include the execution host. Paired servers use the existing relay-scoped client, and an unavailable relay never falls back to the desktop. SSH workspaces retain their existing host-aware pane and launch paths; this screen does not claim SSH transcript history when the connection cannot list it. Folder workspaces do not require a Git branch. + +The standalone mobile app has no shared localization catalog. The conversation screen provides English and Russian copy using the device locale; the existing history, launch and advanced workspace screens keep their current language. Desktop’s language setting is not synchronized into this small mobile copy module. Local development uses two processes: diff --git a/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx b/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx index 1c48ab2d218b..eee3e95cbf2e 100644 --- a/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx +++ b/mobile/app/h/[hostId]/agent-history/[worktreeId].tsx @@ -5,7 +5,10 @@ import { } from '../../../../src/navigation/workspace-execution-host' import { useLocalSearchParams } from 'expo-router' import { MobileWebShellScreen } from '../../../../src/mobile-web-shell/MobileWebShellScreen' -import { shellScreenRoute } from '../../../../src/mobile-web-shell/routing/shell-screen-route' +import { + shellScreenRoute, + shellScreenRouteKey +} from '../../../../src/mobile-web-shell/routing/shell-screen-route' import { PageRouteUnavailableScreen } from '../../../../src/mobile-web-shell/presentation/PageRouteUnavailableScreen' import { firstParam } from '../../../../src/navigation/route-param-reader' @@ -16,16 +19,19 @@ export default withWorkspaceRoute(function MobileAgentSessionHistoryScreen() { hostId?: string | string[] worktreeId?: string | string[] name?: string | string[] + conversationId?: string | string[] origin?: string | string[] }>() const hostId = firstParam(params.hostId) const worktreeId = firstParam(params.worktreeId) const name = firstParam(params.name) + const conversationId = firstParam(params.conversationId) const origin = firstParam(params.origin) const executionHost = useWorkspaceExecutionHost() const routeParams = { ...(name === '' ? {} : { name }), ...(origin === '' ? {} : { origin }), + ...(conversationId === '' ? {} : { conversationId }), ...workspaceRouteParams(executionHost) } @@ -41,5 +47,5 @@ export default withWorkspaceRoute(function MobileAgentSessionHistoryScreen() { return } // Key by route to dispose the old grant-bearing bridge and await fresh init; prop changes would retain the previous route’s grants. - return + return }) diff --git a/mobile/app/h/[hostId]/agent-history/[worktreeId].web.tsx b/mobile/app/h/[hostId]/agent-history/[worktreeId].web.tsx index 4839f4f57d35..6ff05ad08357 100644 --- a/mobile/app/h/[hostId]/agent-history/[worktreeId].web.tsx +++ b/mobile/app/h/[hostId]/agent-history/[worktreeId].web.tsx @@ -9,6 +9,7 @@ export default withWorkspaceRoute(function MobileAgentSessionHistoryScreen() { hostId?: string | string[] worktreeId?: string | string[] name?: string | string[] + conversationId?: string | string[] origin?: string | string[] }>() return ( @@ -16,6 +17,7 @@ export default withWorkspaceRoute(function MobileAgentSessionHistoryScreen() { hostId={firstParam(params.hostId)} worktreeId={firstParam(params.worktreeId)} name={firstParam(params.name)} + conversationId={firstParam(params.conversationId)} origin={firstParam(params.origin)} /> ) diff --git a/mobile/src/agent-history/AgentHistoryLoadState.tsx b/mobile/src/agent-history/AgentHistoryLoadState.tsx new file mode 100644 index 000000000000..976ce05141e1 --- /dev/null +++ b/mobile/src/agent-history/AgentHistoryLoadState.tsx @@ -0,0 +1,102 @@ +import type { ReactNode } from 'react' +import { History } from 'lucide-react-native' +import { + MobileLoadErrorState, + MobileNoMatchState, + MobileOfflineState, + MobileStateView +} from '../components/feedback/MobileStateView' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import type { AgentHistoryScreenState } from './mobile-agent-history-screen-state' + +export function AgentHistoryLoadState({ + state, + connected, + onRetry, + children +}: { + state: AgentHistoryScreenState + connected: boolean + onRetry: (() => void) | null + children: ReactNode +}) { + const t = useMobileTranslation() + if (state.kind === 'loading') { + return ( + + ) + } + if (state.kind === 'unsupported') { + return ( + + ) + } + if (state.kind === 'error') { + return connected ? ( + + ) : ( + + ) + } + return <>{children} +} + +/** A loaded list with nothing to show: a search or agent filter to clear, or nothing in scope. */ +export function AgentHistoryEmptyList({ + query, + agentFiltered, + conversation, + bottomInset, + onClearQuery, + onShowAllAgents +}: { + query: string + agentFiltered: boolean + /** One conversation's history, which this host could not find. */ + conversation: boolean + bottomInset: number + onClearQuery: () => void + onShowAllAgents: () => void +}) { + const t = useMobileTranslation() + if (query) { + return ( + + ) + } + if (agentFiltered) { + return ( + + ) + } + return ( + + ) +} diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx index 2d7d75ca84fe..6011c628f15b 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx @@ -22,6 +22,8 @@ type Props = { primaryAction?: 'resume' | 'handoff' onLongPress?: (session: AiVaultSession) => void onRefresh: () => void + initialExpandedId?: string + hideSectionHeaders?: boolean /** Clears the bottom search bar floating over the list. */ bottomPadding?: number } @@ -36,10 +38,12 @@ export function MobileAgentSessionHistoryList({ primaryAction, onLongPress, onRefresh, - bottomPadding = 0 + bottomPadding = 0, + initialExpandedId, + hideSectionHeaders = false }: Props) { const colorScheme = useMobileColorScheme() - const [expandedId, setExpandedId] = useState(null) + const [expandedId, setExpandedId] = useState(initialExpandedId ?? null) const toggleExpanded = useCallback((id: string) => { setExpandedId((prev) => (prev === id ? null : id)) @@ -85,13 +89,15 @@ export function MobileAgentSessionHistoryList({ tintColor={colors.textSecondary} /> } - renderSectionHeader={({ section }) => ( - - )} + renderSectionHeader={({ section }) => + hideSectionHeaders ? null : ( + + ) + } renderItem={renderItem} ItemSeparatorComponent={RowSeparator} keyboardDismissMode="on-drag" diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx index 649d0cfd1656..a24ef8494a04 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx @@ -1,12 +1,11 @@ +import { AgentHistoryEmptyList, AgentHistoryLoadState } from './AgentHistoryLoadState' +import { scopeSegments } from './agent-history-scope-segments' import { useMemo, useState } from 'react' import { View } from 'react-native' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' -import { ChevronLeft, History, MessageSquarePlus, Play, RefreshCw } from 'lucide-react-native' +import { ChevronLeft, MessageSquarePlus, Play, RefreshCw } from 'lucide-react-native' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { - MobileSegmentedControl, - type MobileSegment -} from '../components/controls/MobileSegmentedControl' +import { MobileSegmentedControl } from '../components/controls/MobileSegmentedControl' import { NavBar } from '../components/nav-bar/NavBar' import { NavBarButton } from '../components/nav-bar/NavBarButton' import { useWorkspaceClient } from '../worktree/execution-hosts/use-workspace-client' @@ -21,12 +20,6 @@ import { shouldShowMobileCurrentWorktreeBadge } from './agent-history-current-wo import { MobileAgentSessionHistoryList } from './MobileAgentSessionHistoryList' import { buildMobileAgentHistoryResumeActionState } from './agent-history-session-card' import { styles } from './agent-history-styles' -import { - MobileLoadErrorState, - MobileNoMatchState, - MobileOfflineState, - MobileStateView -} from '../components/feedback/MobileStateView' import { AgentHistoryInterruptedNotice, AgentHistoryResumeNotice, @@ -42,7 +35,7 @@ import { useAgentHistoryRestartOffer } from './use-agent-history-restart-offer' import { TransientToast } from '../components/feedback/TransientToast' import { useNow } from '../hooks/use-now' import { useMobileResumeOperationOwnership } from './use-mobile-resume-operation-ownership' -import type { Translate } from '../i18n/mobile-i18n' +import { conversationCopy } from '../host-screen/conversation-copy' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { ActionSheetModal } from '../components/sheets/ActionSheetModal' import { AgentHistoryHandoffDrawer } from './AgentHistoryHandoffSheet' @@ -53,18 +46,11 @@ export type MobileAgentSessionHistoryPanelProps = { hostId: string worktreeId: string name?: string + conversationId?: string /** `handoff`: opened from the workspace menu to pick a session to hand off. */ origin?: string } -function scopeSegments(t: Translate): MobileSegment[] { - return [ - { value: 'workspace', label: t('agentHistory.panel.workspace', 'Workspace') }, - { value: 'project', label: t('agentHistory.panel.project', 'Project') }, - { value: 'all', label: t('agentHistory.panel.all', 'All') } - ] -} - export function MobileAgentSessionHistoryPanel(props: MobileAgentSessionHistoryPanelProps) { return } @@ -73,6 +59,7 @@ function MobileAgentSessionHistoryPanelContent({ hostId, worktreeId, name = '', + conversationId, origin = '' }: MobileAgentSessionHistoryPanelProps) { useMobileColorScheme() @@ -90,6 +77,7 @@ function MobileAgentSessionHistoryPanelContent({ connState ) const [query, setQuery] = useState('') + const effectiveQuery = conversationId ? '' : query const [agents, setAgents] = useState(AiVault.AI_VAULT_AGENTS) const [sort, setSort] = useState(AGENT_HISTORY_DEFAULT_SORT) const [searchBarHeight, setSearchBarHeight] = useState(0) @@ -109,9 +97,19 @@ function MobileAgentSessionHistoryPanelContent({ onSelectScope, onRefresh, retry - } = useMobileAgentHistoryState({ hostId, worktreeId, worktrees, worktreesLoaded, projectSetups }) + } = useMobileAgentHistoryState({ + hostId, + worktreeId, + conversationId, + worktrees, + worktreesLoaded, + projectSetups + }) - const sessions = screenState.kind === 'ready' ? screenState.sessions : EMPTY_SESSIONS + const sessions = useMemo(() => { + const all = screenState.kind === 'ready' ? screenState.sessions : EMPTY_SESSIONS + return conversationId ? all.filter((session) => session.id === conversationId) : all + }, [screenState, conversationId]) const issues = screenState.kind === 'ready' ? screenState.issues : EMPTY_ISSUES const sessionsById = useMemo( () => new Map(sessions.map((session) => [session.id, session])), @@ -120,15 +118,26 @@ function MobileAgentSessionHistoryPanelContent({ const sections = useMemo( () => buildMobileAgentHistorySections(sessions, { - query, + query: effectiveQuery, agents, sort, - scope, + scope: conversationId ? 'all' : scope, scopeFilterPaths, activeWorktreePath, now }), - [sessions, query, agents, sort, scope, scopeFilterPaths, activeWorktreePath, now, t] + [ + sessions, + effectiveQuery, + conversationId, + agents, + sort, + scope, + scopeFilterPaths, + activeWorktreePath, + now, + t + ] ) const showRefreshLine = useRefreshHint(revalidating) @@ -163,7 +172,9 @@ function MobileAgentSessionHistoryPanelContent({ title={ pickingHandoff ? t('agentHistory.handoff.title', 'Hand off to agent') - : t('agentHistory.panel.title', 'Agent Session History') + : conversationId + ? conversationCopy().history + : t('agentHistory.panel.title', 'Agent Session History') } subtitle={worktreeLabel} refreshing={showRefreshLine} @@ -175,7 +186,7 @@ function MobileAgentSessionHistoryPanelContent({ /> } accessory={ - screenState.kind === 'ready' ? ( + screenState.kind === 'ready' && !conversationId ? ( - {screenState.kind === 'loading' ? ( - + {conversationId ? null : } + + + setResumeMessage(null)} /> - ) : screenState.kind === 'unsupported' ? ( - - ) : screenState.kind === 'error' && connState !== 'connected' ? ( - - ) : screenState.kind === 'error' ? ( - - ) : ( - <> - - - setResumeMessage(null)} + {sections.length === 0 ? ( + setQuery('')} + onShowAllAgents={() => setAgents(AiVault.AI_VAULT_AGENTS)} /> - - {sections.length === 0 ? ( - query ? ( - setQuery('')} - bottomInset={searchBarHeight} - /> - ) : !agentHistoryShowsEveryAgent(agents) ? ( - setAgents(AiVault.AI_VAULT_AGENTS)} - clearLabel={t('agentHistory.panel.showAllAgents', 'Show all agents')} - bottomInset={searchBarHeight} - /> - ) : ( - - ) - ) : ( - void onRefresh()} - bottomPadding={searchBarHeight} - /> - )} + ) : ( + void onRefresh()} + bottomPadding={searchBarHeight} + /> + )} + {!conversationId && ( - - )} + )} + [] { + return [ + { value: 'workspace', label: t('agentHistory.panel.workspace', 'Workspace') }, + { value: 'project', label: t('agentHistory.panel.project', 'Project') }, + { value: 'all', label: t('agentHistory.panel.all', 'All') } + ] +} diff --git a/mobile/src/agent-history/agent-history-sections.ts b/mobile/src/agent-history/agent-history-sections.ts index 290f48435973..97f34742d80d 100644 --- a/mobile/src/agent-history/agent-history-sections.ts +++ b/mobile/src/agent-history/agent-history-sections.ts @@ -4,16 +4,26 @@ import { } from '../../../src/shared/ai-vault/session-display/ai-vault-session-filters' import type { AiVaultAgent, + AiVaultScanIssue, AiVaultScope, AiVaultSession, AiVaultSort } from '../../../src/shared/ai-vault/contracts/ai-vault-types' - import { buildMobileAgentHistoryCard, type MobileAgentHistoryCard } from './agent-history-session-card' +export type AgentHistoryScreenState = + | { kind: 'loading' } + | { kind: 'unsupported' } + | { kind: 'error'; message: string } + | { + kind: 'ready' + sessions: AiVaultSession[] + issues: AiVaultScanIssue[] + } + // SectionList requires data field; naming it cards renders no rows. export type MobileAgentHistorySection = { key: string diff --git a/mobile/src/agent-history/mobile-agent-history-screen-state.ts b/mobile/src/agent-history/mobile-agent-history-screen-state.ts new file mode 100644 index 000000000000..a388a506311e --- /dev/null +++ b/mobile/src/agent-history/mobile-agent-history-screen-state.ts @@ -0,0 +1,19 @@ +import type { + AiVaultScanIssue, + AiVaultSession +} from '../../../src/shared/ai-vault/contracts/ai-vault-types' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' + +export type AgentHistoryScreenState = + | { kind: 'loading' } + | { kind: 'unsupported' } + | { kind: 'error'; message: string } + | { + kind: 'ready' + sessions: AiVaultSession[] + issues: AiVaultScanIssue[] + } + +export type FetchedHistoryState = + | Exclude + | (Extract & { hostId: string; client: RpcClient }) diff --git a/mobile/src/agent-history/mobile-agent-history-state-contract.ts b/mobile/src/agent-history/mobile-agent-history-state-contract.ts new file mode 100644 index 000000000000..69a57f7fa1c9 --- /dev/null +++ b/mobile/src/agent-history/mobile-agent-history-state-contract.ts @@ -0,0 +1,12 @@ +import type { Worktree } from '../worktree/workspace-list/workspace-list-types' +import type { MobileAiVaultProjectSetup } from './agent-history-scope-paths' + +export type MobileAgentHistoryStateParams = { + hostId: string + worktreeId: string + conversationId?: string + worktrees: readonly Worktree[] + // Distinguish unfetched worktree list from fetched-but-missing workspace; only first holds loading. + worktreesLoaded: boolean + projectSetups?: readonly MobileAiVaultProjectSetup[] +} diff --git a/mobile/src/agent-history/use-mobile-agent-history-state.ts b/mobile/src/agent-history/use-mobile-agent-history-state.ts index 0b56309c0086..adf5dcb31345 100644 --- a/mobile/src/agent-history/use-mobile-agent-history-state.ts +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -12,14 +12,14 @@ import type { AiVaultScope, AiVaultSession } from '../../../src/shared/ai-vault/contracts/ai-vault-types' -import type { Worktree } from '../worktree/workspace-list/workspace-list-types' +import type { MobileAgentHistoryStateParams } from './mobile-agent-history-state-contract' +import { AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY } from '../../../src/shared/ai-vault/contracts/ai-vault-runtime-capabilities' import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' import { defineHostQuery, readHostQueryLive, useHostQuery } from '../query/host-query' import { hostScreenState } from '../query/host-query-screen-state' import { deriveMobileAiVaultScopePaths, - mobileAiVaultScanScopeArgs, - type MobileAiVaultProjectSetup + mobileAiVaultScanScopeArgs } from './agent-history-scope-paths' import { agentHistoryCapabilityRead, @@ -66,7 +66,11 @@ type AgentHistoryRead = associationRevision: number } -type ScanScope = { scopeFilterPaths: string[]; activeWorktreePath: string | null } +type ScanScope = { + scopeFilterPaths: string[] + activeWorktreePath: string | null + conversationId?: string +} async function readAgentHistory( client: RpcClient, @@ -89,8 +93,15 @@ async function readAgentHistory( // Like desktop History: IDE transcripts continue in a new CLI conversation. includeAntigravityIdeSessions: true, force, - // From the query's own scope key, so rows cached under Workspace are always Workspace-only ones. - ...mobileAiVaultScanScopeArgs(scope, scan.scopeFilterPaths) + ...(scan.conversationId ? { includeStructuredSessions: true } : {}), + ...(scan.conversationId && + status.capabilities?.includes(AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY) + ? { selectedSessionId: scan.conversationId } + : {}), + ...mobileAiVaultScanScopeArgs( + scan.conversationId ? 'all' : scope, + scan.conversationId ? [] : scan.scopeFilterPaths + ) }) const result = interpretOrThrowRefusalMessage( () => agentHistorySessionScan.interpret(reply), @@ -124,18 +135,9 @@ function agentHistoryQuery( }) } -export type MobileAgentHistoryStateParams = { - hostId: string - worktreeId: string - worktrees: readonly Worktree[] - // Distinguish unfetched worktree list from fetched-but-missing workspace; only first holds loading. - worktreesLoaded: boolean - projectSetups?: readonly MobileAiVaultProjectSetup[] -} - export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams) { const t = useMobileTranslation() - const { hostId, worktreeId, worktrees, worktreesLoaded, projectSetups } = params + const { hostId, worktreeId, conversationId, worktrees, worktreesLoaded, projectSetups } = params const { client, state: connState } = useWorkspaceClient(hostId) const forceReconnect = useForceReconnect() const queryClient = useQueryClient() @@ -151,14 +153,15 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams (): ScanScope => ({ // Reuse host hint prefixes for client narrowing: host union only widens; All is not narrowed. scopeFilterPaths: deriveMobileAiVaultScopePaths( - scope, + conversationId ? 'all' : scope, activeWorktree, worktrees, projectSetups ), - activeWorktreePath: activeWorktree?.path ?? null + activeWorktreePath: activeWorktree?.path ?? null, + conversationId }), - [scope, activeWorktree, worktrees, projectSetups] + [scope, activeWorktree, worktrees, projectSetups, conversationId] ) // Subscribed before the query so the feed's stream opens ahead of the first read, on the page bridge as natively. const feed = useMemo(() => (client ? mobileStructuredSessionStatusFeed(client) : null), [client]) @@ -187,7 +190,7 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams [liveScan, startRevision] ) const target = useMemo(() => ({ exec, worktree: worktreeId }), [exec, worktreeId]) - const input = useMemo(() => ({ scope }), [scope]) + const input = useMemo(() => ({ scope, conversationId }), [scope, conversationId]) const host = useMemo(() => ({ hostId, client }), [hostId, client]) // Wait for worktree list before fetching to avoid unrelated history; once loaded, proceed even if workspace is missing. // Not gated on the connection: the query keeps its connected-edge watcher, and a read while down fails fast. diff --git a/mobile/src/host-screen/ConversationHistoryLoadStatus.tsx b/mobile/src/host-screen/ConversationHistoryLoadStatus.tsx new file mode 100644 index 000000000000..19609086a02d --- /dev/null +++ b/mobile/src/host-screen/ConversationHistoryLoadStatus.tsx @@ -0,0 +1,36 @@ +import { ActivityIndicator } from 'react-native' +import { HostRouteNoticeBanner } from '../components/host-connection/HostRouteNoticeBanner' +import { colors } from '../theme/mobile-theme' +import { conversationCopy } from './conversation-copy' +import { conversationStyles as styles } from './conversation-styles' + +export function ConversationHistoryLoadStatus({ + loading, + failed, + connected, + onRefresh +}: { + loading: boolean + failed: boolean + connected: boolean + onRefresh: () => void +}) { + const copy = conversationCopy() + return ( + <> + {failed ? ( + + ) : null} + {loading ? ( + + ) : null} + + ) +} diff --git a/mobile/src/host-screen/ConversationListRow.tsx b/mobile/src/host-screen/ConversationListRow.tsx new file mode 100644 index 000000000000..f6a4fc353872 --- /dev/null +++ b/mobile/src/host-screen/ConversationListRow.tsx @@ -0,0 +1,101 @@ +import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { MoreHorizontal, Pin } from 'lucide-react-native' +import { formatAgentTypeLabel } from '../../../src/shared/agent-status/presentation/agent-type-label' +import { MobileAgentIcon } from '../components/icons/MobileAgentIcon' +import { AgentStateDot } from '../agents/presentation/AgentStateDot' +import { colors } from '../theme/mobile-theme' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import type { ConversationRow } from './conversation-project' +import { conversationCopy, conversationTimeAgo } from './conversation-copy' +import { agentStateLabel } from '../worktree/agent-lineage/agent-row-display' +import { conversationStyles as styles } from './conversation-styles' + +export function ConversationListRow({ + item, + connected, + busy, + pinned, + now, + onOpen, + onDetails +}: { + item: ConversationRow + connected: boolean + busy: string | null + pinned: boolean + now: number + onOpen: (row: ConversationRow) => void + onDetails: (row: ConversationRow) => void +}) { + useMobileColorScheme() + const copy = conversationCopy() + const offline = !connected || Boolean(item.workspaceContext?.hostContextHealthLabel) + return ( + + onOpen(item)} + onLongPress={() => onDetails(item)} + disabled={offline || busy !== null} + style={({ pressed }) => [styles.rowButton, pressed && styles.pressed]} + accessibilityRole="button" + accessibilityLabel={[item.title, item.preview].filter(Boolean).join('. ')} + > + + + + {pinned ? : null} + + {item.title} + + + {item.preview ? ( + + {item.preview} + + ) : null} + + + + {[ + item.agent ? formatAgentTypeLabel(item.agent) : null, + offline + ? copy.offline + : item.status === 'saved' + ? copy.saved + : item.status === 'transcript' + ? copy.transcript + : item.status === 'failed' + ? copy.failedState + : item.status === 'unverifiable' + ? copy.unconfirmed + : item.status === 'permission' + ? agentStateLabel(item.status) + : copy[item.status], + item.at ? conversationTimeAgo(item.at, now) : null + ] + .filter(Boolean) + .join(' · ')} + + + + {busy === item.key ? : null} + + onDetails(item)} + style={styles.iconButton} + accessibilityRole="button" + accessibilityLabel={`${copy.details}: ${item.title}`} + > + + + + ) +} diff --git a/mobile/src/host-screen/ConversationProjectHeader.tsx b/mobile/src/host-screen/ConversationProjectHeader.tsx new file mode 100644 index 000000000000..1fc32d3d8458 --- /dev/null +++ b/mobile/src/host-screen/ConversationProjectHeader.tsx @@ -0,0 +1,65 @@ +import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { MoreHorizontal, Plus } from 'lucide-react-native' +import { MobileRepoIcon } from '../components/icons/MobileRepoIcon' +import { readMobileRepoIcon } from './host-screen-reply-schema' +import { colors } from '../theme/mobile-theme' +import { conversationStyles as styles } from './conversation-styles' +import { conversationCopy } from './conversation-copy' +import type { ConversationProject } from './project-conversations' + +export function ConversationProjectHeader({ + project, + connected, + busy, + onPrepare, + onOptions +}: { + project: ConversationProject + connected: boolean + busy: string | null + onPrepare: () => void + onOptions: () => void +}) { + const copy = conversationCopy() + const canStart = + connected && !project.hostHealthLabel && busy === null && project.workspaces.length > 0 + return ( + + + + + {project.title} + + {project.hostLabel || project.hostHealthLabel ? ( + + {[project.hostLabel, project.hostHealthLabel].filter(Boolean).join(' · ')} + + ) : null} + + + + + {project.workspaces.length > 0 ? ( + + {busy === project.key ? ( + + ) : ( + + )} + {copy.newChat} + + ) : null} + + ) +} diff --git a/mobile/src/host-screen/HostConversations.tsx b/mobile/src/host-screen/HostConversations.tsx new file mode 100644 index 000000000000..4fe78d5cf93a --- /dev/null +++ b/mobile/src/host-screen/HostConversations.tsx @@ -0,0 +1,348 @@ +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useMemo, useState } from 'react' +import { useNow } from '../hooks/use-now' +import { Pressable, RefreshControl, SectionList, Text, View } from 'react-native' +import { SafeAreaView } from 'react-native-safe-area-context' +import { ArrowDownAZ, ChevronLeft, Settings } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { StatusDot } from '../components/feedback/StatusDot' +import { MobileSearchField } from '../components/controls/MobileSearchField' +import { ConversationAgentSheet } from './conversation-agent-sheet' +import { ConversationSidebarOptions } from './conversation-sidebar-options' +import { ConversationHistoryLoadStatus } from './ConversationHistoryLoadStatus' +import { AuthFailedBanner } from '../components/host-connection/AuthFailedBanner' +import type { HostScreenController } from './use-host-screen-controller' +import { HiddenConversationProjectsSheet } from './hidden-conversation-projects-sheet' +import { ConversationListRow } from './ConversationListRow' +import { ConversationProjectHeader } from './ConversationProjectHeader' +import { ConversationProjectActionsSheet } from './conversation-project-actions-sheet' +import { buildProjectConversations, type ConversationProject } from './project-conversations' +import { useConversationActions } from './use-conversation-actions' +import { conversationCopy } from './conversation-copy' +import { conversationStyles as styles } from './conversation-styles' +import { buildProjectSectionCatalog } from '../worktree/project-sections/project-section-catalog' +import { ConversationProjectOrderSheet } from './conversation-project-order-sheet' +import { ConversationDetailsSheet } from './conversation-details-sheet' +import { useConversationPreferences } from './use-conversation-preferences' +import { useConversationDetails } from './use-conversation-details' +import { PROJECT_CONVERSATION_PAGE_SIZE } from '../../../src/shared/project-conversation-list' +import { useProjectConversations } from './use-project-conversations' + +export function HostConversations({ + controller, + onWorkspaces +}: { + controller: HostScreenController + onWorkspaces: () => void +}) { + const t = useMobileTranslation() + const now = useNow(30_000) + const copy = conversationCopy() + const { hostId, connState, actions, state } = controller + const data = useProjectConversations(controller) + const conversationPreferences = useConversationPreferences(controller) + const [query, setQuery] = useState('') + const [options, setOptions] = useState(false) + const [sorting, setSorting] = useState(false) + const [managingHidden, setManagingHidden] = useState(false) + const [projectAction, setProjectAction] = useState<{ + project: ConversationProject + client: typeof controller.client + hostId: string + generation: number + } | null>(null) + const actionProject = + projectAction?.client === controller.client && + projectAction.hostId === hostId && + projectAction.generation === data.generation + ? projectAction.project + : null + const [archived, setArchived] = useState(false) + const [expandedProjects, setExpandedProjects] = useState>(new Set()) + const { details, setDetails } = useConversationDetails({ + client: controller.client, + hostId, + generation: controller.client?.getGeneration?.() ?? 0 + }) + const { busy, error, newChat, setNewChat, prepare, launch, open } = useConversationActions( + controller, + data + ) + const projectCatalog = useMemo( + () => + buildProjectSectionCatalog( + controller.projectCatalog, + [...controller.sectionsResult.repoById.values()], + state.hostProjectGroups, + state.view.filters.visibleHostIds, + controller.projectOrderBy + ), + [ + controller.projectCatalog, + controller.sectionsResult.repoById, + controller.projectOrderBy, + state.hostProjectGroups, + state.view + ] + ) + const projects = useMemo( + () => + buildProjectConversations({ + workspaces: data.workspaces, + hostContextOf: controller.hostContextOf, + visibleHostIds: state.view.filters.visibleHostIds, + repos: [...controller.sectionsResult.repoById.values()], + tabs: data.tabs, + history: data.history, + now: now, + untitled: copy.untitled, + query, + projectCatalog, + preferences: conversationPreferences.preferences, + archived + }), + [ + data.workspaces, + controller.hostContextOf, + state.view.filters.visibleHostIds, + controller.sectionsResult.repoById, + data.tabs, + data.history, + now, + copy.untitled, + query, + projectCatalog, + conversationPreferences.preferences, + archived + ] + ) + + const sections = useMemo( + () => + projects.map((project) => ({ + ...project, + totalCount: project.data.length, + data: + query.trim() || expandedProjects.has(project.key) + ? project.data + : project.data.slice(0, PROJECT_CONVERSATION_PAGE_SIZE) + })), + [projects, query, expandedProjects] + ) + const connected = connState === 'connected' + return ( + + + + + + + + {archived ? copy.archived : copy.projects} + + + + {controller.hostDisplay.title} + + + + {controller.embedded && controller.onHideSidebar ? ( + + + + ) : null} + setOptions(true)} + style={styles.iconButton} + accessibilityRole="button" + accessibilityLabel={copy.settings} + > + + + + + {(connState === 'auth-failed' || controller.relayRecovery.pairingRejected) && ( + void controller.forceReconnectHost?.(hostId)} + onRepair={() => controller.router.push('/pair-scan')} + onRemove={() => state.setConfirmRemoveHost(true)} + /> + )} + + + + + setSorting(true)} + style={styles.iconButton} + accessibilityRole="button" + accessibilityLabel={copy.projectOrder} + > + + + + {!connected && {copy.offline}} + {error || state.actionError || conversationPreferences.error ? ( + + {error || state.actionError || conversationPreferences.error} + + ) : null} + + row.key} + stickySectionHeadersEnabled={false} + keyboardShouldPersistTaps="handled" + contentContainerStyle={[ + styles.list, + { paddingBottom: controller.insets.bottom + 24 }, + controller.isWideLayout && !controller.embedded + ? { maxWidth: controller.contentMaxWidth, width: '100%', alignSelf: 'center' } + : null + ]} + refreshControl={ + + } + ListEmptyComponent={ + {state.worktreesLoaded ? copy.noProjects : copy.loading} + } + renderSectionHeader={({ section }) => ( + prepare(section)} + onOptions={() => + setProjectAction({ + project: section, + client: controller.client, + hostId, + generation: data.generation + }) + } + /> + )} + renderSectionFooter={({ section }) => ( + <> + {section.totalCount > section.data.length ? ( + setExpandedProjects((current) => new Set([...current, section.key]))} + style={styles.agentButton} + accessibilityRole="button" + > + + {copy.showMore} ({section.totalCount - section.data.length}) + + + ) : null} + {section.data.length === 0 ? {copy.empty} : null} + {section.hostId.startsWith('ssh:') ? ( + {copy.ssh} + ) : null} + + )} + renderItem={({ item }) => ( + + )} + /> + setProjectAction(null)} + onWorkspaces={onWorkspaces} + onHide={ + actionProject && + connected && + !conversationPreferences.writing && + conversationPreferences.projectVisibilitySupported + ? () => + void conversationPreferences.setProjectHidden( + actionProject.visibilityKey ?? actionProject.key, + actionProject.title, + true + ) + : undefined + } + /> + setManagingHidden(false)} + onRestore={(key, label) => void conversationPreferences.setProjectHidden(key, label, false)} + /> + setSorting(false)} + controller={controller} + /> + setOptions(false)} + onToggleArchive={() => setArchived((value) => !value)} + onWorkspaces={onWorkspaces} + onHiddenProjects={ + Object.keys(conversationPreferences.preferences?.hiddenProjects ?? {}).length + ? () => setManagingHidden(true) + : undefined + } + /> + setDetails(null)} + hostTitle={controller.hostDisplay.title} + canManage={conversationPreferences.supported} + writing={conversationPreferences.writing} + preferences={conversationPreferences.preferences} + onPreference={conversationPreferences.setPreference} + {...{ archived, connected }} + /> + setNewChat(null)} + onLaunch={launch} + /> + + ) +} diff --git a/mobile/src/host-screen/conversation-agent-sheet.tsx b/mobile/src/host-screen/conversation-agent-sheet.tsx new file mode 100644 index 000000000000..b5e0d49a2e5d --- /dev/null +++ b/mobile/src/host-screen/conversation-agent-sheet.tsx @@ -0,0 +1,37 @@ +import { Pressable, Text, View } from 'react-native' +import { BottomDrawer } from '../components/bottom-drawer/BottomDrawer' +import { MobileAgentIcon } from '../components/icons/MobileAgentIcon' +import type { MobileNewTabAgentOption } from '../session/agent-launch/mobile-new-tab-agent-options' +import { conversationCopy } from './conversation-copy' +import { conversationStyles as styles } from './conversation-styles' + +export function ConversationAgentSheet({ + visible, + agents, + onClose, + onLaunch +}: { + visible: boolean + agents: readonly MobileNewTabAgentOption[] + onClose: () => void + onLaunch: (option: MobileNewTabAgentOption) => void +}) { + return ( + + + {conversationCopy().agent} + {agents.map((option) => ( + onLaunch(option)} + style={({ pressed }) => [styles.agentButton, pressed && styles.pressed]} + accessibilityRole="button" + > + + {option.label} + + ))} + + + ) +} diff --git a/mobile/src/host-screen/conversation-copy.ts b/mobile/src/host-screen/conversation-copy.ts new file mode 100644 index 000000000000..b4c72dc4b88c --- /dev/null +++ b/mobile/src/host-screen/conversation-copy.ts @@ -0,0 +1,147 @@ +import { formatTimeAgo } from '../worktree/agent-lineage/agent-row-display' + +const english = { + conversations: 'Conversations', + projects: 'Projects', + archived: 'Archived chats', + pinChat: 'Pin chat', + unpinChat: 'Unpin chat', + archiveChat: 'Archive chat', + restoreChat: 'Restore chat', + saveFailed: 'Could not save chat preferences. Try again.', + showMore: 'Show more', + projectOrder: 'Project order', + projectOrderLabels: { + manual: 'Manual', + recent: 'Recent activity' + }, + projectOptions: 'Project options', + hideProject: 'Hide project from list', + hiddenProjects: 'Hidden projects', + keepFiles: 'Files and history are kept.', + restoreProject: 'Restore project', + pinProject: 'Pin project', + unpinProject: 'Unpin project', + newChat: 'New chat', + untitled: 'New conversation', + search: 'Search conversations…', + empty: 'Start a conversation in this project.', + noProjects: 'Add a project from workspace settings to start chatting.', + settings: 'More options', + workspaces: 'Advanced: workspaces', + back: 'Back to projects', + details: 'Conversation details', + history: 'Conversation history', + saved: 'Saved conversation', + transcript: 'Saved transcript', + offline: 'Waiting for host', + loading: 'Loading conversations…', + failed: 'Could not refresh the full chat list.', + failedState: 'Failed', + ssh: 'Open chats on this SSH host. Transcript history is not available through this connection.', + noAgents: 'No supported agents found on this host.', + update: 'Update Orca on this host to start or reopen this conversation.', + workspaceNeeded: 'Create a workspace for this project in advanced settings first.', + agent: 'Choose an agent', + accounts: 'Accounts', + tasks: 'Tasks', + newWorkspace: 'Add project or workspace', + close: 'Close', + working: 'Working', + monitoring: 'Monitoring', + blocked: 'Blocked', + waiting: 'Waiting for input', + done: 'Done', + idle: 'Ready', + interrupted: 'Interrupted', + unconfirmed: 'Unconfirmed', + unavailable: 'Could not open this conversation on its host.', + refresh: 'Refresh', + host: 'Host', + workspace: 'Workspace', + branch: 'Branch', + model: 'Model' +} + +const russian: typeof english = { + conversations: 'Разговоры', + projects: 'Проекты', + archived: 'Архив чатов', + pinChat: 'Закрепить чат', + unpinChat: 'Открепить чат', + archiveChat: 'В архив', + restoreChat: 'Восстановить чат', + saveFailed: 'Не удалось сохранить настройки чата. Попробуйте ещё раз.', + showMore: 'Показать ещё', + projectOrder: 'Порядок проектов', + projectOrderLabels: { + manual: 'Вручную', + recent: 'Недавняя активность' + }, + projectOptions: 'Действия с проектом', + hideProject: 'Скрыть проект из списка', + hiddenProjects: 'Скрытые проекты', + keepFiles: 'Файлы и история сохраняются.', + restoreProject: 'Показать проект', + pinProject: 'Закрепить проект', + unpinProject: 'Открепить проект', + newChat: 'Новый чат', + untitled: 'Новый разговор', + search: 'Поиск разговоров…', + empty: 'Начните разговор в этом проекте.', + noProjects: 'Добавьте проект в настройках рабочих каталогов, чтобы начать разговор.', + settings: 'Другие действия', + workspaces: 'Дополнительно: рабочие каталоги', + back: 'К проектам', + details: 'Детали разговора', + history: 'История разговоров', + saved: 'Сохранённый разговор', + transcript: 'Сохранённая переписка', + offline: 'Ожидание подключения', + loading: 'Загружаем разговоры…', + failed: 'Не удалось обновить весь список чатов.', + failedState: 'Ошибка', + ssh: 'Открытые чаты на этом SSH-хосте. История переписки недоступна через это подключение.', + noAgents: 'На этом хосте не найдено поддерживаемых агентов.', + update: 'Обновите Orca на этом хосте, чтобы начать или открыть разговор.', + workspaceNeeded: 'Сначала создайте рабочий каталог проекта в дополнительных настройках.', + agent: 'Выберите агента', + accounts: 'Аккаунты', + tasks: 'Задачи', + newWorkspace: 'Добавить проект или рабочий каталог', + close: 'Закрыть', + working: 'Работает', + monitoring: 'Наблюдает', + blocked: 'Заблокирован', + waiting: 'Ждёт ответа', + done: 'Готово', + idle: 'Готов к работе', + interrupted: 'Остановлен', + unconfirmed: 'Не подтверждено', + unavailable: 'Не удалось открыть разговор на его хосте.', + refresh: 'Обновить', + host: 'Хост', + workspace: 'Рабочий каталог', + branch: 'Ветка', + model: 'Модель' +} + +export function conversationCopy(locale = Intl.DateTimeFormat().resolvedOptions().locale) { + return locale.toLowerCase().startsWith('ru') ? russian : english +} + +export function conversationTimeAgo( + at: number, + now: number, + locale = Intl.DateTimeFormat().resolvedOptions().locale +) { + const label = formatTimeAgo(at, now) + if (!locale.toLowerCase().startsWith('ru')) { + return label + } + return label + .replace('just now', 'сейчас') + .replace(/m$/, ' мин') + .replace(/h$/, ' ч') + .replace(/d$/, ' дн') +} diff --git a/mobile/src/host-screen/conversation-details-sheet.tsx b/mobile/src/host-screen/conversation-details-sheet.tsx new file mode 100644 index 000000000000..d2ffe3958852 --- /dev/null +++ b/mobile/src/host-screen/conversation-details-sheet.tsx @@ -0,0 +1,106 @@ +import { Pressable, Text, View } from 'react-native' +import type { + ConversationPreference, + ConversationPreferences +} from '../../../src/shared/conversation-navigation-preferences' +import { BottomDrawer } from '../components/bottom-drawer/BottomDrawer' +import type { ConversationRow } from './project-conversations' +import { conversationCopy } from './conversation-copy' +import { conversationStyles as styles } from './conversation-styles' + +export function ConversationDetailsSheet({ + details, + onClose, + hostTitle, + canManage, + writing, + preferences, + onPreference, + archived, + connected +}: { + details: ConversationRow | null + onClose: () => void + hostTitle: string + canManage: boolean + writing: boolean + preferences: ConversationPreferences | undefined + onPreference: (key: string, patch: ConversationPreference) => Promise + archived: boolean + connected: boolean +}) { + const copy = conversationCopy() + return ( + onClose()}> + {details && ( + + {details.title} + + {[ + `${copy.host}: ${details.workspaceContext?.hostContextLabel ?? hostTitle}`, + details.workspace + ? `${copy.workspace}: ${details.workspace.displayName}\n${details.workspace.path}` + : details.history?.cwd, + details.workspace?.branch ? `${copy.branch}: ${details.workspace.branch}` : null, + details.workspace?.linkedPR ? `PR #${details.workspace.linkedPR.number}` : null, + details.history?.model ? `${copy.model}: ${details.history.model}` : null + ] + .filter(Boolean) + .join('\n')} + + {details.preferenceKey && canManage ? ( + <> + { + if ( + details.preferenceKey && + (await onPreference(details.preferenceKey, { + pinned: !preferences?.entries[details.preferenceKey]?.pinned + })) + ) { + onClose() + } + }} + style={styles.agentButton} + accessibilityRole="button" + disabled={!connected || writing} + > + + {preferences?.entries[details.preferenceKey]?.pinned + ? copy.unpinChat + : copy.pinChat} + + + { + if ( + details.preferenceKey && + (await onPreference(details.preferenceKey, { + archived: !archived + })) + ) { + onClose() + } + }} + style={styles.agentButton} + accessibilityRole="button" + disabled={!connected || writing} + > + + {archived ? copy.restoreChat : copy.archiveChat} + + + + ) : null} + onClose()} + style={styles.agentButton} + accessibilityRole="button" + > + {copy.close} + + + )} + + ) +} diff --git a/mobile/src/host-screen/conversation-history-index.ts b/mobile/src/host-screen/conversation-history-index.ts new file mode 100644 index 000000000000..38b6fb114754 --- /dev/null +++ b/mobile/src/host-screen/conversation-history-index.ts @@ -0,0 +1,29 @@ +import type { ExecutionHostId } from '../../../src/shared/execution-host/execution-host' +import type { ConversationHistory, ConversationTab } from './conversation-records' + +export function createConversationHistoryIndex(history: readonly ConversationHistory[]) { + const byIdentity = new Map() + for (const session of history) { + const key = session.structuredSession + ? JSON.stringify([ + session.executionHostId, + 'structured', + session.structuredSession.workspaceId, + session.structuredSession.sessionId + ]) + : JSON.stringify([session.executionHostId, 'native', session.agent, session.sessionId]) + byIdentity.set(key, [...(byIdentity.get(key) ?? []), session]) + } + return ( + tab: ConversationTab, + hostId: ExecutionHostId, + workspaceId: string, + agent?: string | null + ) => { + const key = tab.sessionId + ? JSON.stringify([hostId, 'structured', workspaceId, tab.sessionId]) + : JSON.stringify([hostId, 'native', agent, tab.agentStatus?.sessionId]) + const candidates = byIdentity.get(key) + return candidates?.length === 1 ? candidates[0] : undefined + } +} diff --git a/mobile/src/host-screen/conversation-open.test.ts b/mobile/src/host-screen/conversation-open.test.ts new file mode 100644 index 000000000000..8e29d6f9e97a --- /dev/null +++ b/mobile/src/host-screen/conversation-open.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/capabilities/structured-agent-session-surface-capabilities' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../src/shared/remote-runtime/relay/mobile-desktop-relay-contract' +import { rpcClientForExecutionHost } from '../worktree/execution-hosts/execution-host-scoped-rpc-client' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { conversationOpenPane } from './conversation-open' +import type { ConversationRow } from './project-conversations' +import { conversationHistory, conversationWorkspace } from './project-conversations.test-fixture' + +function saved(): ConversationRow & { workspace: ReturnType } { + const workspace = conversationWorkspace({ hostId: 'runtime:server' }) + return { + key: 'saved', + title: 'Saved chat', + status: 'saved', + agent: 'codex', + at: 1, + workspace, + history: conversationHistory({ + executionHostId: 'runtime:server', + structuredSession: { sessionId: 'saved-chat', workspaceId: workspace.worktreeId } + }) + } +} +const capabilities = [STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY] + +describe('opening the selected conversation', () => { + it('selects an existing pane without restarting an agent', async () => { + const client = new FakeSession('connected') + expect( + await conversationOpenPane({ + row: { ...saved(), paneKey: 'chosen-pane' }, + client, + capabilities: [] + }) + ).toBe('chosen-pane') + expect(client.sendRequest).not.toHaveBeenCalled() + }) + + it('reveals a retained record on its owning server through the existing scoped client', async () => { + const client = new FakeSession('connected') + const row = saved() + client.sendRequest.mockResolvedValue({ + id: 'one', + ok: true, + result: { ok: true, sessionId: 'saved-chat', workspaceId: row.workspace.worktreeId } + }) + const scoped = rpcClientForExecutionHost( + client, + [MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY], + row.workspace.hostId + ) + expect(scoped).not.toBeNull() + if (!scoped) { + throw new Error('missing scoped client') + } + expect(await conversationOpenPane({ row, client: scoped, capabilities })).toContain( + 'structured-agent-session-saved-chat:' + ) + expect(client.sendRequest).toHaveBeenCalledWith( + 'agentSession.reveal', + { sessionId: 'saved-chat' }, + { envelope: { executionHost: 'runtime:server' } } + ) + }) + + it('does not call a missing reveal API on an older host or use a local fallback', async () => { + const client = new FakeSession('connected') + await expect(conversationOpenPane({ row: saved(), client, capabilities: [] })).rejects.toThrow( + 'conversation_host_update_required' + ) + expect(client.sendRequest).not.toHaveBeenCalled() + expect(rpcClientForExecutionHost(client, [], 'runtime:server')).toBeNull() + }) + + it('refuses a reveal reply for another workspace', async () => { + const client = new FakeSession('connected') + client.sendRequest.mockResolvedValue({ + id: 'one', + ok: true, + result: { ok: true, sessionId: 'saved-chat', workspaceId: 'another-workspace' } + }) + await expect(conversationOpenPane({ row: saved(), client, capabilities })).rejects.toThrow( + 'conversation_host_identity_changed' + ) + }) +}) diff --git a/mobile/src/host-screen/conversation-open.ts b/mobile/src/host-screen/conversation-open.ts new file mode 100644 index 000000000000..61aed643924b --- /dev/null +++ b/mobile/src/host-screen/conversation-open.ts @@ -0,0 +1,48 @@ +import * as z from 'zod' +import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/capabilities/structured-agent-session-surface-capabilities' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../src/shared/agent-session/view/structured-agent-session-projection' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { ConversationRow } from './project-conversations' + +const revealSchema = z.object({ + ok: z.literal(true), + sessionId: z.string(), + workspaceId: z.string() +}) + +export async function conversationOpenPane(args: { + row: ConversationRow + client: RpcClient + capabilities: readonly string[] +}): Promise { + if (args.row.paneKey) { + return args.row.paneKey + } + const structured = args.row.history?.structuredSession + if (!structured) { + return null + } + if (!args.capabilities.includes(STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY)) { + throw new Error('conversation_host_update_required') + } + const response = await args.client.sendRequest('agentSession.reveal', { + sessionId: structured.sessionId + }) + if (!response.ok) { + throw new Error(response.error.message) + } + const result = revealSchema.parse(response.result) + if ( + result.sessionId !== structured.sessionId || + result.workspaceId !== (args.row.workspace?.worktreeId ?? structured.workspaceId) + ) { + throw new Error('conversation_host_identity_changed') + } + return structuredAgentSessionPaneKey( + structuredAgentSessionTabId(result.sessionId), + result.sessionId + ) +} diff --git a/mobile/src/host-screen/conversation-project-actions-sheet.tsx b/mobile/src/host-screen/conversation-project-actions-sheet.tsx new file mode 100644 index 000000000000..5e227d1ade12 --- /dev/null +++ b/mobile/src/host-screen/conversation-project-actions-sheet.tsx @@ -0,0 +1,37 @@ +import { EyeOff, Folder } from 'lucide-react-native' +import { ActionSheetModal } from '../components/sheets/ActionSheetModal' +import type { HostScreenController } from './use-host-screen-controller' +import type { ConversationProject } from './project-conversations' +import { conversationCopy } from './conversation-copy' + +export function ConversationProjectActionsSheet({ + project, + onClose, + onWorkspaces, + onHide +}: { + project: ConversationProject | null + controller: HostScreenController + onClose: () => void + onWorkspaces: () => void + onHide?: () => void +}) { + const copy = conversationCopy() + return ( + onHide?.() + } + ]} + /> + ) +} diff --git a/mobile/src/host-screen/conversation-project-actions.test.tsx b/mobile/src/host-screen/conversation-project-actions.test.tsx new file mode 100644 index 000000000000..7adc4c2e66b4 --- /dev/null +++ b/mobile/src/host-screen/conversation-project-actions.test.tsx @@ -0,0 +1,146 @@ +import { createElement, type ReactNode, type ReactElement } from 'react' +import { Pressable, Text } from 'react-native' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { ConversationProjectHeader } from './ConversationProjectHeader' +import { ConversationProjectActionsSheet } from './conversation-project-actions-sheet' +import { HiddenConversationProjectsSheet } from './hidden-conversation-projects-sheet' +import { conversationCopy } from './conversation-copy' +import type { ConversationProject } from './project-conversations' +import { conversationWorkspace } from './project-conversations.test-fixture' +import { mountFixture } from '../test-support/rpc-recording/react-mounting/recorder-fixture-shape' +import type { HostScreenController } from './use-host-screen-controller' + +vi.mock('react-native', () => ({ + View: 'View', + Text: 'Text', + Pressable: 'Pressable', + ActivityIndicator: 'ActivityIndicator', + StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 } +})) +vi.mock('../components/bottom-drawer/BottomDrawer', () => ({ + BottomDrawer: ({ children }: { children: ReactNode }) => children +})) +vi.mock('../components/icons/MobileRepoIcon', () => ({ MobileRepoIcon: 'MobileRepoIcon' })) +vi.mock('lucide-react-native', () => ({ + Eye: 'Icon', + EyeOff: 'Icon', + Folder: 'Icon', + Pin: 'Icon', + PinOff: 'Icon', + MoreHorizontal: 'Icon', + Plus: 'Icon', + Edit3: 'Icon', + Trash2: 'Icon' +})) + +const trees: ReactTestRenderer[] = [] +afterEach(() => + act(() => { + trees.forEach((tree) => tree.unmount()) + trees.length = 0 + }) +) +async function mount(element: ReactElement) { + let tree: ReactTestRenderer | undefined + await act(async () => { + tree = create(element) + trees.push(tree) + }) + if (!tree) { + throw new Error('missing render') + } + return tree +} +const project: ConversationProject = { + key: 'notes', + title: 'Notes', + hostId: 'local', + data: [], + workspaces: [] +} + +it('offers accessible options on a discovered group without inventing a new-chat target', async () => { + const onOptions = vi.fn() + const tree = await mount( + createElement(ConversationProjectHeader, { + project, + connected: true, + busy: null, + onPrepare: vi.fn(), + onOptions + }) + ) + const buttons = tree.root.findAll((node) => node.type === Pressable) + expect(buttons).toHaveLength(1) + expect(buttons[0]?.props).toMatchObject({ + accessibilityRole: 'button', + accessibilityLabel: `${conversationCopy().projectOptions}: Notes` + }) + act(() => buttons[0]?.props.onPress()) + expect(onOptions).toHaveBeenCalledOnce() + await act(async () => + tree.update( + createElement(ConversationProjectHeader, { + project: { ...project, workspaces: [conversationWorkspace()] }, + connected: true, + busy: null, + onPrepare: vi.fn(), + onOptions + }) + ) + ) + expect(tree.root.findAll((node) => node.type === Pressable)).toHaveLength(2) +}) + +it('uses neutral hide and restore actions and exposes disabled state on older hosts', async () => { + const onHide = vi.fn() + const controller = mountFixture({ connState: 'connected' }) + const tree = await mount( + createElement(ConversationProjectActionsSheet, { + project, + controller, + onClose: vi.fn(), + onWorkspaces: vi.fn() + }) + ) + const hide = () => tree.root.findAll((node) => node.type === Pressable).at(-1) + expect(hide()?.props).toMatchObject({ + accessibilityRole: 'button', + disabled: true, + accessibilityState: { disabled: true } + }) + expect( + tree.root.findAll((node) => node.type === Text).map((node) => node.props.children) + ).toContain(conversationCopy().keepFiles) + await act(async () => + tree.update( + createElement(ConversationProjectActionsSheet, { + project, + controller, + onClose: vi.fn(), + onWorkspaces: vi.fn(), + onHide + }) + ) + ) + expect(hide()?.props.accessibilityState.disabled).toBe(false) + act(() => hide()?.props.onPress()) + expect(onHide).toHaveBeenCalledOnce() + const onRestore = vi.fn() + await act(async () => + tree.update( + createElement(HiddenConversationProjectsSheet, { + visible: true, + projects: { notes: 'Notes' }, + connected: true, + writing: false, + supported: true, + onClose: vi.fn(), + onRestore + }) + ) + ) + act(() => tree.root.find((node) => node.type === Pressable).props.onPress()) + expect(onRestore).toHaveBeenCalledWith('notes', 'Notes') +}) diff --git a/mobile/src/host-screen/conversation-project-order-sheet.tsx b/mobile/src/host-screen/conversation-project-order-sheet.tsx new file mode 100644 index 000000000000..7a9d1feba0c3 --- /dev/null +++ b/mobile/src/host-screen/conversation-project-order-sheet.tsx @@ -0,0 +1,33 @@ +import { ActionSheetModal } from '../components/sheets/ActionSheetModal' +import { projectOrderChoices } from './workspace-options/workspace-option-controls-copy' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import type { HostScreenController } from './use-host-screen-controller' +import { conversationCopy } from './conversation-copy' + +export function ConversationProjectOrderSheet({ + visible, + onClose, + controller +}: { + visible: boolean + onClose: () => void + controller: HostScreenController +}) { + const t = useMobileTranslation() + const copy = conversationCopy() + const connected = controller.connState === 'connected' + return ( + onClose()} + actions={projectOrderChoices(t).map((choice) => ({ + label: `${controller.projectOrderBy === choice.id ? '✓ ' : ''}${choice.label}`, + onPress: () => { + void controller.settings.setProjectOrderBy(choice.id) + }, + disabled: !connected + }))} + /> + ) +} diff --git a/mobile/src/host-screen/conversation-project.ts b/mobile/src/host-screen/conversation-project.ts new file mode 100644 index 000000000000..66262a257666 --- /dev/null +++ b/mobile/src/host-screen/conversation-project.ts @@ -0,0 +1,59 @@ +import type { ExecutionHostId } from '../../../src/shared/execution-host/execution-host' +import type { AgentDotState } from '../worktree/agent-lineage/agent-row-display' +import type { + SectionRepo, + Worktree, + WorktreeHostContextView +} from '../worktree/workspace-list/workspace-list-types' +import type { ConversationHistory } from './conversation-records' + +export type ConversationRow = { + key: string + title: string + preview?: string + agent: string | null + status: AgentDotState | 'saved' | 'transcript' + at: number + workspace: Worktree | null + workspaceContext?: WorktreeHostContextView + executionHostId?: ExecutionHostId + paneKey?: string + preferenceKey?: string + history?: ConversationHistory +} +export type ConversationProject = { + key: string + title: string + hostId: ExecutionHostId + hostLabel?: string + hostHealthLabel?: string + repo?: SectionRepo + visibilityKey?: string + workspaces: Worktree[] + data: ConversationRow[] +} + +export function projectConversationTarget(project: ConversationProject): Worktree | null { + return ( + project.workspaces.find( + (workspace) => workspace.isMainWorktree || workspace.workspaceKind === 'folder-workspace' + ) ?? (project.workspaces.length === 1 ? project.workspaces[0] : null) + ) +} + +export function folderOnlyConversationRepoKeys( + workspaces: readonly Worktree[], + hostOf: (workspace: Worktree) => ExecutionHostId +): ReadonlySet { + const folders = new Set( + workspaces + .filter((workspace) => workspace.workspaceKind === 'folder-workspace') + .map((workspace) => `${hostOf(workspace)}\0${workspace.repoId}`) + ) + for (const workspace of workspaces) { + if (workspace.workspaceKind !== 'folder-workspace') { + folders.delete(`${hostOf(workspace)}\0${workspace.repoId}`) + } + } + return folders +} diff --git a/mobile/src/host-screen/conversation-records.ts b/mobile/src/host-screen/conversation-records.ts new file mode 100644 index 000000000000..f0823ec5dacc --- /dev/null +++ b/mobile/src/host-screen/conversation-records.ts @@ -0,0 +1,79 @@ +import * as z from 'zod' +import { normalizeExecutionHostId } from '../../../src/shared/execution-host/execution-host' + +const historySchema = z.looseObject({ + id: z.string(), + executionHostId: z.string().transform((value) => normalizeExecutionHostId(value)), + sessionId: z.string(), + agent: z.string(), + title: z.string(), + cwd: z.string().nullable(), + cwdAliases: z.array(z.string()).optional(), + filePath: z.string().optional().catch(undefined), + projectOwnerKey: z.string().nullable().optional().catch(undefined), + updatedAt: z.string().nullable(), + modifiedAt: z.string(), + model: z.string().nullable().optional(), + conversationContent: z.enum(['empty', 'present', 'unknown']).optional().catch(undefined), + firstUserPrompt: z.string().nullable().optional(), + lastUserPrompt: z.string().nullable().optional().catch(undefined), + previewMessagesTruncated: z.boolean().optional(), + previewMessages: z + .array( + z.object({ + role: z.enum(['user', 'assistant', 'system', 'tool', 'unknown']), + text: z.string(), + timestamp: z.string().nullable() + }) + ) + .optional() + .default([]), + subagent: z.unknown().optional(), + structuredSession: z.object({ sessionId: z.string(), workspaceId: z.string() }).optional() +}) +export type ConversationHistory = z.infer +const historyListSchema = z.object({ + sessions: z.array(historySchema), + issues: z.array(z.unknown()).default([]), + fingerprint: z.string().optional(), + unchanged: z.literal(true).optional(), + includesStructuredSessions: z.literal(true).optional() +}) +export function readConversationHistory(value: unknown) { + return historyListSchema.parse(value) +} + +const tabSchema = z.object({ + type: z.enum(['terminal', 'agent-session']), + id: z.string(), + title: z.string(), + sessionId: z.string().optional(), + agent: z.string().optional(), + terminal: z.string().nullable().optional(), + launchAgent: z.string().optional(), + parentTabId: z.string().optional(), + leafId: z.string().optional(), + agentStatus: z + .object({ + agentType: z.string().nullable().optional(), + sessionId: z.string().nullable().optional() + }) + .nullable() + .optional() +}) +export type ConversationTab = z.infer +export function readConversationTabs(value: unknown): ConversationTab[] { + return z + .object({ tabs: z.array(z.unknown()) }) + .parse(value) + .tabs.flatMap((tab) => { + const parsed = tabSchema.safeParse(tab) + return parsed.success ? [parsed.data] : [] + }) +} + +const noticeSchema = z.object({ kind: z.literal('notice') }) + +export function isConversationHistoryNotice(issue: unknown): boolean { + return noticeSchema.safeParse(issue).success +} diff --git a/mobile/src/host-screen/conversation-row-content.ts b/mobile/src/host-screen/conversation-row-content.ts new file mode 100644 index 000000000000..925488c1bfae --- /dev/null +++ b/mobile/src/host-screen/conversation-row-content.ts @@ -0,0 +1,38 @@ +import { isKnownHarnessInjectedUserTurnText } from '../../../src/shared/agent-session/journal/harness-injected-user-turns' +import { isGenericConversationTitle } from '../../../src/shared/project-conversation-list' +import type { Worktree } from '../worktree/workspace-list/workspace-list-types' +import type { ConversationHistory } from './conversation-records' + +export function conversationTitle( + values: readonly (string | null | undefined)[], + workspace: Worktree, + untitled: string +): string { + return ( + values + .map((value) => value?.trim()) + .find( + (value) => + value && + !isGenericConversationTitle(value) && + value !== workspace.branch && + value !== workspace.path && + value !== workspace.displayName + ) ?? untitled + ) +} + +export function conversationUserPreview(prompt?: string | null, history?: ConversationHistory) { + const savedPrompt = + history?.lastUserPrompt === undefined + ? history?.previewMessages.findLast( + (message) => + message.role === 'user' && + message.text.trim() && + !isKnownHarnessInjectedUserTurnText(message.text) + )?.text + : history.lastUserPrompt + return [prompt, savedPrompt] + .find((text) => text?.trim() && !isKnownHarnessInjectedUserTurnText(text)) + ?.trim() +} diff --git a/mobile/src/host-screen/conversation-sidebar-options.tsx b/mobile/src/host-screen/conversation-sidebar-options.tsx new file mode 100644 index 000000000000..c511c8c34cb3 --- /dev/null +++ b/mobile/src/host-screen/conversation-sidebar-options.tsx @@ -0,0 +1,59 @@ +import { Eye } from 'lucide-react-native' +import { ActionSheetModal } from '../components/sheets/ActionSheetModal' +import { conversationCopy } from './conversation-copy' +import type { HostScreenController } from './use-host-screen-controller' + +export function ConversationSidebarOptions({ + visible, + controller, + archived, + onClose, + onToggleArchive, + onWorkspaces, + onHiddenProjects +}: { + visible: boolean + controller: HostScreenController + archived: boolean + onClose: () => void + onToggleArchive: () => void + onWorkspaces: () => void + onHiddenProjects?: () => void +}) { + const copy = conversationCopy() + const { hostId, actions, connState } = controller + return ( + actions.navigateFromHostList(`/h/${encodeURIComponent(hostId)}/accounts`) + }, + { + label: copy.tasks, + onPress: () => actions.navigateFromHostList(`/h/${encodeURIComponent(hostId)}/tasks`) + }, + { + label: copy.newWorkspace, + onPress: actions.openNewWorktreeModal, + disabled: connState !== 'connected' + } + ]} + /> + ) +} diff --git a/mobile/src/host-screen/conversation-styles.ts b/mobile/src/host-screen/conversation-styles.ts new file mode 100644 index 000000000000..fd541ba10381 --- /dev/null +++ b/mobile/src/host-screen/conversation-styles.ts @@ -0,0 +1,91 @@ +import { themedStyleSheet } from '../theme/themed-styles' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' + +export const conversationStyles = themedStyleSheet(() => ({ + container: { flex: 1, backgroundColor: colors.bgBase }, + header: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.md, + paddingVertical: spacing.sm, + borderBottomWidth: 1, + borderBottomColor: colors.borderSubtle + }, + headerText: { flex: 1, gap: spacing.xs }, + title: { fontSize: typography.titleSize, fontWeight: '600', color: colors.textPrimary }, + host: { flexDirection: 'row', gap: spacing.sm, alignItems: 'center' }, + meta: { fontSize: typography.metaSize, color: colors.textMuted }, + iconButton: { + minWidth: 44, + minHeight: 44, + alignItems: 'center', + justifyContent: 'center', + borderRadius: radii.control + }, + pressed: { backgroundColor: colors.bgRaised }, + search: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md + }, + searchField: { flex: 1 }, + list: { paddingHorizontal: spacing.lg, paddingBottom: spacing.xl }, + section: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingTop: spacing.xl, + paddingBottom: spacing.sm + }, + sectionName: { flex: 1, gap: spacing.xs }, + projectTitle: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' }, + newChat: { + minHeight: 44, + flexDirection: 'row', + gap: spacing.xs, + alignItems: 'center', + paddingHorizontal: spacing.md, + borderRadius: radii.control, + backgroundColor: colors.bgRaised + }, + actionText: { color: colors.textPrimary, fontSize: typography.bodySize }, + disabled: { opacity: 0.5 }, + row: { flexDirection: 'row', alignItems: 'center', borderRadius: radii.control }, + rowButton: { + flex: 1, + minWidth: 0, + minHeight: 64, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingVertical: spacing.md, + paddingLeft: spacing.sm + }, + rowText: { flex: 1, minWidth: 0, gap: spacing.xs }, + rowTitle: { fontSize: typography.bodySize, fontWeight: '600', color: colors.textPrimary }, + rowPreview: { fontSize: typography.metaSize, color: colors.textSecondary }, + rowMeta: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + notice: { + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + color: colors.textSecondary, + fontSize: typography.metaSize, + lineHeight: 18 + }, + failure: { color: colors.statusRed }, + empty: { color: colors.textMuted, fontSize: typography.bodySize, paddingVertical: spacing.md }, + drawer: { padding: spacing.lg, gap: spacing.md }, + detail: { color: colors.textSecondary, fontSize: typography.bodySize, lineHeight: 20 }, + agentButton: { + flexDirection: 'row', + gap: spacing.md, + minHeight: 48, + alignItems: 'center', + paddingHorizontal: spacing.md, + borderRadius: radii.control + }, + spinner: { marginVertical: spacing.lg } +})) diff --git a/mobile/src/host-screen/hidden-conversation-projects-sheet.tsx b/mobile/src/host-screen/hidden-conversation-projects-sheet.tsx new file mode 100644 index 000000000000..42a20feb9a13 --- /dev/null +++ b/mobile/src/host-screen/hidden-conversation-projects-sheet.tsx @@ -0,0 +1,37 @@ +import { Eye } from 'lucide-react-native' +import { ActionSheetModal } from '../components/sheets/ActionSheetModal' +import { conversationCopy } from './conversation-copy' + +export function HiddenConversationProjectsSheet({ + visible, + projects, + supported, + writing, + connected, + onClose, + onRestore +}: { + visible: boolean + projects: Record | undefined + supported: boolean + writing: boolean + connected: boolean + onClose: () => void + onRestore: (key: string, label: string) => void +}) { + const copy = conversationCopy() + return ( + ({ + label: `${copy.restoreProject}: ${label}`, + icon: Eye, + disabled: !connected || writing || !supported, + onPress: () => onRestore(key, label) + }))} + /> + ) +} diff --git a/mobile/src/host-screen/host-screen-operations.ts b/mobile/src/host-screen/host-screen-operations.ts index 56232c98c626..ab205052e623 100644 --- a/mobile/src/host-screen/host-screen-operations.ts +++ b/mobile/src/host-screen/host-screen-operations.ts @@ -1,3 +1,5 @@ +import * as z from 'zod' +import { ConversationPreferencesSchema } from '../../../src/shared/conversation-navigation-preferences' import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' import { @@ -150,3 +152,16 @@ export const worktreeActivate = bindDeferredRpcOperation( read: rpcResultVariant('worktree-activated', hostScreenUnreadReplySchema) }) ) + +export const conversationPreferenceWrite = bindDeferredRpcOperation( + defineRpcOperation({ + name: 'ui.set-conversation-preference', + method: 'ui.setConversationPreference', + acceptance: 'success-result-or-skip', + barrier: 'after-caller-barrier', + read: rpcResultVariant( + 'conversation-preference-written', + z.object({ preferences: ConversationPreferencesSchema }) + ) + }) +) diff --git a/mobile/src/host-screen/host-screen-reply-schema.ts b/mobile/src/host-screen/host-screen-reply-schema.ts index 77a5ac75f0e4..e4147e729669 100644 --- a/mobile/src/host-screen/host-screen-reply-schema.ts +++ b/mobile/src/host-screen/host-screen-reply-schema.ts @@ -1,4 +1,5 @@ import * as z from 'zod' +import { ConversationPreferencesSchema } from '../../../src/shared/conversation-navigation-preferences' import type { PersistedUIState } from '../../../src/shared/orca-profiles/persisted-ui-state-types' import type { RepoIcon } from '../../../src/shared/repository/appearance/repo-icon' import { @@ -134,6 +135,10 @@ export const hostViewSettingsSchema = z 'hideWorkspacesFromOtherDevices', z.boolean() ), + conversationPreferences: salvagedOptional( + 'conversationPreferences', + ConversationPreferencesSchema + ), projectOrderBy: salvagedOptional('projectOrderBy', z.enum(WORKSPACE_PROJECT_ORDER_ARMS)), // Kept as strings: a property a newer desktop adds is carried back unchanged on write. worktreeCardProperties: salvagedOptional('worktreeCardProperties', z.array(z.string())), diff --git a/mobile/src/host-screen/host-screen-view.tsx b/mobile/src/host-screen/host-screen-view.tsx index c566c1e3d9b2..d75f5068c9de 100644 --- a/mobile/src/host-screen/host-screen-view.tsx +++ b/mobile/src/host-screen/host-screen-view.tsx @@ -1,5 +1,5 @@ import { useCallback, useState } from 'react' -import { Text, View } from 'react-native' +import { Pressable, Text, View } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { PageTitle, useCollapsingTitle } from '../components/nav-bar/PageTitle' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' @@ -9,8 +9,12 @@ import { HostConnectionStatus, HostScreenHeader } from './host-screen-header' import { HostScreenOverlays } from './host-screen-overlays' import { HostWorkspaceList } from './workspace-list/host-workspace-list' import type { HostScreenController } from './use-host-screen-controller' +import { HostConversations } from './HostConversations' +import { conversationCopy } from './conversation-copy' +import { conversationStyles } from './conversation-styles' export function HostScreenView({ controller }: { controller: HostScreenController }) { + const [advanced, setAdvanced] = useState(false) useMobileColorScheme() const [bottomBarHeight, setBottomBarHeight] = useState(0) const listRef = controller.activeWorktreeScroll.sectionListRef @@ -28,10 +32,26 @@ export function HostScreenView({ controller }: { controller: HostScreenControlle ) } + if (!advanced) { + return ( + + setAdvanced(true)} /> + + + ) + } + return ( + setAdvanced(false)} + style={conversationStyles.agentButton} + accessibilityRole="button" + > + {conversationCopy().back} + { + let scans = 0 + const sendRequest = vi.fn(async (method) => ({ + id: 'host', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : ++scans === 1 + ? { sessions: [], issues: [], unchanged: true, fingerprint: 'other' } + : { + sessions: [conversationHistory()], + issues: [], + fingerprint: 'fresh', + includesStructuredSessions: true + } + })) + const client = { ...new FakeSession('connected'), sendRequest } + const previous = + reason === 'missing prior snapshot' + ? undefined + : { + sessions: [conversationHistory()], + issues: [], + fingerprint: 'old', + includesStructuredSessions: true as const + } + const result = await refreshProjectConversationHistory(client, false, previous) + expect(result.history?.sessions).toHaveLength(1) + expect(result.history?.fingerprint).toBe('fresh') + const requests = sendRequest.mock.calls.filter(([method]) => method === 'aiVault.listSessions') + expect(requests).toHaveLength(2) + expect(requests[1]?.[1]).not.toHaveProperty('afterFingerprint') + } +) + +it('reports a host that never supplies the requested full history instead of accepting an empty unchanged reply', async () => { + const sendRequest = vi.fn(async (method) => ({ + id: 'host', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : { sessions: [], issues: [], unchanged: true, fingerprint: 'unknown' } + })) + const client = { ...new FakeSession('connected'), sendRequest } + await expect(refreshProjectConversationHistory(client, false)).rejects.toThrow('full snapshot') +}) diff --git a/mobile/src/host-screen/project-conversation-history-refresh.ts b/mobile/src/host-screen/project-conversation-history-refresh.ts new file mode 100644 index 000000000000..45e72f88fd60 --- /dev/null +++ b/mobile/src/host-screen/project-conversation-history-refresh.ts @@ -0,0 +1,53 @@ +import { AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY } from '../../../src/shared/ai-vault/contracts/ai-vault-runtime-capabilities' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { + agentHistoryHostStatusRead, + agentHistorySessionScan +} from '../agent-history/mobile-agent-history-operations' +import { readConversationHistory } from './conversation-records' + +export type ProjectConversationHistorySnapshot = ReturnType + +export async function refreshProjectConversationHistory( + client: RpcClient, + force: boolean, + previous?: ProjectConversationHistorySnapshot +) { + const status = agentHistoryHostStatusRead.interpret( + await agentHistoryHostStatusRead.request(client) + ) + const capabilities = status.capabilities ?? [] + if (!capabilities.includes('aiVault.v1')) { + return { capabilities, history: null } + } + const request = { + ...(capabilities.includes(AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY) + ? { historyOwnership: {} } + : {}), + unlimited: true, + includeAntigravityIdeSessions: true, + includeStructuredSessions: true, + force + } + const afterFingerprint = force ? undefined : previous?.fingerprint + const read = async (conditional: boolean) => + readConversationHistory( + agentHistorySessionScan.interpret( + await agentHistorySessionScan.request(client, { + ...request, + ...(conditional && afterFingerprint ? { afterFingerprint } : {}) + }) + ) + ) + let history = await read(true) + if (history.unchanged) { + if (previous && afterFingerprint && history.fingerprint === afterFingerprint) { + return { capabilities, history: previous } + } + history = await read(false) + if (history.unchanged) { + throw new Error('Conversation history refresh did not return a full snapshot') + } + } + return { capabilities, history } +} diff --git a/mobile/src/host-screen/project-conversation-order.ts b/mobile/src/host-screen/project-conversation-order.ts new file mode 100644 index 000000000000..828c6e3548a2 --- /dev/null +++ b/mobile/src/host-screen/project-conversation-order.ts @@ -0,0 +1,65 @@ +import type { ConversationPreferences } from '../../../src/shared/conversation-navigation-preferences' +import { sortProjectEntries } from '../../../src/shared/sidebar-list/sections/project-section-order' +import type { ProjectSectionCatalog } from '../worktree/workspace-list/workspace-list-sections' +import type { ConversationProject } from './project-conversations' + +export function orderProjectConversations( + projects: Iterable, + args: { + query?: string + projectCatalog?: ProjectSectionCatalog + preferences?: ConversationPreferences + archived?: boolean + } +): ConversationProject[] { + const catalog = args.projectCatalog + const query = args.query?.trim().toLocaleLowerCase() + const entries = [...projects].map( + (project) => + [ + project.key, + { + ...project, + label: project.title, + items: project.workspaces, + repoIds: new Set(project.workspaces.map((workspace) => workspace.repoId)) + } + ] as const + ) + return sortProjectEntries(entries, catalog?.projectOrderBy ?? 'manual', catalog?.repoOrder) + .map(([, project]) => project) + .map((project) => ({ + ...project, + data: project.data + .filter( + (row) => + (row.preferenceKey !== undefined && + args.preferences?.entries[row.preferenceKey]?.archived === true) === + (args.archived === true) + ) + .sort( + (a, b) => + Number( + b.preferenceKey !== undefined && + args.preferences?.entries[b.preferenceKey]?.pinned === true + ) - + Number( + a.preferenceKey !== undefined && + args.preferences?.entries[a.preferenceKey]?.pinned === true + ) || b.at - a.at + ) + .filter( + (row) => + !query || + `${project.title} ${row.title} ${row.preview ?? ''} ${row.agent ?? ''}` + .toLocaleLowerCase() + .includes(query) + ) + })) + .filter( + (project) => + !args.preferences?.hiddenProjects?.[project.visibilityKey ?? project.key] && + (!args.archived || project.data.length > 0) && + (!query || project.data.length > 0 || project.title.toLocaleLowerCase().includes(query)) + ) +} diff --git a/mobile/src/host-screen/project-conversation-preview.test.ts b/mobile/src/host-screen/project-conversation-preview.test.ts new file mode 100644 index 000000000000..f6f54e08f086 --- /dev/null +++ b/mobile/src/host-screen/project-conversation-preview.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from 'vitest' +import { structuredAgentSessionPaneKey } from '../../../src/shared/agent-session/view/structured-agent-session-projection' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { buildProjectConversations, readConversationHistory } from './project-conversations' +import { + conversationAgent, + conversationHistory, + conversationWorkspace +} from './project-conversations.test-fixture' + +const defaults = { + repos: [], + tabs: new Map(), + history: [], + now: 1000, + untitled: 'New conversation' +} + +describe('conversation names and latest human previews', () => { + it.each([true, false])( + 'keeps a live session name separate from its prompt (tab: %s)', + (hasTab) => { + const workspace = conversationWorkspace({ + agents: [ + conversationAgent({ + paneKey: hasTab ? structuredAgentSessionPaneKey('tab', 'session') : 'chat-pane', + conversationName: 'Mobile navigation', + taskTitle: 'Current work', + prompt: 'Why does the list show my latest message?', + lastAssistantMessage: 'I will inspect the row.' + }) + ] + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [workspace], + tabs: hasTab + ? new Map([ + [ + getWorktreeRowIdentity(workspace), + [{ type: 'agent-session', id: 'tab', sessionId: 'session', title: 'Old title' }] + ] + ]) + : new Map() + }) + expect(project?.data[0]).toMatchObject({ + title: 'Mobile navigation', + preview: 'Why does the list show my latest message?' + }) + } + ) + + it('preserves a renamed tab on an older host without the optional conversation name', () => { + const workspace = conversationWorkspace({ + agents: [ + conversationAgent({ + paneKey: structuredAgentSessionPaneKey('tab', 'session'), + prompt: 'Another request' + }) + ] + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [workspace], + tabs: new Map([ + [ + getWorktreeRowIdentity(workspace), + [{ type: 'agent-session', id: 'tab', sessionId: 'session', title: 'Renamed chat' }] + ] + ]) + }) + expect(project?.data[0]).toMatchObject({ title: 'Renamed chat', preview: 'Another request' }) + }) + + it('uses the authenticated latest prompt for saved chats and searches its separate preview', () => { + const { sessions } = readConversationHistory({ + sessions: [ + conversationHistory({ + title: 'A stable saved title', + firstUserPrompt: 'Opening question', + lastUserPrompt: 'Check the latest layout', + previewMessages: [{ role: 'assistant', text: 'Result from the agent', timestamp: null }] + }) + ] + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [], + history: sessions, + query: 'latest layout' + }) + expect(project?.data[0]).toMatchObject({ + title: 'A stable saved title', + preview: 'Check the latest layout' + }) + }) + + it.each([undefined, null])( + 'handles old or unavailable latest-prompt evidence: %s', + (lastUserPrompt) => { + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [], + history: [ + conversationHistory({ + lastUserPrompt, + previewMessages: [ + { role: 'user', text: 'First message', timestamp: null }, + { role: 'user', text: 'Last human message', timestamp: null }, + { + role: 'user', + text: 'Internal update', + timestamp: null + }, + { role: 'tool', text: 'Tool output', timestamp: null }, + { role: 'assistant', text: 'Latest answer', timestamp: null } + ] + }) + ] + }) + expect(project?.data[0]?.preview).toBe( + lastUserPrompt === undefined ? 'Last human message' : undefined + ) + } + ) + + it('does not substitute the opening prompt or assistant output for a missing human preview', () => { + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [], + history: [ + conversationHistory({ + firstUserPrompt: 'An old opening request', + previewMessages: [{ role: 'assistant', text: 'Only an answer remains', timestamp: null }] + }) + ] + }) + expect(project?.data[0]?.preview).toBeUndefined() + }) +}) diff --git a/mobile/src/host-screen/project-conversation-visibility.test.ts b/mobile/src/host-screen/project-conversation-visibility.test.ts new file mode 100644 index 000000000000..7b6db16976d7 --- /dev/null +++ b/mobile/src/host-screen/project-conversation-visibility.test.ts @@ -0,0 +1,121 @@ +import { projectHostSetupProjectionFromRepos } from '../../../src/shared/project/host-setup/project-host-setup-projection' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { expect, it } from 'vitest' +import { buildProjectConversations, projectConversationTarget } from './project-conversations' +import { conversationHistory, conversationWorkspace } from './project-conversations.test-fixture' +import { updateConversationPreference } from '../../../src/shared/conversation-navigation-preferences' + +const defaults = { + repos: [], + tabs: new Map(), + workspaces: [], + history: [], + now: 1000, + untitled: 'New conversation' +} + +it('keeps discovered history groups reversible without inventing a workspace target', () => { + const history = [conversationHistory({ cwd: '/lost/notes', filePath: '/logs/one.jsonl' })] + const [project] = buildProjectConversations({ ...defaults, history }) + expect(project?.data).toHaveLength(1) + expect(project?.data[0]?.workspace).toBeNull() + expect(project && projectConversationTarget(project)).toBeNull() + if (!project?.visibilityKey) { + throw new Error('missing visibility identity') + } + const hidden = updateConversationPreference(null, { + projectKey: project.visibilityKey, + label: project.title, + hidden: true + }) + expect(buildProjectConversations({ ...defaults, history, preferences: hidden })).toEqual([]) + const restored = updateConversationPreference(hidden, { + projectKey: project.visibilityKey, + label: project.title, + hidden: false + }) + expect( + buildProjectConversations({ ...defaults, history, preferences: restored })[0]?.data[0]?.history + ).toEqual(history[0]) +}) + +it('respects canonical project ownership over a conflicting recorded cwd', () => { + const workspace = conversationWorkspace({ repoId: 'one', path: '/projects/one' }) + const repos = ['one', 'two'].map((id) => ({ id, path: `/projects/${id}`, displayName: id })) + const history = [ + conversationHistory({ + cwd: workspace.path, + projectOwnerKey: 'repo:two', + filePath: '/logs/one.jsonl' + }) + ] + const projects = buildProjectConversations({ + ...defaults, + repos, + workspaces: [workspace], + history + }) + expect(projects.find((project) => project.repo?.id === 'one')?.data).toEqual([]) + expect(projects.find((project) => project.repo?.id === 'two')?.data[0]?.workspace).toBeNull() + expect(projects.find((project) => project.repo?.id === 'two')?.data[0]?.history).toEqual( + history[0] + ) +}) + +it('keeps ambiguous native transcripts distinct when an open tab shares their provider ID', () => { + const workspace = conversationWorkspace() + const history = [ + conversationHistory({ id: 'native', filePath: '/logs/same.jsonl' }), + conversationHistory({ id: 'wsl', filePath: '\\\\wsl$\\Ubuntu\\home\\me\\same.jsonl' }) + ] + const projects = buildProjectConversations({ + ...defaults, + workspaces: [workspace], + history, + tabs: new Map([ + [ + getWorktreeRowIdentity(workspace), + [ + { + type: 'terminal' as const, + id: 'tab', + title: 'Open', + agent: 'claude', + agentStatus: { sessionId: 'provider-one', agentType: 'claude' } + } + ] + ] + ]) + }) + expect(projects.flatMap((project) => project.data).filter((row) => row.history)).toHaveLength(2) + expect( + new Set(projects.flatMap((project) => project.data).map((row) => row.preferenceKey)).size + ).toBeGreaterThanOrEqual(2) +}) + +it('maps canonical host-local keys to registered project sections with mobile visibility parity', () => { + const repo = { + id: 'atlas', + displayName: 'Atlas', + path: '/projects/atlas', + addedAt: 0, + badgeColor: '', + executionHostId: 'local' as const + } + const projection = projectHostSetupProjectionFromRepos([repo]) + const [project] = buildProjectConversations({ + ...defaults, + repos: [repo], + history: [conversationHistory({ projectOwnerKey: 'repo:atlas' })], + projectCatalog: { + repos: [repo], + projectOrderBy: 'manual', + repoOrder: undefined, + projectGroups: [], + grouping: { projects: projection.projects, projectHostSetups: projection.setups } + } + }) + expect(project?.repo?.id).toBe('atlas') + expect(project?.data).toHaveLength(1) + expect(project?.visibilityKey).toBe(JSON.stringify(['local', 'project:repo:atlas'])) +}) diff --git a/mobile/src/host-screen/project-conversations-host-filter.test.ts b/mobile/src/host-screen/project-conversations-host-filter.test.ts new file mode 100644 index 000000000000..566467553b04 --- /dev/null +++ b/mobile/src/host-screen/project-conversations-host-filter.test.ts @@ -0,0 +1,75 @@ +import { expect, it } from 'vitest' +import type { ExecutionHostId } from '../../../src/shared/execution-host/execution-host' +import { buildProjectConversations } from './project-conversations' +import { + conversationAgent, + conversationHistory, + conversationWorkspace +} from './project-conversations.test-fixture' + +const hosts = ['local', 'runtime:one', 'ssh:one'] as const +it.each<{ visibleHostIds: ExecutionHostId[] | null; expected: readonly ExecutionHostId[] }>([ + { visibleHostIds: null, expected: hosts }, + { visibleHostIds: [], expected: [] }, + { visibleHostIds: ['local'], expected: ['local'] }, + { visibleHostIds: ['runtime:one'], expected: ['runtime:one'] } +])( + 'never recreates hidden-host projects from workspaces or unmatched history: $visibleHostIds', + ({ visibleHostIds, expected }) => { + const projects = buildProjectConversations({ + workspaces: hosts.map((hostId) => + conversationWorkspace({ + hostId, + workspaceKind: hostId === 'runtime:one' ? 'folder-workspace' : undefined, + agents: [conversationAgent({ paneKey: `chat:${hostId}` })] + }) + ), + history: hosts.map((executionHostId) => + conversationHistory({ + executionHostId, + id: `history:${executionHostId}`, + cwd: '/unmatched/old-project' + }) + ), + repos: [], + tabs: new Map(), + now: 1000, + untitled: 'New conversation', + visibleHostIds + }) + expect([...new Set(projects.map((project) => project.hostId))].sort()).toEqual( + [...expected].sort() + ) + expect(projects).toHaveLength(expected.length * 2) + } +) + +it('uses phone-owned host context for legacy rows without trusting same-named wire fields', () => { + const workspace = { + ...conversationWorkspace({ + hostId: undefined, + agents: [conversationAgent({ paneKey: 'chat:remote' })] + }), + hostContextHostId: 'local', + hostContextHealthLabel: 'healthy' + } + const context = { + hostContextHostId: 'ssh:one', + hostContextLabel: 'Remote development', + hostContextHealthLabel: 'Disconnected' + } as const + const [project] = buildProjectConversations({ + workspaces: [workspace], + hostContextOf: () => context, + visibleHostIds: ['ssh:one'], + history: [], + repos: [], + tabs: new Map(), + now: 1000, + untitled: 'New conversation' + }) + expect(project?.hostId).toBe('ssh:one') + expect(project?.hostLabel).toBe('Remote development') + expect(project?.data[0]?.workspace).toBe(workspace) + expect(project?.data[0]?.workspaceContext).toBe(context) +}) diff --git a/mobile/src/host-screen/project-conversations.test-fixture.ts b/mobile/src/host-screen/project-conversations.test-fixture.ts new file mode 100644 index 000000000000..3f1e51011cda --- /dev/null +++ b/mobile/src/host-screen/project-conversations.test-fixture.ts @@ -0,0 +1,60 @@ +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/worktree/catalog/runtime-worktree-contracts' +import type { Worktree } from '../worktree/workspace-list/workspace-list-types' +import type { ConversationHistory } from './project-conversations' + +export function conversationAgent( + overrides: Partial = {} +): RuntimeWorktreeAgentRow { + return { + paneKey: 'chat-pane', + parentPaneKey: null, + state: 'done', + agentType: 'codex', + prompt: 'Make the navigation clearer', + taskTitle: 'Clearer navigation', + displayName: null, + lastAssistantMessage: 'Updated the list', + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: 100, + updatedAt: 100, + ...overrides + } +} + +export function conversationWorkspace(overrides: Partial = {}): Worktree { + return { + worktreeId: 'atlas::/projects/atlas', + repoId: 'atlas', + hostId: 'local', + repo: 'Atlas', + path: '/projects/atlas', + branch: 'feat/private-branch', + displayName: 'feat/private-branch', + liveTerminalCount: 1, + hasAttachedPty: true, + unread: false, + isPinned: false, + linkedPR: { number: 42, state: 'open' }, + isMainWorktree: true, + ...overrides + } +} + +export function conversationHistory( + overrides: Partial = {} +): ConversationHistory { + return { + id: 'history-one', + executionHostId: 'local', + sessionId: 'provider-one', + agent: 'claude', + title: 'Improve the onboarding', + cwd: '/projects/atlas', + updatedAt: null, + previewMessages: [], + modifiedAt: '2026-10-24T12:00:00Z', + ...overrides + } +} diff --git a/mobile/src/host-screen/project-conversations.test.ts b/mobile/src/host-screen/project-conversations.test.ts new file mode 100644 index 000000000000..4575c22497cf --- /dev/null +++ b/mobile/src/host-screen/project-conversations.test.ts @@ -0,0 +1,314 @@ +import { describe, expect, it } from 'vitest' +import { conversationPreferenceKey } from '../../../src/shared/conversation-navigation-preferences' +import type { ProjectSectionCatalog } from '../worktree/workspace-list/workspace-list-sections' +import { structuredAgentSessionPaneKey } from '../../../src/shared/agent-session/view/structured-agent-session-projection' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { + buildProjectConversations, + projectConversationTarget, + readConversationHistory +} from './project-conversations' +import type { ConversationTab } from './project-conversations' +import { + conversationAgent, + conversationHistory, + conversationWorkspace +} from './project-conversations.test-fixture' + +const defaults = { + repos: [], + tabs: new Map(), + history: [], + now: 1000, + untitled: 'New conversation' +} + +describe('projects containing conversations', () => { + it('does not duplicate a folder project as an empty catalog placeholder', () => { + const folder = conversationWorkspace({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:notes', + repoId: 'notes', + repo: 'Notes', + displayName: 'Notes', + path: '/documents/notes', + agents: [conversationAgent({ taskTitle: 'Organize the release notes' })] + }) + const projects = buildProjectConversations({ + ...defaults, + workspaces: [folder], + repos: [{ id: 'notes', displayName: 'Notes', path: '/documents/notes', connectionId: null }] + }) + expect(projects.map((project) => project.title)).toEqual(['Notes']) + expect(projects[0]?.data.map((row) => row.title)).toEqual(['Organize the release notes']) + expect(projectConversationTarget(projects[0]!)).toBe(folder) + }) + it.each([ + { type: 'terminal', id: 'child', terminal: 'worker', launchAgent: 'codex', title: 'Worker' }, + { + type: 'terminal', + id: 'child', + parentTabId: 'split', + leafId: 'leaf', + agentStatus: { agentType: 'codex' }, + title: 'Worker' + } + ] satisfies ConversationTab[])('excludes known child terminal tabs: $id $leafId', (tab) => { + const paneKey = tab.leafId ? `${tab.parentTabId}:${tab.leafId}` : tab.terminal + const workspace = conversationWorkspace({ + agents: [conversationAgent({ paneKey: paneKey ?? 'worker', parentPaneKey: 'parent' })] + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [workspace], + tabs: new Map([[getWorktreeRowIdentity(workspace), [tab]]]) + }) + expect(project?.data).toEqual([]) + + const [legacy] = buildProjectConversations({ + ...defaults, + workspaces: [{ ...workspace, agents: undefined }], + tabs: new Map([[getWorktreeRowIdentity(workspace), [tab]]]) + }) + expect(legacy?.data).toHaveLength(1) + expect(legacy?.data[0]?.paneKey).toBe(paneKey) + }) + + it('flattens root agent conversations across workspaces and excludes worker panes', () => { + const one = conversationWorkspace({ + agents: [ + conversationAgent(), + conversationAgent({ paneKey: 'worker', parentPaneKey: 'chat-pane' }) + ] + }) + const two = conversationWorkspace({ + worktreeId: 'sibling', + branch: 'master', + agents: [conversationAgent({ paneKey: 'other', taskTitle: 'Polish the composer' })] + }) + const projects = buildProjectConversations({ ...defaults, workspaces: [one, two] }) + expect(projects).toHaveLength(1) + expect(projects[0]?.title).toBe('Atlas') + expect(projects[0]?.data.map((row) => row.title)).toEqual([ + 'Clearer navigation', + 'Polish the composer' + ]) + expect(projects[0]?.data.map((row) => row.paneKey)).toEqual(['chat-pane', 'other']) + }) + + it('keeps persisted empty folder chats with their recorded workspace and provider after restart', () => { + const folder = conversationWorkspace({ + workspaceKind: 'folder-workspace', + worktreeId: 'folder:notes', + repoId: 'notes', + repo: 'Notes', + path: '/documents/notes', + branch: '', + isMainWorktree: false + }) + const saved = conversationHistory({ + title: 'An empty saved chat', + cwd: null, + structuredSession: { sessionId: 'saved-chat', workspaceId: folder.worktreeId } + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [folder], + history: [saved] + }) + expect(project?.data).toEqual([ + expect.objectContaining({ + title: saved.title, + status: 'saved', + workspace: folder, + agent: 'claude' + }) + ]) + expect(project && projectConversationTarget(project)).toBe(folder) + }) + + it('deduplicates an open structured conversation against retained history', () => { + const workspace = conversationWorkspace() + const sessionId = 'saved-chat' + const tabs = new Map([ + [ + getWorktreeRowIdentity(workspace), + [ + { + type: 'agent-session' as const, + id: 'tab-one', + title: 'Human conversation', + agent: 'codex', + sessionId + } + ] + ] + ]) + const saved = conversationHistory({ + structuredSession: { sessionId, workspaceId: workspace.worktreeId } + }) + const [project] = buildProjectConversations({ + ...defaults, + workspaces: [workspace], + tabs, + history: [saved] + }) + expect(project?.data).toHaveLength(1) + expect(project?.data[0]?.paneKey).toBe(structuredAgentSessionPaneKey('tab-one', sessionId)) + }) + + it('does not cross host boundaries when workspace ids and paths are identical', () => { + const local = conversationWorkspace() + const remote = conversationWorkspace({ hostId: 'runtime:server' }) + const ssh = conversationWorkspace({ hostId: 'ssh:target' }) + const saved = conversationHistory({ executionHostId: 'runtime:server' }) + const projects = buildProjectConversations({ + ...defaults, + workspaces: [local, remote, ssh], + history: [saved] + }) + expect(projects).toHaveLength(3) + expect( + projects.filter((project) => project.data.length).map((project) => project.hostId) + ).toEqual(['runtime:server']) + }) + + it('uses the nearest recorded directory without guessing ownership from a branch name', () => { + const parent = conversationWorkspace({ path: 'C:\\projects', worktreeId: 'parent' }) + const child = conversationWorkspace({ + path: 'C:\\projects\\atlas', + worktreeId: 'child', + repoId: 'child', + repo: 'Atlas child', + branch: 'claude-opus' + }) + const project = buildProjectConversations({ + ...defaults, + workspaces: [parent, child], + history: [conversationHistory({ cwd: 'C:\\projects\\atlas\\src' })] + }).find((project) => project.data.length) + expect(project?.data[0]?.workspace).toBe(child) + expect(project?.data[0]?.agent).toBe('claude') + }) + + it('never promotes branch or worktree names to conversation titles or guesses an agent', () => { + const workspace = conversationWorkspace({ + branch: 'claude-opus', + displayName: 'claude-opus', + agents: [conversationAgent({ taskTitle: 'claude-opus', prompt: '', agentType: null })] + }) + const [project] = buildProjectConversations({ ...defaults, workspaces: [workspace] }) + expect(project?.data[0]).toMatchObject({ title: 'New conversation', agent: null }) + }) + + it('searches conversation titles and agents without searching technical branch metadata', () => { + const workspace = conversationWorkspace({ agents: [conversationAgent()] }) + expect( + buildProjectConversations({ ...defaults, workspaces: [workspace], query: 'private-branch' }) + ).toEqual([]) + expect( + buildProjectConversations({ ...defaults, workspaces: [workspace], query: 'clearer' })[0]?.data + ).toHaveLength(1) + }) + + it('uses canonical recent and manual ordering from the served project catalog', () => { + const repos = ['Beta', 'Alpha', 'Pinned'].map((displayName) => ({ + id: displayName, + displayName, + path: `/projects/${displayName}` + })) + const projectCatalog: ProjectSectionCatalog = { + repos, + grouping: { + projects: repos.map((repo) => ({ id: `github:${repo.id}`, displayName: repo.displayName })), + projectHostSetups: repos.map((repo) => ({ + id: repo.id, + projectId: `github:${repo.id}`, + hostId: 'local', + repoId: repo.id, + path: repo.path, + displayName: repo.displayName, + setupMethod: 'imported-existing-folder' + })) + }, + projectGroups: [], + repoOrder: new Map(repos.map((repo, index) => [repo.id, index])), + projectOrderBy: 'recent' + } + const workspaces = repos.map((repo) => + conversationWorkspace({ + repoId: repo.id, + repo: repo.displayName, + worktreeId: repo.id, + path: repo.path, + lastActivityAt: repo.id === 'Alpha' ? 9999 : 0 + }) + ) + const titles = () => + buildProjectConversations({ ...defaults, repos, workspaces, projectCatalog }).map( + (project) => project.title + ) + + expect(titles()).toEqual(['Alpha', 'Beta', 'Pinned']) + projectCatalog.projectOrderBy = 'manual' + expect(titles()).toEqual(['Beta', 'Alpha', 'Pinned']) + }) + + it('shares chat pins and archive identity while hiding only confirmed empty history', () => { + const saved = conversationHistory({ + title: 'Codex Chat', + agent: 'codex', + firstUserPrompt: 'Repair the history scroll', + structuredSession: { + sessionId: 'native-chat', + workspaceId: conversationWorkspace().worktreeId + } + }) + const newer = conversationHistory({ + id: 'newer', + sessionId: 'provider-newer', + modifiedAt: '2026-10-25T12:00:00Z' + }) + const empty = conversationHistory({ + id: 'empty', + sessionId: 'provider-empty', + conversationContent: 'empty' + }) + const unknown = conversationHistory({ + id: 'unknown', + sessionId: 'provider-unknown', + conversationContent: 'unknown' + }) + const key = conversationPreferenceKey({ ...saved, executionHostId: 'local' }) + const preferences = { revision: 1, entries: { [key]: { pinned: true, archived: false } } } + const args = { + ...defaults, + workspaces: [conversationWorkspace()], + history: [newer, saved, empty, unknown], + preferences + } + const active = buildProjectConversations(args)[0]?.data + expect(active?.map((row) => row.history?.id)).toEqual([saved.id, newer.id, unknown.id]) + expect(active?.[0]?.title).toBe('Repair the history scroll') + + preferences.entries[key] = { pinned: true, archived: true } + expect(buildProjectConversations(args)[0]?.data.map((row) => row.history?.id)).toEqual([ + newer.id, + unknown.id + ]) + expect( + buildProjectConversations({ ...args, archived: true })[0]?.data.map((row) => row.history?.id) + ).toEqual([saved.id]) + preferences.entries[key] = { pinned: true, archived: false } + expect(buildProjectConversations({ ...args, archived: true })).toEqual([]) + expect(buildProjectConversations(args)[0]?.data[0]?.preferenceKey).toBe(key) + }) + + it('leaves old-host durable coverage unconfirmed rather than claiming no saved conversations', () => { + expect(readConversationHistory({ sessions: [] }).includesStructuredSessions).toBeUndefined() + expect( + readConversationHistory({ sessions: [], includesStructuredSessions: true }) + .includesStructuredSessions + ).toBe(true) + }) +}) diff --git a/mobile/src/host-screen/project-conversations.ts b/mobile/src/host-screen/project-conversations.ts new file mode 100644 index 000000000000..9ed597ee4ca5 --- /dev/null +++ b/mobile/src/host-screen/project-conversations.ts @@ -0,0 +1,299 @@ +import type { WorktreeHostContextOf } from '../worktree/row-presentation/worktree-host-context-labels' +import { toAiVaultProjectKey } from '../../../src/shared/ai-vault/scanning/ai-vault-project-key' +import { createConversationWorkspaceMatcher } from '../../../src/shared/conversation-workspace-matcher' +import { + folderGroupKey, + folderLabel +} from '../../../src/shared/ai-vault/session-display/ai-vault-session-filters' +import { + conversationPreferenceKey, + conversationProjectVisibilityKey, + type ConversationPreferences +} from '../../../src/shared/conversation-navigation-preferences' +import { projectConversationTitle } from '../../../src/shared/project-conversation-list' +import { + buildProjectGroupingIndex, + getProjectGroupingForRepo +} from '../../../src/shared/sidebar-list/sections/project-section-grouping' +import type { ProjectSectionCatalog } from '../worktree/workspace-list/workspace-list-sections' +import { + getRepoExecutionHostId, + type ExecutionHostId +} from '../../../src/shared/execution-host/execution-host' +import { structuredAgentSessionPaneKey } from '../../../src/shared/agent-session/view/structured-agent-session-projection' +import { agentDotState, agentRowTimeAt } from '../worktree/agent-lineage/agent-row-display' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { createConversationHistoryIndex } from './conversation-history-index' +import { orderProjectConversations } from './project-conversation-order' +import { conversationTitle, conversationUserPreview } from './conversation-row-content' +import type { SectionRepo, Worktree } from '../worktree/workspace-list/workspace-list-types' + +export { readConversationHistory, readConversationTabs } from './conversation-records' +export type { ConversationHistory, ConversationTab } from './conversation-records' +import type { ConversationHistory, ConversationTab } from './conversation-records' +import type { ConversationProject } from './conversation-project' +import { folderOnlyConversationRepoKeys } from './conversation-project' +export { projectConversationTarget } from './conversation-project' +export type { ConversationRow, ConversationProject } from './conversation-project' + +export function buildProjectConversations(args: { + workspaces: readonly Worktree[] + hostContextOf?: WorktreeHostContextOf + repos: readonly SectionRepo[] + tabs: ReadonlyMap + history: readonly ConversationHistory[] + now: number + untitled: string + query?: string + projectCatalog?: ProjectSectionCatalog + preferences?: ConversationPreferences + archived?: boolean + visibleHostIds?: readonly ExecutionHostId[] | null +}): ConversationProject[] { + const projects = new Map() + const ownerKeys = new Map() + const hostOf = (workspace: Worktree) => + workspace.hostId ?? args.hostContextOf?.(workspace)?.hostContextHostId ?? 'local' + const visibleHosts = args.visibleHostIds ? new Set(args.visibleHostIds) : null + const workspaces = visibleHosts + ? args.workspaces.filter((workspace) => visibleHosts.has(hostOf(workspace))) + : args.workspaces + const history = visibleHosts + ? args.history.filter( + (session) => session.executionHostId && visibleHosts.has(session.executionHostId) + ) + : args.history + const savedForTab = createConversationHistoryIndex(history) + const catalog = args.projectCatalog + const allRepos = catalog?.repos ?? args.repos + const repos = visibleHosts + ? allRepos.filter((repo) => visibleHosts.has(getRepoExecutionHostId(repo))) + : allRepos + const repoMap = new Map(repos.map((repo) => [repo.id, repo])) + const projectIndex = buildProjectGroupingIndex(catalog?.grouping ?? undefined) + const groupingFor = (hostId: ExecutionHostId, repoId: string) => { + const repo = repos.find((repo) => repo.id === repoId && getRepoExecutionHostId(repo) === hostId) + return getProjectGroupingForRepo( + repoId, + repo ? new Map(repoMap).set(repoId, repo) : repoMap, + projectIndex + ) + } + const projectKey = (hostId: ExecutionHostId, repoId: string) => + `${hostId}\0${groupingFor(hostId, repoId).key}` + const workspaceProjectKey = (workspace: Worktree) => + workspace.workspaceKind === 'folder-workspace' + ? `${hostOf(workspace)}\0${workspace.worktreeId}` + : projectKey(hostOf(workspace), workspace.repoId) + const folderOnlyRepos = folderOnlyConversationRepoKeys(workspaces, hostOf) + for (const repo of repos) { + const hostId = getRepoExecutionHostId(repo) + if (folderOnlyRepos.has(`${hostId}\0${repo.id}`)) { + continue + } + const key = projectKey(hostId, repo.id) + const ownerKey = `${hostId}\0${toAiVaultProjectKey(groupingFor(hostId, repo.id).projectId, repo.id)}` + const previous = ownerKeys.get(ownerKey) + ownerKeys.set(ownerKey, previous === undefined || previous === key ? key : null) + if (projects.has(key)) { + continue + } + projects.set(key, { + key, + visibilityKey: conversationProjectVisibilityKey(hostId, groupingFor(hostId, repo.id).key), + title: groupingFor(hostId, repo.id).label, + hostId, + repo, + workspaces: [], + data: [] + }) + } + for (const workspace of workspaces) { + const hostId = hostOf(workspace) + const key = workspaceProjectKey(workspace) + let project = projects.get(key) + if (!project) { + project = { + key, + visibilityKey: conversationProjectVisibilityKey(hostId, workspace.worktreeId), + title: + workspace.workspaceKind === 'folder-workspace' ? workspace.displayName : workspace.repo, + hostId, + workspaces: [], + data: [] + } + projects.set(key, project) + } + project.hostLabel ??= args.hostContextOf?.(workspace)?.hostContextLabel + project.hostHealthLabel ??= args.hostContextOf?.(workspace)?.hostContextHealthLabel + project.workspaces.push(workspace) + const agents = (workspace.agents ?? []).filter((agent) => !agent.parentPaneKey) + const used = new Set() + for (const tab of args.tabs.get(getWorktreeRowIdentity(workspace)) ?? []) { + const paneKey = + tab.type === 'agent-session' && tab.sessionId + ? structuredAgentSessionPaneKey(tab.id, tab.sessionId) + : tab.leafId + ? `${tab.parentTabId ?? tab.id}:${tab.leafId}` + : (tab.terminal ?? tab.id) + const agent = workspace.agents?.find((agent) => agent.paneKey === paneKey) + if (agent?.parentPaneKey) { + continue + } + const agentType = + tab.agent ?? tab.launchAgent ?? tab.agentStatus?.agentType ?? agent?.agentType + if (tab.type === 'terminal' && !agentType && !agent) { + continue + } + used.add(paneKey) + const saved = savedForTab(tab, hostId, workspace.worktreeId, agentType) + if (saved?.conversationContent === 'empty') { + continue + } + project.data.push({ + key: `${key}\0${workspace.worktreeId}\0${tab.sessionId ?? paneKey}`, + title: conversationTitle( + [ + agent?.conversationName, + tab.type === 'agent-session' ? tab.title : undefined, + saved ? projectConversationTitle(saved) : tab.title, + agent?.taskTitle, + agent?.prompt + ], + workspace, + args.untitled + ), + preview: conversationUserPreview(agent?.prompt, saved), + agent: agentType ?? null, + status: agent ? agentDotState(agent, args.now) : 'idle', + at: agent ? agentRowTimeAt(agent) : 0, + workspace, + workspaceContext: args.hostContextOf?.(workspace), + paneKey, + history: saved, + preferenceKey: saved + ? conversationPreferenceKey({ ...saved, executionHostId: hostId }) + : tab.sessionId + ? conversationPreferenceKey({ + executionHostId: hostId, + agent: agentType ?? '', + sessionId: tab.sessionId, + structuredSession: { sessionId: tab.sessionId, workspaceId: workspace.worktreeId } + }) + : undefined + }) + } + for (const agent of agents) { + if (used.has(agent.paneKey)) { + continue + } + project.data.push({ + key: `${key}\0${workspace.worktreeId}\0${agent.paneKey}`, + title: conversationTitle( + [agent.conversationName, agent.taskTitle, agent.prompt], + workspace, + args.untitled + ), + preview: conversationUserPreview(agent.prompt), + agent: agent.agentType, + status: agentDotState(agent, args.now), + at: agentRowTimeAt(agent), + workspace, + workspaceContext: args.hostContextOf?.(workspace), + paneKey: agent.paneKey + }) + } + } + const matchWorkspace = createConversationWorkspaceMatcher( + workspaces.map((workspace) => ({ + ...workspace, + id: workspace.worktreeId, + hostId: hostOf(workspace) + })) + ) + for (const session of history) { + if (!session.executionHostId || session.subagent || session.conversationContent === 'empty') { + continue + } + const canonical = + typeof session.projectOwnerKey === 'string' + ? projects.get( + ownerKeys.get(`${session.executionHostId}\0${session.projectOwnerKey}`) ?? + `${session.executionHostId}\0${session.projectOwnerKey}` + ) + : undefined + const matched = matchWorkspace({ ...session, executionHostId: session.executionHostId }) + let workspace = matched + ? (workspaces.find( + (item) => + item.worktreeId === matched.worktreeId && hostOf(item) === session.executionHostId + ) ?? null) + : null + if ( + session.projectOwnerKey !== undefined && + workspace && + workspace.workspaceKind !== 'folder-workspace' && + toAiVaultProjectKey( + groupingFor(session.executionHostId, workspace.repoId).projectId, + workspace.repoId + ) !== session.projectOwnerKey + ) { + workspace = null + } + const projectKey = + canonical?.key ?? + (workspace + ? workspaceProjectKey(workspace) + : `${session.executionHostId}\0${session.projectOwnerKey ?? folderGroupKey(session.cwd)}`) + let project = projects.get(projectKey) + if (!project) { + project = { + key: projectKey, + visibilityKey: conversationProjectVisibilityKey( + session.executionHostId, + session.projectOwnerKey ?? folderGroupKey(session.cwd) + ), + title: folderLabel(session.cwd) || args.untitled, + hostId: session.executionHostId, + workspaces: [], + data: [] + } + projects.set(projectKey, project) + } + const sessionId = session.structuredSession?.sessionId + const hostId = session.executionHostId + const workspaceId = workspace?.worktreeId + const tab = + workspace && workspaceId + ? (args.tabs.get(getWorktreeRowIdentity(workspace)) ?? []).find( + (tab) => savedForTab(tab, hostId, workspaceId, session.agent) === session + ) + : undefined + if (tab) { + continue + } + const key = `${project.key}\0history\0${conversationPreferenceKey({ ...session, executionHostId: session.executionHostId })}` + if (project.data.some((row) => row.key === key)) { + continue + } + project.data.push({ + key, + title: workspace + ? conversationTitle([projectConversationTitle(session)], workspace, args.untitled) + : projectConversationTitle(session) || args.untitled, + preview: conversationUserPreview(undefined, session), + agent: session.agent, + status: sessionId ? 'saved' : 'transcript', + at: Date.parse(session.updatedAt ?? session.modifiedAt) || 0, + workspace, + workspaceContext: workspace ? args.hostContextOf?.(workspace) : undefined, + executionHostId: session.executionHostId, + history: session, + preferenceKey: conversationPreferenceKey({ + ...session, + executionHostId: session.executionHostId + }) + }) + } + return orderProjectConversations(projects.values(), args) +} diff --git a/mobile/src/host-screen/use-conversation-actions.test.tsx b/mobile/src/host-screen/use-conversation-actions.test.tsx new file mode 100644 index 000000000000..3181d6e72776 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-actions.test.tsx @@ -0,0 +1,224 @@ +import { createElement } from 'react' +import { createWithQueryClient } from '../test-support/query-client-test-renderer' +import { act, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_LAUNCH_REPLAY_REQUIRED_RUNTIME_CAPABILITY, + AGENT_LAUNCH_RUNTIME_CAPABILITY +} from '../../../src/shared/agent-launch/contracts/agent-launch-runtime-capability' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../src/shared/remote-runtime/relay/mobile-desktop-relay-contract' +import { PREFLIGHT_OTHER_RUNTIME_REFUSAL_RUNTIME_CAPABILITY } from '../../../src/shared/remote-runtime/protocol/preflight-runtime-capabilities' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { createStableLogicalRpcClient } from '../transport/connection/stable-logical-rpc-client' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { buildProjectConversations } from './project-conversations' +import { conversationHistory, conversationWorkspace } from './project-conversations.test-fixture' +import { useConversationActions } from './use-conversation-actions' +import { useHostScreenState } from './use-host-screen-state' +import { useHostWorktreeActions } from './workspace-actions/use-host-worktree-actions' +import { + useProjectConversations, + type ProjectConversationsSource +} from './use-project-conversations' + +vi.mock('expo-router', () => ({})) +vi.mock('react-native', () => ({ Platform: { OS: 'ios' } })) +vi.mock('../storage/preferences', () => ({ savePinnedIds: async () => {} })) +vi.mock('../host-catalog/host-removal-lifecycle', () => ({ + removeHostAndCloseClient: async () => {} +})) +vi.mock('../host-route-exit', () => ({ leaveHostRoute: () => {} })) + +const trees: ReactTestRenderer[] = [] +afterEach(() => { + act(() => trees.splice(0).forEach((tree) => tree.unmount())) +}) + +const capabilities = [ + 'aiVault.v1', + MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY, + AGENT_LAUNCH_RUNTIME_CAPABILITY, + AGENT_LAUNCH_REPLAY_REQUIRED_RUNTIME_CAPABILITY, + PREFLIGHT_OTHER_RUNTIME_REFUSAL_RUNTIME_CAPABILITY +] + +function session() { + const physical = new FakeSession('connected') + physical.sendRequest.mockImplementation(async (method) => ({ + id: 'reply', + ok: true, + result: + method === 'status.get' + ? { capabilities } + : method === 'aiVault.listSessions' + ? { sessions: [], issues: [], includesStructuredSessions: true } + : method === 'session.tabs.list' + ? { tabs: [] } + : method === 'settings.get' + ? { settings: {} } + : method === 'preflight.detectAgents' + ? ['codex'] + : {} + })) + return physical +} + +async function mount(client: ProjectConversationsSource['client']) { + const workspace = conversationWorkspace({ + worktreeId: 'folder:notes', + workspaceKind: 'folder-workspace' + }) + const input: ProjectConversationsSource = { + client, + hostId: 'host', + connState: 'connected', + displayWorktrees: [workspace], + hostCapabilities: capabilities, + state: { serverWorkspaces: { hosts: [], worktrees: [] }, repoHostIdByRepoId: new Map() }, + catalog: { onRefresh: async () => {} } + } + const push = vi.fn() + const replace = vi.fn() + const held: { current: ReturnType | null } = { current: null } + function Probe() { + const actions = useHostWorktreeActions({ + ...input, + embedded: true, + fetchWorktrees: async () => {}, + forgetHostClient: () => {}, + pathname: '/h/host/agent-history/folder%3Anotes', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these actions only call push and replace; both are provided and recorded. + router: { push, replace } as unknown as Parameters< + typeof useHostWorktreeActions + >[0]['router'], + state: useHostScreenState('host') + }) + const data = useProjectConversations(input) + held.current = useConversationActions({ ...input, actions }, data) + return null + } + await act(async () => { + trees.push(createWithQueryClient(createElement(Probe))) + }) + const [project] = buildProjectConversations({ + workspaces: [workspace], + repos: [], + tabs: new Map(), + history: [conversationHistory({ cwd: workspace.path })], + now: 1000, + untitled: 'New conversation' + }) + if (!project || !project.data[0]) { + throw new Error('missing fixture conversation') + } + return { + project, + row: project.data[0], + push, + replace, + read() { + if (!held.current) { + throw new Error('missing hook') + } + return held.current + } + } +} + +describe('conversation action ownership and selection', () => { + it.each(['local', 'runtime:server-a', 'runtime:server-b'] as const)( + 'switches transcripts on the same tablet workspace route for %s', + async (hostId) => { + const probe = await mount(session()) + if (!probe.row.workspace) { + throw new Error('missing fixture workspace') + } + const workspace = probe.row.workspace + for (const id of ['first', 'second']) { + await act(async () => { + probe.read().open({ + ...probe.row, + title: id, + workspace: { ...workspace, hostId }, + history: conversationHistory({ id, executionHostId: hostId }) + }) + }) + const executionHost = + hostId === 'local' ? '' : `&executionHost=${encodeURIComponent(hostId)}` + expect(probe.replace).toHaveBeenLastCalledWith( + `/h/host/agent-history/folder%3Anotes?name=${id}&conversationId=${id}${executionHost}` + ) + } + expect(probe.replace).toHaveBeenCalledTimes(2) + expect(probe.push).not.toHaveBeenCalled() + } + ) + + it('opens an orphan transcript on its owning host without revealing or starting a workspace', async () => { + const physical = session() + const probe = await mount(physical) + physical.sendRequest.mockClear() + await act(async () => { + probe.read().open({ + ...probe.row, + workspace: null, + executionHostId: 'runtime:server-a', + history: conversationHistory({ id: 'orphan', executionHostId: 'runtime:server-a' }) + }) + }) + expect(probe.replace).toHaveBeenCalledWith( + `/h/host/agent-history/history?name=${encodeURIComponent(probe.row.title)}&conversationId=orphan&executionHost=runtime%3Aserver-a` + ) + expect(physical.sendRequest).not.toHaveBeenCalled() + }) + + it('closes the old authority agent choice and cannot launch its selected option after cutover', async () => { + const client = createStableLogicalRpcClient(session(), 'lan') + const probe = await mount(client) + await act(async () => { + probe.read().prepare(probe.project) + }) + const choice = probe.read().newChat + expect(choice?.agents).toEqual([{ agent: 'codex', label: 'Codex' }]) + const replacement = session() + await act(async () => { + await client.migrateTo(replacement, 'relay') + }) + expect(probe.read().newChat).toBeNull() + await act(async () => { + probe.read().launch({ agent: 'codex', label: 'Codex' }) + }) + expect( + replacement.sendRequest.mock.calls.some(([method]) => method === 'agent.launchReplay') + ).toBe(false) + await act(async () => { + probe.read().prepare(probe.project) + }) + expect(probe.read().newChat?.generation).toBe(client.getGeneration()) + }) + + it('rejects an agent inventory that arrives after its authority was replaced', async () => { + const original = session() + let settle: (reply: RpcResponse) => void = () => {} + const client = createStableLogicalRpcClient(original, 'lan') + const probe = await mount(client) + original.sendRequest.mockImplementationOnce( + () => + new Promise((resolve) => { + settle = resolve + }) + ) + await act(async () => { + probe.read().prepare(probe.project) + }) + expect(probe.read().busy).toBe(probe.project.key) + await act(async () => { + await client.migrateTo(session(), 'relay') + }) + expect(probe.read().busy).toBeNull() + await act(async () => { + settle({ id: 'old', ok: true, result: ['codex'] }) + }) + expect(probe.read().newChat).toBeNull() + }) +}) diff --git a/mobile/src/host-screen/use-conversation-actions.ts b/mobile/src/host-screen/use-conversation-actions.ts new file mode 100644 index 000000000000..39d1c4cb6d5a --- /dev/null +++ b/mobile/src/host-screen/use-conversation-actions.ts @@ -0,0 +1,235 @@ +import { useEffect, useRef, useState } from 'react' +import { rpcClientForExecutionHost } from '../worktree/execution-hosts/execution-host-scoped-rpc-client' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../src/shared/agent-session/view/structured-agent-session-projection' +import { + loadMobileAgentLaunchContext, + newTabAgentOptionsFrom, + hostRefusesOtherRuntimeWorkspace +} from '../session/agent-launch/mobile-new-tab-agent-loader' +import { + launchAgentInExistingWorkspace, + supportsMobileExistingAgentLaunch +} from '../session/agent-launch/mobile-existing-agent-launch' +import type { MobileNewTabAgentOption } from '../session/agent-launch/mobile-new-tab-agent-options' +import type { Worktree } from '../worktree/workspace-list/workspace-list-types' +import type { HostScreenController } from './use-host-screen-controller' +import type { useProjectConversations } from './use-project-conversations' +import { + projectConversationTarget, + type ConversationProject, + type ConversationRow +} from './project-conversations' +import { conversationOpenPane } from './conversation-open' +import { conversationCopy } from './conversation-copy' + +export function useConversationActions( + controller: Pick< + HostScreenController, + 'client' | 'hostCapabilities' | 'hostId' | 'connState' | 'actions' + >, + data: ReturnType +) { + const { client, hostCapabilities, hostId, connState, actions } = controller + const { generation } = data + const copy = conversationCopy() + const [chatChoice, setChatChoice] = useState<{ + client: typeof client + hostId: typeof hostId + generation: number + project: ConversationProject + workspace: Worktree + agents: MobileNewTabAgentOption[] + } | null>(null) + const [busyOwner, setBusyOwner] = useState<{ + client: typeof client + hostId: typeof hostId + generation: number + key: string + } | null>(null) + const [errorOwner, setErrorOwner] = useState<{ + client: typeof client + hostId: typeof hostId + generation: number + message: string + } | null>(null) + const newChat = + chatChoice?.client === client && + chatChoice.hostId === hostId && + chatChoice.generation === generation + ? chatChoice + : null + const busy = + busyOwner?.client === client && + busyOwner.hostId === hostId && + busyOwner.generation === generation + ? busyOwner.key + : null + const error = + errorOwner?.client === client && + errorOwner.hostId === hostId && + errorOwner.generation === generation + ? errorOwner.message + : '' + const setError = (message: string) => setErrorOwner({ client, hostId, generation, message }) + const setNewChat = (_value: null) => setChatChoice(null) + const locked = useRef(false) + const mounted = useRef(true) + useEffect(() => { + mounted.current = true + return () => { + mounted.current = false + } + }, []) + const owner = useRef({ client, hostId, connState }) + owner.current = { client, hostId, connState } + async function perform(key: string, run: (isCurrent: () => boolean) => Promise) { + if ( + locked.current || + connState !== 'connected' || + generation !== (client?.getGeneration?.() ?? 0) + ) { + return + } + const captured = owner.current + const current = () => + mounted.current && + owner.current.connState === 'connected' && + owner.current.client === captured.client && + owner.current.hostId === captured.hostId && + generation === (client?.getGeneration?.() ?? 0) + locked.current = true + setBusyOwner({ client, hostId, generation, key }) + setError('') + try { + await run(current) + } catch (error) { + if (current()) { + setError( + error instanceof Error && error.message !== 'conversation_host_update_required' + ? error.message + : copy.update + ) + } + } finally { + locked.current = false + if (current()) { + setBusyOwner(null) + } + } + } + + function rowClient(workspace: Worktree) { + const scoped = client && rpcClientForExecutionHost(client, hostCapabilities, workspace.hostId) + if (!scoped) { + throw new Error(copy.unavailable) + } + return scoped + } + + function open(row: ConversationRow) { + void perform(row.key, async (current) => { + if (!row.workspace) { + if (row.history) { + const executionHost = row.executionHostId?.startsWith('runtime:') + ? `&executionHost=${encodeURIComponent(row.executionHostId)}` + : '' + actions.navigateFromHostList( + `/h/${encodeURIComponent(hostId)}/agent-history/${encodeURIComponent(row.history.structuredSession?.workspaceId ?? 'history')}?name=${encodeURIComponent(row.title)}&conversationId=${encodeURIComponent(row.history.id)}${executionHost}`, + true + ) + } + return + } + const paneKey = await conversationOpenPane({ + row, + client: rowClient(row.workspace), + capabilities: data.capabilitiesFor(row.workspace.hostId ?? 'local') + }) + if (!current()) { + return + } + if (paneKey) { + actions.openWorktreeSession({ ...row.workspace, displayName: row.title }, paneKey) + } else if (row.history) { + const executionHost = row.workspace.hostId?.startsWith('runtime:') + ? `&executionHost=${encodeURIComponent(row.workspace.hostId)}` + : '' + actions.navigateFromHostList( + `/h/${encodeURIComponent(hostId)}/agent-history/${encodeURIComponent(row.workspace.worktreeId)}?name=${encodeURIComponent(row.title)}&conversationId=${encodeURIComponent(row.history.id)}${executionHost}`, + true + ) + } + }) + } + + function prepare(project: ConversationProject) { + const workspace = projectConversationTarget(project) + if (!workspace) { + setError(copy.workspaceNeeded) + return + } + void perform(project.key, async (current) => { + const capabilities = data.capabilitiesFor(project.hostId) + if (!supportsMobileExistingAgentLaunch(capabilities)) { + throw new Error(copy.update) + } + const inventory = await loadMobileAgentLaunchContext({ + client: rowClient(workspace), + worktreeId: workspace.worktreeId, + hostRefusesOtherRuntime: hostRefusesOtherRuntimeWorkspace(capabilities) + }) + if (!current()) { + return + } + const options = newTabAgentOptionsFrom(inventory.settings, inventory.detectedAgents) + if (options.length === 0) { + setError(copy.noAgents) + return + } + setChatChoice({ client, hostId, generation, project, workspace, agents: options }) + }) + } + + function launch(option: MobileNewTabAgentOption) { + if (!newChat) { + return + } + const target = newChat + setNewChat(null) + void perform(target.project.key, async (current) => { + const launched = await launchAgentInExistingWorkspace({ + client: rowClient(target.workspace), + hostCapabilities: data.capabilitiesFor(target.project.hostId), + worktreeId: target.workspace.worktreeId, + agent: option.agent + }) + if (!current()) { + return + } + if (launched.kind === 'unsupported') { + throw new Error(copy.update) + } + if (launched.kind !== 'launched') { + throw new Error(launched.message) + } + if (launched.result.worktreeId !== target.workspace.worktreeId) { + throw new Error(copy.unavailable) + } + const outcome = launched.result.outcome + const paneKey = + outcome.kind === 'structured' + ? structuredAgentSessionPaneKey( + structuredAgentSessionTabId(outcome.sessionId), + outcome.sessionId + ) + : outcome.handle + actions.openWorktreeSession({ ...target.workspace, displayName: copy.untitled }, paneKey) + data.onRefresh() + }) + } + + return { busy, error, newChat, setNewChat, prepare, launch, open } +} diff --git a/mobile/src/host-screen/use-conversation-details.test.tsx b/mobile/src/host-screen/use-conversation-details.test.tsx new file mode 100644 index 000000000000..1bc0cc11fdf7 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-details.test.tsx @@ -0,0 +1,49 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { expect, it } from 'vitest' +import { conversationWorkspace } from './project-conversations.test-fixture' +import { useConversationDetails } from './use-conversation-details' + +it('drops details and ignores an old drawer selection after client, host or generation cutover', () => { + const firstClient = {} + let owner = { client: firstClient, hostId: 'first', generation: 1 } + const observed: { current: ReturnType | null } = { current: null } + const row = { + key: 'chat', + title: 'First host chat', + agent: 'codex', + status: 'saved' as const, + at: 1, + workspace: conversationWorkspace() + } + function Probe() { + observed.current = useConversationDetails(owner) + return null + } + let tree: ReactTestRenderer | undefined + try { + act(() => { + tree = create(createElement(Probe)) + }) + for (const next of [ + { client: {}, hostId: 'first', generation: 1 }, + { client: firstClient, hostId: 'second', generation: 1 }, + { client: firstClient, hostId: 'first', generation: 2 } + ]) { + owner = { client: firstClient, hostId: 'first', generation: 1 } + act(() => tree?.update(createElement(Probe))) + const select = observed.current?.setDetails + act(() => select?.(row)) + expect(observed.current?.details).toBe(row) + owner = next + act(() => tree?.update(createElement(Probe))) + expect(observed.current?.details).toBeNull() + const newRow = { ...row, key: 'new-owner-chat' } + act(() => observed.current?.setDetails(newRow)) + act(() => select?.(row)) + expect(observed.current?.details).toBe(newRow) + } + } finally { + act(() => tree?.unmount()) + } +}) diff --git a/mobile/src/host-screen/use-conversation-details.ts b/mobile/src/host-screen/use-conversation-details.ts new file mode 100644 index 000000000000..8786ee843877 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-details.ts @@ -0,0 +1,26 @@ +import { useRef, useState } from 'react' +import type { ConversationRow } from './project-conversations' + +type DetailsOwner = { client: object | null; hostId: string | undefined; generation: number } + +function sameDetailsOwner(left: DetailsOwner, right: DetailsOwner): boolean { + return ( + left.client === right.client && + left.hostId === right.hostId && + left.generation === right.generation + ) +} + +export function useConversationDetails(owner: DetailsOwner) { + const current = useRef(owner) + current.current = owner + const [selection, setSelection] = useState<(DetailsOwner & { row: ConversationRow }) | null>(null) + return { + details: selection && sameDetailsOwner(selection, owner) ? selection.row : null, + setDetails: (row: ConversationRow | null) => { + if (sameDetailsOwner(current.current, owner)) { + setSelection(row ? { ...owner, row } : null) + } + } + } +} diff --git a/mobile/src/host-screen/use-conversation-preferences.test.tsx b/mobile/src/host-screen/use-conversation-preferences.test.tsx new file mode 100644 index 000000000000..e6b91809c7b3 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-preferences.test.tsx @@ -0,0 +1,158 @@ +import { createElement, useState } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { describe, expect, it, vi } from 'vitest' +import { + CONVERSATION_NAVIGATION_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY, + SetConversationPreferenceParams, + updateConversationPreference +} from '../../../src/shared/conversation-navigation-preferences' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { + INITIAL_MOBILE_VIEW, + type MobileViewState +} from '../worktree/workspace-list/workspace-view-settings' +import { useConversationPreferences } from './use-conversation-preferences' + +function endpoint() { + let preferences = { revision: 0, entries: {} } + let generation = 0 + const sendRequest = vi.fn(async (_method, params) => { + preferences = updateConversationPreference( + preferences, + SetConversationPreferenceParams.parse(params) + ) + return { id: 'write', ok: true, result: { preferences } } + }) + return { + client: { ...new FakeSession('connected'), getGeneration: () => generation, sendRequest }, + sendRequest, + advanceGeneration: () => { + generation += 1 + } + } +} + +describe('host-owned mobile conversation preferences', () => { + it('applies atomic chat changes and rejects a prior host completion after cutover', async () => { + const first = endpoint() + const second = endpoint() + let client: RpcClient = first.client + let hostId = 'first' + let hostCapabilities = [CONVERSATION_NAVIGATION_CAPABILITY] + const observed: { + current: ReturnType | null + view: MobileViewState + } = { current: null, view: INITIAL_MOBILE_VIEW } + const viewRef = { current: INITIAL_MOBILE_VIEW } + function Probe() { + const [view, setView] = useState(INITIAL_MOBILE_VIEW) + viewRef.current = view + observed.view = view + observed.current = useConversationPreferences({ + client, + hostId, + connState: 'connected', + hostCapabilities, + state: { view, viewRef, setView } + }) + return null + } + let tree: ReactTestRenderer | undefined + try { + await act(async () => { + tree = create(createElement(Probe)) + }) + await act(async () => { + expect(await observed.current?.setPreference('chat', { pinned: true })).toBe(true) + }) + expect(observed.view.conversationPreferences).toEqual({ + revision: 1, + entries: { chat: { pinned: true } } + }) + + await act(async () => { + expect(await observed.current?.setProjectHidden('project', 'Notes', true)).toBe(false) + }) + expect(first.sendRequest).toHaveBeenCalledTimes(1) + hostCapabilities = [ + CONVERSATION_NAVIGATION_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY + ] + await act(async () => tree?.update(createElement(Probe))) + await act(async () => { + expect(await observed.current?.setProjectHidden('project', 'Notes', true)).toBe(true) + }) + expect(observed.view.conversationPreferences?.hiddenProjects).toEqual({ project: 'Notes' }) + expect(observed.view.conversationPreferences?.entries).toEqual({ chat: { pinned: true } }) + await act(async () => { + expect(await observed.current?.setProjectHidden('project', 'Notes', false)).toBe(true) + }) + expect(observed.view.conversationPreferences?.hiddenProjects).toEqual({}) + + let resolveOld: (reply: RpcResponse) => void = () => {} + first.sendRequest.mockImplementation( + () => + new Promise((resolve) => { + resolveOld = resolve + }) + ) + let pending: Promise | undefined + act(() => { + pending = observed.current?.setPreference('chat', { archived: true }) + }) + expect(observed.current?.writing).toBe(true) + client = second.client + hostId = 'second' + await act(async () => tree?.update(createElement(Probe))) + expect(observed.current?.writing).toBe(false) + await act(async () => { + expect(await observed.current?.setPreference('second-chat', { archived: true })).toBe(true) + }) + expect(observed.view.conversationPreferences?.entries).toEqual({ + 'second-chat': { archived: true } + }) + + await act(async () => { + resolveOld({ + id: 'old-write', + ok: true, + result: { preferences: { revision: 999, entries: { chat: { archived: true } } } } + }) + expect(await pending).toBe(false) + }) + expect(observed.view.conversationPreferences?.entries).toEqual({ + 'second-chat': { archived: true } + }) + second.sendRequest.mockImplementation( + () => + new Promise((resolve) => { + resolveOld = resolve + }) + ) + act(() => { + pending = observed.current?.setPreference('second-chat', { pinned: true }) + }) + second.advanceGeneration() + await act(async () => tree?.update(createElement(Probe))) + expect(observed.current?.writing).toBe(false) + await act(async () => { + resolveOld({ + id: 'old-generation', + ok: true, + result: { + preferences: { revision: 999, entries: { 'second-chat': { pinned: true } } } + } + }) + expect(await pending).toBe(false) + }) + expect(observed.view.conversationPreferences?.entries).toEqual({ + 'second-chat': { archived: true } + }) + } finally { + act(() => tree?.unmount()) + } + }) +}) diff --git a/mobile/src/host-screen/use-conversation-preferences.ts b/mobile/src/host-screen/use-conversation-preferences.ts new file mode 100644 index 000000000000..25e7e2407059 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-preferences.ts @@ -0,0 +1,95 @@ +import { useRef, useState } from 'react' +import { + CONVERSATION_NAVIGATION_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY, + type ConversationPreference, + type SetConversationPreferenceParams +} from '../../../src/shared/conversation-navigation-preferences' +import type { z } from 'zod' +import type { HostScreenController } from './use-host-screen-controller' +import { conversationPreferenceWrite } from './host-screen-operations' +import { conversationCopy } from './conversation-copy' + +export function useConversationPreferences( + controller: Pick & { + state: Pick + } +) { + const { client, hostId, connState, state, hostCapabilities } = controller + const preferences = state.view.conversationPreferences + const supported = + preferences !== undefined || hostCapabilities.includes(CONVERSATION_NAVIGATION_CAPABILITY) + type WriteOwner = { client: typeof client; hostId: typeof hostId; generation: number } + const generation = client?.getGeneration?.() ?? 0 + const owns = (value: WriteOwner | null) => + value?.client === client && value.hostId === hostId && value.generation === generation + const [writingOwner, setWriting] = useState(null) + const [errorOwner, setError] = useState<(WriteOwner & { message: string }) | null>(null) + const locked = useRef(null) + const acceptedOwner = useRef(null) + const owner = useRef({ client, hostId, connState }) + owner.current = { client, hostId, connState } + const projectVisibilitySupported = hostCapabilities.includes( + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY + ) + async function writePreference( + params: z.infer + ): Promise { + if (!client || !supported || connState !== 'connected' || owns(locked.current)) { + return false + } + const request = { client, hostId, generation } + const current = () => + owner.current.client === client && + owner.current.hostId === hostId && + owner.current.connState === 'connected' && + generation === (client.getGeneration?.() ?? 0) + locked.current = request + setWriting(request) + setError(null) + try { + const reply = await conversationPreferenceWrite.request(client, params) + if (!current()) { + return false + } + const result = conversationPreferenceWrite.interpret(reply) + if (!result.accepted) { + throw new Error('conversation_preference_refused') + } + if ( + !owns(acceptedOwner.current) || + result.value.preferences.revision >= + (state.viewRef.current.conversationPreferences?.revision ?? 0) + ) { + acceptedOwner.current = request + const next = { ...state.viewRef.current, conversationPreferences: result.value.preferences } + state.viewRef.current = next + state.setView(next) + } + return true + } catch { + if (current()) { + setError({ ...request, message: conversationCopy().saveFailed }) + } + return false + } finally { + if (locked.current === request) { + locked.current = null + } + setWriting((pending) => (pending === request ? null : pending)) + } + } + return { + preferences, + supported, + writing: owns(writingOwner), + error: owns(errorOwner) ? (errorOwner?.message ?? '') : '', + setPreference: (key: string, patch: ConversationPreference) => + writePreference({ key, ...patch }), + projectVisibilitySupported, + setProjectHidden: (projectKey: string, label: string, hidden: boolean) => + projectVisibilitySupported + ? writePreference({ projectKey, label, hidden }) + : Promise.resolve(false) + } +} diff --git a/mobile/src/host-screen/use-host-screen-controller.ts b/mobile/src/host-screen/use-host-screen-controller.ts index 4491127e4278..d312eaf2a86a 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -85,6 +85,10 @@ export function useHostScreenController({ useHostScreenIdentity({ client, hostId, state }) const sidebarFeed = useSwitchedHostSidebarFeed(client, hostId) + const projectCatalog = + sidebarFeed?.feed.kind === 'ready' + ? (sidebarFeed.feed.domains.projectCatalog ?? state.servedProjectSections) + : state.servedProjectSections // The host's botsChanged re-reads its own bots; a reconnect or the foreground, every host's. const [botsChangeKeys, noteBotsChanged] = useReducer( (keys: Record, scope: BotsChangeScope) => ({ @@ -186,11 +190,13 @@ export function useHostScreenController({ collapsedGroups, feed, projectOrderBy, + projectCatalog, client, connectionVerdict, connState, contentMaxWidth, displayWorktrees, + hostContextOf, embedded, existingWorktreePaths, floatingWorkspaceEnabled, diff --git a/mobile/src/host-screen/use-project-conversations.test.tsx b/mobile/src/host-screen/use-project-conversations.test.tsx new file mode 100644 index 000000000000..950ef9daf094 --- /dev/null +++ b/mobile/src/host-screen/use-project-conversations.test.tsx @@ -0,0 +1,423 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../src/shared/remote-runtime/relay/mobile-desktop-relay-contract' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { RpcResponse } from '../transport/rpc/rpc-wire-types' +import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes' +import { createStableLogicalRpcClient } from '../transport/connection/stable-logical-rpc-client' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { conversationHistory, conversationWorkspace } from './project-conversations.test-fixture' +import { + useProjectConversations, + type ProjectConversationsSource +} from './use-project-conversations' + +const trees: ReactTestRenderer[] = [] +afterEach(() => { + act(() => trees.forEach((tree) => tree.unmount())) + trees.length = 0 + vi.useRealTimers() +}) + +function source(client: RpcClient): ProjectConversationsSource { + return { + client, + hostId: 'paired-host', + connState: 'connected', + displayWorktrees: [conversationWorkspace()], + hostCapabilities: [], + state: { serverWorkspaces: { hosts: [], worktrees: [] }, repoHostIdByRepoId: new Map() }, + catalog: { onRefresh: async () => {} } + } +} + +function replies() { + const sendRequest = vi.fn(async (method) => ({ + id: 'one', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : method === 'aiVault.listSessions' + ? { sessions: [conversationHistory()], issues: [], includesStructuredSessions: true } + : { + tabs: [ + { + type: 'agent-session', + id: 'empty-tab', + sessionId: 'empty-chat', + agent: 'codex', + title: 'An empty open chat' + } + ] + } + })) + return { client: { ...new FakeSession('connected'), sendRequest }, sendRequest } +} + +async function mount(initial: ProjectConversationsSource) { + let props = initial + const observed: { current: ReturnType | null } = { current: null } + function Probe() { + observed.current = useProjectConversations(props) + return null + } + let tree: ReactTestRenderer | undefined + await act(async () => { + tree = create(createElement(Probe)) + trees.push(tree) + }) + return { + read: () => { + if (!observed.current) { + throw new Error('missing hook') + } + return observed.current + }, + unmount: () => act(() => tree?.unmount()), + update: async (next: ProjectConversationsSource) => { + props = next + await act(async () => tree?.update(createElement(Probe))) + } + } +} + +describe('host-owned conversation snapshots', () => { + it('shows the warm list immediately on return and refreshes stale rows in the background', async () => { + vi.useFakeTimers() + const { client, sendRequest } = replies() + const initial = { ...source(client), hostCapabilities: ['known-host-capability'] } + const first = await mount(initial) + first.unmount() + const calls = sendRequest.mock.calls.length + const warm = await mount({ ...initial, hostCapabilities: [] }) + expect(warm.read().loading).toBe(false) + expect(warm.read().history).toHaveLength(1) + expect(sendRequest).toHaveBeenCalledTimes(calls) + warm.unmount() + await vi.advanceTimersByTimeAsync(15_000) + let settle: (reply: RpcResponse) => void = () => {} + sendRequest.mockImplementation((method) => + method === 'aiVault.listSessions' + ? new Promise((resolve) => { + settle = resolve + }) + : Promise.resolve({ + id: 'next', + ok: true, + result: method === 'status.get' ? { capabilities: ['aiVault.v1'] } : { tabs: [] } + }) + ) + const returned = await mount(initial) + expect(returned.read().loading).toBe(false) + expect(returned.read().history).toHaveLength(1) + await act(async () => + settle({ + id: 'fresh', + ok: true, + result: { sessions: [], issues: [], includesStructuredSessions: true } + }) + ) + expect(returned.read().history).toEqual([]) + expect(returned.read().tabs.get(getWorktreeRowIdentity(conversationWorkspace()))).toEqual([]) + }) + + it('does not restore a cached list after a host or generation change while unmounted', async () => { + const original = replies() + const client = createStableLogicalRpcClient(original.client, 'lan') + const first = await mount(source(client)) + first.unmount() + const replacement = replies() + replacement.sendRequest.mockImplementation(() => new Promise(() => {})) + await client.migrateTo(replacement.client, 'relay') + const returned = await mount(source(client)) + expect(returned.read().loading).toBe(true) + expect(returned.read().history).toEqual([]) + returned.unmount() + const other = await mount({ ...source(original.client), hostId: 'another-host' }) + other.unmount() + original.sendRequest.mockImplementation(() => new Promise(() => {})) + const changed = await mount(source(original.client)) + expect(changed.read().history).toEqual([]) + expect(changed.read().loading).toBe(true) + }) + + it('invalidates connected cutover snapshots immediately and continues polling the new authority', async () => { + vi.useFakeTimers() + const original = replies() + const client = createStableLogicalRpcClient(original.client, 'lan') + const probe = await mount({ ...source(client), hostCapabilities: ['old-authority'] }) + expect(probe.read().complete).toBe(true) + expect(probe.read().history).toHaveLength(1) + expect(probe.read().tabs.size).toBe(1) + + const replacement = replies() + let settle: (reply: RpcResponse) => void = () => {} + replacement.sendRequest.mockImplementation((method) => + method === 'status.get' + ? new Promise((resolve) => { + settle = resolve + }) + : Promise.reject(new Error('new authority temporarily unavailable')) + ) + await act(async () => { + await client.migrateTo(replacement.client, 'relay') + }) + expect(client.getState()).toBe('connected') + expect(probe.read().loading).toBe(true) + expect(probe.read().complete).toBe(false) + expect(probe.read().history).toEqual([]) + expect(probe.read().tabs.size).toBe(0) + expect(probe.read().capabilitiesFor('local')).toEqual([]) + await act(async () => { + settle({ + id: 'unavailable', + ok: false, + error: { code: 'unavailable', message: 'temporarily offline' } + }) + }) + expect(probe.read().failed).toBe(true) + expect(probe.read().history).toEqual([]) + expect(probe.read().capabilitiesFor('local')).toEqual([]) + + replacement.sendRequest.mockImplementation(async (method) => ({ + id: 'replacement', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1', 'new-authority'] } + : method === 'aiVault.listSessions' + ? { sessions: [], issues: [], includesStructuredSessions: true } + : { tabs: [] } + })) + await act(async () => { + await vi.advanceTimersByTimeAsync(30_000) + }) + expect(probe.read().complete).toBe(true) + expect(probe.read().failed).toBe(false) + expect(probe.read().history).toEqual([]) + expect(probe.read().tabs.get(getWorktreeRowIdentity(conversationWorkspace()))).toEqual([]) + expect(probe.read().capabilitiesFor('local')).toContain('new-authority') + expect( + replacement.sendRequest.mock.calls.filter(([method]) => method === 'aiVault.listSessions') + ).toHaveLength(2) + expect( + replacement.sendRequest.mock.calls.filter(([method]) => method === 'session.tabs.list') + ).toHaveLength(3) + }) + + it('rejects a prior generation scan that settles after its replacement', async () => { + const original = replies() + let settle: (reply: RpcResponse) => void = () => {} + original.sendRequest.mockImplementation( + () => + new Promise((resolve) => { + settle = resolve + }) + ) + const client = createStableLogicalRpcClient(original.client, 'lan') + const probe = await mount({ ...source(client), displayWorktrees: [] }) + const replacement = replies() + await act(async () => { + await client.migrateTo(replacement.client, 'relay') + }) + expect(probe.read().complete).toBe(true) + expect(probe.read().history).toHaveLength(1) + await act(async () => { + settle({ id: 'old', ok: true, result: { capabilities: [] } }) + }) + expect(probe.read().complete).toBe(true) + expect(probe.read().capabilitiesFor('local')).toEqual(['aiVault.v1']) + }) + + it('loads open empty chats and history without depending on worktree activity', async () => { + const { client, sendRequest } = replies() + const probe = await mount(source(client)) + expect(probe.read().complete).toBe(true) + expect( + probe.read().tabs.get(getWorktreeRowIdentity(conversationWorkspace()))?.[0]?.sessionId + ).toBe('empty-chat') + expect(sendRequest).toHaveBeenCalledWith('aiVault.listSessions', { + unlimited: true, + includeAntigravityIdeSessions: true, + includeStructuredSessions: true, + force: false + }) + }) + + it('keeps old snapshots on read failure and never borrows them across paired hosts', async () => { + const { client, sendRequest } = replies() + const original = source(client) + const probe = await mount(original) + sendRequest.mockRejectedValue(new Error('temporarily offline')) + await act(async () => { + probe.read().onRefresh() + }) + expect(probe.read().failed).toBe(true) + expect(probe.read().history).toHaveLength(1) + expect(probe.read().tabs.size).toBe(1) + expect(probe.read().capabilitiesFor('local')).toEqual(['aiVault.v1']) + const replacement = replies() + let settle: (reply: RpcResponse) => void = () => {} + replacement.sendRequest.mockImplementation( + () => + new Promise((resolve) => { + settle = resolve + }) + ) + await probe.update({ + ...source(replacement.client), + hostId: 'other-paired-host', + displayWorktrees: [] + }) + expect(probe.read().history).toEqual([]) + expect(probe.read().tabs.size).toBe(0) + await act(async () => { + settle({ id: 'late', ok: true, result: { capabilities: [] } }) + }) + }) + + it('uses scoped envelopes for a reachable server and refuses any local fallback without relay support', async () => { + const { client, sendRequest } = replies() + const original = source(client) + const remote = conversationWorkspace({ hostId: 'runtime:server' }) + const remoteSource: ProjectConversationsSource = { + ...original, + displayWorktrees: [remote], + hostCapabilities: [MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY], + state: { + ...original.state, + serverWorkspaces: { + hosts: [ + { hostId: 'runtime:server', label: 'Build server', relay: 'ready', health: 'available' } + ], + worktrees: [remote] + } + } + } + const probe = await mount(remoteSource) + expect(sendRequest).toHaveBeenCalledWith( + 'session.tabs.list', + { worktree: `id:${remote.worktreeId}` }, + { envelope: { executionHost: 'runtime:server' } } + ) + expect(probe.read().history.some((row) => row.executionHostId === 'runtime:server')).toBe(true) + sendRequest.mockClear() + await probe.update({ ...remoteSource, hostCapabilities: [] }) + expect(sendRequest.mock.calls.some(([method]) => method === 'session.tabs.list')).toBe(false) + expect(probe.read().capabilitiesFor('runtime:server')).toEqual([]) + }) +}) + +it('marks successful partial history replies incomplete while keeping their readable rows', async () => { + const { client, sendRequest } = replies() + sendRequest.mockImplementation(async (method) => ({ + id: 'partial', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : method === 'aiVault.listSessions' + ? { + sessions: [conversationHistory()], + issues: [{ message: 'One provider could not be scanned' }], + includesStructuredSessions: true + } + : { tabs: [] } + })) + const probe = await mount(source(client)) + expect(probe.read().history).toHaveLength(1) + expect(probe.read().complete).toBe(false) + expect(probe.read().failed).toBe(true) +}) + +it('reuses per-host history fingerprints on automatic refresh while manual refresh requests a full snapshot', async () => { + vi.useFakeTimers() + const fingerprint = 'a'.repeat(64) + const { client, sendRequest } = replies() + sendRequest.mockImplementation(async (method, params) => { + const query = params !== null && typeof params === 'object' ? params : {} + return { + id: 'conditional', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : method === 'aiVault.listSessions' + ? 'afterFingerprint' in query && query.afterFingerprint === fingerprint + ? { + sessions: [], + issues: [], + unchanged: true, + fingerprint, + includesStructuredSessions: true + } + : { + sessions: 'force' in query && query.force ? [] : [conversationHistory()], + issues: [], + fingerprint, + includesStructuredSessions: true + } + : { tabs: [] } + } + }) + const probe = await mount(source(client)) + expect(probe.read().history).toHaveLength(1) + await act(async () => { + await vi.advanceTimersByTimeAsync(15_000) + }) + const requests = () => + sendRequest.mock.calls.filter(([method]) => method === 'aiVault.listSessions') + expect(requests().at(-1)?.[1]).toHaveProperty('afterFingerprint', fingerprint) + expect(probe.read().history).toHaveLength(1) + await act(async () => { + probe.read().onRefresh() + }) + expect(requests().at(-1)?.[1]).not.toHaveProperty('afterFingerprint') + expect(requests().at(-1)?.[1]).toHaveProperty('force', true) + expect(probe.read().history).toEqual([]) +}) + +it('keeps informational record notices out of the loading-failure state', async () => { + const { client, sendRequest } = replies() + sendRequest.mockImplementation(async (method) => ({ + id: 'notice', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : method === 'aiVault.listSessions' + ? { + sessions: [conversationHistory()], + includesStructuredSessions: true, + issues: [{ kind: 'notice', message: 'Skipped 2 oversized transcript records.' }] + } + : { tabs: [] } + })) + const probe = await mount(source(client)) + expect(probe.read().history).toHaveLength(1) + expect(probe.read().complete).toBe(true) + expect(probe.read().failed).toBe(false) +}) + +it.each(['host', 'scope', undefined])('keeps %s history failures actionable', async (kind) => { + const { client, sendRequest } = replies() + sendRequest.mockImplementation(async (method) => ({ + id: 'failure', + ok: true, + result: + method === 'status.get' + ? { capabilities: ['aiVault.v1'] } + : method === 'aiVault.listSessions' + ? { + sessions: [conversationHistory()], + includesStructuredSessions: true, + issues: [{ kind, message: 'History source unavailable' }] + } + : { tabs: [] } + })) + const probe = await mount(source(client)) + expect(probe.read().failed).toBe(true) + expect(probe.read().complete).toBe(false) +}) diff --git a/mobile/src/host-screen/use-project-conversations.ts b/mobile/src/host-screen/use-project-conversations.ts new file mode 100644 index 000000000000..68aa3336b4f6 --- /dev/null +++ b/mobile/src/host-screen/use-project-conversations.ts @@ -0,0 +1,299 @@ +import { + refreshProjectConversationHistory, + type ProjectConversationHistorySnapshot +} from './project-conversation-history-refresh' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { ExecutionHostId } from '../../../src/shared/execution-host/execution-host' +import { + rpcClientForExecutionHost, + reachableServerClients +} from '../worktree/execution-hosts/execution-host-scoped-rpc-client' +import { getWorktreeRowIdentity } from '../worktree/row-presentation/worktree-host-row-identity' +import { resolveWorktreeHostId } from '../worktree/row-presentation/worktree-host-context-labels' +import { isConversationHistoryNotice } from './conversation-records' +import { sessionTabsListRead } from '../session/tabs/mobile-session-tab-read-operations' +import type { HostScreenController } from './use-host-screen-controller' +import { + readConversationTabs, + type ConversationHistory, + type ConversationTab +} from './project-conversations' + +type ConversationSnapshot = { + tabs: Map + history: ConversationHistory[] + historyByHost: Map + capabilities: Map + complete: boolean + failed: boolean +} +const EMPTY: ConversationSnapshot = { + tabs: new Map(), + history: [], + historyByHost: new Map(), + capabilities: new Map(), + complete: false, + failed: false +} + +type LoadedConversations = { + client: RpcClient + hostId: string | undefined + generation: number + authority: string + workspaceStamp: string + at: number + value: ConversationSnapshot +} + +const snapshots = new WeakMap() +const REFRESH_MS = 15_000 + +export type ProjectConversationsSource = Pick< + HostScreenController, + 'client' | 'hostId' | 'connState' | 'displayWorktrees' | 'hostCapabilities' +> & { + state: Pick + catalog: Pick +} + +export function useProjectConversations(controller: ProjectConversationsSource) { + const { client, hostId, connState, displayWorktrees, hostCapabilities, state } = controller + const subscribe = useCallback( + (onChange: () => void) => client?.onStateChange(onChange) ?? (() => {}), + [client] + ) + const readGeneration = useCallback(() => client?.getGeneration?.() ?? 0, [client]) + const generation = useSyncExternalStore(subscribe, readGeneration, readGeneration) + const workspaces = useMemo( + () => + displayWorktrees.map((workspace) => ({ + ...workspace, + hostId: resolveWorktreeHostId(workspace, state.repoHostIdByRepoId) + })), + [displayWorktrees, state.repoHostIdByRepoId] + ) + const workspacesRef = useRef(workspaces) + workspacesRef.current = workspaces + const workspaceStamp = workspaces.map(getWorktreeRowIdentity).sort().join('\0') + const serversRef = useRef(state.serverWorkspaces.hosts) + serversRef.current = state.serverWorkspaces.hosts + const serverStamp = state.serverWorkspaces.hosts + .map((host) => `${host.hostId}:${host.relay}`) + .join('\0') + const sources = useMemo(() => { + const servers = reachableServerClients(client, hostCapabilities, serversRef.current) + return client ? new Map([['local' as const, client], ...servers]) : servers + }, [client, hostCapabilities, serverStamp]) + const authority = serverStamp ? JSON.stringify([hostCapabilities, serverStamp]) : '' + const cached = client ? snapshots.get(client) : undefined + const belongsHere = (entry: LoadedConversations | null | undefined) => + entry?.client === client && + entry.hostId === hostId && + entry.generation === generation && + entry.authority === authority + const [loaded, setLoaded] = useState(null) + const retained = belongsHere(loaded) ? loaded : belongsHere(cached) ? cached : null + const [refreshing, setRefreshing] = useState(false) + const [revision, setRevision] = useState(0) + const onRefresh = useCallback(() => { + setRefreshing(true) + setRevision((value) => value + 1) + void controller.catalog.onRefresh() + }, [controller.catalog.onRefresh]) + + useEffect(() => { + if (!client || connState !== 'connected') { + return + } + let stale = false + let running = false + let firstRefresh = true + const cached = snapshots.get(client) + const fresh = + cached !== undefined && + cached.hostId === hostId && + cached.generation === generation && + cached.authority === authority && + cached.workspaceStamp === workspaceStamp && + !cached.value.failed && + Date.now() - cached.at < REFRESH_MS + const current = () => !stale && generation === (client.getGeneration?.() ?? 0) + const refresh = async () => { + if (running) { + return + } + running = true + const force = firstRefresh && revision > 0 + firstRefresh = false + const previous = snapshots.get(client) + const sameAuthority = + previous !== undefined && + previous.hostId === hostId && + previous.generation === generation && + previous.authority === authority + const failedSources = new Set() + const failedTabs = new Set() + const next: ConversationSnapshot = { + tabs: new Map(), + history: [], + historyByHost: new Map(), + capabilities: new Map(), + complete: true, + failed: false + } + try { + const historyRequests = Promise.all( + [...sources].map(async ([sourceHost, sourceClient]) => { + try { + const { capabilities, history } = await refreshProjectConversationHistory( + sourceClient, + force, + sameAuthority ? previous.value.historyByHost.get(sourceHost) : undefined + ) + next.capabilities.set(sourceHost, capabilities) + if (!history) { + next.complete = false + return + } + next.historyByHost.set(sourceHost, history) + const historyFailed = history.issues.some( + (issue) => !isConversationHistoryNotice(issue) + ) + if (!history.includesStructuredSessions || historyFailed) { + next.complete = false + } + next.failed ||= historyFailed + next.history.push( + ...history.sessions.map((session) => ({ + ...session, + executionHostId: + sourceHost !== 'local' && session.executionHostId === 'local' + ? sourceHost + : session.executionHostId + })) + ) + } catch { + failedSources.add(sourceHost) + next.failed = true + next.complete = false + } + }) + ) + const workspaces = workspacesRef.current + for (let offset = 0; offset < workspaces.length && current(); offset += 4) { + await Promise.all( + workspaces.slice(offset, offset + 4).map(async (workspace) => { + const rowClient = rpcClientForExecutionHost( + client, + hostCapabilities, + workspace.hostId + ) + if (!rowClient) { + return + } + try { + const result = sessionTabsListRead.interpret( + await sessionTabsListRead.request(rowClient, { + worktree: `id:${workspace.worktreeId}` + }) + ) + next.tabs.set(getWorktreeRowIdentity(workspace), readConversationTabs(result)) + } catch { + failedTabs.add(getWorktreeRowIdentity(workspace)) + next.failed = true + } + }) + ) + } + await historyRequests + if (current()) { + const value = (() => { + const tabs = new Map(next.tabs) + const capabilities = new Map(next.capabilities) + const historyByHost = new Map(next.historyByHost) + let history = next.history + if (sameAuthority) { + for (const source of failedSources) { + const priorHistory = previous.value.historyByHost.get(source) + if (priorHistory) { + historyByHost.set(source, priorHistory) + } + const retained = previous.value.capabilities.get(source) + if (!capabilities.has(source) && retained) { + capabilities.set(source, retained) + } + } + for (const key of failedTabs) { + const retained = previous.value.tabs.get(key) + if (retained) { + tabs.set(key, retained) + } + } + history = [ + ...history, + ...previous.value.history.filter( + (session) => + session.executionHostId && + failedSources.has( + session.executionHostId.startsWith('runtime:') + ? session.executionHostId + : 'local' + ) + ) + ] + } + return { ...next, tabs, capabilities, history, historyByHost } + })() + const loaded = { + client, + hostId, + generation, + authority, + workspaceStamp, + at: Date.now(), + value + } + snapshots.set(client, loaded) + setLoaded(loaded) + } + } finally { + running = false + if (current()) { + setRefreshing(false) + } + } + } + if (!fresh || revision > 0) { + void refresh() + } + const timer = setInterval(() => void refresh(), REFRESH_MS) + return () => { + stale = true + clearInterval(timer) + } + }, [ + client, + connState, + hostId, + generation, + sources, + workspaceStamp, + hostCapabilities, + revision, + authority + ]) + + const snapshot = retained?.value ?? EMPTY + return { + ...snapshot, + generation, + workspaces, + refreshing, + onRefresh, + loading: snapshot === EMPTY && connState === 'connected', + capabilitiesFor: (host: ExecutionHostId) => + snapshot.capabilities.get(host.startsWith('runtime:') ? host : 'local') ?? [] + } +} diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 66ac020f356d..daadeb8a2882 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -464,7 +464,8 @@ "hideDetails": "Hide details", "showDetails": "Show details", "loading": "Loading agent sessions…", - "showAllAgents": "Show all agents" + "showAllAgents": "Show all agents", + "conversationUnavailable": "This conversation's history is unavailable on this host." }, "resumeTarget": { "runtimeUnavailable": "Resume from history is not available in runtime-hosted workspaces.", diff --git a/mobile/src/session/notification-pane-tab.test.ts b/mobile/src/session/notification-pane-tab.test.ts new file mode 100644 index 000000000000..f53a273a957d --- /dev/null +++ b/mobile/src/session/notification-pane-tab.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { notificationPaneTab } from './tabs/notification-pane-tab' +import type { MobileSessionTab } from './tabs/mobile-session-tabs' + +const leaf = '10000000-0000-4000-8000-000000000001' +const tabs: MobileSessionTab[] = [ + { + type: 'terminal', + id: 'first', + terminal: 'terminal:first', + title: 'First chat', + isActive: true + }, + { + type: 'terminal', + id: 'second', + parentTabId: 'group', + leafId: leaf, + terminal: 'terminal:second', + title: 'Second chat', + isActive: false + } +] + +describe('conversation route tab selection', () => { + it('selects the exact launch handle even when the host has not supplied pane topology', () => { + expect(notificationPaneTab(tabs, 'terminal:second')).toBe(tabs[1]) + expect(notificationPaneTab(tabs, 'second')).toBe(tabs[1]) + }) + + it('keeps modern stable pane selection inside the routed workspace inventory', () => { + expect(notificationPaneTab(tabs, `group:${leaf}`)).toBe(tabs[1]) + expect(notificationPaneTab(tabs.slice(0, 1), `group:${leaf}`)).toBeUndefined() + }) + + it('never substitutes the active chat when the requested conversation is missing', () => { + expect(notificationPaneTab(tabs, 'terminal:missing')).toBeUndefined() + }) +}) diff --git a/mobile/src/session/tabs/notification-pane-tab.ts b/mobile/src/session/tabs/notification-pane-tab.ts index 4a3c6e3ed904..993c9d56bff2 100644 --- a/mobile/src/session/tabs/notification-pane-tab.ts +++ b/mobile/src/session/tabs/notification-pane-tab.ts @@ -9,7 +9,11 @@ import type { MobileSessionTab } from './mobile-session-tabs' export function notificationPaneTab(tabs: readonly MobileSessionTab[], paneKey: string) { const pane = parsePaneKey(paneKey) if (!pane) { - return undefined + return tabs.find( + (tab) => + tab.type === 'terminal' && + (tab.terminal === paneKey || tab.id === paneKey || tab.agentStatus?.paneKey === paneKey) + ) } return tabs.find((tab) => tab.type === 'terminal' diff --git a/mobile/src/worktree/workspace-list/workspace-view-settings.ts b/mobile/src/worktree/workspace-list/workspace-view-settings.ts index 2e31aa797013..05cf4377f297 100644 --- a/mobile/src/worktree/workspace-list/workspace-view-settings.ts +++ b/mobile/src/worktree/workspace-list/workspace-view-settings.ts @@ -37,6 +37,7 @@ export type WorkspaceViewSettings = { | (typeof WORKSPACE_VIEW_UI_FIELDS)[number] // Written with the card properties only: whether they are a Card layout preset. | '_worktreeCardModeDefaulted' + | 'conversationPreferences' > > @@ -47,6 +48,7 @@ export type MobileViewState = { collapsedGroups: readonly string[] workspaceStatuses: readonly WorkspaceStatusDefinition[] /** Null until the desktop's value is read; the served project list's order stands in. */ + conversationPreferences?: PersistedUIState['conversationPreferences'] projectOrderBy: ProjectOrderBy | null /** May hold a property a newer desktop added; it is carried back unchanged. */ worktreeCardProperties: readonly WorktreeCardProperty[] @@ -172,6 +174,13 @@ export function applyDesktopViewSettings( filters, collapsedGroups: settings.collapsedGroups ?? current.collapsedGroups, workspaceStatuses, + ...(current.conversationPreferences + ? { conversationPreferences: current.conversationPreferences } + : {}), + ...(settings.conversationPreferences && + settings.conversationPreferences.revision >= (current.conversationPreferences?.revision ?? 0) + ? { conversationPreferences: settings.conversationPreferences } + : {}), projectOrderBy: settings.projectOrderBy ?? current.projectOrderBy, worktreeCardProperties: settings.worktreeCardProperties ?? current.worktreeCardProperties, agentActivityDisplayMode: settings.agentActivityDisplayMode ?? current.agentActivityDisplayMode, diff --git a/src/main/ai-vault/discovery/session-scanner-discovery.ts b/src/main/ai-vault/discovery/session-scanner-discovery.ts index e2949fbd2191..0cc6b57584c8 100644 --- a/src/main/ai-vault/discovery/session-scanner-discovery.ts +++ b/src/main/ai-vault/discovery/session-scanner-discovery.ts @@ -12,6 +12,7 @@ import { wslGatedReaddir } from '../../native-chat/transcript-filesystem/wsl-tra import { WslTranscriptFsError } from '../../native-chat/transcript-filesystem/wsl-transcript-fs-error' import { recordSessionScanIssue, scanIssueTextFromError } from '../parsing/session-scan-issues' import { aiVaultScanIssueText } from '../../../shared/ai-vault/scanning/ai-vault-scan-issue-copy' +import { isSelectedSessionFile } from '../session-scanner-selection' import type { FileWithMtime, SessionFileDiscovery, @@ -58,10 +59,13 @@ export async function discoverFiles(args: { onDirectoryEntries?: (dirPath: string, entries: readonly Dirent[]) => void // A scoped scan walks every file this agent has, not only the newest `limit`. keepScopeFiles?: boolean + selectedSessionId?: string + executionHostId?: string statCache?: SessionDiscoveryStatCache signal?: AbortSignal }): Promise { const files = new SessionNewestFiles(args.limit) + const selectedFiles: FileWithMtime[] = [] const scopeFiles: FileWithMtime[] | undefined = args.keepScopeFiles ? [] : undefined let refusedSidecar = false let paths: string[] = [] @@ -91,6 +95,17 @@ export async function discoverFiles(args: { } try { const modifiedAt = new Date(observation.file.mtimeMs) + if ( + selectedFiles.length === 0 && + isSelectedSessionFile( + args.selectedSessionId, + args.agent, + observation.file.path, + args.executionHostId + ) + ) { + selectedFiles.push({ ...observation.file, modifiedAt: modifiedAt.toISOString() }) + } if ( Number.isNaN(modifiedAt.getTime()) || files.wouldRetain(observation.file.mtimeMs) || @@ -225,7 +240,13 @@ export async function discoverFiles(args: { } finally { source.close() } - return { agent: args.agent, rootDir: args.rootDir, files: files.newest(), scopeFiles } + return { + agent: args.agent, + rootDir: args.rootDir, + files: files.newest(), + scopeFiles, + selectedFiles + } } /** Collecting form for callers that want every match; bounded scans stream. */ diff --git a/src/main/ai-vault/discovery/session-scanner-source-discovery.ts b/src/main/ai-vault/discovery/session-scanner-source-discovery.ts index 99d20fba0293..0e8340bccbec 100644 --- a/src/main/ai-vault/discovery/session-scanner-source-discovery.ts +++ b/src/main/ai-vault/discovery/session-scanner-source-discovery.ts @@ -84,6 +84,8 @@ async function agentDiscoveries( contentDependencyPath: source.contentDependencyPath, directoryPredicate: source.directoryPredicate, keepScopeFiles: scopeWalksAgentFiles(agent, options.scopePaths), + selectedSessionId: options.selectedSessionId, + executionHostId: options.executionHostId, statCache: options.statCache, signal: options.signal }) @@ -114,6 +116,7 @@ async function mergedDiscovery( agent, rootDir: rootDirs.join(delimiter), files: files.slice(0, limit), + selectedFiles: discoveries.flatMap((discovery) => discovery.selectedFiles ?? []), ...(scopeFiles ? { scopeFiles } : {}), ...(aliasRootDirs.length ? { aliasRootDirs } : {}) } diff --git a/src/main/ai-vault/listing/cached-session-list.ts b/src/main/ai-vault/listing/cached-session-list.ts index 80e3c9728a9e..77c31ae43bf8 100644 --- a/src/main/ai-vault/listing/cached-session-list.ts +++ b/src/main/ai-vault/listing/cached-session-list.ts @@ -82,7 +82,12 @@ export async function listAiVaultSessions( const cachedList = args?.force === true ? undefined : servingCachedList([key, fullKey], depth, args, now) if (cachedList) { - return truncateAiVaultListResult(cachedList.result, depth, args?.scopePaths) + return truncateAiVaultListResult( + cachedList.result, + depth, + args?.scopePaths, + args?.selectedSessionId + ) } // Capture before the coordinator's start microtask so intervening invalidation still rejects the result. const startGeneration = cacheGeneration @@ -109,6 +114,7 @@ export async function listAiVaultSessions( const scanned = await scanAiVaultSessionsInBackground( { includeAntigravityIdeSessions: args?.includeAntigravityIdeSessions, + selectedSessionId: args?.selectedSessionId, limit: args?.limit, unlimited: args?.unlimited, scopePaths: args?.scopePaths ? scope.scanScopePaths : undefined, diff --git a/src/main/ai-vault/listing/session-list-conversation-evidence.test.ts b/src/main/ai-vault/listing/session-list-conversation-evidence.test.ts new file mode 100644 index 000000000000..f88de8ef4885 --- /dev/null +++ b/src/main/ai-vault/listing/session-list-conversation-evidence.test.ts @@ -0,0 +1,29 @@ +import { expect, it } from 'vitest' +import { listResult } from '../structured-sessions/structured-session-ownership.test-support' +import { parseAiVaultListResult } from './session-list-result-validation' + +it('preserves conversation evidence and retains rows from older and newer hosts', () => { + const fixture = listResult() + const [session] = fixture.sessions + if (!session) { + throw new Error('Conversation fixture is empty') + } + const result = parseAiVaultListResult({ + ...fixture, + sessions: ['empty', 'present', 'unknown', 'future-value', undefined].map( + (conversationContent, index) => ({ + ...session, + id: `session-${index}`, + sessionId: `session-${index}`, + ...(conversationContent === undefined ? {} : { conversationContent }) + }) + ) + }) + expect(result.sessions.map((row) => row.conversationContent)).toEqual([ + 'empty', + 'present', + 'unknown', + undefined, + undefined + ]) +}) diff --git a/src/main/ai-vault/listing/session-list-result-validation.ts b/src/main/ai-vault/listing/session-list-result-validation.ts index 1bcdca4d4ae3..90bee1ad23c5 100644 --- a/src/main/ai-vault/listing/session-list-result-validation.ts +++ b/src/main/ai-vault/listing/session-list-result-validation.ts @@ -47,6 +47,8 @@ const sessionPreviewMessageSchema = z.object({ }) const aiVaultSessionSchema = z.object({ + source: z.literal('structured-record').optional(), + conversationContent: z.enum(['empty', 'present', 'unknown']).optional().catch(undefined), accountHome: AiVaultSessionAccountHomeSchema, accountWslDistro: z.string().nullable().optional().catch(undefined), id: z.string(), @@ -122,7 +124,8 @@ const aiVaultListResultEnvelopeSchema = z .string() .regex(/^[0-9a-f]{64}$/) .optional(), - unchanged: z.literal(true).optional() + unchanged: z.literal(true).optional(), + includesStructuredSessions: z.literal(true).optional() }) .refine( (value) => @@ -185,6 +188,9 @@ export function parseAiVaultListResult(value: unknown): AiVaultListResult { sessions, issues, scannedAt: envelope.data.scannedAt, + ...(envelope.data.includesStructuredSessions + ? { includesStructuredSessions: true as const } + : {}), ...(envelope.data.fingerprint ? { fingerprint: envelope.data.fingerprint } : {}), ...(envelope.data.unchanged ? { unchanged: true as const } : {}) } diff --git a/src/main/ai-vault/listing/session-list-results.test.ts b/src/main/ai-vault/listing/session-list-results.test.ts new file mode 100644 index 000000000000..215cc7231f9f --- /dev/null +++ b/src/main/ai-vault/listing/session-list-results.test.ts @@ -0,0 +1,54 @@ +import { expect, it } from 'vitest' +import type { + AiVaultListResult, + AiVaultScanIssue, + AiVaultSession +} from '../../../shared/ai-vault/contracts/ai-vault-types' +import { mergeAiVaultListResults } from './session-list-results' + +function listResult(issues: AiVaultScanIssue[]): AiVaultListResult { + return { sessions: [], issues, scannedAt: '2026-08-02T00:00:00.000Z' } +} + +function session(index: number): AiVaultSession { + const id = `session-${index}` + const timestamp = new Date(Date.UTC(2026, 7, 2, 0, 0, index)).toISOString() + return { + id, + executionHostId: 'local', + agent: 'codex', + sessionId: id, + title: id, + cwd: '/repo', + branch: null, + model: null, + filePath: `/sessions/${id}.jsonl`, + codexHome: null, + createdAt: timestamp, + updatedAt: timestamp, + modifiedAt: timestamp, + messageCount: 1, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: id, + subagent: null + } +} + +it('retains a selected remote conversation beyond the merged result limit', () => { + const selected = { + ...session(0), + executionHostId: 'runtime:server' as const, + id: 'remote-selected' + } + const results = [ + { ...listResult([]), sessions: [session(2)] }, + { ...listResult([]), sessions: [session(1), selected] } + ] + expect( + mergeAiVaultListResults(results, 1, false, [], 'remote-selected').sessions.map((row) => row.id) + ).toEqual(['session-2', 'remote-selected']) + expect(mergeAiVaultListResults(results, 1).sessions.map((row) => row.id)).toEqual(['session-2']) +}) diff --git a/src/main/ai-vault/listing/session-list-results.ts b/src/main/ai-vault/listing/session-list-results.ts index e64c10912707..c22de25d3275 100644 --- a/src/main/ai-vault/listing/session-list-results.ts +++ b/src/main/ai-vault/listing/session-list-results.ts @@ -44,7 +44,9 @@ export function restampAiVaultListResult( result: AiVaultListResult, executionHostId: ExecutionHostId ): AiVaultListResult { + const { scanId: _localScanId, ...remoteResult } = result return { + ...remoteResult, sessions: result.sessions.map((session) => session.executionHostId === executionHostId ? session @@ -54,8 +56,7 @@ export function restampAiVaultListResult( id: `${executionHostId}:${session.agent}:${session.sessionId}:${session.filePath}` } ), - issues: result.issues.map((issue) => ({ ...issue, executionHostId })), - scannedAt: result.scannedAt + issues: result.issues.map((issue) => ({ ...issue, executionHostId })) } } @@ -63,7 +64,8 @@ export function mergeAiVaultListResults( results: readonly AiVaultListResult[], rawLimit: number | undefined, unlimited = false, - scopePaths: readonly string[] = [] + scopePaths: readonly string[] = [], + selectedSessionId?: string ): AiVaultListResult { const depth = requestedAiVaultSessionDepth({ limit: rawLimit, unlimited }) const byId = new Map() @@ -84,7 +86,8 @@ export function mergeAiVaultListResults( scannedAt: latestAiVaultScannedAt(results) }, depth, - scopePaths + scopePaths, + selectedSessionId ) } diff --git a/src/main/ai-vault/parse-cache/session-scanner-parse-cache.ts b/src/main/ai-vault/parse-cache/session-scanner-parse-cache.ts index 8d85452129ef..94fb07847e80 100644 --- a/src/main/ai-vault/parse-cache/session-scanner-parse-cache.ts +++ b/src/main/ai-vault/parse-cache/session-scanner-parse-cache.ts @@ -272,7 +272,7 @@ async function reuseCachedSession( } let session = entry.session // Zero-turn parents may never change again; recount late subagent transcripts outside the cached file signature. - if (session && session.messageCount === 0) { + if (session && (session.messageCount === 0 || session.conversationContent === 'empty')) { const subagentTranscriptCount = session.agent === 'claude' ? await countSubagentTranscripts(candidate.file.path, signal) @@ -283,7 +283,11 @@ async function reuseCachedSession( subagentTranscriptCount !== null && subagentTranscriptCount !== session.subagentTranscriptCount ) { - session = { ...session, subagentTranscriptCount } + session = { + ...session, + subagentTranscriptCount, + ...(subagentTranscriptCount > 0 ? { conversationContent: 'present' as const } : {}) + } } } // Index titles can change independently of the transcript signature. diff --git a/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-sources.ts b/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-sources.ts index c81509ec7180..2fa22c9fd3a7 100644 --- a/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-sources.ts +++ b/src/main/ai-vault/scanners/antigravity/session-scanner-antigravity-sources.ts @@ -52,6 +52,8 @@ export function antigravityDiscoveries( onDirectoryEntries: (dirPath, entries) => recordAntigravityArtifactPath(antigravityArtifactPaths, rootDir, dirPath, entries), keepScopeFiles: scopeWalksAgentFiles('antigravity', options.scopePaths), + selectedSessionId: options.selectedSessionId, + executionHostId: options.executionHostId, statCache: options.statCache, signal: options.signal }) diff --git a/src/main/ai-vault/scanners/claude/session-scanner-primary-parsers.ts b/src/main/ai-vault/scanners/claude/session-scanner-primary-parsers.ts index 519c1801ce1e..74d7dcb08276 100644 --- a/src/main/ai-vault/scanners/claude/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/scanners/claude/session-scanner-primary-parsers.ts @@ -1,3 +1,4 @@ +import { extractFullFirstUserPromptText } from '../../prompts/session-scanner-first-user-prompt' import { remoteSessionContentLines, type RemoteSessionContent @@ -47,6 +48,7 @@ export type ClaudeSessionParseState = { metaTitle: string | null generatedTitle: string | null firstUserTitle: string | null + conversationContent: NonNullable } export function createClaudeSessionParseState( @@ -62,7 +64,8 @@ export function createClaudeSessionParseState( }), metaTitle: null, generatedTitle: null, - firstUserTitle: null + firstUserTitle: null, + conversationContent: 'empty' } } @@ -76,7 +79,8 @@ export function cloneClaudeSessionParseState( }, metaTitle: state.metaTitle, generatedTitle: state.generatedTitle, - firstUserTitle: state.firstUserTitle + firstUserTitle: state.firstUserTitle, + conversationContent: state.conversationContent } } @@ -99,8 +103,14 @@ const CLAUDE_RECORD_FIELDS: ReadonlySet = new Set([ // Tool results and attachments can parse to ~20x their size; listing never reads them (#42921). export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: string): void { + const markUnknown = () => { + if (line.trim() && state.conversationContent !== 'present') { + state.conversationContent = 'unknown' + } + } const members = readJsonObjectMembers(line, CLAUDE_RECORD_FIELDS) if (!members) { + markUnknown() return } const record: Record = {} @@ -116,6 +126,7 @@ export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: s record.message = JSON.parse(message) } } catch { + markUnknown() return } consumeClaudeSessionRecord(state, record) @@ -146,8 +157,14 @@ export function consumeClaudeSessionRecord( return } - if (record.type === 'agent-name' && !state.generatedTitle) { - state.metaTitle ??= normalizeTitleText(extractString(record.agentName) ?? '') + if (record.type === 'agent-name') { + if (!state.generatedTitle) { + state.metaTitle ??= normalizeTitleText(extractString(record.agentName) ?? '') + } + return + } + + if (record.type === 'mode' || record.type === 'permission-mode') { return } @@ -165,6 +182,7 @@ export function consumeClaudeSessionRecord( const prompt = normalizePromptField(record.lastPrompt) if (prompt) { accumulator.lastUserPrompt = prompt + state.conversationContent = 'present' } return } @@ -178,17 +196,16 @@ export function consumeClaudeSessionRecord( addSessionContent(accumulator, 'user', asRecord(record.message)?.content, record.timestamp, { seedFirstUserPrompt: !isMetaUserTurn }) - if (title) { - if (isMetaUserTurn) { - state.metaTitle ??= title - } else { - state.firstUserTitle ??= title - } + if (!isMetaUserTurn) { + state.conversationContent = 'present' + const prompt = extractFullFirstUserPromptText(asRecord(record.message)?.content) + state.firstUserTitle ??= prompt ? normalizeTitleText(prompt) : null } return } if (record.type === 'assistant') { + state.conversationContent = 'present' accumulator.messageCount++ const message = asRecord(record.message) addSessionContent(accumulator, 'assistant', message?.content, record.timestamp) @@ -197,6 +214,10 @@ export function consumeClaudeSessionRecord( accumulator.model = model } accumulator.totalTokens += claudeUsageTotal(message?.usage) + return + } + if (state.conversationContent !== 'present') { + state.conversationContent = 'unknown' } } @@ -207,7 +228,7 @@ export async function finalizeClaudeSessionParseState( ): Promise { // Detach previews so later appends cannot mutate a published session. const snapshot = cloneClaudeSessionParseState(state) - // Explicit custom titles win, then generated names, real prompts and injected-context fallbacks. + // Explicit custom titles win, then generated names, real prompts and agent names. snapshot.accumulator.fallbackTitle = snapshot.generatedTitle ?? snapshot.firstUserTitle ?? snapshot.metaTitle // Count only on the transcript-owning host; runtime hosts stamp identity after parsing, while SSH walks supply counts. @@ -219,9 +240,17 @@ export async function finalizeClaudeSessionParseState( options.signal ) } - // A rename (custom-title) or Claude's generated name is the session's own; prompts and metadata are stand-ins. const titleKind = snapshot.accumulator.title || snapshot.generatedTitle ? 'named' : 'fallback' - return finalizeSession(snapshot.accumulator, platform, { ...options, titleKind }) + const session = finalizeSession(snapshot.accumulator, platform, { ...options, titleKind }) + return session + ? { + ...session, + conversationContent: + session.queuedMessageCount > 0 || session.subagentTranscriptCount > 0 + ? 'present' + : snapshot.conversationContent + } + : null } export function createClaudeSessionResumeState( diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch.ts index 5df7daf589a6..54f99e9ded33 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-dispatch.ts @@ -68,14 +68,16 @@ export async function handleOpenCodeSqliteRequest( dbPaths: request.dbPaths, limit: request.limit ?? Infinity, issues, - scopePaths: request.scopePaths + scopePaths: request.scopePaths, + selectedSessionId: request.selectedSessionId }) : await listOpenCodeSqliteSessions({ dbPaths: request.dbPaths, limit: request.limit ?? Infinity, issues, agent: request.agent === 'zcode' ? 'zcode' : 'opencode', - scopePaths: request.scopePaths + scopePaths: request.scopePaths, + selectedSessionId: request.selectedSessionId }) return { id: request.id, ok: true, value: { candidates, issues } } } diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process-entry.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process-entry.ts index 30be0b2b143d..a2049daf8c86 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process-entry.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process-entry.ts @@ -52,6 +52,8 @@ function validRequest(value: unknown): value is OpenCodeSqliteWorkerRequest { } if (value.kind === 'list') { return ( + (!('selectedSessionId' in value) || + (typeof value.selectedSessionId === 'string' && value.selectedSessionId.length <= 8192)) && 'dbPaths' in value && Array.isArray(value.dbPaths) && value.dbPaths.every((path) => typeof path === 'string') && diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.ts index 5f2f05725cd3..0c70f81b1821 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-client.ts @@ -78,6 +78,7 @@ export class OpenCodeSqliteWorkerClient { limit: number issues: AiVaultScanIssue[] agent?: SqliteReaderAgent + selectedSessionId?: string scopePaths?: readonly string[] signal?: AbortSignal }): Promise { @@ -93,6 +94,7 @@ export class OpenCodeSqliteWorkerClient { dbPaths: args.dbPaths, limit: Number.isFinite(args.limit) ? args.limit : null, ...(args.agent ? { agent: args.agent } : {}), + ...(args.selectedSessionId ? { selectedSessionId: args.selectedSessionId } : {}), ...(args.scopePaths?.length ? { scopePaths: args.scopePaths } : {}) }), LIST_TIMEOUT_MS, diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-protocol.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-protocol.ts index 8c92c6a186f5..d9580960d3ef 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-protocol.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-protocol.ts @@ -20,6 +20,7 @@ export type OpenCodeSqliteListRequest = { dbPaths: readonly string[] limit: number | null agent?: SqliteReaderAgent + selectedSessionId?: string /** Lists only sessions whose directory is in scope (Hermes: the newest plus those in scope); an older reader ignores it and lists unfiltered. */ scopePaths?: readonly string[] } diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts index 5777d086d1a1..6473ae0cdcf1 100644 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts +++ b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts @@ -1,9 +1,10 @@ +import type * as AiVault from '../../../../../shared/ai-vault/contracts/ai-vault-types' +import { selectedWslSqliteSessionId } from '../../../session-scanner-selection' import { aiVaultScopePathsForWslDistro } from '../../../../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import { recordSessionScanIssue, scanIssueTextFromError } from '../../../parsing/session-scan-issues' -import type * as AiVault from '../../../../../shared/ai-vault/contracts/ai-vault-types' import { throwIfSignalAborted } from '../../../../../shared/concurrency/abort-signal-reason' import { openCodeTranscriptPageLimit } from '../../../../../shared/agent-session/lifecycle/provider-handles/opencode-transcript-page-limit' import type { SessionFileCandidate } from '../../../session-scanner-types' @@ -149,6 +150,11 @@ async function listCandidatesForHost( signal, dbPaths: [...paths.keys()], scopePaths, + selectedSessionId: selectedWslSqliteSessionId( + args.selectedSessionId, + args.agent ?? 'opencode', + paths + ), issues }) }, diff --git a/src/main/ai-vault/scanners/opencode/session-scanner-opencode-sources.ts b/src/main/ai-vault/scanners/opencode/session-scanner-opencode-sources.ts index cdfae6fef3ba..dd42e7a07bec 100644 --- a/src/main/ai-vault/scanners/opencode/session-scanner-opencode-sources.ts +++ b/src/main/ai-vault/scanners/opencode/session-scanner-opencode-sources.ts @@ -1,3 +1,4 @@ +import { isSelectedSessionFile } from '../../session-scanner-selection' import { basename, dirname, join } from 'node:path' import type { AiVaultScanIssue } from '../../../../shared/ai-vault/contracts/ai-vault-types' import type { WslTranscriptFsError } from '../../../native-chat/transcript-filesystem/wsl-transcript-fs-error' @@ -35,6 +36,7 @@ export function opencodeDiscoveries( limitPerAgent: limit, issues, scopePaths: options.scopePaths, + selectedSessionId: options.selectedSessionId, statCache: options.statCache, signal: options.signal }) @@ -101,6 +103,7 @@ async function discoverOpenCode2Sessions( limit, issues, scopePaths, + selectedSessionId: options.selectedSessionId, signal: options.signal }).then((candidates) => candidates.map((candidate) => candidate.file)) const [files, scopeFiles] = await Promise.all([ @@ -111,6 +114,9 @@ async function discoverOpenCode2Sessions( agent: 'opencode2' as const, rootDir: storageDir, files, + selectedFiles: files.filter((file) => + isSelectedSessionFile(options.selectedSessionId, 'opencode2', file.path) + ), ...(scopeFiles ? { scopeFiles } : {}) } } diff --git a/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-discovery.ts b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-discovery.ts index c6e398bdfba9..abe57f1c7e51 100644 --- a/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-discovery.ts +++ b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-discovery.ts @@ -1,3 +1,4 @@ +import { isSelectedSessionFile } from '../../../session-scanner-selection' import { basename, extname, join } from 'node:path' import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types' import { discoverFiles } from '../../../discovery/session-scanner-discovery' @@ -20,6 +21,7 @@ export async function discoverOpenCodeSessions(args: { dbPaths: readonly string[] limitPerAgent: number issues: AiVaultScanIssue[] + selectedSessionId?: string scopePaths?: readonly string[] statCache?: AiVaultScanOptions['statCache'] signal?: AbortSignal @@ -31,6 +33,7 @@ export async function discoverOpenCodeSessions(args: { limit: args.limitPerAgent, issues: args.issues, scopePaths, + selectedSessionId: args.selectedSessionId, signal: args.signal }) const [fileDiscovery, sqliteCandidates, sqliteScopeCandidates] = await Promise.all([ @@ -41,6 +44,7 @@ export async function discoverOpenCodeSessions(args: { issues: args.issues, extensions: ['.json'], keepScopeFiles: walksScope, + selectedSessionId: args.selectedSessionId, statCache: args.statCache, signal: args.signal }), @@ -67,6 +71,12 @@ export async function discoverOpenCodeSessions(args: { agent: 'opencode' as const, rootDir: fileDiscovery.rootDir, files: [...withoutSqliteDuplicates(fileDiscovery.files), ...sqliteFiles], + selectedFiles: [ + ...withoutSqliteDuplicates(fileDiscovery.selectedFiles ?? []), + ...sqliteFiles.filter((file) => + isSelectedSessionFile(args.selectedSessionId, 'opencode', file.path) + ) + ], ...(scopeFiles ? { scopeFiles } : {}) } } diff --git a/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-history-recovery.test.ts b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-history-recovery.test.ts new file mode 100644 index 000000000000..71dd740f7eac --- /dev/null +++ b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-history-recovery.test.ts @@ -0,0 +1,463 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import Database from '../../../../sqlite/sync-database' +import { buildOpenCodeSqliteCandidatePath } from '../../../../../shared/agent-session/lifecycle/provider-handles/opencode-sqlite-session-path' +import { listOpenCodeSqliteSessions } from './session-scanner-opencode-sqlite-list' +import { parseOpenCodeSqliteSession } from './session-scanner-opencode-sqlite' +import { captureOpenCodeSqliteSession } from './session-scanner-opencode-sqlite-capture' +import { withFullFirstUserPromptCapture } from '../../../prompts/session-scanner-first-user-prompt-capture' +import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types' + +let tempDirs: string[] = [] + +afterEach(() => { + for (const dir of tempDirs) { + rmSync(dir, { recursive: true, force: true }) + } + tempDirs = [] +}) + +function createTempDb(): { db: Database.Database; path: string } { + const dir = mkdtempSync(join(tmpdir(), 'orca-opencode-sqlite-')) + tempDirs.push(dir) + const path = join(dir, 'opencode.db') + return { db: new Database(path), path } +} + +function applyOpenCodeSchema(db: Database.Database): void { + db.exec(` + CREATE TABLE session ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + parent_id TEXT, + slug TEXT NOT NULL, + directory TEXT NOT NULL, + title TEXT NOT NULL, + version TEXT NOT NULL, + share_url TEXT, + summary_additions INTEGER, + summary_deletions INTEGER, + summary_files INTEGER, + summary_diffs TEXT, + revert TEXT, + permission TEXT, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + time_compacting INTEGER, + time_archived INTEGER, + workspace_id TEXT, + path TEXT, + agent TEXT, + model TEXT, + cost REAL DEFAULT 0 NOT NULL, + tokens_input INTEGER DEFAULT 0 NOT NULL, + tokens_output INTEGER DEFAULT 0 NOT NULL, + tokens_reasoning INTEGER DEFAULT 0 NOT NULL, + tokens_cache_read INTEGER DEFAULT 0 NOT NULL, + tokens_cache_write INTEGER DEFAULT 0 NOT NULL, + metadata TEXT + ); + CREATE TABLE message ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + data TEXT NOT NULL + ); + CREATE TABLE part ( + id TEXT PRIMARY KEY, + message_id TEXT NOT NULL, + session_id TEXT NOT NULL, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + data TEXT NOT NULL + ); + CREATE TABLE project ( + id TEXT PRIMARY KEY, + worktree TEXT NOT NULL, + vcs TEXT, + name TEXT, + icon_url TEXT, + icon_color TEXT, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + time_initialized INTEGER, + sandboxes TEXT NOT NULL, + commands TEXT, + icon_url_override TEXT + ); + `) +} + +function applyMinimalOpenCodeSchema(db: Database.Database): void { + db.exec(`CREATE TABLE session ( + id TEXT PRIMARY KEY, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL + );`) +} + +function insertSession( + db: Database.Database, + args: { + id: string + title?: string + directory?: string + timeCreated: number + timeUpdated: number + parentId?: string | null + timeArchived?: number | null + model?: string | null + agent?: string | null + tokensInput?: number + tokensOutput?: number + tokensReasoning?: number + tokensCacheRead?: number + cost?: number + } +): void { + db.prepare( + `INSERT INTO session (id, project_id, parent_id, slug, directory, title, version, + time_created, time_updated, time_archived, model, agent, cost, + tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write) + VALUES (?, 'proj-1', ?, ?, ?, ?, '1.0.0', + ?, ?, ?, ?, ?, ?, + ?, ?, ?, ?, 0)` + ).run( + args.id, + args.parentId ?? null, + `slug-${args.id}`, + args.directory ?? '/tmp/opencode', + args.title ?? 'OpenCode title', + args.timeCreated, + args.timeUpdated, + args.timeArchived ?? null, + args.model ?? JSON.stringify({ id: 'glm-5.2', providerID: 'zai-coding-plan' }), + args.agent ?? 'build', + args.cost ?? 0, + args.tokensInput ?? 100, + args.tokensOutput ?? 40, + args.tokensReasoning ?? 10, + args.tokensCacheRead ?? 5 + ) +} + +function insertMessage( + db: Database.Database, + args: { + id: string + sessionId: string + role: 'user' | 'assistant' + timeCreated: number + summaryTitle?: string | null + summaryBody?: string | null + } +): void { + const data = JSON.stringify({ + role: args.role, + time: { created: args.timeCreated }, + agent: 'build', + summary: + args.summaryTitle || args.summaryBody + ? { title: args.summaryTitle ?? null, body: args.summaryBody ?? null } + : undefined + }) + db.prepare( + `INSERT INTO message (id, session_id, time_created, time_updated, data) + VALUES (?, ?, ?, ?, ?)` + ).run(args.id, args.sessionId, args.timeCreated, args.timeCreated, data) +} + +function insertPart( + db: Database.Database, + args: { + id: string + messageId: string + sessionId: string + timeCreated: number + type?: 'text' | 'tool' | 'reasoning' + text?: string + } +): void { + const data = JSON.stringify({ + type: args.type ?? 'text', + text: args.text ?? 'hello world' + }) + db.prepare( + `INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) + VALUES (?, ?, ?, ?, ?, ?)` + ).run(args.id, args.messageId, args.sessionId, args.timeCreated, args.timeCreated, data) +} +describe('listOpenCodeSqliteSessions', () => { + it('lists in-scope sessions past a newer out-of-scope one when scoped', async () => { + const { db, path } = createTempDb() + applyOpenCodeSchema(db) + insertSession(db, { + id: 'ses_in_scope', + directory: '/repo/app/packages/web', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_001_000 + }) + insertSession(db, { + id: 'ses_elsewhere', + directory: '/repo/app-sibling', + timeCreated: 1_777_634_002_000, + timeUpdated: 1_777_634_003_000 + }) + db.close() + + const candidates = await listOpenCodeSqliteSessions({ + dbPaths: [path], + limit: 1, + issues: [], + scopePaths: ['/repo/app'] + }) + expect(candidates.map((candidate) => candidate.file.path)).toEqual([ + buildOpenCodeSqliteCandidatePath(path, 'ses_in_scope') + ]) + }) + + it('dedups matching session ids across databases and keeps the newest row', async () => { + const { db: oldDb, path: oldPath } = createTempDb() + applyOpenCodeSchema(oldDb) + insertSession(oldDb, { + id: 'ses_duplicate', + title: 'Old duplicate', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_001_000 + }) + oldDb.close() + + const { db: newDb, path: newPath } = createTempDb() + applyOpenCodeSchema(newDb) + insertSession(newDb, { + id: 'ses_duplicate', + title: 'New duplicate', + timeCreated: 1_777_634_002_000, + timeUpdated: 1_777_634_003_000 + }) + newDb.close() + + const candidates = await listOpenCodeSqliteSessions({ + dbPaths: [oldPath, newPath], + limit: 10, + issues: [] + }) + expect(candidates).toHaveLength(1) + expect(candidates[0].file.path).toBe(buildOpenCodeSqliteCandidatePath(newPath, 'ses_duplicate')) + }) + it('excludes archived and child sessions', async () => { + const { db, path } = createTempDb() + applyOpenCodeSchema(db) + insertSession(db, { + id: 'ses_normal', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_001_000 + }) + insertSession(db, { + id: 'ses_archived', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_002_000, + timeArchived: 1_777_634_002_500 + }) + insertSession(db, { + id: 'ses_child', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_003_000, + parentId: 'ses_normal' + }) + db.close() + + const candidates = await listOpenCodeSqliteSessions({ + dbPaths: [path], + limit: 10, + issues: [] + }) + expect(candidates.map((c) => c.file.path)).toEqual([ + buildOpenCodeSqliteCandidatePath(path, 'ses_normal') + ]) + }) + + it('lists sessions from a minimal readable session table', async () => { + const { db, path } = createTempDb() + applyMinimalOpenCodeSchema(db) + db.prepare(`INSERT INTO session VALUES ('ses_minimal', 1777634000000, 1777634001000)`).run() + db.close() + + const issues: AiVaultScanIssue[] = [] + const candidates = await listOpenCodeSqliteSessions({ + dbPaths: [path], + limit: 10, + issues + }) + expect(issues).toEqual([]) + expect(candidates).toHaveLength(1) + expect(candidates[0].file.path).toBe(buildOpenCodeSqliteCandidatePath(path, 'ses_minimal')) + }) +}) + +describe('parseOpenCodeSqliteSession', () => { + it('parses a minimal readable session table without optional columns or messages', async () => { + const { db, path } = createTempDb() + applyMinimalOpenCodeSchema(db) + db.prepare(`INSERT INTO session VALUES ('ses_minimal', 1777634000000, 1777634001000)`).run() + db.close() + + const session = await parseOpenCodeSqliteSession({ + dbPath: path, + sessionId: 'ses_minimal', + platform: 'darwin' + }) + expect(session).not.toBeNull() + expect(session!.sessionId).toBe('ses_minimal') + expect(session!.filePath).toBe(path) + expect(session!.title).toBe('OpenCode ses_mini') + expect(session!.cwd).toBeNull() + expect(session!.model).toBeNull() + expect(session!.messageCount).toBe(0) + expect(session!.totalTokens).toBe(0) + expect(session!.previewMessages).toEqual([]) + }) + + // Empty successful capture advances the search cursor, so unreadable parts must fail for retry. + it('refuses to capture a transcript it cannot read the message parts of', async () => { + const { db, path } = createTempDb() + applyMinimalOpenCodeSchema(db) + db.prepare(`INSERT INTO session VALUES ('ses_minimal', 1777634000000, 1777634001000)`).run() + db.close() + + await expect( + captureOpenCodeSqliteSession({ dbPath: path, sessionId: 'ses_minimal', platform: 'darwin' }) + ).rejects.toThrow(/unreadable message-part schema/) + }) + + it('captures every text part of the earliest user message and no later turn', async () => { + const { db, path } = createTempDb() + applyOpenCodeSchema(db) + insertSession(db, { + id: 'ses_fp', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_900_000 + }) + insertMessage(db, { + id: 'msg_1', + sessionId: 'ses_fp', + role: 'user', + timeCreated: 1_777_634_000_000 + }) + insertPart(db, { + id: 'part_1a', + messageId: 'msg_1', + sessionId: 'ses_fp', + timeCreated: 10, + text: 'first ask line one' + }) + insertPart(db, { + id: 'part_1b', + messageId: 'msg_1', + sessionId: 'ses_fp', + timeCreated: 20, + text: 'first ask line two' + }) + insertPart(db, { + id: 'part_1c', + messageId: 'msg_1', + sessionId: 'ses_fp', + timeCreated: 30, + type: 'tool', + text: 'tool output blob' + }) + insertMessage(db, { + id: 'msg_2', + sessionId: 'ses_fp', + role: 'user', + timeCreated: 1_777_634_500_000 + }) + insertPart(db, { + id: 'part_2a', + messageId: 'msg_2', + sessionId: 'ses_fp', + timeCreated: 40, + text: 'a later ask' + }) + db.close() + + const session = await withFullFirstUserPromptCapture(() => + parseOpenCodeSqliteSession({ dbPath: path, sessionId: 'ses_fp', platform: 'darwin' }) + ) + + expect(session!.firstUserPrompt).toBe('first ask line one\nfirst ask line two') + }) + + it('skips an earliest user message that has no text parts', async () => { + const { db, path } = createTempDb() + applyOpenCodeSchema(db) + insertSession(db, { + id: 'ses_fp2', + timeCreated: 1_777_634_000_000, + timeUpdated: 1_777_634_900_000 + }) + insertMessage(db, { + id: 'msg_1', + sessionId: 'ses_fp2', + role: 'user', + timeCreated: 1_777_634_000_000 + }) + insertPart(db, { + id: 'part_1a', + messageId: 'msg_1', + sessionId: 'ses_fp2', + timeCreated: 10, + type: 'tool', + text: 'tool only' + }) + insertMessage(db, { + id: 'msg_2', + sessionId: 'ses_fp2', + role: 'user', + timeCreated: 1_777_634_500_000 + }) + insertPart(db, { + id: 'part_2a', + messageId: 'msg_2', + sessionId: 'ses_fp2', + timeCreated: 40, + text: 'the real typed ask' + }) + db.close() + + const session = await withFullFirstUserPromptCapture(() => + parseOpenCodeSqliteSession({ dbPath: path, sessionId: 'ses_fp2', platform: 'darwin' }) + ) + + expect(session!.firstUserPrompt).toBe('the real typed ask') + }) +}) + +it('adds only the exact selected SQLite identity beyond the recent cap', async () => { + const { db, path } = createTempDb() + applyMinimalOpenCodeSchema(db) + db.prepare('INSERT INTO session VALUES (?, ?, ?)').run('old', 1, 1) + db.prepare('INSERT INTO session VALUES (?, ?, ?)').run('new', 2, 2) + db.close() + const selectedSessionId = `local:opencode:old:${buildOpenCodeSqliteCandidatePath(path, 'old')}` + const listed = await listOpenCodeSqliteSessions({ + dbPaths: [path], + limit: 1, + issues: [], + selectedSessionId + }) + expect(listed.map((candidate) => candidate.file.path)).toEqual([ + buildOpenCodeSqliteCandidatePath(path, 'new'), + buildOpenCodeSqliteCandidatePath(path, 'old') + ]) + const foreign = await listOpenCodeSqliteSessions({ + dbPaths: [path], + limit: 1, + issues: [], + selectedSessionId: selectedSessionId.replace('local:', 'runtime:other:') + }) + expect(foreign).toHaveLength(1) +}) diff --git a/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list.ts b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list.ts index cf6b2237d238..473129ae5420 100644 --- a/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list.ts +++ b/src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list.ts @@ -1,3 +1,4 @@ +import { selectedSqliteSessionId } from '../../../session-scanner-selection' import type { AiVaultScanIssue } from '../../../../../shared/ai-vault/contracts/ai-vault-types' import { buildOpenCodeSqliteCandidatePath, @@ -27,7 +28,12 @@ function canReadOpenCodeSessions(db: SyncDatabase): boolean { ) } -function buildSessionListQuery(db: SyncDatabase, limited: boolean, scoped: boolean): string { +function buildSessionListQuery( + db: SyncDatabase, + limited: boolean, + scoped: boolean, + selected = false +): string { const parentIdPredicate = columnExists(db, 'session', 'parent_id') ? 'AND parent_id IS NULL' : '' const archivedPredicate = columnExists(db, 'session', 'time_archived') ? 'AND time_archived IS NULL' @@ -37,7 +43,7 @@ function buildSessionListQuery(db: SyncDatabase, limited: boolean, scoped: boole const directory = scoped && columnExists(db, 'session', 'directory') ? ', directory' : '' return `SELECT id, time_created, time_updated${directory} FROM session - WHERE 1=1 ${parentIdPredicate} ${archivedPredicate} + WHERE 1=1 ${parentIdPredicate} ${archivedPredicate} ${selected ? 'AND id = ?' : ''} ORDER BY CASE WHEN time_updated > 0 THEN time_updated ELSE time_created END DESC ${limited ? 'LIMIT ?' : ''}` } @@ -46,17 +52,20 @@ function readSessionRows( db: SyncDatabase, limit: number, scopePaths: readonly string[] | undefined, - dbPath: string + dbPath: string, + selectedSessionId?: string ): SessionRow[] { if (!canReadOpenCodeSessions(db)) { return [] } - const scoped = scopePaths !== undefined && scopePaths.length > 0 - const limited = Number.isFinite(limit) && !scoped - const statement = db.prepare(buildSessionListQuery(db, limited, scoped)) + const selected = selectedSessionId !== undefined + const scoped = !selected && scopePaths !== undefined && scopePaths.length > 0 + const limited = !selected && Number.isFinite(limit) && !scoped + const statement = db.prepare(buildSessionListQuery(db, limited, scoped, selected)) + const parameters = selected ? [selectedSessionId] : limited ? [limit] : [] // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query above selects exactly these columns. const rows = ( - limited ? statement.all(limit) : scoped ? statement.iterate() : statement.all() + scoped ? statement.iterate(...parameters) : statement.all(...parameters) ) as Iterable return scoped && scopePaths ? scopedSessionRows(rows, scopePaths, limit, dbPath) @@ -109,6 +118,7 @@ export async function listOpenCodeSqliteSessions(args: { limit: number issues: AiVaultScanIssue[] agent?: 'opencode' | 'zcode' + selectedSessionId?: string /** Lists only sessions whose directory is in scope, newest `limit` of them. */ scopePaths?: readonly string[] }): Promise { @@ -118,7 +128,26 @@ export async function listOpenCodeSqliteSessions(args: { try { const rows = readOpenCodeDatabase({ dbPath, - read: (db) => readSessionRows(db, args.limit, args.scopePaths, dbPath) + read: (db) => { + const rows = readSessionRows(db, args.limit, args.scopePaths, dbPath) + const selected = selectedSqliteSessionId(args.selectedSessionId, agent, dbPath) + if (selected && !rows.some((row) => row.id === selected)) { + const row = readSessionRows(db, 1, undefined, dbPath, selected)[0] + if ( + row && + typeof row.id === 'string' && + typeof row.time_created === 'number' && + typeof row.time_updated === 'number' + ) { + rows.push({ + id: row.id, + time_created: row.time_created, + time_updated: row.time_updated + }) + } + } + return rows + } }) for (const row of rows) { candidates.push(rowToCandidate(row, dbPath, agent)) diff --git a/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-history-recovery.test.ts b/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-history-recovery.test.ts new file mode 100644 index 000000000000..1ab9f99f5b7f --- /dev/null +++ b/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-history-recovery.test.ts @@ -0,0 +1,182 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import Database from '../../../sqlite/sync-database' +import { buildOpenCodeSqliteCandidatePath } from '../../../../shared/agent-session/lifecycle/provider-handles/opencode-sqlite-session-path' +import { listOpenCode2SqliteSessions } from './session-scanner-opencode2-sqlite-list' + +import { + parseOpenCode2SqliteSession, + captureOpenCode2SqliteSession +} from './session-scanner-opencode2-sqlite' + +let tempDirs: string[] = [] + +afterEach(() => { + for (const dir of tempDirs) { + rmSync(dir, { recursive: true, force: true }) + } + tempDirs = [] +}) + +function createTempDb(name = 'opencode-next.db'): { db: Database.Database; path: string } { + const dir = mkdtempSync(join(tmpdir(), 'orca-opencode2-sqlite-')) + tempDirs.push(dir) + const path = join(dir, name) + return { db: new Database(path), path } +} + +function applyOpenCode2Schema(db: Database.Database): void { + db.exec(` + CREATE TABLE session_v2 ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL, + workspace_id TEXT, + parent_id TEXT, + fork_session_id TEXT, + fork_boundary TEXT, + slug TEXT NOT NULL, + directory TEXT NOT NULL, + path TEXT, + title TEXT, + version TEXT NOT NULL, + share_url TEXT, + cost REAL DEFAULT 0 NOT NULL, + tokens_input INTEGER DEFAULT 0 NOT NULL, + tokens_output INTEGER DEFAULT 0 NOT NULL, + tokens_reasoning INTEGER DEFAULT 0 NOT NULL, + tokens_cache_read INTEGER DEFAULT 0 NOT NULL, + tokens_cache_write INTEGER DEFAULT 0 NOT NULL, + agent TEXT, + model TEXT, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + time_compacting INTEGER, + time_archived INTEGER + ); + CREATE TABLE session_message ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + type TEXT NOT NULL, + seq INTEGER NOT NULL, + time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, + data TEXT NOT NULL + ); + `) +} + +function insertSession( + db: Database.Database, + session: { + id: string + directory: string + title?: string | null + timeCreated: number + timeUpdated: number + parentId?: string | null + timeArchived?: number | null + } +): void { + db.prepare( + `INSERT INTO session_v2 + (id, project_id, parent_id, slug, directory, title, version, model, agent, time_created, time_updated, time_archived) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` + ).run( + session.id, + 'project_1', + session.parentId ?? null, + 'slug', + session.directory, + session.title ?? null, + '0.0.0-next-1', + null, + null, + session.timeCreated, + session.timeUpdated, + session.timeArchived ?? null + ) +} + +function insertMessage( + db: Database.Database, + message: { + id: string + sessionId: string + type: string + seq: number + timeCreated: number + data: string + } +): void { + db.prepare( + `INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) + VALUES (?, ?, ?, ?, ?, ?, ?)` + ).run( + message.id, + message.sessionId, + message.type, + message.seq, + message.timeCreated, + message.timeCreated, + message.data + ) +} + +it('captures the full transcript while keeping list previews bounded', async () => { + const { db, path } = createTempDb('opencode.db') + applyOpenCode2Schema(db) + insertSession(db, { id: 'long', directory: '/repo', timeCreated: 1000, timeUpdated: 9000 }) + for (let index = 0; index < 8; index++) { + insertMessage(db, { + id: `message_${index}`, + sessionId: 'long', + type: 'user', + seq: index, + timeCreated: 1000 + index, + data: JSON.stringify({ text: `Turn ${index}` }) + }) + } + db.close() + const args = { dbPath: path, sessionId: 'long', platform: 'darwin' as const } + const preview = await parseOpenCode2SqliteSession(args) + const capture = await captureOpenCode2SqliteSession(args) + expect(preview?.previewMessages).toHaveLength(5) + expect(capture.messages.map((message) => message.text)).toEqual( + Array.from({ length: 8 }, (_, index) => `Turn ${index}`) + ) +}) + +it('keeps one selected v2 identity beyond recency while preserving archive exclusions', async () => { + const { db, path } = createTempDb() + applyOpenCode2Schema(db) + insertSession(db, { id: 'old', directory: '/old', timeCreated: 1, timeUpdated: 1 }) + insertSession(db, { id: 'new', directory: '/new', timeCreated: 2, timeUpdated: 2 }) + insertSession(db, { + id: 'archived', + directory: '/old', + timeCreated: 1, + timeUpdated: 1, + timeArchived: 3 + }) + db.close() + const selectedSessionId = `local:opencode2:old:${buildOpenCodeSqliteCandidatePath(path, 'old')}` + const listed = await listOpenCode2SqliteSessions({ + dbPaths: [path], + limit: 1, + issues: [], + selectedSessionId + }) + expect(listed.map((candidate) => candidate.file.path)).toEqual([ + buildOpenCodeSqliteCandidatePath(path, 'new'), + buildOpenCodeSqliteCandidatePath(path, 'old') + ]) + const archived = await listOpenCode2SqliteSessions({ + dbPaths: [path], + limit: 1, + issues: [], + selectedSessionId: selectedSessionId.replaceAll('old', 'archived') + }) + expect(archived).toHaveLength(1) +}) diff --git a/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list.ts b/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list.ts index 20fccadd7e32..9c96b795edd4 100644 --- a/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list.ts +++ b/src/main/ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list.ts @@ -1,3 +1,4 @@ +import { selectedSqliteSessionId } from '../../session-scanner-selection' import type { AiVaultScanIssue } from '../../../../shared/ai-vault/contracts/ai-vault-types' import { buildOpenCodeSqliteCandidatePath, @@ -34,7 +35,12 @@ function canReadOpenCode2Sessions(db: SyncDatabase): boolean { ) } -function buildSessionListQuery(db: SyncDatabase, limited: boolean, scoped: boolean): string { +function buildSessionListQuery( + db: SyncDatabase, + limited: boolean, + scoped: boolean, + selected = false +): string { const parentIdPredicate = columnExists(db, OPENCODE2_SESSION_TABLE, 'parent_id') ? 'AND parent_id IS NULL' : '' @@ -46,11 +52,32 @@ function buildSessionListQuery(db: SyncDatabase, limited: boolean, scoped: boole scoped && columnExists(db, OPENCODE2_SESSION_TABLE, 'directory') ? ', directory' : '' return `SELECT id, time_created, time_updated${directory} FROM ${OPENCODE2_SESSION_TABLE} - WHERE 1=1 ${parentIdPredicate} ${archivedPredicate} + WHERE 1=1 ${parentIdPredicate} ${archivedPredicate} ${selected ? 'AND id = ?' : ''} ORDER BY CASE WHEN time_updated > 0 THEN time_updated ELSE time_created END DESC ${limited ? 'LIMIT ?' : ''}` } +function readSessionRows( + db: SyncDatabase, + limit: number, + scopePaths: readonly string[] | undefined, + dbPath: string, + selectedSessionId?: string +): SessionRow[] { + const selected = selectedSessionId !== undefined + const scoped = !selected && scopePaths !== undefined && scopePaths.length > 0 + const limited = !selected && Number.isFinite(limit) && !scoped + const statement = db.prepare(buildSessionListQuery(db, limited, scoped, selected)) + const parameters = selected ? [selectedSessionId] : limited ? [limit] : [] + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query above selects exactly these metadata columns. + const rows = ( + scoped ? statement.iterate(...parameters) : statement.all(...parameters) + ) as Iterable + return scoped && scopePaths + ? scopedSessionRows(rows, scopePaths, limit, dbPath) + : Array.from(rows) +} + function rowToCandidate(row: SessionRow, dbPath: string): SessionFileCandidate { const mtimeMs = typeof row.time_updated === 'number' && row.time_updated > 0 @@ -89,11 +116,11 @@ export async function listOpenCode2SqliteSessions(args: { dbPaths: readonly string[] limit: number issues: AiVaultScanIssue[] + selectedSessionId?: string /** Lists only sessions whose directory is in scope, newest `limit` of them. */ scopePaths?: readonly string[] }): Promise { const candidates: SessionFileCandidate[] = [] - const scoped = args.scopePaths !== undefined && args.scopePaths.length > 0 for (const dbPath of args.dbPaths) { let db: SyncDatabase | null = null try { @@ -101,16 +128,28 @@ export async function listOpenCode2SqliteSessions(args: { if (!canReadOpenCode2Sessions(db)) { continue } - const limited = Number.isFinite(args.limit) && !scoped - const statement = db.prepare(buildSessionListQuery(db, limited, scoped)) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the query above selects exactly these metadata columns. - const listed = ( - limited ? statement.all(args.limit) : scoped ? statement.iterate() : statement.all() - ) as Iterable - const rows = - scoped && args.scopePaths - ? scopedSessionRows(listed, args.scopePaths, args.limit, dbPath) - : listed + const rows = readSessionRows(db, args.limit, args.scopePaths, dbPath) + const selected = selectedSqliteSessionId(args.selectedSessionId, 'opencode2', dbPath) + const selectedRow = selected + ? readSessionRows(db, 1, undefined, dbPath, selected)[0] + : undefined + if ( + selectedRow && + typeof selectedRow.id === 'string' && + typeof selectedRow.time_created === 'number' && + typeof selectedRow.time_updated === 'number' + ) { + candidates.push( + rowToCandidate( + { + id: selectedRow.id, + time_created: selectedRow.time_created, + time_updated: selectedRow.time_updated + }, + dbPath + ) + ) + } for (const row of rows) { candidates.push(rowToCandidate(row, dbPath)) } diff --git a/src/main/ai-vault/scanners/zcode/session-scanner-zcode-sources.ts b/src/main/ai-vault/scanners/zcode/session-scanner-zcode-sources.ts index 2943c6299039..49a519ca5cb2 100644 --- a/src/main/ai-vault/scanners/zcode/session-scanner-zcode-sources.ts +++ b/src/main/ai-vault/scanners/zcode/session-scanner-zcode-sources.ts @@ -1,3 +1,4 @@ +import { isSelectedSessionFile } from '../../session-scanner-selection' import { homedir } from 'node:os' import { join } from 'node:path' import type { AiVaultScanIssue } from '../../../../shared/ai-vault/contracts/ai-vault-types' @@ -28,6 +29,7 @@ export function zcodeDiscoveries( limit, issues, scopePaths, + selectedSessionId: options.selectedSessionId, signal: options.signal }).then((candidates) => candidates.map((candidate) => candidate.file)) const [files, scopeFiles] = await Promise.all([ @@ -38,6 +40,9 @@ export function zcodeDiscoveries( agent: 'zcode' as const, rootDir: dbPath, files, + selectedFiles: files.filter((file) => + isSelectedSessionFile(options.selectedSessionId, 'zcode', file.path) + ), ...(scopeFiles ? { scopeFiles } : {}) } }) diff --git a/src/main/ai-vault/session-scanner-claude-conversation-content.test.ts b/src/main/ai-vault/session-scanner-claude-conversation-content.test.ts new file mode 100644 index 000000000000..cb9b3ec761d6 --- /dev/null +++ b/src/main/ai-vault/session-scanner-claude-conversation-content.test.ts @@ -0,0 +1,143 @@ +import { appendFile, mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { projectConversations } from '../../shared/project-conversation-list' +import { scanAiVaultSessions } from './session-scanner' +import { MAX_SESSION_TRANSCRIPT_RECORD_BYTES } from './transcripts/session-transcript-record-budget' +import { isolatedScanRoots, writeJsonlFile } from './scanner-fixtures/session-scanner-test-fixtures' + +const roots: string[] = [] +const caveat = 'Local command output follows' +const preferences = { revision: 0, entries: {} } + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +async function history() { + const root = await mkdtemp(join(tmpdir(), 'orca-native-claude-content-')) + roots.push(root) + const options = { ...isolatedScanRoots(root), claudeProfileProjectsDirs: [] } + return { + options, + file: (id: string) => join(options.claudeProjectsDir, 'project', `${id}.jsonl`) + } +} + +function user(sessionId: string, content: unknown) { + return { + type: 'user', + sessionId, + cwd: '/notes', + timestamp: '2026-10-01T10:00:00.000Z', + message: { role: 'user', content } + } +} + +describe('native Claude conversation content evidence', () => { + it('keeps command transcripts readable without creating a placeholder Projects chat', async () => { + const { options, file } = await history() + await writeJsonlFile(file('command-only'), [ + { type: 'mode', sessionId: 'command-only', mode: 'default' }, + { type: 'permission-mode', sessionId: 'command-only', permissionMode: 'default' }, + user('command-only', caveat), + user('command-only', '/exit'), + user('command-only', 'See you') + ]) + + const result = await scanAiVaultSessions(options) + + expect(result.issues).toEqual([]) + expect(result.sessions).toHaveLength(1) + expect(result.sessions[0]).toMatchObject({ + title: 'Claude command-', + conversationContent: 'empty', + messageCount: 3, + previewMessages: expect.arrayContaining([expect.objectContaining({ text: caveat })]) + }) + expect(projectConversations(result.sessions, preferences)).toEqual([]) + + await appendFile( + file('command-only'), + `${JSON.stringify(user('command-only', 'Repair the reader'))}\n` + ) + const updated = await scanAiVaultSessions(options) + expect(updated.sessions[0]).toMatchObject({ + id: result.sessions[0]?.id, + title: 'Repair the reader', + conversationContent: 'present', + messageCount: 4 + }) + expect(projectConversations(updated.sessions, preferences)).toHaveLength(1) + }) + + it('retains queued, non-text, unknown and corrupt provider history', async () => { + const { options, file } = await history() + await writeJsonlFile(file('queued'), [ + { type: 'queue-operation', operation: 'enqueue', sessionId: 'queued', content: 'Recover me' } + ]) + await writeJsonlFile(file('non-text'), [ + user('non-text', [{ type: 'image', source: { type: 'base64', data: 'aGVsbG8=' } }]) + ]) + await writeJsonlFile(file('tool-result'), [ + user('tool-result', [{ type: 'tool_result', content: 'Tool output cannot name a chat' }]) + ]) + await writeJsonlFile(file('unknown'), [ + { type: 'future-provider-record', sessionId: 'unknown' } + ]) + await writeJsonlFile(file('corrupt'), [user('corrupt', caveat)]) + await appendFile(file('corrupt'), '{incomplete provider record\n') + + const result = await scanAiVaultSessions(options) + const content = new Map( + result.sessions.map((session) => [session.sessionId, session.conversationContent]) + ) + + expect(result.issues).toEqual([]) + expect(content.get('queued')).toBe('present') + expect(content.get('non-text')).toBe('present') + expect(result.sessions.find((session) => session.sessionId === 'tool-result')?.title).toBe( + 'Claude tool-res' + ) + expect(content.get('unknown')).toBe('unknown') + expect(content.get('corrupt')).toBe('unknown') + expect(projectConversations(result.sessions, preferences)).toHaveLength(5) + }) + + it('keeps readable bounded history without warnings or calling the transcript empty', async () => { + const { options, file } = await history() + await writeJsonlFile(file('oversized'), [user('oversized', caveat)]) + await appendFile(file('oversized'), `${'x'.repeat(MAX_SESSION_TRANSCRIPT_RECORD_BYTES + 1)}\n`) + + const result = await scanAiVaultSessions(options) + + expect(result.issues).toEqual([]) + expect(result.sessions[0]?.conversationContent).toBe('unknown') + expect(projectConversations(result.sessions, preferences)).toHaveLength(1) + await appendFile(file('oversized'), `${JSON.stringify(user('oversized', caveat))}\n`) + const updated = await scanAiVaultSessions(options) + expect(updated.sessions[0]?.conversationContent).toBe('unknown') + }) + + it('recovers late child transcripts even when cached command records count as turns', async () => { + const { options, file } = await history() + await writeJsonlFile(file('late-child'), [user('late-child', caveat)]) + const first = await scanAiVaultSessions(options) + expect(first.sessions[0]?.conversationContent).toBe('empty') + + await writeJsonlFile( + join(options.claudeProjectsDir, 'project', 'late-child', 'subagents', 'agent-late.jsonl'), + [user('child', 'Recover this work')] + ) + const second = await scanAiVaultSessions(options) + + expect(second.sessions[0]).toMatchObject({ + id: first.sessions[0]?.id, + messageCount: 1, + subagentTranscriptCount: 1, + conversationContent: 'present' + }) + expect(projectConversations(second.sessions, preferences)).toHaveLength(1) + }) +}) diff --git a/src/main/ai-vault/session-scanner-selected-session.test.ts b/src/main/ai-vault/session-scanner-selected-session.test.ts new file mode 100644 index 000000000000..d21beec31a43 --- /dev/null +++ b/src/main/ai-vault/session-scanner-selected-session.test.ts @@ -0,0 +1,49 @@ +import { mkdtemp, rm, utimes } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots, writeJsonlFile } from './scanner-fixtures/session-scanner-test-fixtures' + +it('retains one exact old selected transcript beyond 500 newer discoveries without widening history', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-selected-history-')) + try { + const roots = isolatedScanRoots(root) + const selectedPath = join(roots.claudeProjectsDir, 'old.jsonl') + await writeJsonlFile(selectedPath, [ + { + type: 'user', + sessionId: 'old', + message: { role: 'user', content: 'Old selected conversation' } + } + ]) + await utimes(selectedPath, new Date('2025-01-01'), new Date('2025-01-01')) + await Promise.all( + Array.from({ length: 501 }, async (_, index) => { + const path = join(roots.claudeProjectsDir, `new-${index}.jsonl`) + await writeJsonlFile(path, [ + { + type: 'user', + sessionId: `new-${index}`, + message: { role: 'user', content: 'New conversation' } + } + ]) + }) + ) + const selectedSessionId = `local:claude:old:${selectedPath}` + const options = { ...roots, limit: 500, limitPerAgent: 500 } + const normal = await scanAiVaultSessions(options) + expect(normal.sessions).toHaveLength(500) + expect(normal.sessions.some((session) => session.id === selectedSessionId)).toBe(false) + const selected = await scanAiVaultSessions({ ...options, selectedSessionId }) + expect(selected.sessions).toHaveLength(501) + expect(selected.sessions.filter((session) => session.id === selectedSessionId)).toHaveLength(1) + const wrongIdentity = await scanAiVaultSessions({ + ...options, + selectedSessionId: `local:claude:wrong:${selectedPath}` + }) + expect(wrongIdentity.sessions).toHaveLength(500) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/main/ai-vault/session-scanner-selection.ts b/src/main/ai-vault/session-scanner-selection.ts new file mode 100644 index 000000000000..ad71bfe7057d --- /dev/null +++ b/src/main/ai-vault/session-scanner-selection.ts @@ -0,0 +1,47 @@ +import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host/execution-host' +import { buildOpenCodeSqliteCandidatePath } from '../../shared/agent-session/lifecycle/provider-handles/opencode-sqlite-session-path' + +export function isSelectedSessionFile( + selectedSessionId: string | undefined, + agent: AiVaultAgent, + filePath: string, + executionHostId: string = LOCAL_EXECUTION_HOST_ID +): boolean { + return Boolean( + selectedSessionId?.startsWith(`${executionHostId}:${agent}:`) && + selectedSessionId.endsWith(`:${filePath}`) + ) +} + +export function selectedSqliteSessionId( + selectedSessionId: string | undefined, + agent: AiVaultAgent, + dbPath: string +): string | undefined { + if (!selectedSessionId) { + return undefined + } + const prefix = `${LOCAL_EXECUTION_HOST_ID}:${agent}:` + const pathStart = selectedSessionId.lastIndexOf(`:${dbPath}#`) + const sessionId = selectedSessionId.slice(prefix.length, pathStart) + return sessionId && + selectedSessionId === + `${prefix}${sessionId}:${buildOpenCodeSqliteCandidatePath(dbPath, sessionId)}` + ? sessionId + : undefined +} + +export function selectedWslSqliteSessionId( + selectedSessionId: string | undefined, + agent: AiVaultAgent, + paths: ReadonlyMap +): string | undefined { + for (const [linuxPath, original] of paths) { + const sessionId = selectedSqliteSessionId(selectedSessionId, agent, original) + if (sessionId) { + return `local:${agent}:${sessionId}:${buildOpenCodeSqliteCandidatePath(linuxPath, sessionId)}` + } + } + return undefined +} diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index cbe679cfd704..d7b23030e53e 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -65,6 +65,7 @@ export type AiVaultScanOptions = { limit?: number unlimited?: boolean limitPerAgent?: number + selectedSessionId?: string // Include sessions for these workspace paths beyond the recency cap (AI_VAULT_SCOPE_CWD_SOURCES). scopePaths?: readonly string[] // Return only scopePaths sessions, skipping the global recency pass (Workspace and Project). @@ -115,6 +116,7 @@ export type SessionFileDiscovery = { agent: AiVaultAgent rootDir: string files: FileWithMtime[] + selectedFiles?: FileWithMtime[] // Discovered beyond `files`, kept only for a scoped scan's in-scope walk. scopeFiles?: FileWithMtime[] // Conversation folder -> one top-level artifact file, seen while walking Antigravity brains. diff --git a/src/main/ai-vault/session-scanner.ts b/src/main/ai-vault/session-scanner.ts index 065370d3a90b..2210bfcd941a 100644 --- a/src/main/ai-vault/session-scanner.ts +++ b/src/main/ai-vault/session-scanner.ts @@ -11,7 +11,10 @@ import { createAntigravityWorkspaceResolver, readLocalAntigravityHistory } from './scanners/antigravity/session-scanner-antigravity-history' -import { sessionCandidatesFromDiscoveries } from './discovery/session-scanner-candidates' +import { + discoveryFileCandidates, + sessionCandidatesFromDiscoveries +} from './discovery/session-scanner-candidates' import { parseSessionCandidates } from './parsing/session-scanner-candidate-parse' import { createSessionParseStats } from './parse-cache/session-scanner-parse-cache' import { recordSessionScanIssue } from './parsing/session-scan-issues' @@ -111,6 +114,25 @@ async function scanAiVaultSessionStores(options: AiVaultScanOptions): Promise aiVaultSessionInScope(inScope, session)) : recentSessions.slice(0, limit) + const selectedSessions = + options.selectedSessionId && + !cappedSessions.some((session) => session.id === options.selectedSessionId) + ? await parseSessionCandidates({ + candidates: discoveries + .flatMap((discovery) => + discoveryFileCandidates(discovery, discovery.selectedFiles ?? [], options) + ) + .slice(0, 1), + limit: 1, + platform, + executionHostId, + issues, + parseStats, + signal: options.signal, + antigravityWorkspaceResolver, + admitSession: (session) => session.id === options.selectedSessionId + }) + : [] const scopeSessions = await scanInScopeSessions({ inventory, discoveries, @@ -146,7 +168,7 @@ async function scanAiVaultSessionStores(options: AiVaultScanOptions): Promise ({ executionHostId, ...issue })), diff --git a/src/main/ai-vault/structured-conversation-journal-preview.ts b/src/main/ai-vault/structured-conversation-journal-preview.ts new file mode 100644 index 000000000000..5fd6ebece18c --- /dev/null +++ b/src/main/ai-vault/structured-conversation-journal-preview.ts @@ -0,0 +1,34 @@ +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AiVaultSession } from '../../shared/ai-vault/contracts/ai-vault-types' +import { mapWithConcurrency } from '../../shared/concurrency/map-with-concurrency' +import type { JournalSqlDatabase } from '../native-chat/agent-session-journal/database/journal-sql-database' + +export type StructuredConversationJournalPreview = { + conversationContent: NonNullable + firstUserPrompt?: string +} + +export async function readStructuredConversationJournalPreviews( + database: { readers: Pick } | undefined, + records: readonly AgentSessionRecord[] +): Promise> { + if (!database) { + return new Map() + } + const entries = await mapWithConcurrency(records, 4, async (record) => { + let preview: StructuredConversationJournalPreview = { conversationContent: 'unknown' } + try { + const result = await database.readers.point({ + sessionId: record.sessionId, + operation: { kind: 'conversation-preview', workspaceId: record.location.workspaceId } + }) + if (result.kind === 'conversation-preview') { + preview = result.preview + } + } catch { + // Unavailable history must remain discoverable. + } + return [record.sessionId, preview] as const + }) + return new Map(entries) +} diff --git a/src/main/ai-vault/structured-conversation-navigation-content.test.ts b/src/main/ai-vault/structured-conversation-navigation-content.test.ts new file mode 100644 index 000000000000..6cae24876273 --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation-content.test.ts @@ -0,0 +1,247 @@ +import { readStructuredConversationJournalPreviews } from './structured-conversation-journal-preview' +import { migrateJournalDomainSchema } from '../native-chat/agent-session-journal/journal-domain-schema' +import { prepareJournalDomainImport } from '../native-chat/agent-session-journal/journal-domain-import' +import { + insertJournalDomainImportPage, + finishJournalDomainImport +} from '../native-chat/agent-session-journal/journal-domain-import-rows' +import { readJournalSqlPoint } from '../native-chat/agent-session-journal/journal-sql-point-read' +import { + openJournalDatabase, + runJournalTransaction +} from '../native-chat/agent-session-journal/database/journal-database' +import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { agentSessionRecordFixture } from '../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AiVaultListResult } from '../../shared/ai-vault/contracts/ai-vault-types' +import type { AgentJournalMessageItem } from '../../shared/agent-session/journal/agent-session-journal-types' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { AgentSessionConversationKeys } from '../runtime/agent-session/records/agent-session-conversation-key-index' +import { + insertJournalRow, + publishJournalSessionEpoch +} from '../native-chat/agent-session-journal/durable-rows/journal-row-table' +import type { JournalRow } from '../native-chat/agent-session-journal/durable-rows/journal-row-schema' +import Database from '../sqlite/sync-database' +import { + projectStructuredAiVaultSessions, + OPENS_EVERY_STRUCTURED_CHAT +} from './structured-sessions/structured-session-ownership' +import { listResult } from './structured-sessions/structured-session-ownership.test-support' +import { parseAiVaultListResult } from './listing/session-list-result-validation' + +const EMPTY: AiVaultListResult = { sessions: [], issues: [], scannedAt: '2026-10-26T00:00:00Z' } +const EPOCH = 'epoch-1' +let db: Database.Database +let record: AgentSessionRecord + +beforeEach(() => { + db = openJournalDatabase(':memory:').db + record = agentSessionRecordFixture() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: projection reads only this host's catalog and journal database. + setStructuredAgentSessionHost({ + deps: { + store: { + getRecord: () => record, + listRecords: () => [record], + listConversations: () => [agentSessionConversationView(record)], + conversationsKeyedBy: (keys: AgentSessionConversationKeys, key: string) => + [agentSessionConversationView(record)].filter((view) => keys(view).includes(key)) + }, + journalDatabase: { db } + } + } as never) +}) +afterEach(() => { + setStructuredAgentSessionHost(null) + db.close() +}) + +function base(seq: number) { + return { v: 2, epoch: EPOCH, seq, fence: 1, ts: 1000 + seq } +} +function register(reason: 'session_created' | 'legacy_import' = 'session_created') { + publishJournalSessionEpoch( + db, + { sessionId: record.sessionId, workspaceId: record.location.workspaceId }, + EPOCH + ) + insertJournalRow(db, record.sessionId, { + ...base(1), + kind: 'epoch', + reason, + providerHandle: { kind: 'opaque', agent: 'claude', value: 'pending' } + }) +} +function item( + seq: number, + text: string, + body: Partial = {}, + linkage = {} +) { + insertJournalRow(db, record.sessionId, { + ...base(seq), + kind: 'item', + itemId: `message-${seq}`, + revision: 1, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }], ...body }, + ...linkage + }) +} +async function project(result = EMPTY) { + const domain = new Database(':memory:') + migrateJournalDomainSchema(domain) + try { + const journalPreviews = await readStructuredConversationJournalPreviews( + { + readers: { + point: async (request) => { + const prepared = prepareJournalDomainImport(db, record.sessionId) + if (prepared) { + runJournalTransaction(domain, () => { + for (const page of prepared.pages) { + insertJournalDomainImportPage(domain, prepared, page) + } + finishJournalDomainImport(domain, prepared) + }) + } + return readJournalSqlPoint(domain, request) + } + } + }, + [record] + ) + return projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true, + journalPreviews + }) + } finally { + domain.close() + } +} +function providerRow(title: string, messageCount = 1) { + return { + ...listResult().sessions[0]!, + agent: 'claude' as const, + sessionId: 'provider-session-alpha-1', + title, + messageCount + } +} + +describe('durable conversation names and bounded content evidence', async () => { + it('preserves a meaningful provider title through ownership and durable projection, then prefers a saved name', async () => { + const input = { ...EMPTY, sessions: [providerRow('Investigate the deployment failure')] } + expect((await project(input)).sessions[0]?.title).toBe('Investigate the deployment failure') + record.conversationName = 'My saved name' + expect((await project(input)).sessions[0]?.title).toBe('My saved name') + }) + + it('marks only a registered, intact creation epoch empty, including a saved default label', async () => { + record.conversationName = 'Claude Chat' + expect((await project()).sessions[0]).toMatchObject({ + conversationContent: 'unknown', + title: 'Claude Chat' + }) + register() + const result = await project() + expect(result.sessions[0]).toMatchObject({ conversationContent: 'empty', title: 'Claude Chat' }) + expect(parseAiVaultListResult(result).sessions[0]?.conversationContent).toBe('empty') + }) + + it('derives the first human prompt from the journal while skipping commands, agent mail and child messages', async () => { + register() + item(2, 'Mailbox notification', { from: { kind: 'agent', senders: [], orchestration: null } }) + item(3, '/compact', { command: { name: 'compact' } }) + item(4, 'Child task', {}, { agentId: 'child' }) + item(5, 'Проверь настройки проекта') + item(6, 'Assistant reply', { role: 'assistant' }) + expect((await project()).sessions[0]).toMatchObject({ + conversationContent: 'present', + firstUserPrompt: 'Проверь настройки проекта', + title: 'Проверь настройки проекта' + }) + record.conversationName = 'Saved title' + expect((await project()).sessions[0]?.title).toBe('Saved title') + }) + + it('does not mark provider conversation or queued recovery evidence empty even if the local epoch has no messages', async () => { + register() + for (const session of [ + providerRow('Provider conversation'), + { ...providerRow('Queued message', 0), queuedMessageCount: 2 } + ]) { + expect( + (await project({ ...EMPTY, sessions: [session] })).sessions[0]?.conversationContent + ).toBe('present') + } + }) + + it('does not let an empty local epoch erase uncertain provider-file history', async () => { + register() + expect( + (await project({ ...EMPTY, sessions: [providerRow('Claude Chat', 0)] })).sessions[0] + ?.conversationContent + ).toBe('unknown') + }) + + it('keeps an intact creation epoch empty when native turns are proven command metadata only', async () => { + register() + const session = { + ...providerRow('Claude Chat', 3), + conversationContent: 'empty' as const + } + expect( + (await project({ ...EMPTY, sessions: [session] })).sessions[0]?.conversationContent + ).toBe('empty') + }) + + it.each(['workspace mismatch', 'missing epoch', 'corrupt row', 'sequence gap', 'adopted-only'])( + 'keeps uncertain history visible: %s', + async (reason) => { + if (reason === 'missing epoch') { + publishJournalSessionEpoch( + db, + { sessionId: record.sessionId, workspaceId: record.location.workspaceId }, + EPOCH + ) + } else { + register(reason === 'adopted-only' ? 'legacy_import' : 'session_created') + if (reason === 'workspace mismatch') { + db.prepare('UPDATE journal_sessions SET workspace_id = ?').run('another-workspace') + } + if (reason === 'corrupt row') { + db.prepare('INSERT INTO journal_rows VALUES (?, ?, ?, ?, ?)').run( + record.sessionId, + EPOCH, + 2, + 1002, + '{broken' + ) + } + if (reason === 'sequence gap') { + item(3, 'Recoverable prompt') + } + } + expect((await project()).sessions[0]?.conversationContent).toBe('unknown') + } + ) + + it('bounds journal discovery and never calls a bounded prefix empty', async () => { + register() + for (let seq = 2; seq <= 42; seq += 1) { + const row: JournalRow = { ...base(seq), kind: 'tombstone', itemId: `old-${seq}`, revision: 1 } + insertJournalRow(db, record.sessionId, row) + } + item(43, 'Prompt outside the prefix') + expect((await project()).sessions[0]).toMatchObject({ conversationContent: 'unknown' }) + expect((await project()).sessions[0]?.firstUserPrompt).toBeUndefined() + }) + + it('keeps oversized journal rows unknown instead of loading unbounded output', async () => { + register() + item(2, 'large prompt '.repeat(10000)) + expect((await project()).sessions[0]?.conversationContent).toBe('unknown') + }) +}) diff --git a/src/main/ai-vault/structured-conversation-navigation.test.ts b/src/main/ai-vault/structured-conversation-navigation.test.ts new file mode 100644 index 000000000000..e99e12e48493 --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation.test.ts @@ -0,0 +1,357 @@ +import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../shared/agent-session/lifecycle/records/agent-session-record.test-fixture' +import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle-encoding' +import type { AiVaultListResult } from '../../shared/ai-vault/contracts/ai-vault-types' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { AgentSessionConversationKeys } from '../runtime/agent-session/records/agent-session-conversation-key-index' +import { + OPENS_EVERY_STRUCTURED_CHAT, + projectStructuredAiVaultSessions +} from './structured-sessions/structured-session-ownership' +import { listResult } from './structured-sessions/structured-session-ownership.test-support' +import { parseAiVaultListResult } from './listing/session-list-result-validation' +import { restampAiVaultListResult } from './listing/session-list-results' +import { aiVaultOrchestrationChildSessionIds } from './structured-conversation-navigation' +import { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db' +import { testOrcaSessionId } from '../../shared/agent-session/identity/orca-session-address-test-fixture' +import { formatOrcaSessionAddress } from '../../shared/agent-session/identity/orca-session-address' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerProcessIncarnation +} from '../runtime/orchestration/terminal-authority/structured-sessions/structured-worker-identity' + +const EMPTY: AiVaultListResult = { sessions: [], issues: [], scannedAt: '2026-10-25T00:00:00Z' } + +function install(records: readonly AgentSessionRecord[]): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: list projection reads only the durable catalog on this host. + setStructuredAgentSessionHost({ + deps: { + store: { + listRecords: () => records, + hostId: 'local', + getRecord: (id: string) => records.find((record) => record.sessionId === id) ?? null, + listConversations: () => records.map(agentSessionConversationView), + conversationsKeyedBy: (keys: AgentSessionConversationKeys, key: string) => + records.map(agentSessionConversationView).filter((view) => keys(view).includes(key)) + } + } + } as never) +} + +function retained(provider = 'claude'): AgentSessionRecord { + const record = agentSessionRecordFixture( + agentSessionLeaseFixture({ + claimStatus: 'released', + ownerProcess: null, + provenHandleLinkId: null + }) + ) + return { + ...record, + provider, + providerHandleChain: [], + location: { ...record.location, workspaceId: 'folder:notes', workspaceKind: 'folder' }, + launchDirectory: '/notes', + conversationName: 'Saved conversation', + createdAt: Date.parse('2026-10-23T00:00:00Z'), + updatedAt: Date.parse('2026-10-24T12:00:00Z') + } +} + +afterEach(() => setStructuredAgentSessionHost(null)) + +describe('primary conversation navigation from the durable session catalog', () => { + it('distinguishes absent orchestration history from an unreadable custody database', () => { + expect(aiVaultOrchestrationChildSessionIds(null)?.size).toBe(0) + expect( + aiVaultOrchestrationChildSessionIds(() => { + throw new Error('database open failed') + }) + ).toBeNull() + }) + + it('keeps the conversation list available when child custody lookup fails', () => { + const db = new OrchestrationDb(':memory:') + try { + vi.spyOn(db, 'hasAnyDispatchContexts').mockReturnValue(true) + const prepare = db.db.prepare.bind(db.db) + const spy = vi + .spyOn(db.db, 'prepare') + .mockImplementation(() => prepare('SELECT NULL AS sessionId')) + expect(aiVaultOrchestrationChildSessionIds(db)).toBeNull() + spy.mockImplementation(() => { + throw new Error('custody database unavailable') + }) + expect(aiVaultOrchestrationChildSessionIds(db)).toBeNull() + } finally { + db.close() + } + }) + it('keeps provider history but does not project retained children without custody evidence', () => { + install([retained()]) + const providerList = listResult() + const projected = projectStructuredAiVaultSessions(providerList, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true, + childSessionIds: null + }) + expect(projected.sessions).toEqual(providerList.sessions) + expect(projected).not.toHaveProperty('includesStructuredSessions') + }) + + it('keeps released worker journals inside the parent using existing orchestration custody records', () => { + const db = new OrchestrationDb(':memory:') + try { + const parent = testOrcaSessionId('4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') + const worker = testOrcaSessionId('7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64') + const run = db.createRun({ + objective: 'Inspect', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: parent + }) + const started = db.createStartingWorkerDispatch({ + taskSpec: 'Worker', + taskRunId: run.id, + startOptions: {}, + creator: { kind: 'session', orcaSessionId: parent }, + maxDepth: 10 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: started.dispatch.id, + handle: mintStructuredWorkerHandle(), + paneKey: mintStructuredWorkerPaneKey(worker), + processIncarnation: structuredWorkerProcessIncarnation(worker), + worktreeId: 'folder:notes', + effects: [], + setupState: 'ready', + terminalOwnership: 'created' + }) + db.markWorkerDispatchReady(started.dispatch.id) + db.settleWorkerReport({ + taskId: started.task.id, + dispatchId: started.dispatch.id, + outcome: 'succeeded', + result: 'Done' + }) + const resource = db.getWorkerTerminalResourceByOwner(started.dispatch.id)! + db.settleDeadWorkerTerminalRelease({ + requestingDispatchId: started.dispatch.id, + resourceId: resource.id, + processIncarnation: resource.process_incarnation! + }) + const successor = testOrcaSessionId('561bb50e-6281-43a7-a761-4e15dc4c730a') + const records: AgentSessionRecord[] = [parent, worker, successor].map((sessionId) => ({ + ...retained(), + sessionId + })) + records[1]!.conversationCommand = { + command: 'clear', + state: 'completed', + phase: 'committed', + operationId: 'clear-worker', + callerKey: 'worker', + replacementSessionId: successor + } + install(records) + expect( + projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true, + childSessionIds: aiVaultOrchestrationChildSessionIds(db) + }).sessions.map((row) => row.structuredSession?.sessionId) + ).toEqual([parent]) + } finally { + db.close() + } + }) + it.each(['chat', 'structured-worker'] as const)( + 'keeps directly assigned %s conversations inside the parent without terminal custody', + (kind) => { + const db = new OrchestrationDb(':memory:') + try { + const parent = testOrcaSessionId('4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') + const worker = testOrcaSessionId('7e3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64') + const standalone = testOrcaSessionId('561bb50e-6281-43a7-a761-4e15dc4c730a') + const run = db.createRun({ + objective: 'Adopt an existing conversation', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: parent + }) + const dispatch = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Inspect' }).id, + ...(kind === 'chat' + ? { assigneeHandle: formatOrcaSessionAddress(worker) } + : { + assigneeHandle: mintStructuredWorkerHandle(), + assigneePaneKey: mintStructuredWorkerPaneKey(worker), + processIncarnation: structuredWorkerProcessIncarnation(worker) + }), + creator: { kind: 'session', orcaSessionId: parent }, + maxDepth: 10 + }) + expect(dispatch).toMatchObject({ + assignee_orca_session_id: worker, + creator_orca_session_id: parent + }) + expect(db.getWorkerTerminalResourceByOwner(dispatch.id)).toBeUndefined() + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Coordinator bookkeeping' }).id, + assigneeHandle: formatOrcaSessionAddress(parent), + creator: { kind: 'session', orcaSessionId: parent }, + maxDepth: 10 + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Root assignment' }).id, + assigneeHandle: formatOrcaSessionAddress(standalone), + creator: { kind: 'system' }, + maxDepth: 10 + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Legacy terminal' }).id, + assigneeHandle: 'term_without_session_identity', + creator: { kind: 'session', orcaSessionId: parent }, + maxDepth: 10 + }) + const records = [parent, worker, standalone].map((sessionId) => ({ + ...retained(), + sessionId + })) + install(records) + const topLevel = () => + projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true, + childSessionIds: aiVaultOrchestrationChildSessionIds(db) + }).sessions.map((row) => row.structuredSession?.sessionId) + expect(aiVaultOrchestrationChildSessionIds(db)).toEqual(new Set([worker])) + expect(topLevel()).toEqual([parent, standalone]) + expect( + db.settleWorkerReport({ + taskId: dispatch.task_id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: 'Done' + }) + ).toMatchObject({ action: 'settled' }) + expect(aiVaultOrchestrationChildSessionIds(db)).toEqual(new Set([worker])) + expect(topLevel()).toEqual([parent, standalone]) + } finally { + db.close() + } + } + ) + + it.each(['claude', 'codex'])( + 'retains an empty %s chat without a provider handle or file, without changing transcript browsing', + (provider) => { + const record = retained(provider) + install([record]) + expect(projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT)).toBe(EMPTY) + const result = projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true + }) + expect(result.sessions).toEqual([ + expect.objectContaining({ + source: 'structured-record', + agent: provider, + title: record.conversationName, + cwd: '/notes', + filePath: '', + resumeCommand: '', + createdAt: '2026-10-23T00:00:00.000Z', + updatedAt: '2026-10-24T12:00:00.000Z', + structuredSession: { sessionId: record.sessionId, workspaceId: 'folder:notes' } + }) + ]) + expect( + projectStructuredAiVaultSessions(EMPTY, () => false, { includeStructuredSessions: true }) + .sessions + ).toEqual([]) + expect( + parseAiVaultListResult(restampAiVaultListResult(result, 'runtime:remote')).sessions[0] + ).toMatchObject({ + source: 'structured-record', + executionHostId: 'runtime:remote', + structuredSession: { sessionId: record.sessionId } + }) + } + ) + + it('deduplicates all provider handles and duplicate files by stored chat while preserving another host', () => { + const record = retained() + record.providerHandleChain = ['provider-first', 'provider-latest'].map((id, index) => ({ + linkId: `link-${index}`, + origin: 'created', + mintedAtFence: index + 1, + observedAt: index + 1, + handle: claudeProviderHandle(id, null) + })) + install([record]) + const base = listResult().sessions[0]! + const files = record.providerHandleChain.map((link, index) => ({ + ...base, + agent: 'claude' as const, + sessionId: index === 0 ? 'provider-first' : 'provider-latest', + id: `file-${index}`, + filePath: `/transcripts/${link.linkId}.jsonl`, + updatedAt: new Date(record.updatedAt + index).toISOString() + })) + const remote = { ...files[0]!, id: 'remote', executionHostId: 'runtime:remote' as const } + const result = projectStructuredAiVaultSessions( + { ...EMPTY, sessions: [...files, remote] }, + OPENS_EVERY_STRUCTURED_CHAT, + { includeStructuredSessions: true } + ) + expect(result.sessions).toHaveLength(2) + expect(result.sessions.find((row) => row.executionHostId === 'local')).toMatchObject({ + id: 'file-1', + filePath: '/transcripts/link-1.jsonl', + title: 'Saved conversation', + structuredSession: { sessionId: record.sessionId } + }) + expect(result.sessions.find((row) => row.executionHostId === 'runtime:remote')).toBe(remote) + }) + + it('never imports another execution host or WSL namespace and omits orchestration children', () => { + const local = retained() + const remote = { + ...retained(), + sessionId: 'remote-chat', + location: { ...local.location, executionHostId: 'runtime:remote' as const } + } + const wsl = { + ...retained(), + sessionId: 'wsl-chat', + location: { ...local.location, wslDistro: 'Ubuntu' } + } + const child = { ...retained(), sessionId: 'released-child' } + install([local, remote, wsl, child]) + expect( + projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true, + childSessionIds: new Set([child.sessionId]) + }).sessions.map((row) => row.structuredSession?.sessionId) + ).toEqual([local.sessionId]) + }) + + it('reads live stored names and recency even when the provider scan stamp does not change', () => { + const record = retained() + install([record]) + const before = projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true + }) + record.conversationName = 'Renamed after closing' + record.updatedAt += 1000 + const after = projectStructuredAiVaultSessions(EMPTY, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true + }) + expect(after.scannedAt).toBe(before.scannedAt) + expect(after.sessions[0]?.title).toBe('Renamed after closing') + expect(after.sessions[0]?.updatedAt).not.toBe(before.sessions[0]?.updatedAt) + }) +}) diff --git a/src/main/ai-vault/structured-conversation-navigation.ts b/src/main/ai-vault/structured-conversation-navigation.ts new file mode 100644 index 000000000000..ed80d6551552 --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation.ts @@ -0,0 +1,170 @@ +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import { agentSessionConversationView } from '../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' +import { defaultAgentChatLabel } from '../../shared/agent-session/conversation-naming/agent-session-chat-label' +import { + isAiVaultAgent, + isAiVaultSessionResumableContent, + aiVaultSessionRecoverableSignalCount, + type AiVaultListResult, + type AiVaultSession +} from '../../shared/ai-vault/contracts/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host/execution-host' +import { splitWorktreeIdForFilesystem } from '../../shared/worktree/id' +import { structuredAgentRuntimeMetadata } from '../runtime/agent-session/installation/structured-agent-runtime-metadata' +import type { StructuredChatOpener } from './structured-sessions/structured-session-ownership' +import type { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db' +import { z } from 'zod' +import { clearedInto } from '../runtime/orchestration/addressing/session-lineage/structured-session-lineage' +import { isGenericConversationTitle } from '../../shared/project-conversation-list' +import { conversationNameSeed } from '../../shared/source-control/ai/generation/conversation-name-generation' +import type { StructuredConversationJournalPreview } from './structured-conversation-journal-preview' + +/** Project the existing record catalog; provider files remain optional evidence, never identity. */ +export function projectDurableAiVaultConversations( + result: AiVaultListResult, + records: readonly AgentSessionRecord[], + opensChat: StructuredChatOpener, + childSessionIds: ReadonlySet = new Set(), + journalPreviews?: ReadonlyMap +): AiVaultListResult { + const excluded = new Set(childSessionIds) + const recordsById = new Map(records.map((record) => [record.sessionId, record])) + for (const id of excluded) { + const record = recordsById.get(id) + const successor = record && clearedInto(agentSessionConversationView(record)) + if (successor) { + excluded.add(successor) + } + } + const bySessionId = new Map() + const otherRows: AiVaultSession[] = [] + for (const row of result.sessions) { + if (row.executionHostId !== LOCAL_EXECUTION_HOST_ID || !row.structuredSession) { + otherRows.push(row) + continue + } + const id = row.structuredSession.sessionId + if (excluded.has(id)) { + continue + } + const previous = bySessionId.get(id) + if (!previous || rowTime(row) > rowTime(previous)) { + bySessionId.set(id, row) + } + } + for (const record of records) { + const registration = structuredAgentRuntimeMetadata(record.provider) + const agent = registration?.sessionHistory.rowAgents[0] + if ( + record.location.executionHostId !== LOCAL_EXECUTION_HOST_ID || + record.location.wslDistro !== null || + !registration || + !isAiVaultAgent(agent) || + !opensChat(registration.definition.agent) || + excluded.has(record.sessionId) + ) { + continue + } + const previous = bySessionId.get(record.sessionId) + const providerHasContent = + previous && + (previous.conversationContent === 'present' || + (previous.conversationContent !== 'empty' && isAiVaultSessionResumableContent(previous)) || + aiVaultSessionRecoverableSignalCount(previous) > 0 || + previous.firstUserPrompt?.trim() || + previous.lastUserPrompt?.trim()) + const preview = providerHasContent + ? { conversationContent: 'present' as const } + : !previous || + previous.source === 'structured-record' || + isGenericConversationTitle(previous.title) + ? (journalPreviews?.get(record.sessionId) ?? { conversationContent: 'unknown' as const }) + : { conversationContent: 'unknown' as const } + const firstUserPrompt = + previous?.firstUserPrompt?.trim() || + ('firstUserPrompt' in preview ? preview.firstUserPrompt : undefined) + const recordTitle = record.conversationName?.trim() + const providerTitle = previous?.title.trim() + const title = + [recordTitle, providerTitle].find((value) => value && !isGenericConversationTitle(value)) || + conversationNameSeed(firstUserPrompt ?? '') || + recordTitle || + providerTitle || + defaultAgentChatLabel(registration.definition.agent) + const createdAt = new Date(record.createdAt).toISOString() + const updatedAt = new Date( + Math.max(record.updatedAt, previous ? rowTime(previous) : 0) + ).toISOString() + const cwd = + record.launchDirectory ?? + splitWorktreeIdForFilesystem(record.location.workspaceId)?.worktreePath ?? + previous?.cwd ?? + null + bySessionId.set(record.sessionId, { + ...(previous ?? { + source: 'structured-record' as const, + id: `${LOCAL_EXECUTION_HOST_ID}:structured:${record.sessionId}`, + executionHostId: LOCAL_EXECUTION_HOST_ID, + agent, + sessionId: record.sessionId, + filePath: '', + codexHome: null, + branch: null, + messageCount: 0, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null + }), + title, + conversationContent: + previous && + previous.source !== 'structured-record' && + previous.conversationContent !== 'empty' && + preview.conversationContent === 'empty' + ? 'unknown' + : preview.conversationContent, + ...(firstUserPrompt ? { firstUserPrompt } : {}), + cwd, + model: record.options?.model ?? previous?.model ?? null, + createdAt, + updatedAt, + modifiedAt: updatedAt, + structuredSession: { sessionId: record.sessionId, workspaceId: record.location.workspaceId } + }) + } + return { + ...result, + includesStructuredSessions: true, + sessions: [...otherRows, ...bySessionId.values()].sort((a, b) => rowTime(b) - rowTime(a)) + } +} + +function rowTime(row: AiVaultSession): number { + return Date.parse(row.updatedAt ?? row.modifiedAt) || 0 +} + +/** Child conversations are reached through the parent's journal, including after release. */ +export function aiVaultOrchestrationChildSessionIds( + source: OrchestrationDb | null | (() => OrchestrationDb | null) +): ReadonlySet | null { + try { + const db = typeof source === 'function' ? source() : source + if (!db?.hasAnyDispatchContexts()) { + return new Set() + } + const rows = z.array(z.object({ sessionId: z.string() })).parse( + db.db + .prepare(`SELECT DISTINCT dispatch.assignee_orca_session_id AS sessionId FROM dispatch_contexts dispatch + WHERE dispatch.assignee_orca_session_id IS NOT NULL AND dispatch.creator_orca_session_id IS NOT NULL + AND dispatch.assignee_orca_session_id != dispatch.creator_orca_session_id`) + .all() + ) + return new Set(rows.map((row) => row.sessionId)) + } catch (error) { + console.warn('[ai-vault] Child conversation lookup unavailable', error) + return null + } +} diff --git a/src/main/ai-vault/structured-session-history-account.ts b/src/main/ai-vault/structured-session-history-account.ts new file mode 100644 index 000000000000..c3670d33d76a --- /dev/null +++ b/src/main/ai-vault/structured-session-history-account.ts @@ -0,0 +1,53 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import { acquiredAgentSessionAccount } from '../../shared/agent-session/lifecycle/accounts/agent-session-acquired-account' +import { CLAUDE_STRUCTURED_AGENT } from '../claude/structured/claude-structured-agent-definition' +import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { + agentSessionAccountHome, + type AgentSessionAccountHome, + isLegacyAgentSessionAccountHome +} from '../../shared/agent-session/lifecycle/accounts/agent-session-account-home' +import { normalizeRuntimePathForComparison } from '../../shared/file-access/cross-platform-path' +import { resolveOrcaManagedCodexHomePath } from '../codex/configuration/homes/codex-home-paths' +import type { StructuredProviderSessionOwnership } from '../native-chat/agent-session-wire/host/structured-provider-session-ownership' + +export function projectedAccountHome(ownership: StructuredProviderSessionOwnership) { + const home = acquiredAccountHome(ownership.sessionId) ?? ownership.key.home + if (!home) { + return undefined + } + if (!isLegacyAgentSessionAccountHome(home)) { + return home + } + if ( + ownership.provider === 'codex' && + !ownership.wslDistro && + normalizeRuntimePathForComparison(home.path) === + normalizeRuntimePathForComparison(resolveOrcaManagedCodexHomePath()) + ) { + return undefined + } + const directory = + ownership.provider === 'claude' && home.variable === 'CLAUDE_CONFIG_DIR' + ? '.claude' + : ownership.provider === 'codex' && home.variable === 'CODEX_HOME' + ? '.codex' + : null + // Only a known native default proves identity; custom and legacy shared homes do not. + return !ownership.wslDistro && + directory && + normalizeRuntimePathForComparison(home.path) === + normalizeRuntimePathForComparison(join(homedir(), directory)) + ? null + : home +} + +function acquiredAccountHome(sessionId: string): AgentSessionAccountHome | undefined { + const store = getStructuredAgentSessionHost()?.deps.store + const record = store?.getRecord(sessionId) + const acquired = store && record ? acquiredAgentSessionAccount(record, store.hostId) : null + return acquired + ? agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, acquired.recipe.home) + : undefined +} diff --git a/src/main/ai-vault/structured-sessions/history-row-ownership-lookup.ts b/src/main/ai-vault/structured-sessions/history-row-ownership-lookup.ts index 7d8becec098e..3b53e1603c67 100644 --- a/src/main/ai-vault/structured-sessions/history-row-ownership-lookup.ts +++ b/src/main/ai-vault/structured-sessions/history-row-ownership-lookup.ts @@ -1,3 +1,4 @@ +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' import type { StructuredAgentId } from '../../../shared/agent-session/lifecycle/provider-handles/agent-session-provider-handle' import type { AgentSessionConversationView } from '../../../shared/agent-session/lifecycle/leases/agent-session-conversation-view' import type { AgentSessionConversationKeys } from '../../runtime/agent-session/records/agent-session-conversation-key-index' @@ -34,8 +35,10 @@ export function historyRowOwnershipLookup(): // Per provider the first head link, else the first link, in listing order. const found = historyRowOwners(row.agent).flatMap((owner) => { const key = ownershipKey({ provider: owner, providerSessionId: row.sessionId }) + // Only this host's chats own its history rows. const owned = store .conversationsKeyedBy(ownershipKeys, key) + .filter((view) => view.location.executionHostId === LOCAL_EXECUTION_HOST_ID) .flatMap((view) => ownedBy(view).get(key) ?? []) return owned.find((ownership) => ownership.role === 'head') ?? owned[0] ?? [] }) diff --git a/src/main/ai-vault/structured-sessions/structured-session-ownership.test-support.ts b/src/main/ai-vault/structured-sessions/structured-session-ownership.test-support.ts index 3c4df37d4d5a..b7b8765bf7b4 100644 --- a/src/main/ai-vault/structured-sessions/structured-session-ownership.test-support.ts +++ b/src/main/ai-vault/structured-sessions/structured-session-ownership.test-support.ts @@ -27,9 +27,11 @@ export function installOwnership( accountHome?: AgentSessionRecord['accountHome'] acquiredAccount?: AgentSessionRecord['acquiredAccount'] lastTurn?: AgentSessionRecord['lastTurn'] + location?: Partial } = {} ): void { - const { handle, accountHome, acquiredAccount, lastTurn, ...ownershipOverrides } = overrides + const { handle, accountHome, acquiredAccount, location, lastTurn, ...ownershipOverrides } = + overrides const ownership: Omit = { sessionId: 'session-alpha', workspaceId: 'workspace-1', @@ -49,7 +51,8 @@ export function installOwnership( location: { ...fixture.location, workspaceId: ownership.workspaceId, - wslDistro: ownership.wslDistro + wslDistro: ownership.wslDistro, + ...location }, provider: ownership.provider, providerHandleChain: [ @@ -74,6 +77,7 @@ export function installOwnership( setStructuredAgentSessionHost({ deps: { store: { + listRecords: () => [record], hostId: record.lease.ownerProcess?.hostId ?? 'local', getRecord: (sessionId: string) => (sessionId === record.sessionId ? record : null), listConversations: () => [view], diff --git a/src/main/ai-vault/structured-sessions/structured-session-ownership.ts b/src/main/ai-vault/structured-sessions/structured-session-ownership.ts index edcac5015b53..59dd8fef4273 100644 --- a/src/main/ai-vault/structured-sessions/structured-session-ownership.ts +++ b/src/main/ai-vault/structured-sessions/structured-session-ownership.ts @@ -1,15 +1,5 @@ +import { projectedAccountHome } from '../structured-session-history-account' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' -import { homedir } from 'node:os' -import { join } from 'node:path' -import { - agentSessionAccountHome, - isLegacyAgentSessionAccountHome, - type AgentSessionAccountHome -} from '../../../shared/agent-session/lifecycle/accounts/agent-session-account-home' -import { acquiredAgentSessionAccount } from '../../../shared/agent-session/lifecycle/accounts/agent-session-acquired-account' -import { CLAUDE_STRUCTURED_AGENT } from '../../claude/structured/claude-structured-agent-definition' -import { normalizeRuntimePathForComparison } from '../../../shared/file-access/cross-platform-path' -import { resolveOrcaManagedCodexHomePath } from '../../codex/configuration/homes/codex-home-paths' import { agentSessionOwnerObservationIsLive } from '../../../shared/agent-session/lifecycle/leases/agent-session-lease-adjudication' import { defaultAgentChatLabel } from '../../../shared/agent-session/conversation-naming/agent-session-chat-label' import type { AiVaultListResult } from '../../../shared/ai-vault/contracts/ai-vault-types' @@ -43,6 +33,9 @@ import { import { STRUCTURED_AGENT_RUNTIME_METADATA } from '../../runtime/agent-session/installation/structured-agent-runtime-metadata' import type { StructuredAgentRuntimeMetadata } from '../../runtime/agent-session/installation/structured-agent-runtime-registration-types' import { commandName, commandProgramIndex, shellCommands } from './shell-command-words' +import { projectDurableAiVaultConversations } from '../structured-conversation-navigation' +import type { StructuredConversationJournalPreview } from '../structured-conversation-journal-preview' +import { isGenericConversationTitle } from '../../../shared/project-conversation-list' /** Hide chat-owned rows from clients unable to open that agent’s chat. */ export type StructuredChatOpener = (agent: StructuredAgentId) => boolean @@ -51,7 +44,12 @@ export const OPENS_EVERY_STRUCTURED_CHAT: StructuredChatOpener = () => true export function projectStructuredAiVaultSessions( result: AiVaultListResult, - opensChat: StructuredChatOpener + opensChat: StructuredChatOpener, + options?: { + includeStructuredSessions?: boolean + childSessionIds?: ReadonlySet | null + journalPreviews?: ReadonlyMap + } ): AiVaultListResult { const owner = historyRowOwnershipLookup() const deleted = historyRowOfDeletedChat() @@ -74,17 +72,27 @@ export function projectStructuredAiVaultSessions( return [ { ...session, - ...ownedRow(session.agent, ownership), + ...ownedRow(session, ownership), ...(ownership.role === 'head' && isCursorAcpSessionRow(session) ? ownedRowLastTurnPreview(session, ownership.sessionId) : null) } ] }) - return sessions.length === result.sessions.length && + const projected = + sessions.length === result.sessions.length && sessions.every((row, index) => row === result.sessions[index]) - ? result - : { ...result, sessions } + ? result + : { ...result, sessions } + return options?.includeStructuredSessions && options.childSessionIds !== null + ? projectDurableAiVaultConversations( + projected, + getStructuredAgentSessionHost()?.deps.store.listRecords() ?? [], + opensChat, + options.childSessionIds, + options.journalPreviews + ) + : projected } /** Owned search hits open their chat and omit terminal resume commands, matching history rows. */ @@ -112,7 +120,7 @@ export function projectStructuredAiVaultSearchResponse( return [] } const { resumeCommand: _resumeCommand, ...owned } = hit - return [redactForTransport({ ...owned, ...ownedRow(hit.agent, ownership) }, transport)] + return [redactForTransport({ ...owned, ...ownedRow(hit, ownership) }, transport)] }) } } @@ -142,7 +150,10 @@ export async function searchWithStructuredOwners( : response } -function ownedRow(rowAgent: string, ownership: StructuredProviderSessionOwnership) { +function ownedRow( + row: { agent: string; title: string }, + ownership: StructuredProviderSessionOwnership +) { const structuredSession = { sessionId: ownership.sessionId, workspaceId: ownership.workspaceId @@ -151,55 +162,21 @@ function ownedRow(rowAgent: string, ownership: StructuredProviderSessionOwnershi accountHome: projectedAccountHome(ownership), accountWslDistro: ownership.wslDistro } + const name = ownership.conversationName?.trim() const title = - ownership.conversationName ?? - (historyRowFallsBackToChatLabel(rowAgent) ? defaultAgentChatLabel(ownership.provider) : null) + name && !isGenericConversationTitle(name) + ? name + : !isGenericConversationTitle(row.title) + ? null + : name || + (historyRowFallsBackToChatLabel(row.agent) + ? defaultAgentChatLabel(ownership.provider) + : null) return title === null ? { structuredSession, ...account } : { title, structuredSession, ...account } } -function projectedAccountHome(ownership: StructuredProviderSessionOwnership) { - const home = acquiredAccountHome(ownership.sessionId) ?? ownership.key.home - if (!home) { - return undefined - } - if (!isLegacyAgentSessionAccountHome(home)) { - return home - } - if ( - ownership.provider === 'codex' && - !ownership.wslDistro && - normalizeRuntimePathForComparison(home.path) === - normalizeRuntimePathForComparison(resolveOrcaManagedCodexHomePath()) - ) { - return undefined - } - const directory = - ownership.provider === 'claude' && home.variable === 'CLAUDE_CONFIG_DIR' - ? '.claude' - : ownership.provider === 'codex' && home.variable === 'CODEX_HOME' - ? '.codex' - : null - // Only a known native default proves identity; custom and legacy shared homes do not. - return !ownership.wslDistro && - directory && - normalizeRuntimePathForComparison(home.path) === - normalizeRuntimePathForComparison(join(homedir(), directory)) - ? null - : home -} - -/** The account the host last launched this chat under, when it observed one; the founding home otherwise. */ -function acquiredAccountHome(sessionId: string): AgentSessionAccountHome | undefined { - const store = getStructuredAgentSessionHost()?.deps.store - const record = store?.getRecord(sessionId) - const acquired = store && record ? acquiredAgentSessionAccount(record, store.hostId) : null - return acquired - ? agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, acquired.recipe.home) - : undefined -} - export function assertLegacyAiVaultResumeAllowed(args: AiVaultPrepareSessionResumeArgs): void { // A fork writes a new conversation, and preparing its home never writes this one. const blocking = args.fork ? undefined : resumeOwnerships(args).find(terminalResumeBlocked) diff --git a/src/main/ai-vault/transcripts/session-transcript-reader.ts b/src/main/ai-vault/transcripts/session-transcript-reader.ts index 890e20e3a584..f74fe3bd32c9 100644 --- a/src/main/ai-vault/transcripts/session-transcript-reader.ts +++ b/src/main/ai-vault/transcripts/session-transcript-reader.ts @@ -139,8 +139,15 @@ export async function readResumableTranscript( channel.mute(() => displayState.consumeLine(partialLine)) } + const skippedRecords = mergeSkippedTranscriptRecords( + canResume ? resume.skippedRecords : [], + readResult.skippedRecords + ) throwIfAiVaultScanCancelled(args.signal) - const session = await displayState.finalize(args.platform, { signal: args.signal }) + let session = await displayState.finalize(args.platform, { signal: args.signal }) + if (session?.conversationContent === 'empty' && skippedRecords.length > 0) { + session = { ...session, conversationContent: 'unknown' } + } const consumerSession = args.sessionForConsumers ? await waitForAiVaultScan(args.sessionForConsumers(session), args.signal) : session @@ -159,11 +166,7 @@ export async function readResumableTranscript( mtimeMs: file.mtimeMs, sizeBytes: file.sizeBytes, channel, - // Retain earlier skips only for append reads; replacements revisit those records. - skippedRecords: mergeSkippedTranscriptRecords( - canResume ? resume.skippedRecords : [], - readResult.skippedRecords - ), + skippedRecords, prefixHash: readResult.prefixHash ?? null } } diff --git a/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts b/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts index afe32b633bcf..c8f74c1387cb 100644 --- a/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts +++ b/src/main/ipc/ai-vault/ai-vault-host-leg-cache.ts @@ -63,6 +63,7 @@ export async function scanHostLegWithCache(args: { dependency?: AiVaultProjectionDependency depth: AiVaultSessionDepth scopePaths?: readonly string[] + selectedSessionId?: string force: boolean afterFingerprint?: string | null scan: () => Promise @@ -80,7 +81,12 @@ export async function scanHostLegWithCache(args: { (!cached.result.unchanged || (cached.depth === args.depth && cached.result.fingerprint === args.afterFingerprint)) ) { - return truncateAiVaultListResult(cached.result, args.depth, args.scopePaths) + return truncateAiVaultListResult( + cached.result, + args.depth, + args.scopePaths, + args.selectedSessionId + ) } const result = await args.scan() // A delete's invalidation landed while this leg was scanning; caching a diff --git a/src/main/ipc/ai-vault/ai-vault.ts b/src/main/ipc/ai-vault/ai-vault.ts index 4e45cf7822a5..bc39ccb13bee 100644 --- a/src/main/ipc/ai-vault/ai-vault.ts +++ b/src/main/ipc/ai-vault/ai-vault.ts @@ -117,6 +117,7 @@ async function listAiVaultSessions( ? [...new Set(scopePaths)].sort() : scopePaths, executionHostScope, + selectedSessionId: args?.selectedSessionId, includeAntigravityIdeSessions: args?.includeAntigravityIdeSessions === true, ...(args?.scopeOnly === true ? { scopeOnly: true } : {}) }) @@ -144,6 +145,7 @@ async function listAiVaultSessions( dependency, depth, scopePaths, + selectedSessionId: args?.selectedSessionId, force: args?.force === true, afterFingerprint, scan @@ -176,6 +178,7 @@ async function scanAiVaultSessionsByHostScope( dependency: dependency?.forHost(hostInfo.environmentId), depth, scopePaths, + selectedSessionId: args?.selectedSessionId, force: args?.force === true, scan: () => scanRuntimeAiVaultSessions({ @@ -194,7 +197,8 @@ async function scanAiVaultSessionsByHostScope( [...scannedResults, ...runtimeResults], args?.limit, args?.unlimited, - scopePaths + scopePaths, + args?.selectedSessionId ) } diff --git a/src/main/native-chat/agent-session-journal/journal-domain-conversation-preview.ts b/src/main/native-chat/agent-session-journal/journal-domain-conversation-preview.ts new file mode 100644 index 000000000000..0ffaf84580cb --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-domain-conversation-preview.ts @@ -0,0 +1,55 @@ +import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' +import { isAdmissibleAgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-schemas' +import { firstStructuredAgentSessionPrompt } from '../../../shared/agent-session/requests/structured-agent-session-first-prompt' +import type { StructuredConversationJournalPreview } from '../../ai-vault/structured-conversation-journal-preview' +import type { JournalSqlScope } from './journal-sql-scope' + +const ROW_LIMIT = 41 +const ROW_TEXT_LIMIT = 65_536 +const UNKNOWN = { conversationContent: 'unknown' as const } + +/** Current domain facts replace event replay; each read stays in the worker's WAL snapshot. */ +export function readJournalDomainConversationPreview( + scope: JournalSqlScope, + workspaceId: string +): StructuredConversationJournalPreview { + const head = scope.db + .prepare(`SELECT workspace_id,last_sequence,history_origin_json + FROM journal_chat_state WHERE session_id=? AND epoch=?`) + .get(...scope.prefix) + if (!head || head.workspace_id !== workspaceId) { + return UNKNOWN + } + const rows = scope.db + .prepare(`SELECT substr(payload_json,1,?) AS payload + FROM journal_items INDEXED BY journal_items_root_position + WHERE session_id=? AND epoch=? AND hidden=0 AND root=1 AND sequence ROW_TEXT_LIMIT) { + return UNKNOWN + } + const item = scope.parse(payload) + if (!isAdmissibleAgentJournalRenderItem(item)) { + return UNKNOWN + } + items.push(item) + } + const firstUserPrompt = firstStructuredAgentSessionPrompt( + items.filter((item) => item.body.kind !== 'message' || item.body.from === undefined) + ) + return { + conversationContent: + Number(head.last_sequence) >= ROW_LIMIT + ? 'unknown' + : items.length > 0 + ? 'present' + : Number(head.last_sequence) <= 1 && head.history_origin_json === null + ? 'empty' + : 'unknown', + ...(firstUserPrompt ? { firstUserPrompt } : {}) + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-sql-point-read-types.ts b/src/main/native-chat/agent-session-journal/journal-sql-point-read-types.ts index a5529b3a8f3c..7d31937dd6ab 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-point-read-types.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-point-read-types.ts @@ -1,3 +1,4 @@ +import type { StructuredConversationJournalPreview } from '../../ai-vault/structured-conversation-journal-preview' import type { JournalOutlineCache } from './journal-domain-outline' import type { JournalMailAttempt, JournalMailObservation } from './journal-mail-observation' import type { JournalRequestFailureRead } from './journal-request-failure' @@ -57,6 +58,7 @@ export type JournalSqlPointRead = { compareSubmissions: boolean } | { kind: 'saved-content' } + | { kind: 'conversation-preview'; workspaceId: string } | { kind: 'conversation-outline'; budgetBytes: number } | { kind: 'rewind-target'; itemId: string } | { kind: 'rewind-cut'; target: JournalRewindSelection } @@ -101,6 +103,7 @@ export type JournalSqlPointReadResult = | { kind: 'rewind-cut'; cut: JournalRewindCut | null } | { kind: 'fork-boundary'; boundary: JournalForkBoundary } | { kind: 'saved-content'; content: JournalSavedContent } + | { kind: 'conversation-preview'; preview: StructuredConversationJournalPreview } | { kind: 'conversation-outline' outline: AgentSessionConversationOutline diff --git a/src/main/native-chat/agent-session-journal/journal-sql-point-read.ts b/src/main/native-chat/agent-session-journal/journal-sql-point-read.ts index 5de9b1c0eec5..b8f0988939e5 100644 --- a/src/main/native-chat/agent-session-journal/journal-sql-point-read.ts +++ b/src/main/native-chat/agent-session-journal/journal-sql-point-read.ts @@ -1,3 +1,4 @@ +import { readJournalDomainConversationPreview } from './journal-domain-conversation-preview' import { planJournalDomainRewindCut } from './journal-domain-rewind-cut' import { readJournalDomainMailObservation } from './journal-domain-mail-observation' import { readJournalDomainOutline } from './journal-domain-outline' @@ -68,6 +69,11 @@ function read( operation.compareSubmissions ) } + case 'conversation-preview': + return { + kind: operation.kind, + preview: readJournalDomainConversationPreview(scope, operation.workspaceId) + } case 'saved-content': return { kind: operation.kind, content: readJournalDomainSavedContent(scope) } case 'conversation-outline': diff --git a/src/main/persistence/applying-settings/ui-state-read.ts b/src/main/persistence/applying-settings/ui-state-read.ts index 54ae018b80af..b357588db075 100644 --- a/src/main/persistence/applying-settings/ui-state-read.ts +++ b/src/main/persistence/applying-settings/ui-state-read.ts @@ -1,4 +1,5 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' +import { normalizeConversationPreferences } from '../../../shared/conversation-navigation-preferences' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/orca-profiles/persisted-state-types' import { getDefaultUIState } from '../../../shared/orca-profiles/constants' @@ -45,6 +46,7 @@ export function getPersistedUI( ...uiState, groupBy: normalizeGroupBy(state.ui?.groupBy), sortBy: normalizeSortBy(state.ui?.sortBy), + conversationPreferences: normalizeConversationPreferences(state.ui?.conversationPreferences), projectOrderBy: normalizeProjectOrderBy(state.ui?.projectOrderBy), rightSidebarTab: normalizeRightSidebarTab(state.ui?.rightSidebarTab), rightSidebarExplorerView: normalizeRightSidebarExplorerView( diff --git a/src/main/persistence/applying-settings/ui-state-update.ts b/src/main/persistence/applying-settings/ui-state-update.ts index 58a3568f50b9..c03f394dec3a 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -1,4 +1,5 @@ import { normalizeGitGraphFilters } from '../../../shared/git/history/git-graph-filters' +import { normalizeConversationPreferences } from '../../../shared/conversation-navigation-preferences' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-listing/file-explorer-display-root' import type { PersistedState } from '../../../shared/orca-profiles/persisted-state-types' import { getDefaultUIState } from '../../../shared/orca-profiles/constants' @@ -120,6 +121,9 @@ export function updatePersistedUI( sortBy: durableUpdates.sortBy ? normalizeSortBy(durableUpdates.sortBy) : normalizeSortBy(operations.state.ui?.sortBy), + conversationPreferences: normalizeConversationPreferences( + durableUpdates.conversationPreferences ?? currentUI.conversationPreferences + ), projectOrderBy: sanitizedUpdates.projectOrderBy ? normalizeProjectOrderBy(sanitizedUpdates.projectOrderBy) : normalizeProjectOrderBy(operations.state.ui?.projectOrderBy), diff --git a/src/main/runtime/rpc/methods/client-state/client-ui.ts b/src/main/runtime/rpc/methods/client-state/client-ui.ts index 151645cf5b9e..0a793af8e1f1 100644 --- a/src/main/runtime/rpc/methods/client-state/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-state/client-ui.ts @@ -1,5 +1,9 @@ import { normalizeJiraQuickFilterState } from '../../../../../shared/jira/jira-quick-filters' import { JiraQuickFilterStateParam } from '../../../../../shared/rpc-contract/jira/jira-quick-filter-params' +import { + SetConversationPreferenceParams, + updateConversationPreference +} from '../../../../../shared/conversation-navigation-preferences' import { normalizeJiraSavedFilterState, mutateJiraSavedFilterState @@ -45,6 +49,19 @@ function uiForCaller( } export const CLIENT_UI_METHODS = [ + defineMethod({ + name: 'ui.setConversationPreference', + permission: 'workspace', + params: SetConversationPreferenceParams, + handler: (params, { runtime }) => ({ + preferences: runtime.updateUIState({ + conversationPreferences: updateConversationPreference( + runtime.getUIState().conversationPreferences, + params + ) + }).conversationPreferences + }) + }), defineMethod({ name: 'ui.getJiraQuickFilters', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/client-state/ui-state-schema-parity-checks.ts b/src/main/runtime/rpc/methods/client-state/ui-state-schema-parity-checks.ts index 4f739cacf8d5..47b24b8724da 100644 --- a/src/main/runtime/rpc/methods/client-state/ui-state-schema-parity-checks.ts +++ b/src/main/runtime/rpc/methods/client-state/ui-state-schema-parity-checks.ts @@ -6,6 +6,7 @@ import type { AssertNoMissingKeys, AssertNoMissingValues } from './ui-state-sche // Main-only UI fields never arrive from clients; parity checks enforce their deliberate omission from the strict schema. type MainOwnedUIState = + | 'conversationPreferences' | 'jiraSavedFilterState' | 'jiraQuickFilterState' | '_explorerDisplayRootMigrated' diff --git a/src/main/runtime/rpc/methods/client-ui-conversation-preferences.test.ts b/src/main/runtime/rpc/methods/client-ui-conversation-preferences.test.ts new file mode 100644 index 000000000000..6d2aca8e7373 --- /dev/null +++ b/src/main/runtime/rpc/methods/client-ui-conversation-preferences.test.ts @@ -0,0 +1,103 @@ +import '../dispatch/testing/unused-default-rpc-methods.test-fixture' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { + closeTestStores, + createStore, + testState +} from '../../../persistence/persistence-test-harness' +import { OrcaRuntimeService } from '../../orca-runtime' +import { RpcDispatcher } from '../dispatcher' +import { CLIENT_UI_METHODS } from './client-state/client-ui' + +beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-conversation-preferences-')) +}) +afterEach(async () => { + await closeTestStores() + rmSync(testState.dir, { recursive: true, force: true }) +}) + +function dispatcherFor(store: ReturnType) { + return new RpcDispatcher({ + runtime: new OrcaRuntimeService(store), + methods: CLIENT_UI_METHODS + }) +} + +it('merges concurrent host-qualified conversation changes through RPC and persists restore across restart', async () => { + const store = createStore() + const dispatcher = dispatcherFor(store) + const remote = JSON.stringify(['ssh:alpha', 'structured', 'same-session']) + const local = JSON.stringify(['local', 'structured', 'same-session']) + const mutate = (id: string, params: unknown) => + dispatcher.dispatch({ id, authToken: 'tok', method: 'ui.setConversationPreference', params }) + + const responses = await Promise.all([ + mutate('pin-remote', { key: remote, pinned: true }), + mutate('archive-remote', { key: remote, archived: true }), + mutate('pin-local', { key: local, pinned: true }) + ]) + expect(responses).toEqual([ + expect.objectContaining({ ok: true }), + expect.objectContaining({ ok: true }), + expect.objectContaining({ ok: true }) + ]) + expect(store.getUI().conversationPreferences).toEqual({ + revision: 3, + entries: { [remote]: { pinned: true, archived: true }, [local]: { pinned: true } } + }) + + expect(await mutate('restore-remote', { key: remote, archived: false })).toMatchObject({ + ok: true, + result: { preferences: { revision: 4 } } + }) + expect( + await dispatcher.dispatch({ + id: 'resize', + authToken: 'tok', + method: 'ui.set', + params: { sidebarWidth: 280 } + }) + ).toMatchObject({ ok: true }) + store.flush() + await closeTestStores() + + const reopened = createStore() + expect(reopened.getUI()).toMatchObject({ + sidebarWidth: 280, + conversationPreferences: { + revision: 4, + entries: { [remote]: { pinned: true, archived: false }, [local]: { pinned: true } } + } + }) +}) + +it('persists hidden discovered groups and restores them without touching project files or history', async () => { + const file = join(testState.dir, 'project-file.txt') + const history = join(testState.dir, 'transcript.jsonl') + writeFileSync(file, 'keep project contents') + writeFileSync(history, 'keep conversation contents') + const key = JSON.stringify(['runtime:remote', 'folder:/notes']) + let store = createStore() + const mutate = (hidden: boolean) => + dispatcherFor(store).dispatch({ + id: hidden ? 'hide' : 'restore', + authToken: 'tok', + method: 'ui.setConversationPreference', + params: { projectKey: key, label: 'Notes', hidden } + }) + expect(await mutate(true)).toMatchObject({ ok: true }) + store.flush() + await closeTestStores() + store = createStore() + expect(store.getUI().conversationPreferences?.hiddenProjects).toEqual({ [key]: 'Notes' }) + expect(await mutate(false)).toMatchObject({ ok: true }) + store.flush() + await closeTestStores() + expect(createStore().getUI().conversationPreferences?.hiddenProjects).toEqual({}) + expect(readFileSync(file, 'utf8')).toBe('keep project contents') + expect(readFileSync(history, 'utf8')).toBe('keep conversation contents') +}) diff --git a/src/main/runtime/rpc/methods/history/ai-vault-history-recovery.test.ts b/src/main/runtime/rpc/methods/history/ai-vault-history-recovery.test.ts new file mode 100644 index 000000000000..64bb269b2e00 --- /dev/null +++ b/src/main/runtime/rpc/methods/history/ai-vault-history-recovery.test.ts @@ -0,0 +1,307 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { RpcDispatcher } from '../../dispatcher' + +import type { RpcRequest } from '../../core' + +import type { OrcaRuntimeService } from '../../../orca-runtime' + +import '../../../orca-runtime' +import { RuntimeAiVaultCommands } from '../../../integrations/ai-vault/runtime-ai-vault-commands' + +import type { + AiVaultListResult, + AiVaultSession +} from '../../../../../shared/ai-vault/contracts/ai-vault-types' + +import type { AiVaultServiceScanOptions } from '../../../../ai-vault/scan-service/session-scanner-service-protocol' + +import '../../../../../shared/remote-runtime/protocol/protocol-version' +import '../../../../../shared/ai-vault/contracts/ai-vault-runtime-capabilities' + +const { scanAiVaultSessionsInService, resolveAiVaultSessionTitlesInService } = vi.hoisted(() => ({ + scanAiVaultSessionsInService: + vi.fn< + (options: AiVaultServiceScanOptions, signal?: AbortSignal) => Promise + >(), + resolveAiVaultSessionTitlesInService: vi.fn() +})) + +vi.mock( + '../../../../ai-vault/scan-service/session-scanner-service-spawn', + async (importOriginal) => ({ + ...(await importOriginal()), + scanAiVaultSessionsInService, + resolveAiVaultSessionTitlesInService + }) +) + +import { AI_VAULT_METHODS } from './ai-vault' + +import '../../../../../shared/rpc-contract/ai-vault/ai-vault-params' + +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { installOwnership } from '../../../../ai-vault/structured-sessions/structured-session-ownership.test-support' +import { resetAiVaultSessionListCacheForTests } from '../../../../ai-vault/listing/cached-session-list' + +function makeRequest(method: string, params?: unknown): RpcRequest { + return { id: 'req-1', authToken: 'tok', method, params } +} + +const SCANNED_AT = '2026-06-29T00:00:00.000Z' + +function makeResult(): AiVaultListResult { + return { sessions: [], issues: [], scannedAt: SCANNED_AT } +} + +function makeSession(): AiVaultSession { + return { + id: 'local:claude:sess-1:/tmp/t.jsonl', + executionHostId: 'local', + agent: 'claude', + sessionId: 'sess-1', + title: 'Test session', + cwd: '/tmp', + branch: null, + model: null, + filePath: '/tmp/t.jsonl', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: SCANNED_AT, + messageCount: 2, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: 'claude --resume sess-1', + subagent: null + } +} + +function makeDispatcher(): RpcDispatcher { + // Exercise the same shared vault cache used by desktop IPC. + const vault = new RuntimeAiVaultCommands(() => null) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the handlers under test read only these three runtime members. + const runtime = { + getRuntimeId: () => 'test-runtime', + ensureStructuredAgentSessionHost: vi.fn(async () => undefined), + getExistingOrchestrationDb: () => null, + listAiVaultSessions: vault.list.bind(vault), + resolveAiVaultSessionTitles: (requests: unknown[], signal?: AbortSignal) => + resolveAiVaultSessionTitlesInService(requests, signal) + } as unknown as OrcaRuntimeService + return new RpcDispatcher({ runtime, methods: AI_VAULT_METHODS }) +} + +describe('aiVault.listSessions handler + shared cache', () => { + beforeEach(() => { + resetAiVaultSessionListCacheForTests() + scanAiVaultSessionsInService.mockReset() + scanAiVaultSessionsInService.mockResolvedValue(makeResult()) + resolveAiVaultSessionTitlesInService.mockReset() + resolveAiVaultSessionTitlesInService.mockResolvedValue({ titles: [] }) + }) + + afterEach(() => { + resetAiVaultSessionListCacheForTests() + }) + + it.each([undefined, 'runtime:test-runtime'] as const)( + 'includes retained records only on opt-in with catalog coverage for %s', + async (executionHostId) => { + const dispatcher = makeDispatcher() + installOwnership({ conversationName: 'Retained conversation' }) + try { + await expect( + dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + includeStructuredSessions: true, + executionHostId + }) + ) + ).resolves.toMatchObject({ + ok: true, + result: { + includesStructuredSessions: true, + sessions: [ + expect.objectContaining({ + source: 'structured-record', + title: 'Retained conversation', + structuredSession: { sessionId: 'session-alpha', workspaceId: 'workspace-1' } + }) + ] + } + }) + const transcriptOnly = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { executionHostId }) + ) + expect(transcriptOnly).toMatchObject({ ok: true, result: { sessions: [] } }) + if (transcriptOnly.ok) { + expect(transcriptOnly.result).not.toHaveProperty('includesStructuredSessions') + } + setStructuredAgentSessionHost(null) + const unsupported = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { includeStructuredSessions: true, executionHostId }) + ) + expect(unsupported.ok).toBe(true) + if (unsupported.ok) { + expect(unsupported.result).not.toHaveProperty('includesStructuredSessions') + } + } finally { + setStructuredAgentSessionHost(null) + } + } + ) + + it.each([undefined, 'runtime:test-runtime'] as const)( + 'keeps a selected record after 500 newer rows and separates its cache (%s)', + async (executionHostId) => { + const selected = { + ...makeSession(), + id: 'local:claude:old:/old.jsonl', + sessionId: 'old', + filePath: '/old.jsonl' + } + const recent = Array.from({ length: 501 }, (_, index) => ({ + ...makeSession(), + id: `local:claude:new-${index}:/new-${index}.jsonl`, + sessionId: `new-${index}`, + filePath: `/new-${index}.jsonl` + })) + scanAiVaultSessionsInService.mockResolvedValue({ + ...makeResult(), + sessions: [...recent, selected] + }) + const dispatcher = makeDispatcher() + const selectedSessionId = executionHostId + ? selected.id.replace('local:', `${executionHostId}:`) + : selected.id + const response = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + limit: 500, + includeStructuredSessions: true, + selectedSessionId, + executionHostId + }) + ) + expect(response.ok).toBe(true) + if (response.ok) { + expect(response.result).toMatchObject({ + sessions: expect.arrayContaining([expect.objectContaining({ id: selectedSessionId })]) + }) + expect(response.result).toHaveProperty('sessions.length', 501) + } + expect(scanAiVaultSessionsInService.mock.calls.at(-1)?.[0]).toMatchObject({ + selectedSessionId: selected.id, + limit: 500 + }) + await dispatcher.dispatch(makeRequest('aiVault.listSessions', { limit: 500 })) + expect(scanAiVaultSessionsInService).toHaveBeenCalledTimes(2) + } + ) + + it('omits unchanged session bodies only for clients with the matching fingerprint', async () => { + const dispatcher = makeDispatcher() + const first = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { afterFingerprint: null }) + ) + if ( + !first.ok || + typeof first.result !== 'object' || + first.result === null || + !('fingerprint' in first.result) || + typeof first.result.fingerprint !== 'string' + ) { + throw new Error('Opt-in response did not include a fingerprint') + } + const afterFingerprint = first.result.fingerprint + expect(afterFingerprint).toMatch(/^[0-9a-f]{64}$/) + await expect( + dispatcher.dispatch(makeRequest('aiVault.listSessions', { afterFingerprint })) + ).resolves.toMatchObject({ + ok: true, + result: { unchanged: true, fingerprint: afterFingerprint } + }) + const legacy = await dispatcher.dispatch(makeRequest('aiVault.listSessions', {})) + expect(legacy).toMatchObject({ ok: true, result: makeResult() }) + if (legacy.ok) { + expect(legacy.result).not.toHaveProperty('fingerprint') + } + }) + + it('fingerprints live projected content even when the cached scan stamp does not change', async () => { + const source = { ...makeResult(), sessions: [makeSession()] } + scanAiVaultSessionsInService.mockResolvedValue(source) + const dispatcher = makeDispatcher() + const first = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { afterFingerprint: null }) + ) + if ( + !first.ok || + typeof first.result !== 'object' || + first.result === null || + !('fingerprint' in first.result) || + typeof first.result.fingerprint !== 'string' + ) { + throw new Error('Expected fingerprint') + } + source.sessions[0].title = 'Changed without a new scan stamp' + const changed = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + afterFingerprint: first.result.fingerprint + }) + ) + expect(changed).toMatchObject({ + ok: true, + result: { + sessions: [{ title: 'Changed without a new scan stamp' }], + scannedAt: SCANNED_AT + } + }) + if (changed.ok) { + expect(changed.result).not.toHaveProperty('unchanged') + expect(changed.result).not.toMatchObject({ fingerprint: first.result.fingerprint }) + } + + const forced = await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + afterFingerprint: first.result.fingerprint, + force: true + }) + ) + expect(forced.ok).toBe(true) + if (forced.ok) { + expect(forced.result).not.toHaveProperty('unchanged') + } + }) + + it('restamps the shared cached result as the addressed runtime host', async () => { + scanAiVaultSessionsInService.mockResolvedValue({ + sessions: [makeSession()], + issues: [{ executionHostId: 'local', agent: 'claude', path: '/tmp', message: 'boom' }], + scannedAt: SCANNED_AT + }) + const dispatcher = makeDispatcher() + const localResponse = (await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { limit: 500 }) + )) as { ok: boolean; result: AiVaultListResult } + const runtimeResponse = (await dispatcher.dispatch( + makeRequest('aiVault.listSessions', { + limit: 500, + executionHostId: 'runtime:remote-server' + }) + )) as { ok: boolean; result: AiVaultListResult } + + // Host identity changes response stamps, never host-local scan/cache identity. + + expect(localResponse.result.sessions[0]?.executionHostId).toBe('local') + expect(localResponse.result.scanId).toEqual(expect.any(String)) + expect(runtimeResponse.result).not.toHaveProperty('scanId') + expect(runtimeResponse.result.sessions[0]?.executionHostId).toBe('runtime:remote-server') + expect(runtimeResponse.result.sessions[0]?.id).toBe( + 'runtime:remote-server:claude:sess-1:/tmp/t.jsonl' + ) + expect(runtimeResponse.result.issues[0]?.executionHostId).toBe('runtime:remote-server') + }) +}) diff --git a/src/main/runtime/rpc/methods/history/ai-vault.ts b/src/main/runtime/rpc/methods/history/ai-vault.ts index 18741f4d8638..047e208d0eed 100644 --- a/src/main/runtime/rpc/methods/history/ai-vault.ts +++ b/src/main/runtime/rpc/methods/history/ai-vault.ts @@ -1,4 +1,11 @@ +import { getStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import { readStructuredConversationJournalPreviews } from '../../../../ai-vault/structured-conversation-journal-preview' import { prepareStructuredChatCliFork } from '../../../../ai-vault/structured-sessions/structured-chat-cli-fork' +import { aiVaultOrchestrationChildSessionIds } from '../../../../ai-vault/structured-conversation-navigation' +import { + requestedAiVaultSessionDepth, + truncateAiVaultListResult +} from '../../../../../shared/ai-vault/scanning/ai-vault-session-depth' import { writeAiVaultSessionHandoffSnapshot } from '../../../../ai-vault/session-handoff-snapshot' import { prepareAiVaultSessionHandoffPrompts } from '../../../../ai-vault/session-handoff-prompt' import { @@ -103,6 +110,10 @@ export const AI_VAULT_METHODS = [ await ensureStructuredAgentSessionHostUnlessRefused(() => runtime.ensureStructuredAgentSessionHost() ) + const selectedSessionId = + params.executionHostId && params.selectedSessionId?.startsWith(`${params.executionHostId}:`) + ? `${LOCAL_EXECUTION_HOST_ID}:${params.selectedSessionId.slice(params.executionHostId.length + 1)}` + : params.selectedSessionId let result try { result = await runtime.listAiVaultSessions( @@ -111,6 +122,7 @@ export const AI_VAULT_METHODS = [ unlimited: params.unlimited, force: params.force, scopePaths: params.scopePaths, + selectedSessionId, scopeOnly: params.scopeOnly, includeAntigravityIdeSessions: params.includeAntigravityIdeSessions }, @@ -124,14 +136,45 @@ export const AI_VAULT_METHODS = [ throw new Error(describeAiVaultScanError(String(error))) } // Web clients have no parent retagging, so stamp sessions with the runtime host they addressed. - const projected = projectStructuredAiVaultSessions(result, (agent) => - clientOpensStructuredChatFromHistory({ clientKind, clientCapabilities }, agent) + const projected = projectStructuredAiVaultSessions( + result, + (agent) => clientOpensStructuredChatFromHistory({ clientKind, clientCapabilities }, agent), + { + includeStructuredSessions: params.includeStructuredSessions, + ...(params.includeStructuredSessions + ? { + journalPreviews: await readStructuredConversationJournalPreviews( + getStructuredAgentSessionHost()?.deps.journalDatabase, + getStructuredAgentSessionHost()?.deps.store.listRecords() ?? [] + ) + } + : {}), + ...(params.includeStructuredSessions + ? { + childSessionIds: aiVaultOrchestrationChildSessionIds(() => + runtime.getExistingOrchestrationDb() + ) + } + : {}) + } ) + const limited = params.includeStructuredSessions + ? truncateAiVaultListResult( + projected, + requestedAiVaultSessionDepth(params), + params.scopePaths, + selectedSessionId + ) + : projected return conditionalAiVaultListResult( params.executionHostId - ? restampAiVaultListResult(projected, params.executionHostId) - : projected, - params.unlimited ? undefined : params.afterFingerprint, + ? restampAiVaultListResult(limited, params.executionHostId) + : limited, + params.includeStructuredSessions + ? (params.afterFingerprint ?? null) + : params.unlimited + ? undefined + : params.afterFingerprint, params.force ) } diff --git a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts index 1dfcb6c93680..e41a9465edbd 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-mobile-paired-desktop-methods.ts @@ -40,6 +40,7 @@ export const PAIRED_DESKTOP_METHODS = [ 'stats.summary', 'ui.get', 'ui.recordFeatureInteraction', + 'ui.setConversationPreference', 'ui.set', // The desktop's accounts pane and project pickers target its active runtime, not a workspace's host. 'accounts.consumeCodexResetCredit', diff --git a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts index 09ec01e2c0e6..3dc5cc4ff838 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault/session-actions/ai-vault-session-resume-here.ts @@ -1,9 +1,11 @@ import { admitStructuredAgentSession } from '@/lib/agent-session/structured-agent-session-busy' import { useAppStore } from '@/store/index' +import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import { readBotGroups } from '@/lib/bot-group-catalog-snapshot' import { botGroupRoomOfRow } from '@/lib/bot-group-room-history' import { activateAiVaultStructuredSession, + structuredSessionOpenFeedback, openDesktopStructuredSession } from '@/lib/agent-session/open/activate-ai-vault-structured-session' import { insertUnifiedTabAfterAnchor } from '@/lib/workspace/tabs/unified-tab-anchor-insertion' @@ -23,6 +25,7 @@ import type { } from '../../../../../../shared/ai-vault/contracts/ai-vault-types' import { adoptsCliConversations } from '../../../../../../shared/agent-session/view/structured-agent-cli-conversation-adoption' import type { CliConversationRowAgent } from '../../../../../../shared/agent-session/view/structured-agent-cli-conversation-adoption' +import type { RuntimeClientTarget } from '../../../../../../shared/remote-runtime/host-catalog/runtime-client-target' import { structuredLaunchConversationOwner } from '@/lib/agent-session/launch/structured-agent-session-launch-failure' import { resumeAiVaultSessionInNewChat } from './ai-vault-session-resume-in-chat-launch' import type { ConfirmationDialogContextValue } from '@/components/dismiss/confirmation/confirmation-dialog-context' @@ -75,20 +78,31 @@ export function resumeAiVaultSessionHere(args: { if (!here.agent || !aiVaultHistoryAgents(here.agent).includes(session.agent)) { return false } + const target = session.executionHostId + ? structuredAgentSessionTargetForHost(session.executionHostId) + : undefined let replace: () => Promise if (structured) { if (structured.workspaceId !== here.workspaceId) { return false } - replace = () => revealInPlaceOf(here, structured) + if (target === null) { + structuredSessionOpenFeedback.hostCannotOpen() + return Promise.resolve() + } + replace = () => revealInPlaceOf(here, structured, target) } else if ( actions.resumeInNewChatWorkspaceId && adoptsCliConversations(session.agent) && // Session cwd ties between same-folder workspaces resolve to either. worktreeIdsShareCheckout(actions.resumeInNewChatWorkspaceId, here.workspaceId) ) { + if (target === null) { + structuredSessionOpenFeedback.hostCannotOpen() + return Promise.resolve() + } const rowAgent = session.agent - replace = () => resumeInPlaceOf(here, session, rowAgent) + replace = () => resumeInPlaceOf(here, session, rowAgent, target) } else { return false } @@ -137,7 +151,8 @@ export function resumeAiVaultSessionHere(args: { function resumeInPlaceOf( here: AiVaultReplacement, session: AiVaultSession, - rowAgent: CliConversationRowAgent + rowAgent: CliConversationRowAgent, + target: RuntimeClientTarget | undefined ): Promise { const focus = captureNativeChatComposerFocusIntent() let openedTabId: string | null = null @@ -175,8 +190,8 @@ function resumeInPlaceOf( owner.workspaceId !== here.workspaceId || findChatTabWhere(owner.workspaceId, (tab) => tab.entityId === owner.sessionId) ownerShown = elsewhere - ? activateAiVaultStructuredSession({ structuredSession: owner }) - : revealInPlaceOf(here, owner) + ? activateAiVaultStructuredSession({ structuredSession: owner }, undefined, target) + : revealInPlaceOf(here, owner, target) } if ( settlement?.kind === 'structured' && @@ -199,25 +214,27 @@ function resumeInPlaceOf( /** Reopens a closed chat in place of this one, which closes only once the reopened tab exists. */ function revealInPlaceOf( here: AiVaultReplacement, - structured: NonNullable + structured: NonNullable, + target: RuntimeClientTarget | undefined ): Promise { - return openDesktopStructuredSession({ kind: 'history', structuredSession: structured }).then( - (result) => { - if (result.kind !== 'opened' || !here.current()) { - return - } - // Reported reopen success may lack a tab; replace this chat only when the reopened tab exists. - const reopened = findChatTabWhere( - result.target.worktreeId, - (tab) => tab.id === result.tab.id && tab.entityId === result.target.sessionId - ) - if (reopened) { - // Reveal appends to the group; take this chat's slot as a new chat does (a no-op across splits). - insertUnifiedTabAfterAnchor(result.target.worktreeId, reopened.id, here.tabId) - closeReplacedChat(here) - } + return openDesktopStructuredSession( + { kind: 'history', structuredSession: structured }, + target + ).then((result) => { + if (result.kind !== 'opened' || !here.current()) { + return } - ) + // Reported reopen success may lack a tab; replace this chat only when the reopened tab exists. + const reopened = findChatTabWhere( + result.target.worktreeId, + (tab) => tab.id === result.tab.id && tab.entityId === result.target.sessionId + ) + if (reopened) { + // Reveal appends to the group; take this chat's slot as a new chat does (a no-op across splits). + insertUnifiedTabAfterAnchor(result.target.worktreeId, reopened.id, here.tabId) + closeReplacedChat(here) + } + }) } function findChatTabWhere(workspaceId: string, matches: (tab: Tab) => boolean): Tab | undefined { diff --git a/src/renderer/src/lib/agent-session/open/activate-ai-vault-structured-session.ts b/src/renderer/src/lib/agent-session/open/activate-ai-vault-structured-session.ts index e3641cc2c83c..92f3c1f3e364 100644 --- a/src/renderer/src/lib/agent-session/open/activate-ai-vault-structured-session.ts +++ b/src/renderer/src/lib/agent-session/open/activate-ai-vault-structured-session.ts @@ -1,3 +1,4 @@ +import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import { openDesktopStructuredSessionInteraction } from './open-existing-structured-session' import type { StructuredSessionOpenAdapterDeps } from './open-existing-structured-session' import { showAgentPaneUnavailable } from '@/components/terminal-pane/agent-status/stale-agent-row' @@ -68,7 +69,8 @@ export const structuredSessionOpenFeedback: StructuredSessionOpenFeedback = { /** Read only structuredSession so history clicks and drag payloads follow the same reveal path. */ export async function activateAiVaultStructuredSession( - session: Pick & { agent?: string }, + session: Pick & + Partial> & { agent?: string }, deps?: StructuredSessionActivationDeps, target?: RuntimeClientTarget ): Promise { @@ -81,6 +83,14 @@ export async function activateAiVaultStructuredSession( await openBotGroupRoom(room.group, room.roomId, room.label) return true } + if (!target && session.executionHostId) { + const owner = structuredAgentSessionTargetForHost(session.executionHostId) + if (!owner) { + ;(deps ?? structuredSessionOpenFeedback).hostCannotOpen() + return true + } + target = owner + } await openDesktopStructuredSession( { kind: 'history', structuredSession: session.structuredSession, agent: session.agent }, target, diff --git a/src/shared/ai-vault/contracts/ai-vault-runtime-capabilities.ts b/src/shared/ai-vault/contracts/ai-vault-runtime-capabilities.ts index ddfe235ec4f3..94ab13e38185 100644 --- a/src/shared/ai-vault/contracts/ai-vault-runtime-capabilities.ts +++ b/src/shared/ai-vault/contracts/ai-vault-runtime-capabilities.ts @@ -5,13 +5,19 @@ export const AI_VAULT_RUNTIME_CAPABILITY = 'aiVault.v1' as const export const AI_VAULT_SESSION_TITLES_RUNTIME_CAPABILITY = 'aiVault.session-titles.v1' as const export const AI_VAULT_SESSION_TITLE_REFRESH_RUNTIME_CAPABILITY = 'aiVault.session-title-refresh.v1' as const +export const AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY = 'aiVault.selected-session.v1' as const /** The host deletes its own history rows through aiVault.deleteSession. */ export const AI_VAULT_DELETE_SESSION_RUNTIME_CAPABILITY = 'aiVault.delete-session.v1' as const /** The host builds History hand-off prompts through aiVault.prepareSessionHandoffPrompt. */ export const AI_VAULT_SESSION_HANDOFF_RUNTIME_CAPABILITY = 'aiVault.session-handoff.v1' as const +/** Older hosts may annotate canonical history ownership. */ +export const AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY = + 'aiVault.search.canonical-project.v1' as const + export const AI_VAULT_RUNTIME_CAPABILITIES = [ AI_VAULT_RUNTIME_CAPABILITY, + AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY, AI_VAULT_SESSION_TITLES_RUNTIME_CAPABILITY, AI_VAULT_SESSION_TITLE_REFRESH_RUNTIME_CAPABILITY, AI_VAULT_DELETE_SESSION_RUNTIME_CAPABILITY, diff --git a/src/shared/ai-vault/contracts/ai-vault-types.ts b/src/shared/ai-vault/contracts/ai-vault-types.ts index 5b6c624766c0..90acc49efcc4 100644 --- a/src/shared/ai-vault/contracts/ai-vault-types.ts +++ b/src/shared/ai-vault/contracts/ai-vault-types.ts @@ -114,6 +114,10 @@ export type AiVaultSessionSubagentInfo = { export type AiVaultSessionTitleKind = 'named' | 'fallback' export type AiVaultSession = { + /** A durable Orca conversation with no provider transcript to read or mutate. */ + source?: 'structured-record' + /** Host-proven content; absent or unknown must preserve recoverable conversations. */ + conversationContent?: 'empty' | 'present' | 'unknown' /** Recorded account home; null proves System default, absent means unknown. */ accountHome?: AgentSessionAccountHome | null accountWslDistro?: string | null @@ -144,7 +148,7 @@ export type AiVaultSession = { antigravityOpeningPrompt?: { hash: string; timestamp: string | null } /** One top-level artifact file in the agy conversation folder; revealing it opens that folder. */ antigravityArtifactPath?: string - /** Full first non-injected prompt only on on-demand getFirstUserPrompt reparses; list scans omit it for payload/cost. */ + /** Opening human prompt; durable journal previews are bounded, provider-file full reads remain on demand. */ firstUserPrompt?: string | null /** Latest provider-authenticated user prompt; absent when the transcript has no trustworthy signal. */ lastUserPrompt?: string | null @@ -231,6 +235,10 @@ export type AiVaultScanIssue = { } & Omit export type AiVaultListArgs = { + selectedSessionId?: string + /** Primary conversation navigation includes durable chats without provider files. */ + includeStructuredSessions?: boolean + historyOwnership?: { projectKey?: string } /** Opts a selected runtime-host refresh into content-conditional replies. */ afterFingerprint?: string | null /** Opt-in promises this client starts IDE history in a new CLI conversation. */ @@ -262,6 +270,8 @@ export function boundedAiVaultScopeArgs( } export type AiVaultListResult = { + /** This host included durable Orca records, even when no provider transcript exists. */ + includesStructuredSessions?: true /** Local scan entry that produced this result; absent for remote and merged results. */ scanId?: string fingerprint?: string diff --git a/src/shared/ai-vault/scanning/ai-vault-local-scan-key.ts b/src/shared/ai-vault/scanning/ai-vault-local-scan-key.ts index f605ed4f34b6..ab2ab763c821 100644 --- a/src/shared/ai-vault/scanning/ai-vault-local-scan-key.ts +++ b/src/shared/ai-vault/scanning/ai-vault-local-scan-key.ts @@ -11,6 +11,7 @@ export function aiVaultLocalScanKey(args?: AiVaultListArgs): string { export function aiVaultLocalScanScopeKey(args?: AiVaultListArgs): string { return JSON.stringify({ + selectedSessionId: args?.selectedSessionId, scopePaths: [...new Set(args?.scopePaths ?? [])].sort(), includeAntigravityIdeSessions: args?.includeAntigravityIdeSessions === true, // A scope-only result lacks the newest sessions elsewhere, so it never serves a full request. diff --git a/src/shared/ai-vault/scanning/ai-vault-session-depth.ts b/src/shared/ai-vault/scanning/ai-vault-session-depth.ts index fe2adf8dc38b..b9d9cb087b76 100644 --- a/src/shared/ai-vault/scanning/ai-vault-session-depth.ts +++ b/src/shared/ai-vault/scanning/ai-vault-session-depth.ts @@ -42,7 +42,8 @@ export function aiVaultCachedDepthServes( export function truncateAiVaultListResult( result: AiVaultListResult, depth: AiVaultSessionDepth, - scopePaths: readonly string[] = [] + scopePaths: readonly string[] = [], + selectedSessionId?: string ): AiVaultListResult { if (depth === 'unlimited') { return result @@ -51,7 +52,9 @@ export function truncateAiVaultListResult( let outOfScopeCount = 0 const sessions = result.sessions.filter( (session) => - (inScope !== null && aiVaultSessionInScope(inScope, session)) || outOfScopeCount++ < depth + session.id === selectedSessionId || + (inScope !== null && aiVaultSessionInScope(inScope, session)) || + outOfScopeCount++ < depth ) return { ...result, diff --git a/src/shared/ai-vault/session-display/ai-vault-session-display.ts b/src/shared/ai-vault/session-display/ai-vault-session-display.ts index fab7f23795ae..78b741a5bcdf 100644 --- a/src/shared/ai-vault/session-display/ai-vault-session-display.ts +++ b/src/shared/ai-vault/session-display/ai-vault-session-display.ts @@ -50,7 +50,9 @@ export function sessionDetailConversationTurns( } /** Prompt text with enough provenance for the renderer to avoid overclaiming. */ -export function sessionPromptPreview(session: AiVaultSession): AiVaultSessionPromptPreview | null { +export function sessionPromptPreview< + T extends Pick +>(session: T): AiVaultSessionPromptPreview | null { const stored = session.firstUserPrompt?.trim() if (stored) { return { text: stored, source: 'first-user-prompt' } diff --git a/src/shared/ai-vault/session-display/ai-vault-session-worktree.ts b/src/shared/ai-vault/session-display/ai-vault-session-worktree.ts index fb3807453264..72da843c3e46 100644 --- a/src/shared/ai-vault/session-display/ai-vault-session-worktree.ts +++ b/src/shared/ai-vault/session-display/ai-vault-session-worktree.ts @@ -1,5 +1,6 @@ // Which live workspace owns a saved session's cwd, on the host that recorded it; shared by desktop and mobile. +import { createNormalizedAiVaultScopeCwdMatcher } from '../scanning/ai-vault-scope-cwd-match' import { parseWslUncPath } from '../../file-access/wsl-paths' import { splitWorktreeIdForFilesystem } from '../../worktree/id' import { @@ -9,7 +10,6 @@ import { type ExecutionHostId } from '../../execution-host/execution-host' import { - createNormalizedPathInsideOrEqualMatcher, isRuntimePathAbsolute, normalizeRuntimePathForComparison, normalizeRuntimePathSeparators @@ -47,7 +47,7 @@ type WorktreeCandidate = { status: Exclude source: 'current-path' | 'prior-path' // Precomputed so a 500-session scan doesn't re-normalize ~500 roots per session. - ownsNormalizedCwd: (normalizedCwd: string) => boolean + ownsNormalizedCwd: ReturnType normalizedPathLength: number normalizedPath: string } @@ -267,7 +267,7 @@ function makeWorktreeCandidates( hostId, status: worktree.isArchived ? 'archived' : 'active', source, - ownsNormalizedCwd: createNormalizedPathInsideOrEqualMatcher(cwdPath), + ownsNormalizedCwd: createNormalizedAiVaultScopeCwdMatcher([path]), normalizedPath: normalizeRuntimePathForComparison(cwdPath), normalizedPathLength: normalizeRuntimePathForComparison(path).length })) diff --git a/src/shared/conversation-navigation-preferences.test.ts b/src/shared/conversation-navigation-preferences.test.ts new file mode 100644 index 000000000000..0d4bdf04c20b --- /dev/null +++ b/src/shared/conversation-navigation-preferences.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest' +import { + conversationPreferenceKey, + normalizeConversationPreferences, + updateConversationPreference +} from './conversation-navigation-preferences' + +describe('conversation navigation preferences', () => { + it('keeps host identities and provider transcripts separate while native handles share one identity', () => { + const row = { + executionHostId: 'local' as const, + agent: 'claude' as const, + sessionId: 'provider-old', + structuredSession: { sessionId: 'chat', workspaceId: 'folder:notes' } + } + expect(conversationPreferenceKey(row)).toBe( + conversationPreferenceKey({ ...row, sessionId: 'provider-new' }) + ) + expect(conversationPreferenceKey(row)).not.toBe( + conversationPreferenceKey({ ...row, executionHostId: 'runtime:remote' }) + ) + expect(conversationPreferenceKey(row)).not.toBe( + conversationPreferenceKey({ ...row, structuredSession: undefined }) + ) + }) + it('merges independent pin/archive writes and restores an archived pinned conversation', () => { + const pin = updateConversationPreference(null, { key: 'a', pinned: true }) + const archive = updateConversationPreference(pin, { key: 'a', archived: true }) + const other = updateConversationPreference(archive, { key: 'b', pinned: true }) + const restored = updateConversationPreference(other, { key: 'a', archived: false }) + expect(restored).toEqual({ + revision: 4, + entries: { a: { pinned: true, archived: false }, b: { pinned: true } } + }) + }) + it('tolerates absent and malformed older persisted state', () => { + expect(normalizeConversationPreferences(null)).toEqual({ revision: 0, entries: {} }) + expect(normalizeConversationPreferences({ revision: 3, entries: { a: 'bad' } })).toEqual({ + revision: 3, + entries: { a: {} } + }) + }) + it('hides and restores one host-qualified project without changing chat preferences', () => { + const pinned = updateConversationPreference(null, { key: 'chat', pinned: true }) + const local = JSON.stringify(['local', 'folder:/notes']) + const remote = JSON.stringify(['runtime:server', 'folder:/notes']) + const hidden = updateConversationPreference(pinned, { + projectKey: local, + label: 'Notes', + hidden: true + }) + const both = updateConversationPreference(hidden, { + projectKey: remote, + label: 'Remote notes', + hidden: true + }) + const restored = updateConversationPreference(both, { + projectKey: local, + label: 'Notes', + hidden: false + }) + expect(restored).toEqual({ + revision: 4, + entries: { chat: { pinned: true } }, + hiddenProjects: { [remote]: 'Remote notes' } + }) + }) + it('separates provider histories by distro and Antigravity origin while keeping stored chat handles stable', () => { + const row = { + executionHostId: 'local' as const, + agent: 'codex', + sessionId: 'same', + filePath: '/home/me/.codex/a.jsonl' + } + const ubuntu = { ...row, filePath: '//wsl.localhost/Ubuntu/home/me/.codex/a.jsonl' } + const debian = { ...row, filePath: '//wsl.localhost/Debian/home/me/.codex/a.jsonl' } + expect(new Set([row, ubuntu, debian].map(conversationPreferenceKey)).size).toBe(3) + const cli = { + ...row, + agent: 'antigravity', + filePath: '/home/me/.gemini/antigravity-cli/brain/same/transcript.jsonl' + } + const ide = { ...cli, filePath: cli.filePath.replace('antigravity-cli', 'antigravity-ide') } + expect(conversationPreferenceKey(cli)).not.toBe(conversationPreferenceKey(ide)) + }) +}) diff --git a/src/shared/conversation-navigation-preferences.ts b/src/shared/conversation-navigation-preferences.ts new file mode 100644 index 000000000000..6dc3637913ad --- /dev/null +++ b/src/shared/conversation-navigation-preferences.ts @@ -0,0 +1,110 @@ +import * as z from 'zod' +import type { AiVaultSession } from './ai-vault/contracts/ai-vault-types' +import { sessionFileExecutionNamespace } from './ai-vault/scanning/ai-vault-scope-cwd-match' +import { antigravitySessionOrigin } from './agent-session/lifecycle/provider-handles/antigravity-session-origin' + +export const CONVERSATION_NAVIGATION_CAPABILITY = 'ui.conversationPreferences.v1' +export const CONVERSATION_PROJECT_VISIBILITY_CAPABILITY = 'ui.conversationProjectVisibility.v1' +const Preference = z.object({ pinned: z.boolean().optional(), archived: z.boolean().optional() }) +export const ConversationPreferencesSchema = z.object({ + revision: z.number().int().nonnegative().catch(0), + entries: z.record(z.string().max(2048), Preference.catch({})).catch({}), + hiddenProjects: z.record(z.string().max(2048), z.string().max(1024)).optional().catch(undefined) +}) +export type ConversationPreferences = z.infer +export type ConversationPreference = z.infer +const SetChatPreferenceParams = z + .object({ + key: z.string().min(1).max(2048), + pinned: z.boolean().optional(), + archived: z.boolean().optional() + }) + .strict() + .refine((value) => value.pinned !== undefined || value.archived !== undefined) +export const SetConversationProjectVisibilityParams = z + .object({ + projectKey: z.string().min(1).max(2048), + label: z.string().min(1).max(1024), + hidden: z.boolean() + }) + .strict() +export const SetConversationPreferenceParams = z.union([ + SetChatPreferenceParams, + SetConversationProjectVisibilityParams +]) + +export function conversationProjectVisibilityKey(host: string, projectKey: string): string { + return JSON.stringify([host, projectKey]) +} + +export function normalizeConversationPreferences(value: unknown): ConversationPreferences { + const result = ConversationPreferencesSchema.safeParse(value) + return result.success ? result.data : { revision: 0, entries: {} } +} + +export function conversationPreferenceKey( + session: Pick & { + agent: string + filePath?: string + id?: string + } +): string { + const owner = [ + session.executionHostId, + session.structuredSession ? 'structured' : session.agent, + session.structuredSession?.sessionId ?? session.sessionId + ] + if (session.structuredSession) { + return JSON.stringify(owner) + } + if (!session.filePath) { + return JSON.stringify([...owner, 'unknown', session.id ?? session.sessionId]) + } + const namespace = sessionFileExecutionNamespace(session.filePath) + if (namespace === 'native' && session.agent !== 'antigravity') { + return JSON.stringify(owner) + } + return JSON.stringify([ + ...owner, + namespace, + ...(session.agent === 'antigravity' + ? [ + antigravitySessionOrigin(session.filePath), + session.filePath + .split(/[\\/]+/) + .slice(0, -4) + .join('/') + ] + : []) + ]) +} + +export function updateConversationPreference( + current: unknown, + request: z.infer +): ConversationPreferences { + const state = normalizeConversationPreferences(current) + const revision = Math.min(Number.MAX_SAFE_INTEGER, state.revision + 1) + if ('projectKey' in request) { + const hiddenProjects = { ...state.hiddenProjects } + if (request.hidden) { + hiddenProjects[request.projectKey] = request.label + } else { + delete hiddenProjects[request.projectKey] + } + return { ...state, revision, hiddenProjects } + } + const previous = state.entries[request.key] ?? {} + return { + ...state, + revision, + entries: { + ...state.entries, + [request.key]: { + ...previous, + ...(request.pinned !== undefined ? { pinned: request.pinned } : {}), + ...(request.archived !== undefined ? { archived: request.archived } : {}) + } + } + } +} diff --git a/src/shared/conversation-workspace-matcher.test.ts b/src/shared/conversation-workspace-matcher.test.ts new file mode 100644 index 000000000000..af4c1f8d4904 --- /dev/null +++ b/src/shared/conversation-workspace-matcher.test.ts @@ -0,0 +1,32 @@ +import { expect, it } from 'vitest' +import { createConversationWorkspaceMatcher } from './conversation-workspace-matcher' + +it('matches the most specific folder within its authenticated host and distro', () => { + const rows = [ + { id: 'ubuntu', path: '//wsl.localhost/Ubuntu/home/me/project', hostId: 'local' as const }, + { id: 'debian', path: '//wsl.localhost/Debian/home/me/project', hostId: 'local' as const }, + { id: 'nested', path: '//wsl.localhost/Ubuntu/home/me/project/docs', hostId: 'local' as const }, + { id: 'remote', path: '/home/me/project', hostId: 'runtime:server' as const } + ] + const match = createConversationWorkspaceMatcher(rows) + const session = { + cwd: '/home/me/project/docs/subfolder', + filePath: '//wsl.localhost/Ubuntu/home/me/.codex/chat.jsonl', + executionHostId: 'local' as const + } + expect(match(session)?.id).toBe('nested') + expect(match({ ...session, filePath: '/home/me/.codex/chat.jsonl' })).toBeNull() + expect(match({ ...session, executionHostId: 'runtime:server' })?.id).toBe('remote') +}) + +it('keeps structured workspace ownership exact and refuses ambiguous folder twins', () => { + const rows = [ + { id: 'one', path: '/notes', hostId: 'local' as const }, + { id: 'two', path: '/notes', hostId: 'local' as const } + ] + const match = createConversationWorkspaceMatcher(rows) + const session = { cwd: '/notes/child', executionHostId: 'local' as const } + expect(match(session)).toBeNull() + expect(match({ ...session, structuredSession: { workspaceId: 'two' } })).toBe(rows[1]) + expect(match({ ...session, structuredSession: { workspaceId: 'missing' } })).toBeNull() +}) diff --git a/src/shared/conversation-workspace-matcher.ts b/src/shared/conversation-workspace-matcher.ts new file mode 100644 index 000000000000..588954fddc94 --- /dev/null +++ b/src/shared/conversation-workspace-matcher.ts @@ -0,0 +1,41 @@ +import { createAiVaultScopeCwdMatcher } from './ai-vault/scanning/ai-vault-scope-cwd-match' +import { normalizeRuntimePathForComparison } from './file-access/cross-platform-path' +import type { ExecutionHostId } from './execution-host/execution-host' + +type Workspace = { id: string; path: string; hostId?: ExecutionHostId } +type Conversation = { + executionHostId: ExecutionHostId + cwd: string | null + cwdAliases?: string[] + filePath?: string + structuredSession?: { workspaceId: string } +} + +export function createConversationWorkspaceMatcher(workspaces: readonly T[]) { + const candidates = workspaces + .map((workspace) => ({ + workspace, + length: normalizeRuntimePathForComparison(workspace.path).length, + contains: createAiVaultScopeCwdMatcher([workspace.path]) + })) + .sort((a, b) => b.length - a.length) + return (session: Conversation): T | null => { + const matches = candidates.filter( + ({ workspace, contains }) => + (workspace.hostId ?? 'local') === session.executionHostId && + (session.structuredSession + ? workspace.id === session.structuredSession.workspaceId + : [session.cwd, ...(session.cwdAliases ?? [])].some((cwd) => + contains(cwd, session.filePath) + )) + ) + const best = matches[0] + return best && + !matches.some( + (candidate) => + candidate.length === best.length && candidate.workspace.id !== best.workspace.id + ) + ? best.workspace + : null + } +} diff --git a/src/shared/orca-profiles/persisted-ui-state-types.ts b/src/shared/orca-profiles/persisted-ui-state-types.ts index 63301caf278d..349203ad8c42 100644 --- a/src/shared/orca-profiles/persisted-ui-state-types.ts +++ b/src/shared/orca-profiles/persisted-ui-state-types.ts @@ -1,3 +1,4 @@ +import type { ConversationPreferences } from '../conversation-navigation-preferences' import type { GitHistoryRefs } from '../git/history/git-history-types' import type { BotChatFold } from '../bots/bot-chat-tree' import type { JiraQuickFilterState } from '../jira/jira-quick-filters' @@ -59,6 +60,7 @@ export type PersistedUIState = { combinedDiffFileTreeWidth?: number groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status' sortBy: 'name' | 'smart' | 'recent' | 'repo' | 'manual' + conversationPreferences?: ConversationPreferences /** Project-header order in repo grouping, independent of workspace sort: manual permits drag, recent follows visible activity. */ projectOrderBy: ProjectOrderBy /** Deprecated; the Active only filter is retired and ignored on hydration. */ diff --git a/src/shared/project-conversation-list.test.ts b/src/shared/project-conversation-list.test.ts new file mode 100644 index 000000000000..ddafecb0e3f9 --- /dev/null +++ b/src/shared/project-conversation-list.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { projectConversations, projectConversationTitle } from './project-conversation-list' +import { conversationPreferenceKey } from './conversation-navigation-preferences' +import type { AiVaultSession } from './ai-vault/contracts/ai-vault-types' +const row = (id: string, date: string): AiVaultSession => ({ + id, + sessionId: id, + executionHostId: 'local', + agent: 'claude', + title: 'Claude Chat', + cwd: '/notes', + branch: null, + model: null, + filePath: '/log', + codexHome: null, + createdAt: date, + updatedAt: date, + modifiedAt: date, + messageCount: 2, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null +}) +describe('project conversation navigation', () => { + it('puts pinned chats before recency and restores archived chats without changing their identity', () => { + const old = row('old', '2026-10-01') + const recent = row('recent', '2026-10-26') + const archived = row('archived', '2026-10-25') + const preferences = { + revision: 1, + entries: { + [conversationPreferenceKey(old)]: { pinned: true }, + [conversationPreferenceKey(archived)]: { archived: true } + } + } + expect(projectConversations([recent, archived, old], preferences).map((s) => s.id)).toEqual([ + 'old', + 'recent' + ]) + expect(projectConversations([recent, archived, old], preferences, true)).toEqual([archived]) + }) + it('omits only proven empty records, preserving unknown or recoverable conversations', () => { + const unknown = row('unknown', '2026-10-26') + const empty = { ...row('empty', '2026-10-25'), conversationContent: 'empty' as const } + expect(projectConversations([empty, unknown], { revision: 0, entries: {} })).toEqual([unknown]) + }) + it('uses a user prompt for generic names and respects actual saved titles', () => { + const session = { + ...row('chat', '2026-10-26'), + previewMessages: [ + { role: 'user' as const, text: 'Fix reader pagination alignment', timestamp: null } + ] + } + expect(projectConversationTitle(session)).toBe('Fix reader pagination alignment') + expect(projectConversationTitle(session, 'Reader pagination')).toBe('Reader pagination') + }) + + it('replaces injected command titles from older hosts with a human prompt', () => { + const caveat = 'Local command output follows' + const session = { + ...row('chat', '2026-10-26'), + title: caveat, + firstUserPrompt: caveat, + previewMessages: [ + { role: 'user' as const, text: caveat, timestamp: null }, + { role: 'user' as const, text: 'Fix reader pagination alignment', timestamp: null } + ] + } + expect(projectConversationTitle(session)).toBe('Fix reader pagination alignment') + expect(projectConversationTitle({ ...session, previewMessages: [] })).toBe('') + expect(projectConversationTitle(session, ' rendering')).toBe(' rendering') + }) + + it('replaces scanner-generated identifier labels when a human prompt is available', () => { + const session = { + ...row('019f7a2c-1234', '2026-10-26'), + title: 'Claude 019f7a2c', + firstUserPrompt: 'Investigate the intermittent deployment failure' + } + expect(projectConversationTitle(session)).toBe( + 'Investigate the intermittent deployment failure' + ) + }) +}) diff --git a/src/shared/project-conversation-list.ts b/src/shared/project-conversation-list.ts new file mode 100644 index 000000000000..ec74841e9221 --- /dev/null +++ b/src/shared/project-conversation-list.ts @@ -0,0 +1,75 @@ +import { conversationNameSeed } from './source-control/ai/generation/conversation-name-generation' +import { + conversationPreferenceKey, + type ConversationPreferences +} from './conversation-navigation-preferences' +import { AI_VAULT_AGENT_LABELS, type AiVaultSession } from './ai-vault/contracts/ai-vault-types' +import { sessionPromptPreview } from './ai-vault/session-display/ai-vault-session-display' +import { isKnownHarnessInjectedUserTurnText } from './agent-session/journal/harness-injected-user-turns' + +const GENERIC_TITLES = new Set( + Object.values(AI_VAULT_AGENT_LABELS) + .flatMap((label) => [`${label} Chat`, `${label} чат`]) + .map((label) => label.toLowerCase()) +) + +export function isGenericConversationTitle(title: string): boolean { + const value = title.trim() + return ( + !value || + /^[.\s…]+$/u.test(value) || + GENERIC_TITLES.has(value.toLowerCase()) || + isKnownHarnessInjectedUserTurnText(value) || + Object.values(AI_VAULT_AGENT_LABELS).some( + (label) => + value.startsWith(`${label} `) && /^[0-9a-f]{8}$/iu.test(value.slice(label.length + 1)) + ) + ) +} + +export function projectConversationTitle( + session: Pick, + title = session.title +): string { + if (!isGenericConversationTitle(title)) { + return title + } + const prompt = sessionPromptPreview({ + firstUserPrompt: + session.firstUserPrompt && !isKnownHarnessInjectedUserTurnText(session.firstUserPrompt) + ? session.firstUserPrompt + : null, + previewMessages: session.previewMessages.filter( + (message) => !isKnownHarnessInjectedUserTurnText(message.text) + ) + }) + return ( + conversationNameSeed(prompt?.text ?? '') ?? + (isKnownHarnessInjectedUserTurnText(title) ? '' : title) + ) +} + +export function projectConversations( + sessions: readonly AiVaultSession[], + preferences: ConversationPreferences, + archived = false +): AiVaultSession[] { + return sessions + .filter( + (session) => + session.conversationContent !== 'empty' && + (preferences.entries[conversationPreferenceKey(session)]?.archived === true) === archived + ) + .sort((a, b) => { + const pinned = + Number(preferences.entries[conversationPreferenceKey(b)]?.pinned === true) - + Number(preferences.entries[conversationPreferenceKey(a)]?.pinned === true) + return ( + pinned || + (Date.parse(b.updatedAt ?? b.modifiedAt) || 0) - + (Date.parse(a.updatedAt ?? a.modifiedAt) || 0) + ) + }) +} + +export const PROJECT_CONVERSATION_PAGE_SIZE = 5 diff --git a/src/shared/remote-runtime/protocol/protocol-version.ts b/src/shared/remote-runtime/protocol/protocol-version.ts index 9e2add5c1d8a..3fc5011b771b 100644 --- a/src/shared/remote-runtime/protocol/protocol-version.ts +++ b/src/shared/remote-runtime/protocol/protocol-version.ts @@ -3,6 +3,10 @@ import { PROJECT_ROOT_ORDER_RUNTIME_CAPABILITY } from '../../project/groups/project-group-order-capability' import { EMULATOR_RUNTIME_CAPABILITIES } from './emulator-runtime-capabilities' +import { + CONVERSATION_NAVIGATION_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY +} from '../../conversation-navigation-preferences' import { ACCOUNT_RUNTIME_CAPABILITIES } from './account-runtime-capabilities' import * as agentLaunchCapabilities from '../../agent-launch/contracts/agent-launch-runtime-capability' import { @@ -76,6 +80,8 @@ export const RUNTIME_CAPABILITIES = /* @__PURE__ */ (() => [ ...EMULATOR_RUNTIME_CAPABILITIES, SAVED_RESUME_ORIGIN_RUNTIME_CAPABILITY, + CONVERSATION_NAVIGATION_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY, ...HOST_RUNTIME_CAPABILITIES, ...DEVICE_KEY_RUNTIME_CAPABILITIES, E2EE_V2_TOKEN_CAPABILITIES_RUNTIME_CAPABILITY, diff --git a/src/shared/rpc-contract/ai-vault/ai-vault-params.ts b/src/shared/rpc-contract/ai-vault/ai-vault-params.ts index 17a0180fb043..f0be2a7e600e 100644 --- a/src/shared/rpc-contract/ai-vault/ai-vault-params.ts +++ b/src/shared/rpc-contract/ai-vault/ai-vault-params.ts @@ -31,6 +31,8 @@ export const AiVaultListSessionsParams = z .pipe(z.union([z.number().int(), z.undefined()])) .optional(), includeAntigravityIdeSessions: OptionalBoolean, + includeStructuredSessions: OptionalBoolean, + selectedSessionId: z.string().min(1).max(8192).optional(), unlimited: OptionalBoolean, force: OptionalBoolean, afterFingerprint: z diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index a7f3d68b0037..6c59d549d27e 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -39,6 +39,7 @@ import { DesktopBrowserBridgeResultChunkParams, DesktopBrowserBridgeResultParams } from '../browser/client-hosting/desktop-browser-bridge-protocol' +import { SetConversationPreferenceParams } from '../conversation-navigation-preferences' import { MobileWebBundleChunkParamsSchema } from '../mobile-web-bundle/bundle-rpc-contract' import { MobileWebBundleLocaleCatalogParamsSchema } from '../mobile-web-bundle/locale-catalog-contract' import { OrcadMigrationBlobChunkRequestSchema } from '../orcad-migration/orcad-migration-blob-transfer' @@ -2176,6 +2177,7 @@ export const RPC_PARAMS_BY_METHOD = { 'ui.recordFeatureInteraction': FeatureInteractionIdParam, 'ui.set': UiUpdate, 'ui.setCollapsed': SetCollapsedParams, + 'ui.setConversationPreference': SetConversationPreferenceParams, 'ui.setJiraQuickFilters': JiraQuickFilterStateParam, 'updater.check': UpdaterCheckParams, 'updater.download': null, diff --git a/src/shared/wsl-move/wsl-move-ui-dispositions.ts b/src/shared/wsl-move/wsl-move-ui-dispositions.ts index 4aefed9a1892..af7f480afa4a 100644 --- a/src/shared/wsl-move/wsl-move-ui-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-ui-dispositions.ts @@ -14,6 +14,10 @@ export const UI_STATE_DISPOSITIONS = { 'Owed to a paired server; a WSL move only moves local projects.' ), lastActiveWorktreeId: moveDisposition(38, { rewriteDesktopCopy: true }), + conversationPreferences: notApplicableDisposition( + 38, + 'Conversation preferences retain their execution-host-qualified identities.' + ), manualRepoOrder: moveDisposition(38, { rewriteDesktopCopy: true, note: "The desktop copy's hostId changes from 'local' to the WSL host."