From d90628d9dc3e726e2f99bc750dc264e4974ea698 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Wed, 28 Oct 2026 16:20:43 +0700 Subject: [PATCH 01/17] Show mobile conversations within projects instead of branch-first navigation --- .../mobile-web-app-drawer-render.test.mjs | 5 +- ...ile-web-app-handoff-grants-render.test.mjs | 16 +- ...-app-project-conversations-render.test.mjs | 349 +++++++++++++++ .../mobile-web-app-render.test.mjs | 18 +- .../mobile-web-app-safe-area-render.test.mjs | 6 +- mobile/README.md | 10 +- .../h/[hostId]/agent-history/[worktreeId].tsx | 10 +- .../agent-history/[worktreeId].web.tsx | 2 + .../MobileAgentSessionHistoryList.tsx | 26 +- .../MobileAgentSessionHistoryPanel.tsx | 90 ++-- .../agent-history-retry.test.tsx | 251 +++++++++++ .../mobile-agent-history-screen-state.ts | 16 + .../use-mobile-agent-history-state.ts | 75 ++-- mobile/src/components/ActionSheetModal.tsx | 5 + .../host-screen/ConversationProjectHeader.tsx | 65 +++ mobile/src/host-screen/HostConversations.tsx | 397 ++++++++++++++++++ .../host-screen/conversation-agent-sheet.tsx | 37 ++ mobile/src/host-screen/conversation-copy.ts | 151 +++++++ .../conversation-details-sheet.tsx | 106 +++++ .../host-screen/conversation-history-index.ts | 29 ++ .../src/host-screen/conversation-open.test.ts | 87 ++++ mobile/src/host-screen/conversation-open.ts | 48 +++ .../conversation-project-actions-sheet.tsx | 37 ++ .../conversation-project-actions.test.tsx | 145 +++++++ .../conversation-project-order-sheet.tsx | 31 ++ .../src/host-screen/conversation-project.ts | 36 ++ .../src/host-screen/conversation-records.ts | 69 +++ .../conversation-sidebar-options.tsx | 59 +++ mobile/src/host-screen/conversation-styles.ts | 89 ++++ .../hidden-conversation-projects-sheet.tsx | 37 ++ .../src/host-screen/host-screen-operations.ts | 15 + .../host-screen/host-screen-reply-schema.ts | 5 + mobile/src/host-screen/host-screen-view.tsx | 23 +- .../host-screen/project-conversation-order.ts | 63 +++ .../project-conversation-visibility.test.ts | 119 ++++++ .../project-conversations.test-fixture.ts | 60 +++ .../host-screen/project-conversations.test.ts | 297 +++++++++++++ .../src/host-screen/project-conversations.ts | 277 ++++++++++++ .../use-conversation-actions.test.tsx | 217 ++++++++++ .../host-screen/use-conversation-actions.ts | 233 ++++++++++ .../use-conversation-details.test.tsx | 49 +++ .../host-screen/use-conversation-details.ts | 26 ++ .../use-conversation-preferences.test.tsx | 155 +++++++ .../use-conversation-preferences.ts | 95 +++++ .../host-screen/use-host-screen-controller.ts | 2 + .../use-project-conversations.test.tsx | 311 ++++++++++++++ .../host-screen/use-project-conversations.ts | 295 +++++++++++++ .../src/session/notification-pane-tab.test.ts | 39 ++ mobile/src/session/notification-pane-tab.ts | 6 +- .../bridged-parity/c1-page-closure.ts | 19 + .../src/worktree/workspace-view-settings.ts | 9 + src/main/ai-vault/cached-session-list.ts | 8 +- src/main/ai-vault/session-file-observation.ts | 66 +++ .../session-list-result-validation.test.ts | 21 + .../session-list-result-validation.ts | 8 +- .../ai-vault/session-list-results.test.ts | 57 ++- src/main/ai-vault/session-list-results.ts | 5 +- .../ai-vault/session-parse-cache-database.ts | 2 +- .../session-scanner-antigravity-sources.ts | 2 + ...canner-claude-conversation-content.test.ts | 143 +++++++ ...session-scanner-discovery-wsl-gate.test.ts | 16 +- .../ai-vault/session-scanner-discovery.ts | 92 ++-- .../session-scanner-opencode-sources.ts | 6 + ...ssion-scanner-opencode-sqlite-discovery.ts | 10 + ...ession-scanner-opencode-sqlite-dispatch.ts | 6 +- .../session-scanner-opencode-sqlite-list.ts | 32 +- ...n-scanner-opencode-sqlite-process-entry.ts | 2 + ...n-scanner-opencode-sqlite-worker-client.ts | 2 + ...-scanner-opencode-sqlite-worker-factory.ts | 19 + ...scanner-opencode-sqlite-worker-protocol.ts | 1 + ...anner-opencode-sqlite-worker-spawn.test.ts | 17 + ...on-scanner-opencode-sqlite-worker-spawn.ts | 33 +- .../session-scanner-opencode-sqlite.test.ts | 26 ++ .../session-scanner-opencode2-sqlite-list.ts | 32 +- .../session-scanner-opencode2-sqlite.test.ts | 33 ++ .../ai-vault/session-scanner-parse-cache.ts | 8 +- .../session-scanner-primary-parsers.ts | 49 ++- .../session-scanner-selected-session.test.ts | 49 +++ .../ai-vault/session-scanner-selection.ts | 33 ++ .../session-scanner-source-discovery.ts | 3 + src/main/ai-vault/session-scanner-types.ts | 2 + .../ai-vault/session-scanner-zcode-sources.ts | 5 + src/main/ai-vault/session-scanner.ts | 26 +- .../ai-vault/session-transcript-reader.ts | 15 +- ...structured-conversation-journal-preview.ts | 106 +++++ ...ed-conversation-navigation-content.test.ts | 207 +++++++++ ...structured-conversation-navigation.test.ts | 352 ++++++++++++++++ .../structured-conversation-navigation.ts | 171 ++++++++ ...ructured-session-ownership.test-support.ts | 44 +- .../structured-session-ownership.test.ts | 21 +- .../ai-vault/structured-session-ownership.ts | 55 ++- .../applying-settings/ui-state-read.ts | 2 + .../applying-settings/ui-state-update.ts | 4 + src/main/runtime/rpc/methods/ai-vault.test.ts | 102 ++++- src/main/runtime/rpc/methods/ai-vault.ts | 43 +- ...client-ui-conversation-preferences.test.ts | 103 +++++ src/main/runtime/rpc/methods/client-ui.ts | 17 + .../methods/ui-state-schema-parity-checks.ts | 1 + .../runtime-rpc-mobile-method-routing.test.ts | 3 +- ...ntime-rpc-mobile-paired-desktop-methods.ts | 1 + ...iVaultSessionVirtualList.keyboard.test.tsx | 128 +++++- .../ai-vault-session-resume-here.ts | 38 +- .../ai-vault-session-worktree.test.ts | 32 +- ...activation-structured-chat-surface.test.ts | 3 +- src/shared/ai-vault-local-scan-key.ts | 1 + src/shared/ai-vault-runtime-capabilities.ts | 6 + src/shared/ai-vault-session-depth.ts | 7 +- src/shared/ai-vault-session-display.ts | 4 +- src/shared/ai-vault-session-worktree.ts | 16 +- src/shared/ai-vault-types.ts | 12 +- ...onversation-navigation-preferences.test.ts | 86 ++++ .../conversation-navigation-preferences.ts | 110 +++++ .../conversation-workspace-matcher.test.ts | 32 ++ src/shared/conversation-workspace-matcher.ts | 41 ++ src/shared/persisted-ui-state-types.ts | 2 + src/shared/project-conversation-list.test.ts | 87 ++++ src/shared/project-conversation-list.ts | 75 ++++ src/shared/protocol-version.ts | 6 + src/shared/rpc-contract/ai-vault-params.ts | 2 + .../rpc-params-catalog.generated.ts | 2 + .../wsl-move/wsl-move-ui-dispositions.ts | 4 + 121 files changed, 7084 insertions(+), 288 deletions(-) create mode 100644 config/scripts/mobile-web-app/mobile-web-app-project-conversations-render.test.mjs create mode 100644 mobile/src/agent-history/mobile-agent-history-screen-state.ts create mode 100644 mobile/src/host-screen/ConversationProjectHeader.tsx create mode 100644 mobile/src/host-screen/HostConversations.tsx create mode 100644 mobile/src/host-screen/conversation-agent-sheet.tsx create mode 100644 mobile/src/host-screen/conversation-copy.ts create mode 100644 mobile/src/host-screen/conversation-details-sheet.tsx create mode 100644 mobile/src/host-screen/conversation-history-index.ts create mode 100644 mobile/src/host-screen/conversation-open.test.ts create mode 100644 mobile/src/host-screen/conversation-open.ts create mode 100644 mobile/src/host-screen/conversation-project-actions-sheet.tsx create mode 100644 mobile/src/host-screen/conversation-project-actions.test.tsx create mode 100644 mobile/src/host-screen/conversation-project-order-sheet.tsx create mode 100644 mobile/src/host-screen/conversation-project.ts create mode 100644 mobile/src/host-screen/conversation-records.ts create mode 100644 mobile/src/host-screen/conversation-sidebar-options.tsx create mode 100644 mobile/src/host-screen/conversation-styles.ts create mode 100644 mobile/src/host-screen/hidden-conversation-projects-sheet.tsx create mode 100644 mobile/src/host-screen/project-conversation-order.ts create mode 100644 mobile/src/host-screen/project-conversation-visibility.test.ts create mode 100644 mobile/src/host-screen/project-conversations.test-fixture.ts create mode 100644 mobile/src/host-screen/project-conversations.test.ts create mode 100644 mobile/src/host-screen/project-conversations.ts create mode 100644 mobile/src/host-screen/use-conversation-actions.test.tsx create mode 100644 mobile/src/host-screen/use-conversation-actions.ts create mode 100644 mobile/src/host-screen/use-conversation-details.test.tsx create mode 100644 mobile/src/host-screen/use-conversation-details.ts create mode 100644 mobile/src/host-screen/use-conversation-preferences.test.tsx create mode 100644 mobile/src/host-screen/use-conversation-preferences.ts create mode 100644 mobile/src/host-screen/use-project-conversations.test.tsx create mode 100644 mobile/src/host-screen/use-project-conversations.ts create mode 100644 mobile/src/session/notification-pane-tab.test.ts create mode 100644 src/main/ai-vault/session-file-observation.ts create mode 100644 src/main/ai-vault/session-scanner-claude-conversation-content.test.ts create mode 100644 src/main/ai-vault/session-scanner-opencode-sqlite-worker-factory.ts create mode 100644 src/main/ai-vault/session-scanner-selected-session.test.ts create mode 100644 src/main/ai-vault/session-scanner-selection.ts create mode 100644 src/main/ai-vault/structured-conversation-journal-preview.ts create mode 100644 src/main/ai-vault/structured-conversation-navigation-content.test.ts create mode 100644 src/main/ai-vault/structured-conversation-navigation.test.ts create mode 100644 src/main/ai-vault/structured-conversation-navigation.ts create mode 100644 src/main/runtime/rpc/methods/client-ui-conversation-preferences.test.ts create mode 100644 src/shared/conversation-navigation-preferences.test.ts create mode 100644 src/shared/conversation-navigation-preferences.ts create mode 100644 src/shared/conversation-workspace-matcher.test.ts create mode 100644 src/shared/conversation-workspace-matcher.ts create mode 100644 src/shared/project-conversation-list.test.ts create mode 100644 src/shared/project-conversation-list.ts diff --git a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs index 3f280c231fe5..8a0b25465951 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs @@ -120,9 +120,9 @@ function instrumentFrames() { } } -/** The header's Workspace options chip, by its own label. */ +/** Open the project header menu through its accessible name. */ function workspaceOptionsChip(page) { - return page.getByText('Workspace options', { exact: true }) + return page.getByRole('button', { name: 'More options', exact: true }) } describeDrawer('the bottom drawer on the page', () => { @@ -134,6 +134,7 @@ describeDrawer('the bottom drawer on the page', () => { // Reanimated latches media query at import; emulateMedia after goto cannot undo it. const page = await browser.newPage({ viewport: VIEWPORT, + locale: 'en-US', reducedMotion: 'no-preference' }) const errors = [] diff --git a/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs index dd631a62890f..b3b3e7e6c73d 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs @@ -94,7 +94,7 @@ async function openHostRoute({ awaitText = SHELL_HOST.name, ownsHostArea = false }) { - const page = await browser.newPage({ viewport }) + const page = await browser.newPage({ viewport, locale: 'en-US' }) await page.addInitScript(installShellDouble, { version: bridgeVersion, sessionId: SHELL_SESSION_ID, @@ -133,6 +133,10 @@ async function openHostRoute({ timeout: 30_000, polling: 250 }) + const menu = page.getByRole('button', { name: 'More options', exact: true }) + if (route === HOST_ROUTE) { + await menu.click() + } return { page, errors, jsResponses } } @@ -176,7 +180,7 @@ describeRender('the sidebar hop to tasks, under the session it was opened with', }) const { page, errors, jsResponses } = opened // The header's own control, by the name a user reads; it is the sidebar's on a wide layout. - await page.getByLabel('Tasks').first().click() + await page.getByRole('button', { name: 'Tasks', exact: true }).first().click() await expect .poll(() => navigates(page)) .toEqual([ @@ -207,7 +211,7 @@ describeRender('the sidebar hop to tasks, under the session it was opened with', }) const { page, errors } = opened const clickedAt = opened.jsResponses.length - await page.getByLabel('Tasks').first().click() + await page.getByRole('button', { name: 'Tasks', exact: true }).first().click() await waitForTasksRoute(page, opened, clickedAt) expect(await navigates(page)).toEqual([]) expect(errors).toEqual([]) @@ -221,7 +225,7 @@ describeRender('the sidebar hop to tasks, under the session it was opened with', grants: [faultGrant, 'navigate', 'storage', 'haptics'] }) const { page, errors, jsResponses } = opened - const tasks = page.getByLabel('Tasks') + const tasks = page.getByRole('button', { name: 'Tasks', exact: true }) // Require one narrow toolbar control or selecting among duplicates could hide a stray wide header. expect(await tasks.count()).toBe(1) await tasks.click() @@ -248,7 +252,7 @@ describeRender('the sidebar hop to tasks, under the session it was opened with', }) const { page, errors } = opened const clickedAt = opened.jsResponses.length - await page.getByLabel('Tasks').first().click() + await page.getByRole('button', { name: 'Tasks', exact: true }).first().click() await waitForTasksRoute(page, opened, clickedAt) expect(await navigates(page)).toEqual([]) expect(errors).toEqual([]) @@ -268,7 +272,7 @@ describeRender('the sidebar hop to tasks, under the session it was opened with', expect( await page.evaluate((name) => document.body.innerText.includes(name), SHELL_HOST.name) ).toBe(false) - expect(await page.getByLabel('Tasks').count()).toBe(0) + expect(await page.getByRole('button', { name: 'Tasks', exact: true }).count()).toBe(0) expect(errors).toEqual([]) await page.close() }, 60_000) 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..03e508738de2 --- /dev/null +++ b/config/scripts/mobile-web-app/mobile-web-app-project-conversations-render.test.mjs @@ -0,0 +1,349 @@ +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-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) { + 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: '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', exact: true }).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', exact: true }).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', exact: true }).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 + } + }) + await page.getByText('Этот хост показывает открытые чаты', { exact: false }).waitFor() + 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', exact: true }) + .waitFor() + expect(errors).toEqual([]) + await page.close() + }, 60_000) +}) diff --git a/config/scripts/mobile-web-app/mobile-web-app-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-render.test.mjs index 38744327b680..9e948b897546 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-render.test.mjs @@ -358,11 +358,11 @@ describeRender('the Route A page in a real browser', () => { await opened.page.goto(`${origin}/`, { waitUntil: 'load' }) await waitForRoute(opened, HOST_ROUTE, SHELL_HOST.name) const layout = await opened.page.evaluate(() => { - // No-RPC control at root bottom moves furthest if layout collapses. - const fab = [...document.querySelectorAll('[role="button"]')].find( - (element) => element.getAttribute('aria-label') === 'New workspace' + // The host's settings remain reachable even when the host has answered no catalog reads. + const control = [...document.querySelectorAll('[role="button"]')].find( + (element) => element.getAttribute('aria-label') === 'More options' ) - const box = fab?.getBoundingClientRect() ?? null + const box = control?.getBoundingClientRect() ?? null const hit = box === null ? null @@ -370,17 +370,17 @@ describeRender('the Route A page in a real browser', () => { return { rootHeight: document.getElementById('root').getBoundingClientRect().height, viewportHeight: window.innerHeight, - fabTop: box?.top ?? null, - fabBottom: box?.bottom ?? null, - reachesTheControl: hit !== null && fab.contains(hit) + controlTop: box?.top ?? null, + controlBottom: box?.bottom ?? null, + reachesTheControl: hit !== null && control.contains(hit) } }) await opened.page.close() expect(opened.errors).toEqual([]) // Measure height: mounted text/innerText can pass while collapsed root paints blank phone screen. expect(layout.rootHeight).toBe(layout.viewportHeight) - expect(layout.fabTop).toBeGreaterThan(0) - expect(layout.fabBottom).toBeLessThanOrEqual(layout.viewportHeight) + expect(layout.controlTop).toBeGreaterThan(0) + expect(layout.controlBottom).toBeLessThanOrEqual(layout.viewportHeight) // Require reachable tap: clipped scroller rows retain layout rects. expect(layout.reachesTheControl).toBe(true) }, 60_000) diff --git a/config/scripts/mobile-web-app/mobile-web-app-safe-area-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-safe-area-render.test.mjs index 461142f20b0a..1d13b96d0d8e 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-safe-area-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-safe-area-render.test.mjs @@ -97,8 +97,8 @@ function readEdges(page) { if (title !== null) { range.selectNodeContents(title) } - const fab = [...document.querySelectorAll('[role="button"]')].find( - (element) => element.getAttribute('aria-label') === 'New workspace' + const fab = [...document.querySelectorAll('[role="button"]')].find((element) => + ['New workspace', 'More options'].includes(element.getAttribute('aria-label')) ) return { titleTop: title === null ? null : range.getBoundingClientRect().top, @@ -147,6 +147,8 @@ describeRender('the page pads for the system bars once, by the shell insets', () await sideways.page.close() expect([...upright.errors, ...sideways.errors]).toEqual([]) expect(inset.titleLeft - base.titleLeft).toBe(59) + expect(base.fabRight).not.toBeNull() + expect(inset.fabRight).not.toBeNull() expect(base.fabRight - inset.fabRight).toBe(44) }, 60_000) diff --git a/mobile/README.md b/mobile/README.md index abb50c1b87e1..bd78377e0901 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 bc7e194768c3..d985713bd888 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/shell-screen-route' +import { + shellScreenRoute, + shellScreenRouteKey +} from '../../../../src/mobile-web-shell/shell-screen-route' import { PageRouteUnavailableScreen } from '../../../../src/mobile-web-shell/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/MobileAgentSessionHistoryList.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx index 5770bd7b155e..a02793983d33 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryList.tsx @@ -21,6 +21,8 @@ type Props = { resumeActionStateBySessionId?: ReadonlyMap onResume?: (session: AiVaultSession) => void | Promise onRefresh: () => void + initialExpandedId?: string + hideSectionHeaders?: boolean } export function MobileAgentSessionHistoryList({ @@ -30,10 +32,12 @@ export function MobileAgentSessionHistoryList({ showCurrentWorktreeBadges, resumeActionStateBySessionId, onResume, - onRefresh + onRefresh, + 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)) @@ -75,14 +79,16 @@ export function MobileAgentSessionHistoryList({ tintColor={colors.textSecondary} /> } - renderSectionHeader={({ section }) => ( - - - {section.label} - - {section.data.length} - - )} + renderSectionHeader={({ section }) => + hideSectionHeaders ? null : ( + + + {section.label} + + {section.data.length} + + ) + } renderItem={renderItem} /> ) diff --git a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx index 0ac36a4afb63..d8b3fa35886e 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx @@ -31,11 +31,13 @@ import { buildMobileAgentHistoryResumeActionState } from './agent-history-sessio import { styles } from './agent-history-styles' import { useNow } from '../hooks/use-now' import { useMobileResumeOperationOwnership } from './use-mobile-resume-operation-ownership' +import { conversationCopy } from '../host-screen/conversation-copy' export type MobileAgentSessionHistoryPanelProps = { hostId: string worktreeId: string name?: string + conversationId?: string origin?: string } @@ -53,6 +55,7 @@ function MobileAgentSessionHistoryPanelContent({ hostId, worktreeId, name = '', + conversationId, origin = '' }: MobileAgentSessionHistoryPanelProps) { useMobileColorScheme() @@ -69,6 +72,7 @@ function MobileAgentSessionHistoryPanelContent({ const [worktrees, setWorktrees] = useState([]) const [worktreesLoaded, setWorktreesLoaded] = useState(false) const [query, setQuery] = useState('') + const effectiveQuery = conversationId ? '' : query const [resumingSessionId, setResumingSessionId] = useState(null) const [resumeMessage, setResumeMessage] = useState(null) const now = useNow(30_000) @@ -88,7 +92,7 @@ function MobileAgentSessionHistoryPanelContent({ onSelectScope, onRefresh, retry - } = useMobileAgentHistoryState({ hostId, worktreeId, worktrees, worktreesLoaded }) + } = useMobileAgentHistoryState({ hostId, worktreeId, conversationId, worktrees, worktreesLoaded }) // Worktree list seeds host-local scopePaths and current-worktree badge. useEffect(() => { @@ -123,7 +127,10 @@ function MobileAgentSessionHistoryPanelContent({ } }, [client, connState]) - 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])), @@ -132,13 +139,13 @@ function MobileAgentSessionHistoryPanelContent({ const sections = useMemo( () => buildMobileAgentHistorySections(sessions, { - query, - scope, + query: effectiveQuery, + scope: conversationId ? 'all' : scope, scopeFilterPaths, activeWorktreePath, now }), - [sessions, query, scope, scopeFilterPaths, activeWorktreePath, now] + [sessions, effectiveQuery, conversationId, scope, scopeFilterPaths, activeWorktreePath, now] ) const resumeHost = useMemo( @@ -282,7 +289,7 @@ function MobileAgentSessionHistoryPanelContent({ - Agent Session History + {conversationId ? conversationCopy().history : 'Agent Session History'} {worktreeLabel} @@ -322,33 +329,37 @@ function MobileAgentSessionHistoryPanelContent({ ) : ( <> - - {SCOPE_TABS.map((tab) => { - const active = scope === tab.scope - return ( - onSelectScope(tab.scope)} - > - - {tab.label} - - - ) - })} - - - - + {!conversationId && ( + + {SCOPE_TABS.map((tab) => { + const active = scope === tab.scope + return ( + onSelectScope(tab.scope)} + > + + {tab.label} + + + ) + })} + + )} + {!conversationId && ( + + + + )} {issues.length > 0 ? ( @@ -365,15 +376,24 @@ function MobileAgentSessionHistoryPanelContent({ No agent sessions - {query ? 'No sessions match your search.' : 'No past agent sessions in this scope.'} + {conversationId + ? "This conversation's history is unavailable on this host." + : effectiveQuery + ? 'No sessions match your search.' + : 'No past agent sessions in this scope.'} ) : ( void onRefresh()} diff --git a/mobile/src/agent-history/agent-history-retry.test.tsx b/mobile/src/agent-history/agent-history-retry.test.tsx index df17f69cd809..ec7b5041d62d 100644 --- a/mobile/src/agent-history/agent-history-retry.test.tsx +++ b/mobile/src/agent-history/agent-history-retry.test.tsx @@ -63,6 +63,9 @@ import { createFakeBridgePortPair } from '../mobile-web-shell/bridge/bridge-port import { createFakeRpcClient } from '../mobile-web-shell/bridge-host-test-fakes' import { RpcClientProvider, useRpcClientContext } from '../transport/client-context.web' import { MobileAgentSessionHistoryPanel } from './MobileAgentSessionHistoryPanel' +import { MobileAgentSessionHistoryList } from './MobileAgentSessionHistoryList' +import { WorkspaceServerContext } from '../transport/use-workspace-client' +import type { MobileAgentHistorySection } from './agent-history-sections' doubles.read = useRpcClientContext @@ -223,3 +226,251 @@ it.each([ ) } ) + +function conversationSession(id: string, cwd: string | null): AiVaultSession { + return { + id, + executionHostId: 'runtime:selected-host', + agent: 'claude', + sessionId: id, + structuredSession: { sessionId: id, workspaceId: 'folder:notes' }, + title: id, + cwd, + branch: null, + model: null, + filePath: '', + codexHome: null, + createdAt: null, + updatedAt: null, + modifiedAt: '2026-10-25T00:00:00.000Z', + messageCount: 2, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null + } +} + +function historyClient( + sessions: AiVaultSession[], + includesStructuredSessions?: true, + selectedCapability = false +) { + const client = new FakeSession('connected') + client.sendRequest.mockImplementation(async (method) => ({ + id: 'conversation-history', + ok: true, + result: + method === 'status.get' + ? { + capabilities: [ + 'aiVault.v1', + ...(selectedCapability ? ['aiVault.selected-session.v1'] : []) + ], + hostPlatform: 'linux' + } + : method === 'worktree.ps' + ? { worktrees: [{ worktreeId: 'folder:notes', repoId: 'notes', path: '/notes' }] } + : { + sessions, + issues: [], + ...(includesStructuredSessions ? { includesStructuredSessions } : {}) + } + })) + return client +} + +function visibleHistoryIds(rendered: ReactTestRenderer): string[] { + return rendered.root + .findAllByType(MobileAgentSessionHistoryList) + .flatMap((list) => + list.props.sections.flatMap((section: MobileAgentHistorySection) => + section.data.map((card) => card.id) + ) + ) +} + +function historyServer(client: RpcClient | null, state: 'connected' | 'disconnected') { + return { client, state } +} + +it.each([null, '/outside/notes', 'C:\\outside\\notes'])( + 'opens only the selected conversation on its server despite cwd %s', + async (cwd) => { + const pair = createFakeBridgePortPair() + await pair.flush() + const selected = conversationSession('selected', cwd) + const client = historyClient([selected, conversationSession('other', '/notes')], true) + const server = historyServer(client, 'connected') + const local = historyClient([conversationSession('local-only', '/notes')]) + doubles.connection = { client: local, state: 'connected' } + await act(async () => { + tree = create( + + + + + + ) + }) + if (!tree) { + throw new Error('history did not mount') + } + expect.soft(visibleHistoryIds(tree)).toEqual(['selected']) + expect + .soft(client.sendRequest) + .toHaveBeenCalledWith( + 'aiVault.listSessions', + expect.objectContaining({ scopePaths: [], includeStructuredSessions: true }) + ) + expect(local.sendRequest).not.toHaveBeenCalled() + const list = tree.root.findAllByType(MobileAgentSessionHistoryList)[0] + expect.soft(list?.props.initialExpandedId).toBe('selected') + expect.soft(list ? [...list.props.sessionsById.keys()] : []).toEqual(['selected']) + } +) + +it('keeps general history scoped and accepts legacy scan replies without a coverage marker', async () => { + const pair = createFakeBridgePortPair() + await pair.flush() + const sessions = [ + conversationSession('missing-cwd', null), + conversationSession('outside', '/outside/notes'), + conversationSession('inside', '/notes') + ] + const client = historyClient(sessions) + doubles.connection = { client, state: 'connected' } + const render = (conversationId?: string) => ( + + + + ) + await act(async () => { + tree = create(render()) + }) + if (!tree) { + throw new Error('history did not mount') + } + expect(visibleHistoryIds(tree)).toEqual(['inside']) + expect(client.sendRequest).toHaveBeenCalledWith( + 'aiVault.listSessions', + expect.objectContaining({ scopePaths: ['/notes'] }) + ) + client.sendRequest.mockClear() + await act(async () => tree?.update(render('missing-cwd'))) + expect(visibleHistoryIds(tree)).toEqual(['missing-cwd']) + expect(client.sendRequest).toHaveBeenCalledWith( + 'aiVault.listSessions', + expect.objectContaining({ scopePaths: [], includeStructuredSessions: true }) + ) + await act(async () => tree?.update(render('outside'))) + expect(visibleHistoryIds(tree)).toEqual(['outside']) + await act(async () => tree?.update(render())) + expect(visibleHistoryIds(tree)).toEqual(['inside']) +}) + +it('never falls back to the paired host when the selected conversation server is unavailable', async () => { + const pair = createFakeBridgePortPair() + await pair.flush() + const local = historyClient([conversationSession('selected', '/notes')]) + const server = historyServer(null, 'disconnected') + doubles.connection = { client: local, state: 'connected' } + await act(async () => { + tree = create( + + + + + + ) + }) + if (!tree) { + throw new Error('history did not mount') + } + expect(visibleHistoryIds(tree)).toEqual([]) + expect(local.sendRequest).not.toHaveBeenCalled() +}) + +it('ignores the hidden general-history search when opening a selected conversation', async () => { + const pair = createFakeBridgePortPair() + await pair.flush() + const client = historyClient([conversationSession('selected', '/notes')]) + doubles.connection = { client, state: 'connected' } + const render = (conversationId?: string) => ( + + + + ) + await act(async () => { + tree = create(render()) + }) + if (!tree) { + throw new Error('history did not mount') + } + const search = tree.root.findAll((node) => String(node.type) === 'TextInput')[0] + act(() => search?.props.onChangeText('unrelated search')) + expect(visibleHistoryIds(tree)).toEqual([]) + await act(async () => tree?.update(render('selected'))) + expect(tree.root.findAll((node) => String(node.type) === 'TextInput')).toHaveLength(0) + expect(visibleHistoryIds(tree)).toEqual(['selected']) + await act(async () => tree?.update(render())) + expect(visibleHistoryIds(tree)).toEqual([]) +}) + +it.each([false, true])( + 'requests the exact selected session only from a capable host (%s)', + async (capable) => { + const pair = createFakeBridgePortPair() + await pair.flush() + const client = historyClient( + capable ? [conversationSession('selected', '/notes')] : [], + true, + capable + ) + doubles.connection = { client, state: 'connected' } + await act(async () => { + tree = create( + + + + ) + }) + const request = client.sendRequest.mock.calls.find( + ([method]) => method === 'aiVault.listSessions' + ) + expect(request?.[1]).toMatchObject({ limit: 500, scopePaths: [] }) + if (capable) { + expect(request?.[1]).toHaveProperty('selectedSessionId', 'selected') + } else { + expect(request?.[1]).not.toHaveProperty('selectedSessionId') + expect( + tree?.root.findAll( + (node) => + node.props.children === "This conversation's history is unavailable on this host." + ) + ).not.toHaveLength(0) + } + } +) 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..012b99bf36e3 --- /dev/null +++ b/mobile/src/agent-history/mobile-agent-history-screen-state.ts @@ -0,0 +1,16 @@ +import type { AiVaultScanIssue, AiVaultSession } from '../../../src/shared/ai-vault-types' +import type { RpcClient } from '../transport/rpc-client' + +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/use-mobile-agent-history-state.ts b/mobile/src/agent-history/use-mobile-agent-history-state.ts index 2d26dfa2cd55..e2bda90954c9 100644 --- a/mobile/src/agent-history/use-mobile-agent-history-state.ts +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -1,3 +1,8 @@ +import type { + AgentHistoryScreenState, + FetchedHistoryState +} from './mobile-agent-history-screen-state' +export type { AgentHistoryScreenState } from './mobile-agent-history-screen-state' import { useCallback, useEffect, @@ -28,6 +33,7 @@ import { agentHistorySessionScan } from './mobile-agent-history-operations' import { interpretOrThrowRefusalMessage } from '../transport/rpc-refusal-message' +import { AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY } from '../../../src/shared/ai-vault-runtime-capabilities' import { MOBILE_AI_VAULT_CAPABILITY } from './agent-history-capability' export { MOBILE_AI_VAULT_CAPABILITY } @@ -38,30 +44,17 @@ const EMPTY_NAMES: AgentSessionConversationNames = new Map() const noSubscription = () => () => {} const noNames = () => EMPTY_NAMES -export type AgentHistoryScreenState = - | { kind: 'loading' } - | { kind: 'unsupported' } - | { kind: 'error'; message: string } - | { - kind: 'ready' - sessions: AiVaultSession[] - issues: AiVaultScanIssue[] - } - -type FetchedHistoryState = - | Exclude - | (Extract & { hostId: string; client: RpcClient }) - 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 } export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams) { - const { hostId, worktreeId, worktrees, worktreesLoaded } = params + const { hostId, worktreeId, conversationId, worktrees, worktreesLoaded } = params const { client, state: connState } = useWorkspaceClient(hostId) const forceReconnect = useForceReconnect() const [scope, setScope] = useState('workspace') @@ -98,8 +91,8 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams const activeWorktreePath = activeWorktree?.path ?? null // Reuse host hint prefixes for client narrowing: host union only widens; All is not narrowed. const scopeFilterPaths = useMemo( - () => deriveMobileAiVaultScopePaths(scope, activeWorktree, worktrees), - [scope, activeWorktree, worktrees] + () => deriveMobileAiVaultScopePaths(conversationId ? 'all' : scope, activeWorktree, worktrees), + [conversationId, scope, activeWorktree, worktrees] ) const feed = useMemo(() => (client ? mobileStructuredSessionStatusFeed(client) : null), [client]) @@ -115,12 +108,22 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams client, clientGeneration, connState, - worktreeId, + conversation: { worktreeId, conversationId }, worktrees, worktreesLoaded, scope }), - [hostId, client, clientGeneration, connState, worktreeId, worktrees, worktreesLoaded, scope] + [ + hostId, + client, + clientGeneration, + connState, + worktreeId, + conversationId, + worktrees, + worktreesLoaded, + scope + ] ) const identityRef = useRef(identity) useLayoutEffect(() => { @@ -133,6 +136,7 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams async (options: { scope: AiVaultScope; force: boolean }): Promise => { const requestIdentity = identityRef.current const associationRevision = feed?.getAssociationRevision() + const scanScope = conversationId ? 'all' : options.scope const generation = generationRef.current + 1 generationRef.current = generation const isCurrent = () => @@ -172,19 +176,26 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams } // Wait for worktree list before scoped fetch to avoid unrelated history flash; once loaded, proceed even if workspace is missing to avoid stuck spinner. - if (options.scope !== 'all' && !activeWorktree && !worktreesLoaded) { + if (scanScope !== 'all' && !activeWorktree && !worktreesLoaded) { if (isCurrent()) { setScreenState((prev) => (prev.kind === 'ready' ? prev : { kind: 'loading' })) } return } - const scopePaths = mobileAiVaultScanScopePaths( - deriveMobileAiVaultScopePaths(options.scope, activeWorktree, worktrees) - ) + const scopePaths = conversationId + ? [] + : mobileAiVaultScanScopePaths( + deriveMobileAiVaultScopePaths(scanScope, activeWorktree, worktrees) + ) const reply = await agentHistorySessionScan.request(client, { limit: MOBILE_AI_VAULT_SESSION_LIMIT, force: options.force, + ...(conversationId ? { includeStructuredSessions: true } : {}), + ...(conversationId && + status.capabilities?.includes(AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY) + ? { selectedSessionId: conversationId } + : {}), scopePaths }) if (!isCurrent()) { @@ -219,7 +230,17 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams } } }, - [activeWorktree, client, clientGeneration, connState, feed, hostId, worktrees, worktreesLoaded] + [ + activeWorktree, + client, + clientGeneration, + connState, + conversationId, + feed, + hostId, + worktrees, + worktreesLoaded + ] ) // Initial/reconnect/scope loads reuse host’s 15s cache; only explicit refresh bypasses it. @@ -251,10 +272,6 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams } }, [feed, loadSessions, scope]) - const onSelectScope = useCallback((nextScope: AiVaultScope) => { - setScope(nextScope) - }, []) - const onRefresh = useCallback(async () => { setRefreshing(true) try { @@ -304,7 +321,7 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams hostStatusResult, activeWorktreePath, scopeFilterPaths, - onSelectScope, + onSelectScope: setScope, onRefresh, retry } diff --git a/mobile/src/components/ActionSheetModal.tsx b/mobile/src/components/ActionSheetModal.tsx index c2f8cf504280..a6af2b97a686 100644 --- a/mobile/src/components/ActionSheetModal.tsx +++ b/mobile/src/components/ActionSheetModal.tsx @@ -71,6 +71,11 @@ export function ActionSheetContent({ title, message, children, actions, onClose {i > 0 && } [ styles.action, action.disabled && styles.actionDisabled, diff --git a/mobile/src/host-screen/ConversationProjectHeader.tsx b/mobile/src/host-screen/ConversationProjectHeader.tsx new file mode 100644 index 000000000000..9a96cedc70f2 --- /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/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..da77df4d43d2 --- /dev/null +++ b/mobile/src/host-screen/HostConversations.tsx @@ -0,0 +1,397 @@ +import { useMemo, useState } from 'react' +import { ActivityIndicator, Pressable, RefreshControl, SectionList, Text, View } from 'react-native' +import { SafeAreaView } from 'react-native-safe-area-context' +import { ArrowDownAZ, ChevronLeft, MoreHorizontal, Pin, Settings } from 'lucide-react-native' +import { colors } from '../theme/mobile-theme' +import { MobileAgentIcon } from '../components/MobileAgentIcon' +import { AgentStateDot } from '../components/AgentStateDot' +import { StatusDot } from '../components/StatusDot' +import { MobileSearchField } from '../components/MobileSearchField' +import { ConversationAgentSheet } from './conversation-agent-sheet' +import { ConversationSidebarOptions } from './conversation-sidebar-options' +import { AuthFailedBanner } from '../components/AuthFailedBanner' +import { formatAgentTypeLabel } from '../../../src/shared/agent-type-label' +import type { HostScreenController } from './use-host-screen-controller' +import { HiddenConversationProjectsSheet } from './hidden-conversation-projects-sheet' +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, conversationTimeAgo } from './conversation-copy' +import { conversationStyles as styles } from './conversation-styles' +import { buildProjectSectionCatalog } from '../worktree/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 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.view.filters.visibleHostIds, + controller.projectOrderBy + ), + [ + controller.projectCatalog, + controller.sectionsResult.repoById, + controller.projectOrderBy, + state.view + ] + ) + const projects = useMemo( + () => + buildProjectConversations({ + workspaces: data.workspaces, + repos: [...controller.sectionsResult.repoById.values()], + tabs: data.tabs, + history: data.history, + now: controller.now, + untitled: copy.untitled, + query, + projectCatalog, + preferences: conversationPreferences.preferences, + archived + }), + [ + data.workspaces, + controller.sectionsResult.repoById, + data.tabs, + data.history, + controller.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} + {data.failed || state.catalogError ? {copy.failed} : null} + {data.loading ? ( + + ) : !data.complete && connected ? ( + {copy.legacy} + ) : 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 }) => ( + + open(item)} + onLongPress={() => setDetails(item)} + disabled={ + !connected || Boolean(item.workspace?.hostContextHealthLabel) || busy !== null + } + style={({ pressed }) => [styles.rowButton, pressed && styles.pressed]} + accessibilityRole="button" + accessibilityLabel={item.title} + > + + + + {item.preferenceKey && + conversationPreferences.preferences?.entries[item.preferenceKey]?.pinned ? ( + + ) : null} + + {item.title} + + + + + + {[ + item.agent ? formatAgentTypeLabel(item.agent) : null, + !connected || item.workspace?.hostContextHealthLabel + ? copy.offline + : item.status === 'saved' + ? copy.saved + : item.status === 'transcript' + ? copy.transcript + : item.status === 'failed' + ? copy.failedState + : item.status === 'unverifiable' + ? copy.unconfirmed + : copy[item.status], + item.at ? conversationTimeAgo(item.at, controller.now) : null + ] + .filter(Boolean) + .join(' · ')} + + + + {busy === item.key ? ( + + ) : null} + + setDetails(item)} + style={styles.iconButton} + accessibilityRole="button" + accessibilityLabel={`${copy.details}: ${item.title}`} + > + + + + )} + /> + 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..442161ed2b1b --- /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/BottomDrawer' +import { MobileAgentIcon } from '../components/MobileAgentIcon' +import type { MobileNewTabAgentOption } from '../session/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..2867a96d2050 --- /dev/null +++ b/mobile/src/host-screen/conversation-copy.ts @@ -0,0 +1,151 @@ +import { formatTimeAgo } from '../worktree/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: 'Some conversations could not be loaded. Pull to refresh.', + failedState: 'Failed', + legacy: + 'This host lists open chats and saved transcripts. Update Orca to also list closed chats.', + 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: 'Ошибка', + legacy: + 'Этот хост показывает открытые чаты и сохранённую переписку. Обновите Orca, чтобы видеть также закрытые чаты.', + 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..33fd7193c671 --- /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/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.workspace?.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..fbc71604f2c1 --- /dev/null +++ b/mobile/src/host-screen/conversation-history-index.ts @@ -0,0 +1,29 @@ +import type { ExecutionHostId } from '../../../src/shared/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..be1fda786857 --- /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/protocol-version' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' +import { rpcClientForExecutionHost } from '../transport/execution-host-scoped-rpc-client' +import { FakeSession } from '../transport/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 { + 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..62e1d51fbb5e --- /dev/null +++ b/mobile/src/host-screen/conversation-open.ts @@ -0,0 +1,48 @@ +import { z } from 'zod' +import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../src/shared/structured-agent-session-projection' +import type { RpcClient } from '../transport/rpc-client' +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..261177c4d071 --- /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/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..3834ba90579c --- /dev/null +++ b/mobile/src/host-screen/conversation-project-actions.test.tsx @@ -0,0 +1,145 @@ +import { createElement, type ReactNode } from 'react' +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/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/BottomDrawer', () => ({ + BottomDrawer: ({ children }: { children: ReactNode }) => children +})) +vi.mock('../components/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: ReactNode) { + 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..33d4baf4d3eb --- /dev/null +++ b/mobile/src/host-screen/conversation-project-order-sheet.tsx @@ -0,0 +1,31 @@ +import { ActionSheetModal } from '../components/ActionSheetModal' +import { WORKSPACE_PROJECT_ORDER_CHOICES } from '../../../src/shared/workspace-view/workspace-view-options' +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 copy = conversationCopy() + const connected = controller.connState === 'connected' + return ( + onClose()} + actions={WORKSPACE_PROJECT_ORDER_CHOICES.map((choice) => ({ + label: `${controller.projectOrderBy === choice.id ? '✓ ' : ''}${copy.projectOrderLabels[choice.id]}`, + 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..094e80754a10 --- /dev/null +++ b/mobile/src/host-screen/conversation-project.ts @@ -0,0 +1,36 @@ +import type { ExecutionHostId } from '../../../src/shared/execution-host' +import type { AgentDotState } from '../worktree/agent-row-display' +import type { SectionRepo, Worktree } from '../worktree/workspace-list-types' +import type { ConversationHistory } from './conversation-records' + +export type ConversationRow = { + key: string + title: string + agent: string | null + status: AgentDotState | 'saved' | 'transcript' + at: number + workspace: Worktree | null + 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) + ) +} diff --git a/mobile/src/host-screen/conversation-records.ts b/mobile/src/host-screen/conversation-records.ts new file mode 100644 index 000000000000..703583c48bbf --- /dev/null +++ b/mobile/src/host-screen/conversation-records.ts @@ -0,0 +1,69 @@ +import { z } from 'zod' +import { normalizeExecutionHostId } from '../../../src/shared/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(), + 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), + 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] : [] + }) +} 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..656c8769963d --- /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/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..b136937b9ce9 --- /dev/null +++ b/mobile/src/host-screen/conversation-styles.ts @@ -0,0 +1,89 @@ +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.button + }, + 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.button, + backgroundColor: colors.bgRaised + }, + actionText: { color: colors.textPrimary, fontSize: typography.bodySize }, + disabled: { opacity: 0.5 }, + row: { flexDirection: 'row', alignItems: 'center', borderRadius: radii.row }, + rowButton: { + flex: 1, + minHeight: 64, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingVertical: spacing.md, + paddingLeft: spacing.sm + }, + rowText: { flex: 1, gap: spacing.xs }, + rowTitle: { fontSize: typography.bodySize, color: colors.textPrimary }, + 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.button + }, + 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..4bb2688299a9 --- /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/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 e65cc3bc7d6f..807872a00c41 100644 --- a/mobile/src/host-screen/host-screen-operations.ts +++ b/mobile/src/host-screen/host-screen-operations.ts @@ -1,3 +1,5 @@ +import { z } from 'zod' +import { ConversationPreferencesSchema } from '../../../src/shared/conversation-navigation-preferences' import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc-operation' import { rpcResultVariant } from '../transport/rpc-operation-result-reader' import { @@ -115,3 +117,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 f7b049230097..73530007d32b 100644 --- a/mobile/src/host-screen/host-screen-reply-schema.ts +++ b/mobile/src/host-screen/host-screen-reply-schema.ts @@ -1,3 +1,4 @@ +import { ConversationPreferencesSchema } from '../../../src/shared/conversation-navigation-preferences' import { z } from 'zod' import type { PersistedUIState } from '../../../src/shared/persisted-ui-state-types' import type { RepoIcon } from '../../../src/shared/repo-icon' @@ -111,6 +112,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 50fcee8bd410..77c69fab2ad0 100644 --- a/mobile/src/host-screen/host-screen-view.tsx +++ b/mobile/src/host-screen/host-screen-view.tsx @@ -1,4 +1,5 @@ -import { Text, View } from 'react-native' +import { useState } from 'react' +import { Pressable, Text, View } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { hostScreenStyles as styles } from './host-screen-styles' @@ -6,8 +7,12 @@ import { HostScreenHeader } from './host-screen-header' import { HostScreenOverlays } from './host-screen-overlays' import { HostWorkspaceList } from './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() if (controller.state.error) { return ( @@ -17,10 +22,26 @@ export function HostScreenView({ controller }: { controller: HostScreenControlle ) } + if (!advanced) { + return ( + + setAdvanced(true)} /> + + + ) + } + return ( + setAdvanced(false)} + style={conversationStyles.agentButton} + accessibilityRole="button" + > + {conversationCopy().back} + 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..a552734c2f9d --- /dev/null +++ b/mobile/src/host-screen/project-conversation-order.ts @@ -0,0 +1,63 @@ +import type { ConversationPreferences } from '../../../src/shared/conversation-navigation-preferences' +import { sortProjectEntries } from '../../../src/shared/project-section-order' +import type { ProjectSectionCatalog } from '../worktree/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.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-visibility.test.ts b/mobile/src/host-screen/project-conversation-visibility.test.ts new file mode 100644 index 000000000000..342dd9f480ca --- /dev/null +++ b/mobile/src/host-screen/project-conversation-visibility.test.ts @@ -0,0 +1,119 @@ +import { projectHostSetupProjectionFromRepos } from '../../../src/shared/project-host-setup-projection' +import { getWorktreeRowIdentity } from '../worktree/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', + 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.test-fixture.ts b/mobile/src/host-screen/project-conversations.test-fixture.ts new file mode 100644 index 000000000000..3315e3e83252 --- /dev/null +++ b/mobile/src/host-screen/project-conversations.test-fixture.ts @@ -0,0 +1,60 @@ +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import type { Worktree } from '../worktree/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..5923b6d50ced --- /dev/null +++ b/mobile/src/host-screen/project-conversations.test.ts @@ -0,0 +1,297 @@ +import { describe, expect, it } from 'vitest' +import { conversationPreferenceKey } from '../../../src/shared/conversation-navigation-preferences' +import type { ProjectSectionCatalog } from '../worktree/workspace-list-sections' +import { structuredAgentSessionPaneKey } from '../../../src/shared/structured-agent-session-projection' +import { getWorktreeRowIdentity } from '../worktree/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.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', + hostContextLabel: 'Build server' + }) + const ssh = conversationWorkspace({ hostId: 'ssh:target', hostContextLabel: 'SSH' }) + 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' + })) + }, + 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..c6ec8d3ba991 --- /dev/null +++ b/mobile/src/host-screen/project-conversations.ts @@ -0,0 +1,277 @@ +import { toAiVaultProjectKey } from '../../../src/shared/ai-vault-project-key' +import { createConversationWorkspaceMatcher } from '../../../src/shared/conversation-workspace-matcher' +import { folderGroupKey, folderLabel } from '../../../src/shared/ai-vault-session-filters' +import { + conversationPreferenceKey, + conversationProjectVisibilityKey, + type ConversationPreferences +} from '../../../src/shared/conversation-navigation-preferences' +import { + projectConversationTitle, + isGenericConversationTitle +} from '../../../src/shared/project-conversation-list' +import { + buildProjectGroupingIndex, + getProjectGroupingForRepo +} from '../../../src/shared/project-section-grouping' +import type { ProjectSectionCatalog } from '../worktree/workspace-list-sections' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host' +import { structuredAgentSessionPaneKey } from '../../../src/shared/structured-agent-session-projection' +import { agentDotState, agentRowTimeAt } from '../worktree/agent-row-display' +import { getWorktreeRowIdentity } from '../worktree/worktree-host-row-identity' +import { createConversationHistoryIndex } from './conversation-history-index' +import { orderProjectConversations } from './project-conversation-order' +import type { SectionRepo, Worktree } from '../worktree/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' +export { projectConversationTarget } from './conversation-project' +export type { ConversationRow, ConversationProject } from './conversation-project' + +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 buildProjectConversations(args: { + workspaces: readonly Worktree[] + repos: readonly SectionRepo[] + tabs: ReadonlyMap + history: readonly ConversationHistory[] + now: number + untitled: string + query?: string + projectCatalog?: ProjectSectionCatalog + preferences?: ConversationPreferences + archived?: boolean +}): ConversationProject[] { + const projects = new Map() + const ownerKeys = new Map() + const savedForTab = createConversationHistoryIndex(args.history) + const hostOf = (workspace: Worktree) => workspace.hostId ?? workspace.hostContextHostId ?? 'local' + const catalog = args.projectCatalog + const repos = catalog?.repos ?? args.repos + 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) + for (const repo of repos) { + const hostId = getRepoExecutionHostId(repo) + 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 args.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 ??= workspace.hostContextLabel + project.hostHealthLabel ??= 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?.taskTitle, agent?.prompt, saved ? projectConversationTitle(saved) : tab.title], + workspace, + args.untitled + ), + agent: agentType ?? null, + status: agent ? agentDotState(agent, args.now) : 'idle', + at: agent ? agentRowTimeAt(agent) : 0, + 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.taskTitle, agent.prompt], workspace, args.untitled), + agent: agent.agentType, + status: agentDotState(agent, args.now), + at: agentRowTimeAt(agent), + workspace, + paneKey: agent.paneKey + }) + } + } + const matchWorkspace = createConversationWorkspaceMatcher( + args.workspaces.map((workspace) => ({ + ...workspace, + id: workspace.worktreeId, + hostId: hostOf(workspace) + })) + ) + for (const session of args.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 + ? (args.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, + agent: session.agent, + status: sessionId ? 'saved' : 'transcript', + at: Date.parse(session.updatedAt ?? session.modifiedAt) || 0, + workspace, + 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..608c6dcdcea1 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-actions.test.tsx @@ -0,0 +1,217 @@ +import { createElement } from 'react' +import { act, create, 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-runtime-capability' +import { MOBILE_DESKTOP_RELAY_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' +import { PREFLIGHT_OTHER_RUNTIME_REFUSAL_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes' +import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client' +import type { RpcResponse } from '../transport/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 './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('../transport/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(create(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()) + for (const id of ['first', 'second']) { + await act(async () => { + probe.read().open({ + ...probe.row, + title: id, + workspace: { ...probe.row.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..b6c8fc03c65b --- /dev/null +++ b/mobile/src/host-screen/use-conversation-actions.ts @@ -0,0 +1,233 @@ +import { useEffect, useRef, useState } from 'react' +import { rpcClientForExecutionHost } from '../transport/execution-host-scoped-rpc-client' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../src/shared/structured-agent-session-projection' +import { + loadMobileNewTabAgentOptions, + hostRefusesOtherRuntimeWorkspace +} from '../session/mobile-new-tab-agent-loader' +import { + launchAgentInExistingWorkspace, + supportsMobileExistingAgentLaunch +} from '../session/mobile-existing-agent-launch' +import type { MobileNewTabAgentOption } from '../session/mobile-new-tab-agent-options' +import type { Worktree } from '../worktree/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 loadMobileNewTabAgentOptions({ + client: rowClient(workspace), + worktreeId: workspace.worktreeId, + hostRefusesOtherRuntime: hostRefusesOtherRuntimeWorkspace(capabilities) + }) + if (!current()) { + return + } + if (inventory.options.length === 0) { + setError(copy.noAgents) + return + } + setChatChoice({ client, hostId, generation, project, workspace, agents: inventory.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..277e3e578fa2 --- /dev/null +++ b/mobile/src/host-screen/use-conversation-preferences.test.tsx @@ -0,0 +1,155 @@ +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-client' +import type { RpcResponse } from '../transport/types' +import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes' +import { INITIAL_MOBILE_VIEW, type MobileViewState } from '../worktree/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 1fc27a1bde80..0a7aad8fdfa4 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -161,6 +161,8 @@ export function useHostScreenController({ collapsedGroups, feed, projectOrderBy, + projectCatalog: + (feed?.kind === 'ready' ? feed.domains.projectCatalog : null) ?? state.servedProjectSections, client, connectionVerdict, connState, 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..5d37b1ea7f8f --- /dev/null +++ b/mobile/src/host-screen/use-project-conversations.test.tsx @@ -0,0 +1,311 @@ +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/mobile-desktop-relay-contract' +import type { RpcClient } from '../transport/rpc-client' +import type { RpcResponse } from '../transport/types' +import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes' +import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client' +import { getWorktreeRowIdentity } from '../worktree/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([]) + }) +}) 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..c05ad5b1eabd --- /dev/null +++ b/mobile/src/host-screen/use-project-conversations.ts @@ -0,0 +1,295 @@ +import { AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY } from '../../../src/shared/ai-vault-runtime-capabilities' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import type { RpcClient } from '../transport/rpc-client' +import type { ExecutionHostId } from '../../../src/shared/execution-host' +import { + rpcClientForExecutionHost, + reachableServerClients +} from '../transport/execution-host-scoped-rpc-client' +import { getWorktreeRowIdentity } from '../worktree/worktree-host-row-identity' +import { resolveWorktreeHostId } from '../worktree/worktree-host-context-labels' +import { + agentHistoryHostStatusRead, + agentHistorySessionScan +} from '../agent-history/mobile-agent-history-operations' +import { sessionTabsListRead } from '../session/mobile-session-read-operations' +import type { HostScreenController } from './use-host-screen-controller' +import { + readConversationHistory, + readConversationTabs, + type ConversationHistory, + type ConversationTab +} from './project-conversations' + +type ConversationSnapshot = { + tabs: Map + history: ConversationHistory[] + capabilities: Map + complete: boolean + failed: boolean +} +const EMPTY: ConversationSnapshot = { + tabs: new Map(), + history: [], + 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 failedSources = new Set() + const failedTabs = new Set() + const next: ConversationSnapshot = { + tabs: new Map(), + history: [], + capabilities: new Map(), + complete: true, + failed: false + } + try { + const historyRequests = Promise.all( + [...sources].map(async ([sourceHost, sourceClient]) => { + try { + const status = agentHistoryHostStatusRead.interpret( + await agentHistoryHostStatusRead.request(sourceClient) + ) + next.capabilities.set(sourceHost, status.capabilities ?? []) + if (!status.capabilities?.includes('aiVault.v1')) { + next.complete = false + return + } + const reply = await agentHistorySessionScan.request(sourceClient, { + ...(status.capabilities.includes(AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY) + ? { historyOwnership: {} } + : {}), + unlimited: true, + includeAntigravityIdeSessions: true, + includeStructuredSessions: true, + force + }) + const history = readConversationHistory(agentHistorySessionScan.interpret(reply)) + if (!history.includesStructuredSessions) { + next.complete = false + } + 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 previous = snapshots.get(client) + const value = (() => { + const tabs = new Map(next.tabs) + const capabilities = new Map(next.capabilities) + let history = next.history + if ( + previous?.client === client && + previous.hostId === hostId && + previous.generation === generation && + previous.authority === authority + ) { + for (const source of failedSources) { + 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 } + })() + 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/session/notification-pane-tab.test.ts b/mobile/src/session/notification-pane-tab.test.ts new file mode 100644 index 000000000000..7334664ae16f --- /dev/null +++ b/mobile/src/session/notification-pane-tab.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { notificationPaneTab } from './notification-pane-tab' +import type { MobileSessionTab } from './mobile-session-route-types' + +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/notification-pane-tab.ts b/mobile/src/session/notification-pane-tab.ts index ecc04d0ccdfe..b57a68a38222 100644 --- a/mobile/src/session/notification-pane-tab.ts +++ b/mobile/src/session/notification-pane-tab.ts @@ -9,7 +9,11 @@ import type { MobileSessionTab } from './mobile-session-route-types' 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/test-support/bridged-parity/c1-page-closure.ts b/mobile/src/test-support/bridged-parity/c1-page-closure.ts index 3cf73b99267e..b5b85d8f2f84 100644 --- a/mobile/src/test-support/bridged-parity/c1-page-closure.ts +++ b/mobile/src/test-support/bridged-parity/c1-page-closure.ts @@ -4,6 +4,25 @@ import type { PageClosurePins } from './page-closure' export const C1_PAGE_CLOSURE: PageClosurePins = { + 'settings-agent-read': { + 'matrix-settings-agent-read-preflight.detectremoteagents-1': 'result-absent-settlement', + 'matrix-settings-agent-read-repo.list-1': 'result-absent-settlement', + 'matrix-settings-agent-read-settings.get-1': 'result-absent-settlement', + 'probe-new-tab-both-refused': 'identical', + 'probe-new-tab-null-sibling-refused': 'identical', + 'probe-new-tab-refused-sibling-rejects': 'identical', + 'probe-new-tab-rejects-sibling-refused': 'identical', + 'schedules-settings-new-tab-ssh': 'identical', + 'settings-new-tab-refused': 'identical', + 'settings-new-tab-ssh': 'identical', + 'settings-new-tab-transport-error': 'identical' + }, + 'settings.new-tab-local-agents': { + 'matrix-settings.new-tab-local-agents-preflight.detectagents-1': 'result-absent-settlement', + 'matrix-settings.new-tab-local-agents-repo.list-1': 'result-absent-settlement', + 'matrix-settings.new-tab-local-agents-settings.get-1': 'result-absent-settlement', + 'new-tab-local-agents': 'identical' + }, 'settings.repo-metadata': { 'matrix-settings.repo-metadata-host.platform-1': 'result-absent-settlement', 'matrix-settings.repo-metadata-repo.list-1': 'result-absent-settlement', diff --git a/mobile/src/worktree/workspace-view-settings.ts b/mobile/src/worktree/workspace-view-settings.ts index aeb9bc927a30..27d9e2cad524 100644 --- a/mobile/src/worktree/workspace-view-settings.ts +++ b/mobile/src/worktree/workspace-view-settings.ts @@ -39,6 +39,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' > > @@ -49,6 +50,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[] @@ -174,6 +176,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/cached-session-list.ts b/src/main/ai-vault/cached-session-list.ts index e1ac800f5b88..404055f262fc 100644 --- a/src/main/ai-vault/cached-session-list.ts +++ b/src/main/ai-vault/cached-session-list.ts @@ -116,7 +116,12 @@ export async function listAiVaultSessions( cachedList.expiresAt > now && aiVaultCachedDepthServes(cachedList.depth, depth, args?.scopePaths) ) { - 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 @@ -141,6 +146,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/session-file-observation.ts b/src/main/ai-vault/session-file-observation.ts new file mode 100644 index 000000000000..5a827ceae5f8 --- /dev/null +++ b/src/main/ai-vault/session-file-observation.ts @@ -0,0 +1,66 @@ +import { wslGatedStat } from '../native-chat/wsl-transcript-fs-access' +import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' +import type { SessionSidecarObservation } from './session-sidecar-stat' +import type { FileWithMtime } from './session-scanner-types' +import { errorMessage } from './session-scanner-values' + +export type SessionFileObservation = + | { file: Omit; sidecarPath?: string } + | { issue: { path: string; message: string } } + +export async function observeSessionFile( + path: string, + contentDependencyPath?: (path: string) => string | undefined | Promise, + signal?: AbortSignal +): Promise { + try { + const fileStat = await wslGatedStat(path, 'scan', signal) + const sidecarPath = contentDependencyPath ? await contentDependencyPath(path) : undefined + const sidecar = sidecarPath ? await observeSessionSidecar(sidecarPath, signal) : 'none' + return { + file: { + path, + mtimeMs: fileStat.mtimeMs, + sizeBytes: fileStat.size, + sidecar, + dev: fileStat.dev, + ino: fileStat.ino, + nlink: fileStat.nlink + }, + sidecarPath + } + } catch (err) { + return { issue: { path, message: errorMessage(err) } } + } +} + +/** Only missing sidecars are none; other stat failures stay unknown so cached enrichment can retry. */ +async function observeSessionSidecar( + filePath: string | undefined, + signal?: AbortSignal +): Promise { + if (!filePath) { + return 'none' + } + try { + const fileStat = await wslGatedStat(filePath, 'scan', signal) + return { + path: filePath, + mtimeMs: fileStat.mtimeMs, + sizeBytes: fileStat.size + } + } catch (error) { + return isMissingSidecarError(error) ? 'none' : 'unknown' + } +} + +export function isMissingSidecarError(error: unknown): boolean { + if (error instanceof WslTranscriptFsError) { + return false + } + const code = + error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' + ? error.code + : null + return code === 'ENOENT' || code === 'ENOTDIR' +} diff --git a/src/main/ai-vault/session-list-result-validation.test.ts b/src/main/ai-vault/session-list-result-validation.test.ts index 37cddb523dc2..3c1d7aef47ff 100644 --- a/src/main/ai-vault/session-list-result-validation.test.ts +++ b/src/main/ai-vault/session-list-result-validation.test.ts @@ -18,6 +18,27 @@ describe('parseAiVaultListResult', () => { ]) }) + it('keeps optional conversation evidence and degrades unknown future evidence without losing the row', () => { + const result = parseAiVaultListResult({ + sessions: [ + { ...validSession('empty'), conversationContent: 'empty' }, + { ...validSession('present'), conversationContent: 'present' }, + { ...validSession('unknown'), conversationContent: 'unknown' }, + { ...validSession('future'), conversationContent: 'future-value' }, + validSession('legacy') + ], + issues: [], + scannedAt: '2026-10-26T00:00:00Z' + }) + expect(result.sessions.map((session) => session.conversationContent)).toEqual([ + 'empty', + 'present', + 'unknown', + undefined, + undefined + ]) + }) + it('keeps valid sessions when another wire entry is malformed', () => { const parsed = parseAiVaultListResult({ sessions: [validSession(), { id: 42 }], diff --git a/src/main/ai-vault/session-list-result-validation.ts b/src/main/ai-vault/session-list-result-validation.ts index 9c6b49f5a860..73d341d61906 100644 --- a/src/main/ai-vault/session-list-result-validation.ts +++ b/src/main/ai-vault/session-list-result-validation.ts @@ -45,6 +45,8 @@ const sessionPreviewMessageSchema = z.object({ }) const aiVaultSessionSchema = z.object({ + source: z.literal('structured-record').optional(), + conversationContent: z.enum(['empty', 'present', 'unknown']).optional().catch(undefined), id: z.string(), executionHostId: executionHostIdSchema, executionHostPlatform: nodePlatformSchema.nullable().optional(), @@ -110,7 +112,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) => @@ -171,6 +174,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/session-list-results.test.ts b/src/main/ai-vault/session-list-results.test.ts index bb02399f92af..48dda22f4fcb 100644 --- a/src/main/ai-vault/session-list-results.test.ts +++ b/src/main/ai-vault/session-list-results.test.ts @@ -5,7 +5,8 @@ import type { AiVaultSession } from '../../shared/ai-vault-types' import { truncateAiVaultListResult } from '../../shared/ai-vault-session-depth' -import { mergeAiVaultListResults } from './session-list-results' +import { parseAiVaultListResult } from './session-list-result-validation' +import { mergeAiVaultListResults, restampAiVaultListResult } from './session-list-results' function listResult(issues: AiVaultScanIssue[]): AiVaultListResult { return { sessions: [], issues, scannedAt: '2026-08-02T00:00:00.000Z' } @@ -46,6 +47,60 @@ const SCOPE_TRUNCATION: AiVaultScanIssue = { message: 'Only the first 64 project paths were scanned.' } +describe('restampAiVaultListResult', () => { + const catalogs = [ + { name: 'empty', result: listResult([]) }, + { + name: 'populated', + result: { ...listResult([SCOPE_TRUNCATION]), sessions: [session(1)] } + }, + { + name: 'unchanged', + result: { ...listResult([]), fingerprint: 'a'.repeat(64), unchanged: true as const } + } + ] + + it.each(catalogs)('preserves confirmed $name catalog coverage through parsing', ({ result }) => { + const stamped = restampAiVaultListResult( + { ...result, includesStructuredSessions: true }, + 'runtime:server' + ) + const parsed = parseAiVaultListResult(stamped) + + expect(parsed).toEqual(stamped) + expect(parsed.includesStructuredSessions).toBe(true) + expect(parsed.sessions.every((row) => row.executionHostId === 'runtime:server')).toBe(true) + expect(parsed.issues.every((issue) => issue.executionHostId === 'runtime:server')).toBe(true) + }) + + it.each(catalogs)('does not claim coverage for a legacy $name catalog', ({ result }) => { + const parsed = parseAiVaultListResult(restampAiVaultListResult(result, 'runtime:server')) + + expect(parsed).not.toHaveProperty('includesStructuredSessions') + }) + + it.each([ + { name: 'full', metadata: { fingerprint: 'a'.repeat(64) } }, + { name: 'unchanged', metadata: { fingerprint: 'a'.repeat(64), unchanged: true as const } }, + { name: 'cancelled', metadata: { cancelled: true as const } } + ])('omits the local scan id while preserving $name reply metadata', ({ metadata }) => { + const expected = { ...listResult([]), ...metadata, includesStructuredSessions: true as const } + const original = { ...expected, scanId: 'local-scan' } + + expect(restampAiVaultListResult(original, 'runtime:server')).toEqual(expected) + expect(original.scanId).toBe('local-scan') + }) + + it.each([false, null, 'true', 1, {}])('rejects an invalid coverage marker: %j', (marker) => { + expect(() => + parseAiVaultListResult({ + ...restampAiVaultListResult(listResult([]), 'runtime:server'), + includesStructuredSessions: marker + }) + ).toThrow() + }) +}) + describe('mergeAiVaultListResults', () => { afterEach(() => { vi.useRealTimers() diff --git a/src/main/ai-vault/session-list-results.ts b/src/main/ai-vault/session-list-results.ts index b6c4e21f1334..eeddc0ab6fca 100644 --- a/src/main/ai-vault/session-list-results.ts +++ b/src/main/ai-vault/session-list-results.ts @@ -40,7 +40,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 @@ -50,8 +52,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 })) } } diff --git a/src/main/ai-vault/session-parse-cache-database.ts b/src/main/ai-vault/session-parse-cache-database.ts index 6ee3b7fac95f..fd9d814f86d9 100644 --- a/src/main/ai-vault/session-parse-cache-database.ts +++ b/src/main/ai-vault/session-parse-cache-database.ts @@ -20,7 +20,7 @@ import { import { parsePersistedSidecar } from './session-sidecar-stat' // Bump for row-layout or cached-semantic changes; mismatched databases are discarded. -export const SESSION_PARSE_CACHE_SCHEMA_VERSION = 8 +export const SESSION_PARSE_CACHE_SCHEMA_VERSION = 9 const SCHEMA_SQL = ` CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL); diff --git a/src/main/ai-vault/session-scanner-antigravity-sources.ts b/src/main/ai-vault/session-scanner-antigravity-sources.ts index a7749255ec64..31faa4a5c949 100644 --- a/src/main/ai-vault/session-scanner-antigravity-sources.ts +++ b/src/main/ai-vault/session-scanner-antigravity-sources.ts @@ -44,6 +44,8 @@ export function antigravityDiscoveries( filePredicate: isAntigravityTranscriptPath, directoryPredicate: shouldDescendAntigravityBrainDirectory, keepScopeFiles: scopeWalksAgentFiles('antigravity', options.scopePaths), + selectedSessionId: options.selectedSessionId, + executionHostId: options.executionHostId, signal: options.signal }).then((discovery) => completeAntigravityTranscriptPairs(discovery, issues)) ) 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..c7c8f1210406 --- /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 './session-transcript-record-budget' +import { isolatedScanRoots, writeJsonlFile } from './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('never calls a transcript empty when bounded reads skipped possible history', 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.objectContaining({ kind: 'notice' })]) + 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-discovery-wsl-gate.test.ts b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts index e2633387abab..33d60c1ee412 100644 --- a/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts +++ b/src/main/ai-vault/session-scanner-discovery-wsl-gate.test.ts @@ -115,7 +115,13 @@ describe('discoverFiles containment for a stalled WSL root', () => { await expect(Promise.all([discovery, healthy])).resolves.toEqual([ { agent: 'codex', rootDir: UNC_ROOT, files: [] }, - { agent: 'codex', rootDir: '/home/ada/.codex/sessions', files: [] } + { + agent: 'codex', + rootDir: '/home/ada/.codex/sessions', + files: [], + scopeFiles: undefined, + selectedFiles: [] + } ]) expect(issues).toEqual([{ agent: 'codex', path: UNC_ROOT, message: SLOW_MESSAGE }]) } @@ -139,7 +145,13 @@ describe('discoverFiles containment for a stalled WSL root', () => { // Route quarantine makes later stats fail fast; only the first stalled operations reach deadlines. await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS * 2 + 2) - await expect(discovery).resolves.toEqual({ agent: 'codex', rootDir: UNC_ROOT, files: [] }) + await expect(discovery).resolves.toEqual({ + agent: 'codex', + rootDir: UNC_ROOT, + files: [], + scopeFiles: undefined, + selectedFiles: [] + }) expect(issues).toHaveLength(names.length) expect(issues.every((issue) => issue.path.startsWith(UNC_ROOT))).toBe(true) } diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index 65a665bdb634..90dfdaa26c7c 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -1,16 +1,21 @@ import type { Dirent } from 'node:fs' import { extname, join } from 'node:path' +import { isSelectedSessionFile } from './session-scanner-selection' import { mapWithConcurrency } from '../../shared/map-with-concurrency' import { PrioritySemaphore } from '../../shared/priority-semaphore' import { isWslUncPath } from '../../shared/wsl-paths' +import { + observeSessionFile, + isMissingSidecarError, + type SessionFileObservation +} from './session-file-observation' +import { errorMessage } from './session-scanner-values' import { SessionNewestFiles } from './session-newest-files' -import type { SessionSidecarObservation } from './session-sidecar-stat' import type { AiVaultAgent, AiVaultScanIssue } from '../../shared/ai-vault-types' -import { wslGatedReaddir, wslGatedStat } from '../native-chat/wsl-transcript-fs-access' +import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' import { recordSessionScanIssue } from './session-scan-issues' import type { FileWithMtime, SessionFileDiscovery } from './session-scanner-types' -import { errorMessage } from './session-scanner-values' import { throwIfAiVaultScanCancelled } from './ai-vault-scan-cancellation' import { noteAiVaultScanFileFound, @@ -22,10 +27,6 @@ const NATIVE_DISCOVERY_CONCURRENCY = 4 const NATIVE_DISCOVERY_BATCH_SIZE = 16 const nativeDiscoverySlots = new PrioritySemaphore(8) -type SessionFileObservation = - | { file: Omit; sidecarPath?: string } - | { issue: { path: string; message: string } } - async function withNativeDiscoverySlot(read: () => Promise): Promise { const release = await nativeDiscoverySlots.acquire(0) try { @@ -46,9 +47,12 @@ export async function discoverFiles(args: { directoryPredicate?: (name: string, depth: number) => boolean // A scoped scan walks every file this agent has, not only the newest `limit`. keepScopeFiles?: boolean + selectedSessionId?: string + executionHostId?: string 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[] = [] @@ -78,6 +82,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) || @@ -193,64 +208,13 @@ export async function discoverFiles(args: { } finally { source.close() } - return { agent: args.agent, rootDir: args.rootDir, files: files.newest(), scopeFiles } -} - -async function observeSessionFile( - path: string, - contentDependencyPath?: (path: string) => string | undefined | Promise, - signal?: AbortSignal -): Promise { - try { - const fileStat = await wslGatedStat(path, 'scan', signal) - const sidecarPath = contentDependencyPath ? await contentDependencyPath(path) : undefined - const sidecar = sidecarPath ? await observeSessionSidecar(sidecarPath, signal) : 'none' - return { - file: { - path, - mtimeMs: fileStat.mtimeMs, - sizeBytes: fileStat.size, - sidecar, - dev: fileStat.dev, - ino: fileStat.ino, - nlink: fileStat.nlink - }, - sidecarPath - } - } catch (err) { - return { issue: { path, message: errorMessage(err) } } - } -} - -/** Only missing sidecars are none; other stat failures stay unknown so cached enrichment can retry. */ -async function observeSessionSidecar( - filePath: string | undefined, - signal?: AbortSignal -): Promise { - if (!filePath) { - return 'none' - } - try { - const fileStat = await wslGatedStat(filePath, 'scan', signal) - return { - path: filePath, - mtimeMs: fileStat.mtimeMs, - sizeBytes: fileStat.size - } - } catch (error) { - return isMissingSidecarError(error) ? 'none' : 'unknown' - } -} - -function isMissingSidecarError(error: unknown): boolean { - if (error instanceof WslTranscriptFsError) { - return false + return { + agent: args.agent, + rootDir: args.rootDir, + files: files.newest(), + scopeFiles, + selectedFiles } - const code = - error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' - ? error.code - : null - return code === 'ENOENT' || code === 'ENOTDIR' } export type SessionFileWalkOptions = { diff --git a/src/main/ai-vault/session-scanner-opencode-sources.ts b/src/main/ai-vault/session-scanner-opencode-sources.ts index 213c37257e42..8bb799dfa42a 100644 --- a/src/main/ai-vault/session-scanner-opencode-sources.ts +++ b/src/main/ai-vault/session-scanner-opencode-sources.ts @@ -12,6 +12,7 @@ import { listOpenCode2SqliteSessionsViaWorker } from './session-scanner-opencode import { isOpenCodeV2DatabaseName } from '../../shared/opencode-database-name' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' import { scopeWalksAgentFiles } from './session-scope-cwd' +import { isSelectedSessionFile } from './session-scanner-selection' type OpenCodeSource = { storageDir: string @@ -35,6 +36,7 @@ export function opencodeDiscoveries( limitPerAgent: limit, issues, scopePaths: options.scopePaths, + selectedSessionId: options.selectedSessionId, signal: options.signal }) ), @@ -100,6 +102,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([ @@ -110,6 +113,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/session-scanner-opencode-sqlite-discovery.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-discovery.ts index b87a4d7f14b3..7d9aae4dc133 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-discovery.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-discovery.ts @@ -5,6 +5,7 @@ import { splitOpenCodeSqliteCandidate } from './session-scanner-opencode-sqlite- import { listOpenCodeSqliteSessionsViaWorker } from './session-scanner-opencode-sqlite-worker-spawn' import type { FileWithMtime, SessionFileDiscovery } from './session-scanner-types' import { scopeWalksAgentFiles } from './session-scope-cwd' +import { isSelectedSessionFile } from './session-scanner-selection' export { listOpenCodeSqliteSessions } from './session-scanner-opencode-sqlite-list' @@ -18,6 +19,7 @@ export async function discoverOpenCodeSessions(args: { dbPaths: readonly string[] limitPerAgent: number issues: AiVaultScanIssue[] + selectedSessionId?: string scopePaths?: readonly string[] signal?: AbortSignal }): Promise { @@ -28,6 +30,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([ @@ -38,6 +41,7 @@ export async function discoverOpenCodeSessions(args: { issues: args.issues, extensions: ['.json'], keepScopeFiles: walksScope, + selectedSessionId: args.selectedSessionId, signal: args.signal }), listSqlite(), @@ -63,6 +67,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/session-scanner-opencode-sqlite-dispatch.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-dispatch.ts index fa0ce2743d34..cda933d59d08 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-dispatch.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-dispatch.ts @@ -37,14 +37,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/session-scanner-opencode-sqlite-list.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-list.ts index 548507f907dd..9d609034e47a 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-list.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-list.ts @@ -9,6 +9,7 @@ import { } from './session-scanner-opencode-sqlite-open' import type { SessionFileCandidate } from './session-scanner-types' import type SyncDatabase from '../sqlite/sync-database' +import { selectedSqliteSessionId } from './session-scanner-selection' import { scopedSessionRows } from './session-scanner-sqlite-scope-rows' import { columnExists, tableExists } from '../opencode-usage/schema-helpers' @@ -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 ?' : ''}` } @@ -109,6 +115,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 +125,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 && canReadOpenCodeSessions(db) && !rows.some((row) => row.id === selected)) { + const row = db.prepare(buildSessionListQuery(db, false, false, true)).get(selected) + 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/session-scanner-opencode-sqlite-process-entry.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-process-entry.ts index bcd380bc51e4..92aa6846d804 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-process-entry.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-process-entry.ts @@ -43,6 +43,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/session-scanner-opencode-sqlite-worker-client.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts index c6e6588787a6..5c3fe97c48ce 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-client.ts @@ -72,6 +72,7 @@ export class OpenCodeSqliteWorkerClient { limit: number issues: AiVaultScanIssue[] agent?: 'opencode2' | 'zcode' + selectedSessionId?: string scopePaths?: readonly string[] signal?: AbortSignal }): Promise { @@ -87,6 +88,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/session-scanner-opencode-sqlite-worker-factory.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-factory.ts new file mode 100644 index 000000000000..176a87a9ded3 --- /dev/null +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-factory.ts @@ -0,0 +1,19 @@ +import { existsSync } from 'node:fs' +import { Worker } from 'node:worker_threads' +import { findForeignSqliteReaderEntry } from '../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' + +export function resolveOpenCodeSqliteWorkerEntryPath( + runtimeDir = __dirname, + pathExists: (path: string) => boolean = existsSync +): string { + return findForeignSqliteReaderEntry(runtimeDir, pathExists) +} + +export function defaultWorkerFactory(): Worker { + const workerPath = resolveOpenCodeSqliteWorkerEntryPath() + // Fail synchronously for missing bundles rather than waiting for an impossible worker response. + if (!existsSync(workerPath)) { + throw new Error(`OpenCode SQLite worker entry not found: ${workerPath}`) + } + return new Worker(workerPath) +} diff --git a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.ts index a33fd5fb5877..9b802e637b2b 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-protocol.ts @@ -12,6 +12,7 @@ export type OpenCodeSqliteListRequest = { dbPaths: readonly string[] limit: number | null agent?: 'opencode2' | 'zcode' + selectedSessionId?: string /** Lists only sessions whose directory is in scope; an older reader ignores it and lists unfiltered. */ scopePaths?: readonly string[] } diff --git a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.test.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.test.ts index 81f1b0366064..f6cc48196b47 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.test.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.test.ts @@ -67,3 +67,20 @@ it('routes scoped SQLite reads only to the owning distro and reports a scoped-on { agent: 'opencode', kind: 'scope', path: ubuntu, message: 'Scoped read timed out' } ]) }) + +it('translates the exact selected SQLite identity only within its known WSL source', async () => { + mocks.list.mockClear().mockResolvedValue([]) + const path = String.raw`\\wsl.localhost\Ubuntu\home\ada\opencode.db` + await listOpenCodeSqliteSessionsViaWorker({ + dbPaths: [path], + limit: 1, + issues: [], + selectedSessionId: `local:opencode:old:${path}#old` + }) + expect(mocks.list).toHaveBeenCalledWith( + expect.objectContaining({ + selectedSessionId: 'local:opencode:old:/home/ada/opencode.db#old', + limit: 1 + }) + ) +}) diff --git a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts index ebc43b915f06..e42eaab52f52 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-worker-spawn.ts @@ -1,7 +1,6 @@ +import { selectedSqliteSessionId } from './session-scanner-selection' import { aiVaultScopePathsForWslDistro } from '../../shared/ai-vault-scope-cwd-match' import { recordSessionScanIssue } from './session-scan-issues' -import { existsSync } from 'node:fs' -import { Worker } from 'node:worker_threads' import type { AiVaultScanIssue, AiVaultSession } from '../../shared/ai-vault-types' import { throwIfSignalAborted } from '../../shared/abort-signal-reason' import { openCodeTranscriptPageLimit } from '../../shared/opencode-transcript-page-limit' @@ -17,25 +16,11 @@ import { openCodeWslClient, openCodeWslPath } from './session-scanner-opencode-wsl-client' -import { findForeignSqliteReaderEntry } from '../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' +import { defaultWorkerFactory } from './session-scanner-opencode-sqlite-worker-factory' import { runOpenCodeSqliteScanRequest } from './session-scanner-opencode-sqlite-scan-scope' import { noteAiVaultScanDatabases, openAiVaultScanSource } from './ai-vault-scan-progress' -export function resolveOpenCodeSqliteWorkerEntryPath( - runtimeDir = __dirname, - pathExists: (path: string) => boolean = existsSync -): string { - return findForeignSqliteReaderEntry(runtimeDir, pathExists) -} - -function defaultWorkerFactory(): Worker { - const workerPath = resolveOpenCodeSqliteWorkerEntryPath() - // Fail synchronously for missing bundles rather than waiting for an impossible worker response. - if (!existsSync(workerPath)) { - throw new Error(`OpenCode SQLite worker entry not found: ${workerPath}`) - } - return new Worker(workerPath) -} +export { resolveOpenCodeSqliteWorkerEntryPath } from './session-scanner-opencode-sqlite-worker-factory' let sharedClient: OpenCodeSqliteWorkerClient | null = null @@ -181,6 +166,18 @@ async function listCandidatesForHost( signal, dbPaths: [...paths.keys()], scopePaths, + selectedSessionId: [...paths].flatMap(([linuxPath, original]) => { + const sessionId = selectedSqliteSessionId( + args.selectedSessionId, + args.agent ?? 'opencode', + original + ) + return sessionId + ? [ + `local:${args.agent ?? 'opencode'}:${sessionId}:${buildOpenCodeSqliteCandidatePath(linuxPath, sessionId)}` + ] + : [] + })[0], issues }) }, diff --git a/src/main/ai-vault/session-scanner-opencode-sqlite.test.ts b/src/main/ai-vault/session-scanner-opencode-sqlite.test.ts index 3ba2df82a6ca..cce449859019 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite.test.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite.test.ts @@ -641,3 +641,29 @@ describe('parseOpenCodeSqliteSession', () => { 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/session-scanner-opencode2-sqlite-list.ts b/src/main/ai-vault/session-scanner-opencode2-sqlite-list.ts index 18bfd5f70ace..7826e03434ca 100644 --- a/src/main/ai-vault/session-scanner-opencode2-sqlite-list.ts +++ b/src/main/ai-vault/session-scanner-opencode2-sqlite-list.ts @@ -7,6 +7,7 @@ import type { SessionFileCandidate } from './session-scanner-types' import { errorMessage } from './session-scanner-values' import SyncDatabase from '../sqlite/sync-database' import { columnExists, tableExists } from '../opencode-usage/schema-helpers' +import { selectedSqliteSessionId } from './session-scanner-selection' import { scopedSessionRows } from './session-scanner-sqlite-scope-rows' // V2 uses session_v2/session_message tables; guard evolving schemas in shared and channel databases. @@ -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,7 +52,7 @@ 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 ?' : ''}` } @@ -89,6 +95,7 @@ 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 { @@ -111,6 +118,27 @@ export async function listOpenCode2SqliteSessions(args: { scoped && args.scopePaths ? scopedSessionRows(listed, args.scopePaths, args.limit, dbPath) : listed + const selected = selectedSqliteSessionId(args.selectedSessionId, 'opencode2', dbPath) + const selectedRow = selected + ? db.prepare(buildSessionListQuery(db, false, false, true)).get(selected) + : 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/session-scanner-opencode2-sqlite.test.ts b/src/main/ai-vault/session-scanner-opencode2-sqlite.test.ts index c58db6c01f6b..80d4fa03bdd2 100644 --- a/src/main/ai-vault/session-scanner-opencode2-sqlite.test.ts +++ b/src/main/ai-vault/session-scanner-opencode2-sqlite.test.ts @@ -374,3 +374,36 @@ describe('parseOpenCode2SqliteSession', () => { expect(session).toBeNull() }) }) + +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/session-scanner-parse-cache.ts b/src/main/ai-vault/session-scanner-parse-cache.ts index dddb918eb947..71d161aec293 100644 --- a/src/main/ai-vault/session-scanner-parse-cache.ts +++ b/src/main/ai-vault/session-scanner-parse-cache.ts @@ -253,7 +253,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) @@ -264,7 +264,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/session-scanner-primary-parsers.ts b/src/main/ai-vault/session-scanner-primary-parsers.ts index c3807f2e415d..c3edd8c33acf 100644 --- a/src/main/ai-vault/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/session-scanner-primary-parsers.ts @@ -23,6 +23,7 @@ import { updateTimeline } from './session-scanner-accumulator' import { addSessionContent } from './session-scanner-messages' +import { extractFullFirstUserPromptText } from './session-scanner-first-user-prompt' import { countSubagentTranscripts } from './session-scanner-subagent-transcripts' import { asRecord, @@ -43,6 +44,7 @@ export type ClaudeSessionParseState = { metaTitle: string | null generatedTitle: string | null firstUserTitle: string | null + conversationContent: NonNullable } export function createClaudeSessionParseState( @@ -58,7 +60,8 @@ export function createClaudeSessionParseState( }), metaTitle: null, generatedTitle: null, - firstUserTitle: null + firstUserTitle: null, + conversationContent: 'empty' } } @@ -72,7 +75,8 @@ export function cloneClaudeSessionParseState( }, metaTitle: state.metaTitle, generatedTitle: state.generatedTitle, - firstUserTitle: state.firstUserTitle + firstUserTitle: state.firstUserTitle, + conversationContent: state.conversationContent } } @@ -80,6 +84,8 @@ export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: s const record = parseJsonObject(line) if (record) { consumeClaudeSessionRecord(state, record) + } else if (line.trim() && state.conversationContent !== 'present') { + state.conversationContent = 'unknown' } } @@ -108,8 +114,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 } @@ -127,6 +139,7 @@ export function consumeClaudeSessionRecord( const prompt = normalizePromptField(record.lastPrompt) if (prompt) { accumulator.lastUserPrompt = prompt + state.conversationContent = 'present' } return } @@ -140,17 +153,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) @@ -159,6 +171,10 @@ export function consumeClaudeSessionRecord( accumulator.model = model } accumulator.totalTokens += claudeUsageTotal(message?.usage) + return + } + if (state.conversationContent !== 'present') { + state.conversationContent = 'unknown' } } @@ -169,7 +185,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. @@ -180,7 +196,16 @@ export async function finalizeClaudeSessionParseState( snapshot.accumulator.filePath ) } - return finalizeSession(snapshot.accumulator, platform, options) + const session = finalizeSession(snapshot.accumulator, platform, options) + return session + ? { + ...session, + conversationContent: + session.queuedMessageCount > 0 || session.subagentTranscriptCount > 0 + ? 'present' + : snapshot.conversationContent + } + : null } export function createClaudeSessionResumeState( 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..aa4857873615 --- /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 './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..fe5c44a6a286 --- /dev/null +++ b/src/main/ai-vault/session-scanner-selection.ts @@ -0,0 +1,33 @@ +import type { AiVaultAgent } from '../../shared/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import { buildOpenCodeSqliteCandidatePath } from './session-scanner-opencode-sqlite-paths' + +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 +} diff --git a/src/main/ai-vault/session-scanner-source-discovery.ts b/src/main/ai-vault/session-scanner-source-discovery.ts index 0f2599f9910e..0a30b1ce125a 100644 --- a/src/main/ai-vault/session-scanner-source-discovery.ts +++ b/src/main/ai-vault/session-scanner-source-discovery.ts @@ -62,6 +62,8 @@ function agentDiscoveries( contentDependencyPath: source.contentDependencyPath, directoryPredicate: source.directoryPredicate, keepScopeFiles: scopeWalksAgentFiles(agent, options.scopePaths), + selectedSessionId: options.selectedSessionId, + executionHostId: options.executionHostId, signal: options.signal }) return source.mergeRootDiscoveries @@ -87,6 +89,7 @@ async function mergedDiscovery( agent, rootDir: rootDirs.join(delimiter), files: files.slice(0, limit), + selectedFiles: discoveries.flatMap((discovery) => discovery.selectedFiles ?? []), ...(scopeFiles ? { scopeFiles } : {}) } } diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index 7162037c42bb..6d748159f2b3 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -54,6 +54,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[] platform?: NodeJS.Platform @@ -87,6 +88,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[] } diff --git a/src/main/ai-vault/session-scanner-zcode-sources.ts b/src/main/ai-vault/session-scanner-zcode-sources.ts index 53cf3da28d09..8594e6501caa 100644 --- a/src/main/ai-vault/session-scanner-zcode-sources.ts +++ b/src/main/ai-vault/session-scanner-zcode-sources.ts @@ -6,6 +6,7 @@ import { wslGatedAccess } from '../native-chat/wsl-transcript-fs-access' import { listZcodeSqliteSessionsViaWorker } from './session-scanner-opencode-sqlite-worker-spawn' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' import { scopeWalksAgentFiles } from './session-scope-cwd' +import { isSelectedSessionFile } from './session-scanner-selection' // Keep ZCode discovery separate so OpenCode cannot absorb its database rows. export function zcodeDiscoveries( @@ -27,6 +28,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([ @@ -37,6 +39,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.ts b/src/main/ai-vault/session-scanner.ts index 0f5a58e002b2..2c138808060b 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 './session-scanner-antigravity-history' -import { sessionCandidatesFromDiscoveries } from './session-scanner-candidates' +import { + discoveryFileCandidates, + sessionCandidatesFromDiscoveries +} from './session-scanner-candidates' import { parseSessionCandidates } from './session-scanner-candidate-parse' import { createSessionParseStats } from './session-scanner-parse-cache' import { recordSessionScanIssue } from './session-scan-issues' @@ -92,6 +95,25 @@ async function scanAiVaultSessionStores(options: AiVaultScanOptions): Promise sessionSortTime(right) - sessionSortTime(left)) .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, @@ -124,7 +146,7 @@ async function scanAiVaultSessionStores(options: AiVaultScanOptions): Promise ({ executionHostId, ...issue })), scannedAt: new Date().toISOString() } diff --git a/src/main/ai-vault/session-transcript-reader.ts b/src/main/ai-vault/session-transcript-reader.ts index 8fc3ce24cefa..21f25748c411 100644 --- a/src/main/ai-vault/session-transcript-reader.ts +++ b/src/main/ai-vault/session-transcript-reader.ts @@ -104,7 +104,14 @@ export async function readResumableTranscript( channel.mute(() => displayState.consumeLine(partialLine)) } - const session = await displayState.finalize(args.platform) + const skippedRecords = mergeSkippedTranscriptRecords( + canResume ? resume.skippedRecords : [], + readResult.skippedRecords + ) + let session = await displayState.finalize(args.platform) + if (session?.conversationContent === 'empty' && skippedRecords.length > 0) { + session = { ...session, conversationContent: 'unknown' } + } const consumerSession = args.sessionForConsumers ? await args.sessionForConsumers(session) : session @@ -122,11 +129,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 } } } catch (error) { 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..dc644185a375 --- /dev/null +++ b/src/main/ai-vault/structured-conversation-journal-preview.ts @@ -0,0 +1,106 @@ +import { z } from 'zod' +import type { AgentSessionRecord } from '../../shared/agent-session-record' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import { firstStructuredAgentSessionPrompt } from '../../shared/structured-agent-session-first-prompt' +import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' +import { + applyJournalRow, + createJournalReducerState, + renderJournalState +} from '../native-chat/agent-session-journal/journal-reducer' +import { parseJournalRow } from '../native-chat/agent-session-journal/journal-row-schema' + +const ROW_LIMIT = 41 +const ROW_TEXT_LIMIT = 65_536 +const Session = z.object({ epoch: z.string().min(1), workspaceId: z.string() }) +const Rows = z.array( + z.object({ seq: z.number().int(), ts: z.number(), rowJson: z.string().max(ROW_TEXT_LIMIT) }) +) +const UNKNOWN = { conversationContent: 'unknown' as const } + +export type StructuredConversationJournalPreview = { + conversationContent: NonNullable + firstUserPrompt?: string +} + +/** Read only a bounded indexed prefix; uncertainty must never hide recoverable history. */ +export function structuredConversationJournalPreview( + database: Pick | undefined, + record: Pick +): StructuredConversationJournalPreview { + try { + if (!database) { + return UNKNOWN + } + const db = database.db + const session = Session.safeParse( + db + .prepare( + 'SELECT epoch, workspace_id AS workspaceId FROM journal_sessions WHERE session_id = ?' + ) + .get(record.sessionId) + ) + if (!session.success || session.data.workspaceId !== record.location.workspaceId) { + return UNKNOWN + } + const { epoch } = session.data + const entries = Rows.safeParse( + db + .prepare(`SELECT seq, ts, substr(row_json, 1, ?) AS rowJson FROM journal_rows + WHERE session_id = ? AND epoch = ? ORDER BY seq ASC LIMIT ?`) + .all(ROW_TEXT_LIMIT + 1, record.sessionId, epoch, ROW_LIMIT) + ) + if (!entries.success || entries.data.length === 0) { + return UNKNOWN + } + const state = createJournalReducerState(record.sessionId, epoch) + let creationOnly = false + let hasContent = false + for (const [index, entry] of entries.data.entries()) { + const parsed = parseJournalRow(entry.rowJson) + if ( + !parsed.ok || + parsed.row.epoch !== epoch || + parsed.row.seq !== entry.seq || + entry.seq !== index + 1 + ) { + return UNKNOWN + } + const row = parsed.row + if ((index === 0) !== (row.kind === 'epoch')) { + return UNKNOWN + } + if (row.kind === 'epoch') { + creationOnly = + row.reason === 'session_created' && + row.historyOrigin === undefined && + row.recovered !== true + } else { + hasContent ||= + row.kind === 'item' || + row.kind === 'submission' || + (row.kind === 'queue' && 'body' in row.change) || + (row.kind === 'lifecycle-batch' && + row.mutations.some((mutation) => mutation.kind === 'item')) + } + applyJournalRow(state, row, entry.ts) + } + const snapshot = renderJournalState(state) + const firstUserPrompt = firstStructuredAgentSessionPrompt( + snapshot.items.filter((item) => item.body.kind !== 'message' || item.body.from === undefined) + ) + return { + conversationContent: + entries.data.length === ROW_LIMIT + ? 'unknown' + : hasContent + ? 'present' + : creationOnly && entries.data.length === 1 + ? 'empty' + : 'unknown', + ...(firstUserPrompt ? { firstUserPrompt } : {}) + } + } catch { + return UNKNOWN + } +} 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..a6911f91628a --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation-content.test.ts @@ -0,0 +1,207 @@ +import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import type { AgentSessionRecord } from '../../shared/agent-session-record' +import type { AiVaultListResult } from '../../shared/ai-vault-types' +import type { AgentJournalMessageItem } from '../../shared/agent-session-journal-types' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import { createJournalTablesSql } from '../native-chat/agent-session-journal/journal-database-schema' +import { + insertJournalRow, + publishJournalSessionEpoch +} from '../native-chat/agent-session-journal/journal-row-table' +import type { JournalRow } from '../native-chat/agent-session-journal/journal-row-schema' +import Database from '../sqlite/sync-database' +import { + projectStructuredAiVaultSessions, + OPENS_EVERY_STRUCTURED_CHAT +} from './structured-session-ownership' +import { listResult } from './structured-session-ownership.test-support' +import { parseAiVaultListResult } from './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 = new Database(':memory:') + db.exec(createJournalTablesSql()) + record = agentSessionRecordFixture() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: projection reads only this host's catalog and journal database. + setStructuredAgentSessionHost({ + deps: { + store: { + listRecords: () => [record], + listConversations: () => [agentSessionConversationView(record)] + }, + 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 + }) +} +function project(result = EMPTY) { + return projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT, { + includeStructuredSessions: true + }) +} +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', () => { + it('preserves a meaningful provider title through ownership and durable projection, then prefers a saved name', () => { + const input = { ...EMPTY, sessions: [providerRow('Investigate the deployment failure')] } + expect(project(input).sessions[0]?.title).toBe('Investigate the deployment failure') + record.conversationName = 'My saved name' + expect(project(input).sessions[0]?.title).toBe('My saved name') + }) + + it('marks only a registered, intact creation epoch empty, including a saved default label', () => { + record.conversationName = 'Claude Chat' + expect(project().sessions[0]).toMatchObject({ + conversationContent: 'unknown', + title: 'Claude Chat' + }) + register() + const result = 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', () => { + 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(project().sessions[0]).toMatchObject({ + conversationContent: 'present', + firstUserPrompt: 'Проверь настройки проекта', + title: 'Проверь настройки проекта' + }) + record.conversationName = 'Saved title' + expect(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', () => { + register() + for (const session of [ + providerRow('Provider conversation'), + { ...providerRow('Queued message', 0), queuedMessageCount: 2 } + ]) { + expect(project({ ...EMPTY, sessions: [session] }).sessions[0]?.conversationContent).toBe( + 'present' + ) + } + }) + + it('does not let an empty local epoch erase uncertain provider-file history', () => { + register() + expect( + 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', () => { + register() + const session = { + ...providerRow('Claude Chat', 3), + conversationContent: 'empty' as const + } + expect(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', + (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(project().sessions[0]?.conversationContent).toBe('unknown') + } + ) + + it('bounds journal discovery and never calls a bounded prefix empty', () => { + 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(project().sessions[0]).toMatchObject({ conversationContent: 'unknown' }) + expect(project().sessions[0]?.firstUserPrompt).toBeUndefined() + }) + + it('keeps oversized journal rows unknown instead of loading unbounded output', () => { + register() + item(2, 'large prompt '.repeat(10000)) + expect(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..a0231f95056e --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation.test.ts @@ -0,0 +1,352 @@ +import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentSessionRecord } from '../../shared/agent-session-record' +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../shared/agent-session-record.test-fixture' +import { claudeProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import type { AiVaultListResult } from '../../shared/ai-vault-types' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import { + OPENS_EVERY_STRUCTURED_CHAT, + projectStructuredAiVaultSessions +} from './structured-session-ownership' +import { listResult } from './structured-session-ownership.test-support' +import { parseAiVaultListResult } from './session-list-result-validation' +import { restampAiVaultListResult } from './session-list-results' +import { aiVaultOrchestrationChildSessionIds } from './structured-conversation-navigation' +import { OrchestrationDb } from '../runtime/orchestration/db' +import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' +import { formatOrcaSessionAddress } from '../../shared/orca-session-address' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerProcessIncarnation +} from '../runtime/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, + listConversations: () => records.map(agentSessionConversationView) + } + } + } 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..96e9680fcf3f --- /dev/null +++ b/src/main/ai-vault/structured-conversation-navigation.ts @@ -0,0 +1,171 @@ +import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' +import { isGenericConversationTitle } from '../../shared/project-conversation-list' +import { conversationNameSeed } from '../../shared/conversation-name-generation' +import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' +import { structuredConversationJournalPreview } from './structured-conversation-journal-preview' +import type { AgentSessionRecord } from '../../shared/agent-session-record' +import { defaultAgentChatLabel } from '../../shared/agent-session/agent-session-chat-label' +import { + isAiVaultAgent, + isAiVaultSessionResumableContent, + aiVaultSessionRecoverableSignalCount, + type AiVaultListResult, + type AiVaultSession +} from '../../shared/ai-vault-types' +import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +import { splitWorktreeIdForFilesystem } from '../../shared/worktree/id' +import { structuredAgentRuntimeMetadata } from '../runtime/structured-agent-runtime-metadata' +import type { StructuredChatOpener } from './structured-session-ownership' +import type { OrchestrationDb } from '../runtime/orchestration/db' +import { z } from 'zod' +import { clearedInto } from '../runtime/orchestration/structured-session-lineage' + +/** 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(), + journalDatabase?: JournalHostDatabase +): 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) + ? structuredConversationJournalPreview(journalDatabase, record) + : { 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-ownership.test-support.ts b/src/main/ai-vault/structured-session-ownership.test-support.ts index 67868e9e97a1..aecb93246fa5 100644 --- a/src/main/ai-vault/structured-session-ownership.test-support.ts +++ b/src/main/ai-vault/structured-session-ownership.test-support.ts @@ -19,9 +19,10 @@ export const PROVIDER_SESSION = '019fd532-7c11-7a90-b6de-4e1a2c3d5f60' export function installOwnership( overrides: Partial> & { handle?: AgentSessionProviderHandle + location?: Partial } = {} ): void { - const { handle, ...ownershipOverrides } = overrides + const { handle, location, ...ownershipOverrides } = overrides const ownership: Omit = { sessionId: 'session-alpha', workspaceId: 'workspace-1', @@ -33,32 +34,31 @@ export function installOwnership( const record = agentSessionRecordFixture( agentSessionLeaseFixture({ sessionId: ownership.sessionId }) ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the ownership read touches only `deps.store.listConversations`; the rest of the host is never reached. + const ownedRecord = { + ...record, + sessionId: ownership.sessionId, + location: { ...record.location, workspaceId: ownership.workspaceId, ...location }, + provider: ownership.provider, + providerHandleChain: [ + { + ...record.providerHandleChain[0]!, + handle: + handle ?? + (ownership.provider === 'claude' + ? claudeProviderHandle(ownership.providerSessionId, null) + : codexProviderHandle(ownership.providerSessionId)) + } + ], + ...(ownership.conversationName ? { conversationName: ownership.conversationName } : {}) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership and history projection read only the catalog and its conversation views. setStructuredAgentSessionHost({ deps: { store: { + listRecords: () => [ownedRecord], listConversations: () => [ { - ...agentSessionConversationView({ - ...record, - sessionId: ownership.sessionId, - location: { ...record.location, workspaceId: ownership.workspaceId }, - provider: ownership.provider, - providerHandleChain: [ - { - ...record.providerHandleChain[0]!, - handle: - handle ?? - (ownership.provider === 'claude' - ? claudeProviderHandle(ownership.providerSessionId, null) - : codexProviderHandle(ownership.providerSessionId)) - } - ], - lease: record.lease, - ...(ownership.conversationName - ? { conversationName: ownership.conversationName } - : {}) - }), + ...agentSessionConversationView(ownedRecord), ownerObservation: ownership.ownerObservation } ] diff --git a/src/main/ai-vault/structured-session-ownership.test.ts b/src/main/ai-vault/structured-session-ownership.test.ts index 2d4c206398d8..8deaef5b4551 100644 --- a/src/main/ai-vault/structured-session-ownership.test.ts +++ b/src/main/ai-vault/structured-session-ownership.test.ts @@ -39,6 +39,23 @@ describe('structured AI Vault ownership', () => { }) }) + it('retains local WSL ownership while excluding records owned by another execution host', () => { + const result = listResult() + installOwnership({ conversationName: 'WSL conversation', location: { wslDistro: 'Ubuntu' } }) + expect( + projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT).sessions[0] + ).toMatchObject({ + title: 'WSL conversation', + structuredSession: { sessionId: 'session-alpha' } + }) + expect(projectStructuredAiVaultSessions(result, () => false).sessions).toEqual([]) + installOwnership({ + conversationName: 'Remote conversation', + location: { executionHostId: 'runtime:other' } + }) + expect(projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT)).toBe(result) + }) + it('uses the owning record name while leaving an unowned row alone', () => { installOwnership({ conversationName: 'auth/login' }) const result = listResult() @@ -80,7 +97,7 @@ describe('structured AI Vault ownership', () => { }) it.each(['claude', 'codex'] as const)( - 'keeps an unnamed %s chat at its ordinary label', + 'keeps a meaningful provider title for an unnamed %s chat', (provider) => { installOwnership({ provider }) const result = listResult() @@ -91,7 +108,7 @@ describe('structured AI Vault ownership', () => { })) expect( projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT).sessions[0]?.title - ).toBe(provider === 'claude' ? 'Claude Chat' : 'Codex Chat') + ).toBe('First prompt') } ) diff --git a/src/main/ai-vault/structured-session-ownership.ts b/src/main/ai-vault/structured-session-ownership.ts index c81e38824bc0..1ef140c8b0a8 100644 --- a/src/main/ai-vault/structured-session-ownership.ts +++ b/src/main/ai-vault/structured-session-ownership.ts @@ -21,6 +21,8 @@ import { import { STRUCTURED_AGENT_RUNTIME_METADATA } from '../runtime/structured-agent-runtime-metadata' import type { StructuredAgentRuntimeMetadata } from '../runtime/structured-agent-runtime-registration-types' import { commandName, commandProgramIndex, shellCommands } from './shell-command-words' +import { projectDurableAiVaultConversations } from './structured-conversation-navigation' +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 @@ -29,7 +31,8 @@ export const OPENS_EVERY_STRUCTURED_CHAT: StructuredChatOpener = () => true export function projectStructuredAiVaultSessions( result: AiVaultListResult, - opensChat: StructuredChatOpener + opensChat: StructuredChatOpener, + options?: { includeStructuredSessions?: boolean; childSessionIds?: ReadonlySet | null } ): AiVaultListResult { const owner = ownershipLookup() if (!owner) { @@ -43,12 +46,22 @@ export function projectStructuredAiVaultSessions( if (!opensChat(ownership.provider)) { return [] } - return [{ ...session, ...ownedRow(session.agent, ownership) }] + return [{ ...session, ...ownedRow(session, ownership) }] }) - 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, + getStructuredAgentSessionHost()?.deps.journalDatabase + ) + : projected } /** Owned search hits open their chat and omit terminal resume commands, matching history rows. */ @@ -71,7 +84,7 @@ export function projectStructuredAiVaultSearchResponse( return [] } const { resumeCommand: _resumeCommand, ...owned } = hit - return [{ ...owned, ...ownedRow(hit.agent, ownership) }] + return [{ ...owned, ...ownedRow(hit, ownership) }] }) } } @@ -100,14 +113,24 @@ 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 } + 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 } : { title, structuredSession } } @@ -119,7 +142,7 @@ function ownershipLookup(): return null } const byProviderSession = new Map() - for (const ownership of listOwnership()) { + for (const ownership of listOwnership(true)) { const key = `${ownership.provider}\0${ownership.providerSessionId}` const kept = byProviderSession.get(key) if (!kept || (kept.role !== 'head' && ownership.role === 'head')) { @@ -200,9 +223,17 @@ function resumeOwnerships( ] } -function listOwnership(): StructuredProviderSessionOwnership[] { +function listOwnership(localOnly = false): StructuredProviderSessionOwnership[] { const host = getStructuredAgentSessionHost() - return host ? listStructuredProviderSessionOwnership(host.deps.store.listConversations()) : [] + return host + ? listStructuredProviderSessionOwnership( + host.deps.store + .listConversations() + .filter( + (record) => !localOnly || record.location.executionHostId === LOCAL_EXECUTION_HOST_ID + ) + ) + : [] } function resumesOwnedSession( diff --git a/src/main/persistence/applying-settings/ui-state-read.ts b/src/main/persistence/applying-settings/ui-state-read.ts index ba01996be4b5..922b34e07511 100644 --- a/src/main/persistence/applying-settings/ui-state-read.ts +++ b/src/main/persistence/applying-settings/ui-state-read.ts @@ -1,3 +1,4 @@ +import { normalizeConversationPreferences } from '../../../shared/conversation-navigation-preferences' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { @@ -43,6 +44,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 66966709b314..df4ec28ab83b 100644 --- a/src/main/persistence/applying-settings/ui-state-update.ts +++ b/src/main/persistence/applying-settings/ui-state-update.ts @@ -1,3 +1,4 @@ +import { normalizeConversationPreferences } from '../../../shared/conversation-navigation-preferences' import { normalizeExplorerDisplayRootByWorktree } from '../../../shared/file-explorer-display-root' import type { PersistedState } from '../../../shared/persisted-state-types' import { @@ -118,6 +119,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/ai-vault.test.ts b/src/main/runtime/rpc/methods/ai-vault.test.ts index 6399217f5768..3f4e192083e7 100644 --- a/src/main/runtime/rpc/methods/ai-vault.test.ts +++ b/src/main/runtime/rpc/methods/ai-vault.test.ts @@ -33,7 +33,10 @@ import { import { agentSessionRefusalError } from '../../../../shared/agent-session-wire-refusals' import { recordStructuredAgentSessionHostInstallRefusal } from '../../structured-agent-session-host-refusal' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' -import { installCopyingChat } from '../../../ai-vault/structured-session-ownership.test-support' +import { + installCopyingChat, + installOwnership +} from '../../../ai-vault/structured-session-ownership.test-support' import { configureAiVaultSessionSources, listAiVaultSessions, @@ -82,6 +85,7 @@ function makeDispatcher(): RpcDispatcher { 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) @@ -371,6 +375,100 @@ describe('aiVault.listSessions handler + shared cache', () => { 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('aborts the host scan when its last RPC caller disconnects', async () => { scanAiVaultSessionsInService.mockImplementation( (_options, signal) => @@ -643,6 +741,8 @@ describe('aiVault.listSessions handler + shared cache', () => { }) 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' diff --git a/src/main/runtime/rpc/methods/ai-vault.ts b/src/main/runtime/rpc/methods/ai-vault.ts index 97d7c9dba030..1e55e6c8bf6a 100644 --- a/src/main/runtime/rpc/methods/ai-vault.ts +++ b/src/main/runtime/rpc/methods/ai-vault.ts @@ -1,4 +1,9 @@ import { prepareStructuredChatCliFork } from '../../../ai-vault/structured-chat-cli-fork' +import { aiVaultOrchestrationChildSessionIds } from '../../../ai-vault/structured-conversation-navigation' +import { + requestedAiVaultSessionDepth, + truncateAiVaultListResult +} from '../../../../shared/ai-vault-session-depth' import { AiVaultSearchRequestSchema, AiVaultSearchStatusRequestSchema, @@ -99,6 +104,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( @@ -107,6 +116,7 @@ export const AI_VAULT_METHODS = [ unlimited: params.unlimited, force: params.force, scopePaths: params.scopePaths, + selectedSessionId, includeAntigravityIdeSessions: params.includeAntigravityIdeSessions }, signal @@ -119,14 +129,37 @@ 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 + ? { + 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/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..3672e34fc2f9 --- /dev/null +++ b/src/main/runtime/rpc/methods/client-ui-conversation-preferences.test.ts @@ -0,0 +1,103 @@ +import '../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-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/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index 507f872619b0..68da2b458551 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -1,3 +1,7 @@ +import { + SetConversationPreferenceParams, + updateConversationPreference +} from '../../../../shared/conversation-navigation-preferences' import { normalizeJiraQuickFilterState } from '../../../../shared/jira/jira-quick-filters' import { JiraQuickFilterStateParam } from '../../../../shared/rpc-contract/jira-quick-filter-params' import { @@ -43,6 +47,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/ui-state-schema-parity-checks.ts b/src/main/runtime/rpc/methods/ui-state-schema-parity-checks.ts index 8ff34d5bdd96..48b8cf586baa 100644 --- a/src/main/runtime/rpc/methods/ui-state-schema-parity-checks.ts +++ b/src/main/runtime/rpc/methods/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/runtime-rpc/runtime-rpc-mobile-method-routing.test.ts b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-routing.test.ts index 205cab94761e..02c0b17250a2 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-routing.test.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-routing.test.ts @@ -3,12 +3,13 @@ import { MOBILE_RPC_METHOD_ROUTES } from './runtime-rpc-mobile-method-routing' describe('mobile RPC method routing census', () => { it.each([ + 'ui.setConversationPreference', 'jira.status', 'jira.listIssues', 'jira.searchIssues', 'jira.getIssue', 'jira.issueComments' - ])('keeps %s on the paired desktop that owns its Jira connection', (method) => { + ])('keeps %s on the paired desktop that owns its preferences and Jira connection', (method) => { expect(MOBILE_RPC_METHOD_ROUTES.get(method)).toBe('paired-desktop') }) diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-paired-desktop-methods.ts b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-paired-desktop-methods.ts index 95c57a3ddd6f..c8803cc04adb 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-paired-desktop-methods.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-paired-desktop-methods.ts @@ -37,6 +37,7 @@ export const PAIRED_DESKTOP_METHODS = [ 'stats.summary', 'ui.get', 'ui.recordFeatureInteraction', + 'ui.setConversationPreference', 'ui.set', // The desktop's accounts pane, Linear and project pickers target its active runtime, not a workspace's host. 'accounts.consumeCodexResetCredit', diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.keyboard.test.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.keyboard.test.tsx index 4d1ef041b67e..8a919c7e0308 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.keyboard.test.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.keyboard.test.tsx @@ -18,13 +18,16 @@ import { import type { AiVaultSessionListGroup } from './ai-vault-session-filters' import type { AiVaultSessionListKeyboard } from './use-ai-vault-session-keyboard-navigation' import type { AiVaultResumeHere } from './ai-vault-session-resume-here' +import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' import * as resumeHere from './ai-vault-session-resume-here' const VIEWPORT_PX = 600 const ROW_PX = 98 vi.mock('./AiVaultSessionRow', () => ({ - VaultSessionRow: (props: { session: AiVaultSession }) =>
{props.session.title}
+ VaultSessionRow: (props: { session: AiVaultSession; detailsExpanded: boolean }) => ( +
{props.session.title}
+ ) })) // The host's side of a resumed chat: it admits the chat, then the launch settles as the test says. const launch = vi.hoisted( @@ -268,6 +271,8 @@ function selectedTitle(): string | null { beforeEach(() => { toastError.mockClear() + vi.mocked(activateAiVaultStructuredSession).mockClear() + launch.settlement = { kind: 'structured', sessionId: 'new' } // Why: happy-dom has no layout; give the virtualizer a bounded viewport and fixed rows. vi.stubGlobal('ResizeObserver', NoopResizeObserver) vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function ( @@ -292,6 +297,127 @@ afterEach(() => { }) describe('Session History keyboard selection', () => { + it.each(['structured-other-workspace', 'cli-ineligible', 'cli-eligible'] as const)( + 'keeps the Enter fallback for an unroutable %s row', + async (kind) => { + const workspaceId = 'folder:notes' + const picked: AiVaultSession = { + ...session(0), + executionHostId: 'ssh:unroutable', + ...(kind === 'structured-other-workspace' + ? { structuredSession: { sessionId: 'picked', workspaceId: 'folder:elsewhere' } } + : {}) + } + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ activeWorktreeId: workspaceId }) + useAppStore.getState().createUnifiedTab(workspaceId, 'agent-session', { + id: 'old', + entityId: 'old', + executionHostId: LOCAL_EXECUTION_HOST_ID, + agentSessionAgent: 'claude' + }) + main = await drawTabsFromMain(useAppStore) + const dismiss = vi.fn() + const confirm = vi.fn() + const { press, calls } = renderList({ + groups: [{ key: 'picked', label: null, sessions: [picked] }], + eligible: () => kind !== 'cli-ineligible', + resumeHere: { tabId: 'old', workspaceId, agent: 'claude', dismiss, confirm } + }) + press('Enter') + await act(async () => { + await main?.settle() + }) + expect(document.querySelector('[data-details-expanded="true"]') !== null).toBe( + kind !== 'cli-eligible' + ) + expect(toastError).toHaveBeenCalledTimes(kind === 'cli-eligible' ? 1 : 0) + expect(activateAiVaultStructuredSession).not.toHaveBeenCalled() + expect(calls.onResumeInNewChat).not.toHaveBeenCalled() + expect(calls.onResume).not.toHaveBeenCalled() + expect(dismiss).not.toHaveBeenCalled() + expect(confirm).not.toHaveBeenCalled() + expect( + useAppStore.getState().unifiedTabsByWorktree[workspaceId]?.map((tab) => tab.id) + ).toEqual(['old']) + } + ) + + it.each(['structured', 'adopted-here', 'adopted-elsewhere', 'unroutable', 'local'] as const)( + 'keeps the selected owner when reopening %s from /resume', + async (kind) => { + const workspaceId = 'folder:notes' + const owner = { + sessionId: 'picked-owner', + workspaceId: kind === 'adopted-elsewhere' ? 'folder:elsewhere' : workspaceId + } + const picked: AiVaultSession = { + ...session(0), + executionHostId: + kind === 'unroutable' + ? 'ssh:unroutable' + : kind === 'local' + ? 'local' + : 'runtime:selected-host', + ...(kind === 'structured' || kind === 'unroutable' || kind === 'local' + ? { structuredSession: owner } + : {}) + } + useAppStore.setState(useAppStore.getInitialState(), true) + useAppStore.setState({ + activeWorktreeId: workspaceId, + activeWorkspaceExecutionHostId: picked.executionHostId + }) + useAppStore.getState().createUnifiedTab(workspaceId, 'agent-session', { + id: 'old', + entityId: 'old', + executionHostId: LOCAL_EXECUTION_HOST_ID, + agentSessionAgent: 'claude' + }) + main = await drawTabsFromMain(useAppStore) + launch.settlement = { + kind: 'failed', + error: Object.assign(new Error('already adopted'), { + refusal: { + code: 'agent_session_conflict', + details: { reason: 'conversationHeldElsewhere', owner } + } + }) + } + const { press } = renderList({ + groups: [{ key: 'picked', label: null, sessions: [picked] }], + resumeHere: { + tabId: 'old', + workspaceId, + agent: 'claude', + dismiss: vi.fn(), + confirm: vi.fn() + } + }) + press('Enter') + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + await main?.settle() + }) + if (kind === 'unroutable') { + expect(activateAiVaultStructuredSession).not.toHaveBeenCalled() + expect(toastError).toHaveBeenCalledOnce() + expect( + useAppStore.getState().unifiedTabsByWorktree[workspaceId]?.some((tab) => tab.id === 'old') + ).toBe(true) + } else { + expect(activateAiVaultStructuredSession).toHaveBeenCalledExactlyOnceWith( + { structuredSession: owner }, + undefined, + kind === 'local' + ? { kind: 'local' } + : { kind: 'environment', environmentId: 'selected-host' } + ) + expect(toastError).not.toHaveBeenCalled() + } + } + ) + it('moves over sessions only, clamped, and a listed-twice session does not trap it', () => { const { press } = renderList({ groups: [ diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-here.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-here.ts index c45ff0f04880..94fb44e307f3 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-resume-here.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-resume-here.ts @@ -1,6 +1,10 @@ import { admitStructuredAgentSession } from '@/lib/agent-session/structured-agent-session-busy' +import { structuredAgentSessionTargetForHost } from '@/runtime/structured-agent-session-owner' import { useAppStore } from '@/store' -import { activateAiVaultStructuredSession } from '@/lib/activate-ai-vault-structured-session' +import { + activateAiVaultStructuredSession, + structuredSessionOpenFeedback +} from '@/lib/activate-ai-vault-structured-session' import { insertUnifiedTabAfterAnchor } from '@/lib/unified-tab-anchor-insertion' import { newAgentLaunchRequestId } from '@/lib/agent-launch-request-id' import { @@ -20,6 +24,7 @@ import { type CliConversationRowAgent } from '../../../../shared/structured-agent-cli-conversation-adoption' import type { Tab } from '../../../../shared/tab-types' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { structuredLaunchConversationOwner } from '@/lib/structured-agent-session-launch-failure' import type { AiVaultSessionRowChatActions } from './ai-vault-session-chat-action' import { resumeAiVaultSessionInNewChat } from './ai-vault-session-resume-in-chat-launch' @@ -63,18 +68,29 @@ 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 === here.workspaceId && adoptsCliConversations(session.agent) ) { + 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 } @@ -124,7 +140,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 @@ -162,8 +179,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' && @@ -186,9 +203,14 @@ 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 activateAiVaultStructuredSession({ structuredSession: structured }).then(() => { + return activateAiVaultStructuredSession( + { structuredSession: structured }, + undefined, + target + ).then(() => { // Reported reopen success may lack a tab; replace this chat only when the reopened tab exists. const reopened = findChatTabWhere( here.workspaceId, diff --git a/src/renderer/src/components/right-sidebar/ai-vault-session-worktree.test.ts b/src/renderer/src/components/right-sidebar/ai-vault-session-worktree.test.ts index 7357631819b6..c94963a30868 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault-session-worktree.test.ts +++ b/src/renderer/src/components/right-sidebar/ai-vault-session-worktree.test.ts @@ -149,7 +149,11 @@ describe('resolveAiVaultSessionWorktreeInfo', () => { expect( resolveAiVaultSessionWorktreeInfo({ - session: { ...baseSession, cwd: '/home/ada/orca/src' }, + session: { + ...baseSession, + cwd: '/home/ada/orca/src', + filePath: String.raw`\\wsl.localhost\Ubuntu\home\ada\.codex\session.jsonl` + }, worktrees: [worktree], activeWorktreeId: null }) @@ -160,6 +164,26 @@ describe('resolveAiVaultSessionWorktreeInfo', () => { }) }) + it.each([ + { filePath: String.raw`\\wsl.localhost\Ubuntu\home\ada\.codex\session.jsonl`, owner: 'Ubuntu' }, + { filePath: String.raw`\\wsl.localhost\Debian\home\ada\.codex\session.jsonl`, owner: 'Debian' }, + { filePath: '/home/ada/.codex/session.jsonl', owner: undefined } + ])('requires transcript namespace proof for WSL Linux cwd: $owner', ({ filePath, owner }) => { + const worktrees = ['Debian', 'Ubuntu'].map((distro) => + makeWorktree({ + id: `folder:${distro}`, + path: `\\\\wsl.localhost\\${distro}\\home\\ada\\orca` + }) + ) + const found = resolveAiVaultSessionWorktreeInfo({ + session: { ...baseSession, cwd: '/home/ada/orca/src', filePath }, + worktrees, + activeWorktreeId: null + }) + expect(found?.worktreeId).toBe(owner ? `folder:${owner}` : undefined) + expect(found?.status).toBe(owner ? 'active' : 'unavailable') + }) + it('uses the session host when multiple worktrees share the same path', () => { const localWorktree = makeWorktree({ id: 'repo-local::/srv/orca', @@ -280,7 +304,11 @@ describe('folder workspaces as session owners', () => { const wslFolder = makeFolderWorkspace({ folderPath: '\\\\wsl.localhost\\Ubuntu\\home\\ada\\notes' }) - expect(resolveOwner('/home/ada/notes/src', [wslFolder])?.worktreeId).toBe('folder:folder-1') + expect( + resolveOwner('/home/ada/notes/src', [wslFolder], { + filePath: String.raw`\\wsl.localhost\Ubuntu\home\ada\.codex\session.jsonl` + })?.worktreeId + ).toBe('folder:folder-1') }) it('reports an archived folder as archived, which is not a jump target', () => { diff --git a/src/renderer/src/lib/worktree-activation-structured-chat-surface.test.ts b/src/renderer/src/lib/worktree-activation-structured-chat-surface.test.ts index d084dd2e23d9..5b61b3bc879d 100644 --- a/src/renderer/src/lib/worktree-activation-structured-chat-surface.test.ts +++ b/src/renderer/src/lib/worktree-activation-structured-chat-surface.test.ts @@ -19,7 +19,8 @@ const initialAppStoreState = useAppStore.getState() registerWorktreeActivationReset() -afterEach(() => { +afterEach(async () => { + await import('@/runtime/web-runtime-terminal-rename') vi.restoreAllMocks() useAppStore.setState(initialAppStoreState, true) }) diff --git a/src/shared/ai-vault-local-scan-key.ts b/src/shared/ai-vault-local-scan-key.ts index de7f2ffba678..837cd29ab9fb 100644 --- a/src/shared/ai-vault-local-scan-key.ts +++ b/src/shared/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 }) diff --git a/src/shared/ai-vault-runtime-capabilities.ts b/src/shared/ai-vault-runtime-capabilities.ts index 10e78b3034d6..85f1648e2edf 100644 --- a/src/shared/ai-vault-runtime-capabilities.ts +++ b/src/shared/ai-vault-runtime-capabilities.ts @@ -3,11 +3,17 @@ import { AI_VAULT_CHAT_FORK_SOURCE_CAPABILITY } from './ai-vault-resume-preparat // aiVault.listSessions is unconditional, so getStatus advertises this statically rather than as a runtime-dependent capability. 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_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 +/** 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_DELETE_SESSION_RUNTIME_CAPABILITY, AI_VAULT_CHAT_FORK_SOURCE_CAPABILITY diff --git a/src/shared/ai-vault-session-depth.ts b/src/shared/ai-vault-session-depth.ts index 88c405204d6c..12f0915b4034 100644 --- a/src/shared/ai-vault-session-depth.ts +++ b/src/shared/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.ts b/src/shared/ai-vault-session-display.ts index e640638bfd18..84f66b32b736 100644 --- a/src/shared/ai-vault-session-display.ts +++ b/src/shared/ai-vault-session-display.ts @@ -47,7 +47,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-worktree.ts b/src/shared/ai-vault-session-worktree.ts index d400ac2a9bd9..0ae8d04c5a6b 100644 --- a/src/shared/ai-vault-session-worktree.ts +++ b/src/shared/ai-vault-session-worktree.ts @@ -1,6 +1,6 @@ // Which live workspace owns a saved session's cwd, on the host that recorded it; shared by desktop and mobile. -import { parseWslUncPath } from './wsl-paths' +import { createNormalizedAiVaultScopeCwdMatcher } from './ai-vault-scope-cwd-match' import { splitWorktreeIdForFilesystem } from './worktree/id' import { getRepoExecutionHostId, @@ -9,7 +9,6 @@ import { type ExecutionHostId } from './execution-host' import { - createNormalizedPathInsideOrEqualMatcher, isRuntimePathAbsolute, normalizeRuntimePathForComparison, normalizeRuntimePathSeparators @@ -46,7 +45,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 } @@ -89,7 +88,7 @@ function resolveWorktreeInfoFromCandidates( const sessionHostId = normalizeExecutionHostId(session.executionHostId) const normalizedCwd = normalizeRuntimePathForComparison(session.cwd) const matched = candidates - .filter((candidate) => candidate.ownsNormalizedCwd(normalizedCwd)) + .filter((candidate) => candidate.ownsNormalizedCwd(normalizedCwd, session.filePath)) .filter((candidate) => !sessionHostId || candidate.hostId === sessionHostId) .sort(compareWorktreeCandidates) @@ -236,20 +235,13 @@ function makeWorktreeCandidate( hostId: ExecutionHostId, source: WorktreeCandidate['source'] ): WorktreeCandidate { - const ownsCwd = createNormalizedPathInsideOrEqualMatcher(path) - // A WSL UNC root also owns sessions recorded under its Linux-native cwd. - const wslPath = parseWslUncPath(path) - const ownsCwdViaWslAlias = wslPath - ? createNormalizedPathInsideOrEqualMatcher(wslPath.linuxPath) - : null return { worktree, path, hostId, status: worktree.isArchived ? 'archived' : 'active', source, - ownsNormalizedCwd: (normalizedCwd) => - ownsCwd(normalizedCwd) || (ownsCwdViaWslAlias?.(normalizedCwd) ?? false), + ownsNormalizedCwd: createNormalizedAiVaultScopeCwdMatcher([path]), normalizedPathLength: normalizeRuntimePathForComparison(path).length } } diff --git a/src/shared/ai-vault-types.ts b/src/shared/ai-vault-types.ts index 6ffcaf6d2ef1..197699fde3f5 100644 --- a/src/shared/ai-vault-types.ts +++ b/src/shared/ai-vault-types.ts @@ -106,6 +106,10 @@ export type AiVaultSessionSubagentInfo = { } 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' id: string executionHostId: ExecutionHostId executionHostPlatform?: NodeJS.Platform | null @@ -129,7 +133,7 @@ export type AiVaultSession = { previewMessagesTruncated?: boolean /** Bounded opening-prompt identity for Antigravity history joins; never a rolling preview. */ antigravityOpeningPrompt?: { hash: string; timestamp: string | null } - /** 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 @@ -216,6 +220,10 @@ export type AiVaultScanIssue = { } 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. */ @@ -230,6 +238,8 @@ export type AiVaultListArgs = { } 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/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..40ea3d050945 --- /dev/null +++ b/src/shared/conversation-navigation-preferences.ts @@ -0,0 +1,110 @@ +import { z } from 'zod' +import type { AiVaultSession } from './ai-vault-types' +import { sessionFileExecutionNamespace } from './ai-vault-scope-cwd-match' +import { antigravitySessionOrigin } from './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..3c6e4e8c851d --- /dev/null +++ b/src/shared/conversation-workspace-matcher.ts @@ -0,0 +1,41 @@ +import { createAiVaultScopeCwdMatcher } from './ai-vault-scope-cwd-match' +import { normalizeRuntimePathForComparison } from './cross-platform-path' +import type { ExecutionHostId } from './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/persisted-ui-state-types.ts b/src/shared/persisted-ui-state-types.ts index 5babbb20d3ae..77b754fe320b 100644 --- a/src/shared/persisted-ui-state-types.ts +++ b/src/shared/persisted-ui-state-types.ts @@ -1,3 +1,4 @@ +import type { ConversationPreferences } from './conversation-navigation-preferences' import type { JiraQuickFilterState } from './jira/jira-quick-filters' import type { BrowserDevToolsDockLayout } from './browser-devtools-dock' import type { JiraSavedFilterState } from './jira/jira-saved-filters' @@ -50,6 +51,7 @@ export type PersistedUIState = { groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status' sortBy: 'name' | 'smart' | 'recent' | 'repo' | 'manual' /** Project-header order in repo grouping, independent of workspace sort: manual permits drag, recent follows visible activity. */ + conversationPreferences?: ConversationPreferences projectOrderBy: ProjectOrderBy /** Deprecated; the Active only filter is retired and ignored on hydration. */ showActiveOnly: boolean diff --git a/src/shared/project-conversation-list.test.ts b/src/shared/project-conversation-list.test.ts new file mode 100644 index 000000000000..70c1bedff593 --- /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-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..953875cc1fde --- /dev/null +++ b/src/shared/project-conversation-list.ts @@ -0,0 +1,75 @@ +import { conversationNameSeed } from './conversation-name-generation' +import { + conversationPreferenceKey, + type ConversationPreferences +} from './conversation-navigation-preferences' +import { AI_VAULT_AGENT_LABELS, type AiVaultSession } from './ai-vault-types' +import { sessionPromptPreview } from './ai-vault-session-display' +import { isKnownHarnessInjectedUserTurnText } from './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/protocol-version.ts b/src/shared/protocol-version.ts index 5b989c2cc3ff..655588813a31 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -1,3 +1,7 @@ +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-runtime-capability' import { @@ -124,7 +128,9 @@ export const SAVED_RESUME_ORIGIN_RUNTIME_CAPABILITY = 'agent-session.saved-resume-origin.v1' as const export const RUNTIME_CAPABILITIES = [ + CONVERSATION_NAVIGATION_CAPABILITY, SAVED_RESUME_ORIGIN_RUNTIME_CAPABILITY, + CONVERSATION_PROJECT_VISIBILITY_CAPABILITY, ...HOST_RUNTIME_CAPABILITIES, ...DEVICE_KEY_RUNTIME_CAPABILITIES, ...MOBILE_RUNTIME_CAPABILITIES, diff --git a/src/shared/rpc-contract/ai-vault-params.ts b/src/shared/rpc-contract/ai-vault-params.ts index eeca524e47d9..214db3be3a4e 100644 --- a/src/shared/rpc-contract/ai-vault-params.ts +++ b/src/shared/rpc-contract/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 6f40a5363cc8..1eddd7ce7631 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -22,6 +22,7 @@ import { BundledSkillExecuteRequestSchema, BundledSkillPlanRequestSchema } from '../bundled-skill-plan' +import { SetConversationPreferenceParams } from '../conversation-navigation-preferences' import { DelegatedMobileDeviceSyncParamsSchema } from '../delegated-mobile-device-contract' import { DesktopBrowserBridgeAttachParams, @@ -1439,6 +1440,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 eb5831c0113f..4ceac46ac1a3 100644 --- a/src/shared/wsl-move/wsl-move-ui-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-ui-dispositions.ts @@ -8,6 +8,10 @@ import { /** UI fields that name a repo, worktree, pane or path. Everything else in the UI state is global. */ export const UI_STATE_DISPOSITIONS = { + conversationPreferences: notApplicableDisposition( + 38, + 'Conversation preferences retain their execution-host-qualified identities.' + ), lastActiveRepoId: notApplicableDisposition(38, 'repoId is kept.'), pendingRuntimeRepoRemovals: notApplicableDisposition( 38, From 4b1a3c959845de0a0504c958520cf6d65d939bc5 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Thu, 29 Oct 2026 17:13:20 +0700 Subject: [PATCH 02/17] Localize mobile conversation header actions --- mobile/src/host-screen/HostConversations.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mobile/src/host-screen/HostConversations.tsx b/mobile/src/host-screen/HostConversations.tsx index da77df4d43d2..532f43112f61 100644 --- a/mobile/src/host-screen/HostConversations.tsx +++ b/mobile/src/host-screen/HostConversations.tsx @@ -1,3 +1,4 @@ +import { useMobileTranslation } from '../i18n/use-mobile-translation' import { useMemo, useState } from 'react' import { ActivityIndicator, Pressable, RefreshControl, SectionList, Text, View } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' @@ -34,6 +35,7 @@ export function HostConversations({ controller: HostScreenController onWorkspaces: () => void }) { + const t = useMobileTranslation() const copy = conversationCopy() const { hostId, connState, actions, state } = controller const data = useProjectConversations(controller) @@ -129,7 +131,7 @@ export function HostConversations({ onPress={actions.leaveHost} style={styles.iconButton} accessibilityRole="button" - accessibilityLabel="Back to hosts" + accessibilityLabel={t('hostScreen.hostScreenHeader.backToHosts', 'Back to hosts')} >
@@ -147,7 +149,7 @@ export function HostConversations({ onPress={controller.onHideSidebar} style={styles.iconButton} accessibilityRole="button" - accessibilityLabel="Hide sidebar" + accessibilityLabel={t('hostScreen.hostScreenHeader.hideSidebar', 'Hide sidebar')} > From 626332141b1b0e31c58c986fb8ec7873eeeaa5e1 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Thu, 29 Oct 2026 18:22:17 +0700 Subject: [PATCH 03/17] fix: retain mobile history scope, issues and conditional snapshots --- .../agent-history-retry.test.tsx | 1 + .../use-mobile-agent-history-state.ts | 4 +- mobile/src/host-screen/HostConversations.tsx | 2 + .../src/host-screen/conversation-records.ts | 3 + ...oject-conversation-history-refresh.test.ts | 56 +++++++++++++++ .../project-conversation-history-refresh.ts | 53 ++++++++++++++ .../project-conversations-host-filter.test.ts | 45 ++++++++++++ .../src/host-screen/project-conversations.ts | 25 +++++-- .../use-project-conversations.test.tsx | 69 +++++++++++++++++++ .../host-screen/use-project-conversations.ts | 58 ++++++++-------- 10 files changed, 280 insertions(+), 36 deletions(-) create mode 100644 mobile/src/host-screen/project-conversation-history-refresh.test.ts create mode 100644 mobile/src/host-screen/project-conversation-history-refresh.ts create mode 100644 mobile/src/host-screen/project-conversations-host-filter.test.ts diff --git a/mobile/src/agent-history/agent-history-retry.test.tsx b/mobile/src/agent-history/agent-history-retry.test.tsx index ec7b5041d62d..34dee2f4114f 100644 --- a/mobile/src/agent-history/agent-history-retry.test.tsx +++ b/mobile/src/agent-history/agent-history-retry.test.tsx @@ -462,6 +462,7 @@ it.each([false, true])( ) expect(request?.[1]).toMatchObject({ limit: 500, scopePaths: [] }) if (capable) { + expect(request?.[1]).toHaveProperty('includeAntigravityIdeSessions', true) expect(request?.[1]).toHaveProperty('selectedSessionId', 'selected') } else { expect(request?.[1]).not.toHaveProperty('selectedSessionId') 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 cf3580442db2..568009033243 100644 --- a/mobile/src/agent-history/use-mobile-agent-history-state.ts +++ b/mobile/src/agent-history/use-mobile-agent-history-state.ts @@ -185,7 +185,9 @@ export function useMobileAgentHistoryState(params: MobileAgentHistoryStateParams const reply = await agentHistorySessionScan.request(client, { limit: MOBILE_AI_VAULT_SESSION_LIMIT, force: options.force, - ...(conversationId ? { includeStructuredSessions: true } : {}), + ...(conversationId + ? { includeStructuredSessions: true, includeAntigravityIdeSessions: true } + : {}), ...(conversationId && status.capabilities?.includes(AI_VAULT_SELECTED_SESSION_RUNTIME_CAPABILITY) ? { selectedSessionId: conversationId } diff --git a/mobile/src/host-screen/HostConversations.tsx b/mobile/src/host-screen/HostConversations.tsx index 532f43112f61..87a6c2762803 100644 --- a/mobile/src/host-screen/HostConversations.tsx +++ b/mobile/src/host-screen/HostConversations.tsx @@ -86,6 +86,7 @@ export function HostConversations({ () => buildProjectConversations({ workspaces: data.workspaces, + visibleHostIds: state.view.filters.visibleHostIds, repos: [...controller.sectionsResult.repoById.values()], tabs: data.tabs, history: data.history, @@ -98,6 +99,7 @@ export function HostConversations({ }), [ data.workspaces, + state.view.filters.visibleHostIds, controller.sectionsResult.repoById, data.tabs, data.history, diff --git a/mobile/src/host-screen/conversation-records.ts b/mobile/src/host-screen/conversation-records.ts index 703583c48bbf..9681e3dda15e 100644 --- a/mobile/src/host-screen/conversation-records.ts +++ b/mobile/src/host-screen/conversation-records.ts @@ -33,6 +33,9 @@ const historySchema = z.looseObject({ 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) { diff --git a/mobile/src/host-screen/project-conversation-history-refresh.test.ts b/mobile/src/host-screen/project-conversation-history-refresh.test.ts new file mode 100644 index 000000000000..9d2600a374d5 --- /dev/null +++ b/mobile/src/host-screen/project-conversation-history-refresh.test.ts @@ -0,0 +1,56 @@ +import { expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes' +import { conversationHistory } from './project-conversations.test-fixture' +import { refreshProjectConversationHistory } from './project-conversation-history-refresh' + +it.each(['missing prior snapshot', 'mismatched fingerprint'] as const)( + 'recovers a full snapshot instead of clearing the list for an unverifiable unchanged reply: %s', + async (reason) => { + 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..636159223f44 --- /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-runtime-capabilities' +import type { RpcClient } from '../transport/rpc-client' +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-conversations-host-filter.test.ts b/mobile/src/host-screen/project-conversations-host-filter.test.ts new file mode 100644 index 000000000000..65dee5cd1bb9 --- /dev/null +++ b/mobile/src/host-screen/project-conversations-host-filter.test.ts @@ -0,0 +1,45 @@ +import { expect, it } from 'vitest' +import type { ExecutionHostId } from '../../../src/shared/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) + } +) diff --git a/mobile/src/host-screen/project-conversations.ts b/mobile/src/host-screen/project-conversations.ts index c6ec8d3ba991..156705968c18 100644 --- a/mobile/src/host-screen/project-conversations.ts +++ b/mobile/src/host-screen/project-conversations.ts @@ -60,13 +60,26 @@ export function buildProjectConversations(args: { projectCatalog?: ProjectSectionCatalog preferences?: ConversationPreferences archived?: boolean + visibleHostIds?: readonly ExecutionHostId[] | null }): ConversationProject[] { const projects = new Map() const ownerKeys = new Map() - const savedForTab = createConversationHistoryIndex(args.history) const hostOf = (workspace: Worktree) => workspace.hostId ?? 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 repos = catalog?.repos ?? args.repos + 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) => { @@ -102,7 +115,7 @@ export function buildProjectConversations(args: { data: [] }) } - for (const workspace of args.workspaces) { + for (const workspace of workspaces) { const hostId = hostOf(workspace) const key = workspaceProjectKey(workspace) let project = projects.get(key) @@ -185,13 +198,13 @@ export function buildProjectConversations(args: { } } const matchWorkspace = createConversationWorkspaceMatcher( - args.workspaces.map((workspace) => ({ + workspaces.map((workspace) => ({ ...workspace, id: workspace.worktreeId, hostId: hostOf(workspace) })) ) - for (const session of args.history) { + for (const session of history) { if (!session.executionHostId || session.subagent || session.conversationContent === 'empty') { continue } @@ -204,7 +217,7 @@ export function buildProjectConversations(args: { : undefined const matched = matchWorkspace({ ...session, executionHostId: session.executionHostId }) let workspace = matched - ? (args.workspaces.find( + ? (workspaces.find( (item) => item.worktreeId === matched.worktreeId && hostOf(item) === session.executionHostId ) ?? null) diff --git a/mobile/src/host-screen/use-project-conversations.test.tsx b/mobile/src/host-screen/use-project-conversations.test.tsx index 5d37b1ea7f8f..26251ea68541 100644 --- a/mobile/src/host-screen/use-project-conversations.test.tsx +++ b/mobile/src/host-screen/use-project-conversations.test.tsx @@ -309,3 +309,72 @@ describe('host-owned conversation snapshots', () => { 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([]) +}) diff --git a/mobile/src/host-screen/use-project-conversations.ts b/mobile/src/host-screen/use-project-conversations.ts index c05ad5b1eabd..aa42abb9c691 100644 --- a/mobile/src/host-screen/use-project-conversations.ts +++ b/mobile/src/host-screen/use-project-conversations.ts @@ -1,4 +1,7 @@ -import { AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY } from '../../../src/shared/ai-vault-runtime-capabilities' +import { + refreshProjectConversationHistory, + type ProjectConversationHistorySnapshot +} from './project-conversation-history-refresh' import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import type { RpcClient } from '../transport/rpc-client' import type { ExecutionHostId } from '../../../src/shared/execution-host' @@ -8,14 +11,9 @@ import { } from '../transport/execution-host-scoped-rpc-client' import { getWorktreeRowIdentity } from '../worktree/worktree-host-row-identity' import { resolveWorktreeHostId } from '../worktree/worktree-host-context-labels' -import { - agentHistoryHostStatusRead, - agentHistorySessionScan -} from '../agent-history/mobile-agent-history-operations' import { sessionTabsListRead } from '../session/mobile-session-read-operations' import type { HostScreenController } from './use-host-screen-controller' import { - readConversationHistory, readConversationTabs, type ConversationHistory, type ConversationTab @@ -24,6 +22,7 @@ import { type ConversationSnapshot = { tabs: Map history: ConversationHistory[] + historyByHost: Map capabilities: Map complete: boolean failed: boolean @@ -31,6 +30,7 @@ type ConversationSnapshot = { const EMPTY: ConversationSnapshot = { tabs: new Map(), history: [], + historyByHost: new Map(), capabilities: new Map(), complete: false, failed: false @@ -126,11 +126,18 @@ export function useProjectConversations(controller: ProjectConversationsSource) 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 @@ -139,27 +146,21 @@ export function useProjectConversations(controller: ProjectConversationsSource) const historyRequests = Promise.all( [...sources].map(async ([sourceHost, sourceClient]) => { try { - const status = agentHistoryHostStatusRead.interpret( - await agentHistoryHostStatusRead.request(sourceClient) + const { capabilities, history } = await refreshProjectConversationHistory( + sourceClient, + force, + sameAuthority ? previous.value.historyByHost.get(sourceHost) : undefined ) - next.capabilities.set(sourceHost, status.capabilities ?? []) - if (!status.capabilities?.includes('aiVault.v1')) { + next.capabilities.set(sourceHost, capabilities) + if (!history) { next.complete = false return } - const reply = await agentHistorySessionScan.request(sourceClient, { - ...(status.capabilities.includes(AI_VAULT_CANONICAL_PROJECT_SEARCH_CAPABILITY) - ? { historyOwnership: {} } - : {}), - unlimited: true, - includeAntigravityIdeSessions: true, - includeStructuredSessions: true, - force - }) - const history = readConversationHistory(agentHistorySessionScan.interpret(reply)) - if (!history.includesStructuredSessions) { + next.historyByHost.set(sourceHost, history) + if (!history.includesStructuredSessions || history.issues.length > 0) { next.complete = false } + next.failed ||= history.issues.length > 0 next.history.push( ...history.sessions.map((session) => ({ ...session, @@ -204,18 +205,17 @@ export function useProjectConversations(controller: ProjectConversationsSource) } await historyRequests if (current()) { - const previous = snapshots.get(client) 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 ( - previous?.client === client && - previous.hostId === hostId && - previous.generation === generation && - previous.authority === authority - ) { + 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) @@ -240,7 +240,7 @@ export function useProjectConversations(controller: ProjectConversationsSource) ) ] } - return { ...next, tabs, capabilities, history } + return { ...next, tabs, capabilities, history, historyByHost } })() const loaded = { client, From 455b5b670abe6760a4ce5d493013a9bd134d4deb Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sat, 31 Oct 2026 14:31:21 +0700 Subject: [PATCH 04/17] Share catalog slots and project-order labels with adjacent features --- .../src/host-screen/conversation-project-order-sheet.tsx | 8 +++++--- mobile/src/host-screen/use-host-screen-controller.ts | 7 +++++-- src/shared/persisted-ui-state-types.ts | 2 +- src/shared/wsl-move/wsl-move-ui-dispositions.ts | 8 ++++---- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/mobile/src/host-screen/conversation-project-order-sheet.tsx b/mobile/src/host-screen/conversation-project-order-sheet.tsx index 33d4baf4d3eb..3eacfe967b3b 100644 --- a/mobile/src/host-screen/conversation-project-order-sheet.tsx +++ b/mobile/src/host-screen/conversation-project-order-sheet.tsx @@ -1,5 +1,6 @@ import { ActionSheetModal } from '../components/ActionSheetModal' -import { WORKSPACE_PROJECT_ORDER_CHOICES } from '../../../src/shared/workspace-view/workspace-view-options' +import { projectOrderChoices } from './workspace-option-controls-copy' +import { useMobileTranslation } from '../i18n/use-mobile-translation' import type { HostScreenController } from './use-host-screen-controller' import { conversationCopy } from './conversation-copy' @@ -12,6 +13,7 @@ export function ConversationProjectOrderSheet({ onClose: () => void controller: HostScreenController }) { + const t = useMobileTranslation() const copy = conversationCopy() const connected = controller.connState === 'connected' return ( @@ -19,8 +21,8 @@ export function ConversationProjectOrderSheet({ visible={visible} title={copy.projectOrder} onClose={() => onClose()} - actions={WORKSPACE_PROJECT_ORDER_CHOICES.map((choice) => ({ - label: `${controller.projectOrderBy === choice.id ? '✓ ' : ''}${copy.projectOrderLabels[choice.id]}`, + actions={projectOrderChoices(t).map((choice) => ({ + label: `${controller.projectOrderBy === choice.id ? '✓ ' : ''}${choice.label}`, onPress: () => { void controller.settings.setProjectOrderBy(choice.id) }, diff --git a/mobile/src/host-screen/use-host-screen-controller.ts b/mobile/src/host-screen/use-host-screen-controller.ts index 707c05c013d1..13f403c57c61 100644 --- a/mobile/src/host-screen/use-host-screen-controller.ts +++ b/mobile/src/host-screen/use-host-screen-controller.ts @@ -81,6 +81,10 @@ export function useHostScreenController({ useHostScreenIdentity({ client, hostId, state }) const fetchRepoMetadataOnly = useHostRepoMetadata({ client, connState, hostId, state }) const sidebarFeed = useSwitchedHostSidebarFeed(client, hostId) + const projectCatalog = + sidebarFeed?.feed.kind === 'ready' + ? (sidebarFeed.feed.domains.projectCatalog ?? state.servedProjectSections) + : state.servedProjectSections // Read through a ref so the metadata refresh keeps its identity across installs. const feedRef = useRef(sidebarFeed?.feed) useEffect(() => { @@ -160,8 +164,7 @@ export function useHostScreenController({ collapsedGroups, feed, projectOrderBy, - projectCatalog: - (feed?.kind === 'ready' ? feed.domains.projectCatalog : null) ?? state.servedProjectSections, + projectCatalog, client, connectionVerdict, connState, diff --git a/src/shared/persisted-ui-state-types.ts b/src/shared/persisted-ui-state-types.ts index 6d7b0075f235..149d8474cf6b 100644 --- a/src/shared/persisted-ui-state-types.ts +++ b/src/shared/persisted-ui-state-types.ts @@ -50,8 +50,8 @@ export type PersistedUIState = { combinedDiffFileTreeWidth?: number groupBy: 'none' | 'workspace-status' | 'repo' | 'pr-status' sortBy: 'name' | 'smart' | 'recent' | 'repo' | 'manual' - /** Project-header order in repo grouping, independent of workspace sort: manual permits drag, recent follows visible activity. */ 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. */ showActiveOnly: boolean diff --git a/src/shared/wsl-move/wsl-move-ui-dispositions.ts b/src/shared/wsl-move/wsl-move-ui-dispositions.ts index 2f12a406fe06..f9a396a342be 100644 --- a/src/shared/wsl-move/wsl-move-ui-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-ui-dispositions.ts @@ -8,16 +8,16 @@ import { /** UI fields that name a repo, worktree, pane or path. Everything else in the UI state is global. */ export const UI_STATE_DISPOSITIONS = { - conversationPreferences: notApplicableDisposition( - 38, - 'Conversation preferences retain their execution-host-qualified identities.' - ), lastActiveRepoId: notApplicableDisposition(38, 'repoId is kept.'), pendingRuntimeRepoRemovals: notApplicableDisposition( 38, '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." From bad8b7710b3fa9f987e8436201aac763863c1504 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sat, 31 Oct 2026 18:46:25 +0700 Subject: [PATCH 05/17] Preserve checked and busy action sheet accessibility together --- mobile/src/components/ActionSheetModal.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mobile/src/components/ActionSheetModal.tsx b/mobile/src/components/ActionSheetModal.tsx index 01b35c00a809..cb8bf9da370e 100644 --- a/mobile/src/components/ActionSheetModal.tsx +++ b/mobile/src/components/ActionSheetModal.tsx @@ -77,7 +77,8 @@ export function ActionSheetContent({ title, message, children, actions, onClose accessibilityRole="button" accessibilityState={{ disabled: Boolean(action.disabled || action.loading), - busy: action.loading + busy: action.loading, + checked: action.checked || undefined }} style={({ pressed }) => [ styles.action, @@ -85,7 +86,6 @@ export function ActionSheetContent({ title, message, children, actions, onClose pressed && !action.disabled && !action.loading && styles.actionPressed ]} disabled={action.disabled || action.loading} - accessibilityState={action.checked ? { checked: true } : undefined} onPress={() => { action.onPress() if (!action.skipAutoClose && onClose) { From 3843f6a9ab670b48d0a94aefb5de87f899998005 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sat, 31 Oct 2026 19:26:29 +0700 Subject: [PATCH 06/17] Navigate through Projects before mobile workspace browser checks --- .../mobile-web-app-drawer-render.test.mjs | 13 +++++++++++++ .../mobile-web-app-handoff-grants-render.test.mjs | 1 + 2 files changed, 14 insertions(+) diff --git a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs index 69ed1b6d5f6c..8698dbb34490 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs @@ -160,6 +160,8 @@ describeDrawer('the bottom drawer on the page', () => { { timeout: 30_000, polling: 250 } ) // Use header’s Workspace options sheet; same drawer implementation without row-layout prerequisites. + await page.getByRole('button', { name: 'More options', exact: true }).click() + await page.getByText('Advanced: workspaces', { exact: true }).click() const button = workspaceOptionsButton(page) // Wait for actionability before resetting counters; CI WebKit dropped clicks sent as soon as the label existed. await button.click({ trial: true, timeout: 30_000 }) @@ -260,6 +262,17 @@ describeDrawer('the device Back key reaching a sheet on the page', () => { // Closed sheet claims nothing; shell retains its existing pop fallback. expect(await page.evaluate(notifyNames)).not.toContain(backNames.claim) + await page.getByRole('button', { name: 'More options', exact: true }).click() + await page.getByText('Advanced: workspaces', { exact: true }).click() + await page.waitForFunction( + (name) => + globalThis.__orcaRenderCheckNotifies.filter((frame) => frame.name === name).at(-1) + ?.claimed === false, + backNames.claim + ) + await page.evaluate(() => { + globalThis.__orcaRenderCheckNotifies = [] + }) await workspaceOptionsButton(page).click({ timeout: 30_000 }) await page.waitForFunction( () => document.querySelector('[aria-label="Dismiss drawer"]') !== null, diff --git a/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs index b24ace3b7d5e..74aa9cb80f12 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-handoff-grants-render.test.mjs @@ -136,6 +136,7 @@ async function openHostRoute({ const menu = page.getByRole('button', { name: 'More options', exact: true }) if (route === HOST_ROUTE) { await menu.click() + await page.getByText('Advanced: workspaces', { exact: true }).click() } return { page, errors, jsResponses } } From 2402dde4ba229ee92d384ff90fafca82bc0826e2 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sat, 31 Oct 2026 19:48:01 +0700 Subject: [PATCH 07/17] test(mobile): use latest matching drawer notification directly --- .../mobile-web-app/mobile-web-app-drawer-render.test.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs index 8698dbb34490..c82c52335c82 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-drawer-render.test.mjs @@ -266,8 +266,8 @@ describeDrawer('the device Back key reaching a sheet on the page', () => { await page.getByText('Advanced: workspaces', { exact: true }).click() await page.waitForFunction( (name) => - globalThis.__orcaRenderCheckNotifies.filter((frame) => frame.name === name).at(-1) - ?.claimed === false, + globalThis.__orcaRenderCheckNotifies.findLast((frame) => frame.name === name)?.claimed === + false, backNames.claim ) await page.evaluate(() => { From eb708b6fe498282879194fae7e38dd8ccc2ce866 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sun, 1 Nov 2026 09:28:12 +0700 Subject: [PATCH 08/17] fix(mobile): distinguish history notices from loading failures --- ...-app-project-conversations-render.test.mjs | 56 ++++++++++++++++++- .../ConversationHistoryLoadStatus.tsx | 36 ++++++++++++ mobile/src/host-screen/HostConversations.tsx | 17 +++--- mobile/src/host-screen/conversation-copy.ts | 8 +-- .../src/host-screen/conversation-records.ts | 6 ++ .../use-project-conversations.test.tsx | 43 ++++++++++++++ .../host-screen/use-project-conversations.ts | 8 ++- 7 files changed, 153 insertions(+), 21 deletions(-) create mode 100644 mobile/src/host-screen/ConversationHistoryLoadStatus.tsx 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 index 03e508738de2..1adebfdd9256 100644 --- 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 @@ -169,8 +169,8 @@ afterAll(async () => { } }) -async function open(replies = REPLIES) { - const page = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'ru-RU' }) +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, { @@ -333,7 +333,7 @@ describeRender('the actual mobile project conversation list', () => { includesStructuredSessions: undefined } }) - await page.getByText('Этот хост показывает открытые чаты', { exact: false }).waitFor() + 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() @@ -347,3 +347,53 @@ describeRender('the actual mobile project conversation list', () => { 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/src/host-screen/ConversationHistoryLoadStatus.tsx b/mobile/src/host-screen/ConversationHistoryLoadStatus.tsx new file mode 100644 index 000000000000..96ca2b58c82b --- /dev/null +++ b/mobile/src/host-screen/ConversationHistoryLoadStatus.tsx @@ -0,0 +1,36 @@ +import { ActivityIndicator } from 'react-native' +import { HostRouteNoticeBanner } from '../components/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/HostConversations.tsx b/mobile/src/host-screen/HostConversations.tsx index 87a6c2762803..4a25c8700fb3 100644 --- a/mobile/src/host-screen/HostConversations.tsx +++ b/mobile/src/host-screen/HostConversations.tsx @@ -10,6 +10,7 @@ import { StatusDot } from '../components/StatusDot' import { MobileSearchField } from '../components/MobileSearchField' import { ConversationAgentSheet } from './conversation-agent-sheet' import { ConversationSidebarOptions } from './conversation-sidebar-options' +import { ConversationHistoryLoadStatus } from './ConversationHistoryLoadStatus' import { AuthFailedBanner } from '../components/AuthFailedBanner' import { formatAgentTypeLabel } from '../../../src/shared/agent-type-label' import type { HostScreenController } from './use-host-screen-controller' @@ -198,16 +199,12 @@ export function HostConversations({ {error || state.actionError || conversationPreferences.error}
) : null} - {data.failed || state.catalogError ? {copy.failed} : null} - {data.loading ? ( - - ) : !data.complete && connected ? ( - {copy.legacy} - ) : null} + row.key} diff --git a/mobile/src/host-screen/conversation-copy.ts b/mobile/src/host-screen/conversation-copy.ts index 2867a96d2050..130394e221f4 100644 --- a/mobile/src/host-screen/conversation-copy.ts +++ b/mobile/src/host-screen/conversation-copy.ts @@ -36,10 +36,8 @@ const english = { transcript: 'Saved transcript', offline: 'Waiting for host', loading: 'Loading conversations…', - failed: 'Some conversations could not be loaded. Pull to refresh.', + failed: 'Could not refresh the full chat list.', failedState: 'Failed', - legacy: - 'This host lists open chats and saved transcripts. Update Orca to also list closed chats.', 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.', @@ -101,10 +99,8 @@ const russian: typeof english = { transcript: 'Сохранённая переписка', offline: 'Ожидание подключения', loading: 'Загружаем разговоры…', - failed: 'Часть разговоров не загрузилась. Потяните список для обновления.', + failed: 'Не удалось обновить весь список чатов.', failedState: 'Ошибка', - legacy: - 'Этот хост показывает открытые чаты и сохранённую переписку. Обновите Orca, чтобы видеть также закрытые чаты.', ssh: 'Открытые чаты на этом SSH-хосте. История переписки недоступна через это подключение.', noAgents: 'На этом хосте не найдено поддерживаемых агентов.', update: 'Обновите Orca на этом хосте, чтобы начать или открыть разговор.', diff --git a/mobile/src/host-screen/conversation-records.ts b/mobile/src/host-screen/conversation-records.ts index 9681e3dda15e..25a4a57568b8 100644 --- a/mobile/src/host-screen/conversation-records.ts +++ b/mobile/src/host-screen/conversation-records.ts @@ -70,3 +70,9 @@ export function readConversationTabs(value: unknown): ConversationTab[] { 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/use-project-conversations.test.tsx b/mobile/src/host-screen/use-project-conversations.test.tsx index 26251ea68541..8693d08edfa0 100644 --- a/mobile/src/host-screen/use-project-conversations.test.tsx +++ b/mobile/src/host-screen/use-project-conversations.test.tsx @@ -378,3 +378,46 @@ it('reuses per-host history fingerprints on automatic refresh while manual refre 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 index aa42abb9c691..2509e6297440 100644 --- a/mobile/src/host-screen/use-project-conversations.ts +++ b/mobile/src/host-screen/use-project-conversations.ts @@ -11,6 +11,7 @@ import { } from '../transport/execution-host-scoped-rpc-client' import { getWorktreeRowIdentity } from '../worktree/worktree-host-row-identity' import { resolveWorktreeHostId } from '../worktree/worktree-host-context-labels' +import { isConversationHistoryNotice } from './conversation-records' import { sessionTabsListRead } from '../session/mobile-session-read-operations' import type { HostScreenController } from './use-host-screen-controller' import { @@ -157,10 +158,13 @@ export function useProjectConversations(controller: ProjectConversationsSource) return } next.historyByHost.set(sourceHost, history) - if (!history.includesStructuredSessions || history.issues.length > 0) { + const historyFailed = history.issues.some( + (issue) => !isConversationHistoryNotice(issue) + ) + if (!history.includesStructuredSessions || historyFailed) { next.complete = false } - next.failed ||= history.issues.length > 0 + next.failed ||= historyFailed next.history.push( ...history.sessions.map((session) => ({ ...session, From 1ccd7092caca4eee1cd96eae8a631a2f16bb56df Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Tue, 3 Nov 2026 17:05:03 +0700 Subject: [PATCH 09/17] Consolidate scanner candidate imports after relocation --- src/main/ai-vault/session-scanner.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/ai-vault/session-scanner.ts b/src/main/ai-vault/session-scanner.ts index 099379313d96..d1695545b1ab 100644 --- a/src/main/ai-vault/session-scanner.ts +++ b/src/main/ai-vault/session-scanner.ts @@ -1,4 +1,3 @@ -import { discoveryFileCandidates } from './session-scanner-candidates' import type { AiVaultListResult, AiVaultScanIssue, @@ -12,7 +11,10 @@ import { createAntigravityWorkspaceResolver, readLocalAntigravityHistory } from './scanners/antigravity/session-scanner-antigravity-history' -import { sessionCandidatesFromDiscoveries } from './session-scanner-candidates' +import { + discoveryFileCandidates, + sessionCandidatesFromDiscoveries +} from './session-scanner-candidates' import { parseSessionCandidates } from './session-scanner-candidate-parse' import { createSessionParseStats } from './parse-cache/session-scanner-parse-cache' import { recordSessionScanIssue } from './session-scan-issues' From 08fc33bc64f810d6674d330f1ef18969335e394a Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Fri, 6 Nov 2026 16:43:06 +0700 Subject: [PATCH 10/17] Avoid empty duplicate folder projects in conversation lists --- .../src/host-screen/conversation-project.ts | 17 +++++++++++++++++ .../host-screen/project-conversations.test.ts | 19 +++++++++++++++++++ .../src/host-screen/project-conversations.ts | 5 +++++ 3 files changed, 41 insertions(+) diff --git a/mobile/src/host-screen/conversation-project.ts b/mobile/src/host-screen/conversation-project.ts index 13c2e2d43e30..3497cd47f158 100644 --- a/mobile/src/host-screen/conversation-project.ts +++ b/mobile/src/host-screen/conversation-project.ts @@ -40,3 +40,20 @@ export function projectConversationTarget(project: ConversationProject): Worktre ) ?? (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/project-conversations.test.ts b/mobile/src/host-screen/project-conversations.test.ts index 4cd2a00bde88..5d6a8c252dfd 100644 --- a/mobile/src/host-screen/project-conversations.test.ts +++ b/mobile/src/host-screen/project-conversations.test.ts @@ -24,6 +24,25 @@ const defaults = { } 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' }, { diff --git a/mobile/src/host-screen/project-conversations.ts b/mobile/src/host-screen/project-conversations.ts index 8a674c908d90..6f57617e50e5 100644 --- a/mobile/src/host-screen/project-conversations.ts +++ b/mobile/src/host-screen/project-conversations.ts @@ -29,6 +29,7 @@ export { readConversationHistory, readConversationTabs } from './conversation-re 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' @@ -81,8 +82,12 @@ export function buildProjectConversations(args: { 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) From 716fba29f4778f90ac1921f15a583971b3da3c91 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Mon, 9 Nov 2026 02:02:52 +0700 Subject: [PATCH 11/17] Keep host fixture guard explicit --- .../src/lib/activate-ai-vault-structured-session-host.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts b/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts index 20e07eb49def..4d70e0e13d4a 100644 --- a/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts +++ b/src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts @@ -96,7 +96,9 @@ it.each([false, true].map((olderLookup) => ({ olderLookup, rowHost: true })))( async ({ olderLookup, rowHost }) => { if (olderLookup) { const call = mocks.call.getMockImplementation() - if (!call) throw new Error('Missing fixture RPC implementation') + if (!call) { + throw new Error('Missing fixture RPC implementation') + } mocks.call.mockImplementation(async (...args) => { if (args[1] === 'orchestration.partyLocation') { throw Object.assign(new Error('old host'), { code: 'method_not_found' }) From f987ba54dd17bf59d65152d468764beef44fe8b6 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Mon, 9 Nov 2026 02:11:02 +0700 Subject: [PATCH 12/17] Use document query harness for conversation actions --- .../host-screen/use-conversation-actions.test.tsx | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/mobile/src/host-screen/use-conversation-actions.test.tsx b/mobile/src/host-screen/use-conversation-actions.test.tsx index 60f30c74146c..d748ac1d8212 100644 --- a/mobile/src/host-screen/use-conversation-actions.test.tsx +++ b/mobile/src/host-screen/use-conversation-actions.test.tsx @@ -1,6 +1,6 @@ import { createElement } from 'react' -import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' +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, @@ -98,15 +98,7 @@ async function mount(client: ProjectConversationsSource['client']) { return null } await act(async () => { - trees.push( - create( - createElement( - QueryClientProvider, - { client: new QueryClient({ defaultOptions: { queries: { retry: false } } }) }, - createElement(Probe) - ) - ) - ) + trees.push(createWithQueryClient(createElement(Probe))) }) const [project] = buildProjectConversations({ workspaces: [workspace], From 7f5cb25a24f34ff59e9abf987f0cdd684963f39f Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Mon, 9 Nov 2026 09:28:45 +0700 Subject: [PATCH 13/17] fix: show permission attention in mobile conversations --- mobile/src/host-screen/ConversationListRow.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mobile/src/host-screen/ConversationListRow.tsx b/mobile/src/host-screen/ConversationListRow.tsx index daba5c4f4c27..7f4ec173156d 100644 --- a/mobile/src/host-screen/ConversationListRow.tsx +++ b/mobile/src/host-screen/ConversationListRow.tsx @@ -7,6 +7,7 @@ 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-row-display' import { conversationStyles as styles } from './conversation-styles' export function ConversationListRow({ @@ -75,7 +76,9 @@ export function ConversationListRow({ ? copy.failedState : item.status === 'unverifiable' ? copy.unconfirmed - : copy[item.status], + : item.status === 'permission' + ? agentStateLabel(item.status) + : copy[item.status], item.at ? conversationTimeAgo(item.at, now) : null ] .filter(Boolean) From fa39cd7d09dda1e3fbbad7067d1bc31291fbabeb Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Mon, 9 Nov 2026 11:13:01 +0700 Subject: [PATCH 14/17] fix: avoid bundling Zod locale tables with mobile conversations --- mobile/src/host-screen/conversation-open.ts | 2 +- mobile/src/host-screen/conversation-records.ts | 2 +- mobile/src/host-screen/host-screen-operations.ts | 2 +- src/shared/conversation-navigation-preferences.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/mobile/src/host-screen/conversation-open.ts b/mobile/src/host-screen/conversation-open.ts index 48e6905dae86..4d8288ed47bd 100644 --- a/mobile/src/host-screen/conversation-open.ts +++ b/mobile/src/host-screen/conversation-open.ts @@ -1,4 +1,4 @@ -import { z } from 'zod' +import * as z from 'zod' import { STRUCTURED_AGENT_SESSION_REVEAL_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session/structured-agent-session-surface-capabilities' import { structuredAgentSessionPaneKey, diff --git a/mobile/src/host-screen/conversation-records.ts b/mobile/src/host-screen/conversation-records.ts index 7e2b27baa285..c3a089e7c39c 100644 --- a/mobile/src/host-screen/conversation-records.ts +++ b/mobile/src/host-screen/conversation-records.ts @@ -1,4 +1,4 @@ -import { z } from 'zod' +import * as z from 'zod' import { normalizeExecutionHostId } from '../../../src/shared/execution-host' const historySchema = z.looseObject({ diff --git a/mobile/src/host-screen/host-screen-operations.ts b/mobile/src/host-screen/host-screen-operations.ts index 6c52274dc339..4eca3fbaa29a 100644 --- a/mobile/src/host-screen/host-screen-operations.ts +++ b/mobile/src/host-screen/host-screen-operations.ts @@ -1,4 +1,4 @@ -import { z } from 'zod' +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' diff --git a/src/shared/conversation-navigation-preferences.ts b/src/shared/conversation-navigation-preferences.ts index 529c58b06420..392a0cc0e531 100644 --- a/src/shared/conversation-navigation-preferences.ts +++ b/src/shared/conversation-navigation-preferences.ts @@ -1,4 +1,4 @@ -import { z } from 'zod' +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 './antigravity-session-origin' From f8f2b4565deb86a9a3220559e1144cff40191baf Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Thu, 12 Nov 2026 21:37:59 +0700 Subject: [PATCH 15/17] Reuse upstream SQLite worker creation and transcript absence detection --- ...on-scanner-opencode-sqlite-worker-entry.ts | 20 -------------- ...on-scanner-opencode-sqlite-worker-spawn.ts | 26 +++++++++++++++---- src/main/ipc/ai-vault/ai-vault-local-scan.ts | 5 +++- src/main/ipc/ai-vault/ai-vault.ts | 4 +-- 4 files changed, 26 insertions(+), 29 deletions(-) delete mode 100644 src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-entry.ts diff --git a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-entry.ts b/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-entry.ts deleted file mode 100644 index 05cd9573afe4..000000000000 --- a/src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-entry.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { existsSync } from 'node:fs' -import type { Worker } from 'node:worker_threads' -import { spawnWorkerThread } from '../../../../worker-threads/worker-thread-spawn' -import { findForeignSqliteReaderEntry } from '../../../../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' - -export function resolveOpenCodeSqliteWorkerEntryPath( - runtimeDir = __dirname, - pathExists: (path: string) => boolean = existsSync -): string { - return findForeignSqliteReaderEntry(runtimeDir, pathExists) -} - -export function createOpenCodeSqliteWorker(): Worker { - const workerPath = resolveOpenCodeSqliteWorkerEntryPath() - // Fail synchronously for missing bundles rather than waiting for an impossible worker response. - if (!existsSync(workerPath)) { - throw new Error(`OpenCode SQLite worker entry not found: ${workerPath}`) - } - return spawnWorkerThread(workerPath) -} 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 ebe2326cd6c9..a09024861e1b 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,6 +1,8 @@ import type * as AiVault from '../../../../../shared/ai-vault/contracts/ai-vault-types' -import { createOpenCodeSqliteWorker } from './session-scanner-opencode-sqlite-worker-entry' -export { resolveOpenCodeSqliteWorkerEntryPath } from './session-scanner-opencode-sqlite-worker-entry' +import { existsSync } from 'node:fs' +import type { Worker } from 'node:worker_threads' +import { spawnWorkerThread } from '../../../../worker-threads/worker-thread-spawn' +import { findForeignSqliteReaderEntry } from '../../../../foreign-sqlite-readers/foreign-sqlite-reader-entry-path' import { selectedWslSqliteSessionId } from '../../../session-scanner-selection' import { aiVaultScopePathsForWslDistro } from '../../../../../shared/ai-vault/scanning/ai-vault-scope-cwd-match' import { @@ -27,12 +29,26 @@ import { openAiVaultScanSource } from '../../../scan-lifecycle/ai-vault-scan-progress' +export function resolveOpenCodeSqliteWorkerEntryPath( + runtimeDir = __dirname, + pathExists: (path: string) => boolean = existsSync +): string { + return findForeignSqliteReaderEntry(runtimeDir, pathExists) +} + +function defaultWorkerFactory(): Worker { + const workerPath = resolveOpenCodeSqliteWorkerEntryPath() + // Fail synchronously for missing bundles rather than waiting for an impossible worker response. + if (!existsSync(workerPath)) { + throw new Error(`OpenCode SQLite worker entry not found: ${workerPath}`) + } + return spawnWorkerThread(workerPath) +} + let sharedClient: OpenCodeSqliteWorkerClient | null = null function getSharedClient(): OpenCodeSqliteWorkerClient { - sharedClient ??= new OpenCodeSqliteWorkerClient({ - workerFactory: createOpenCodeSqliteWorker - }) + sharedClient ??= new OpenCodeSqliteWorkerClient({ workerFactory: defaultWorkerFactory }) return sharedClient } diff --git a/src/main/ipc/ai-vault/ai-vault-local-scan.ts b/src/main/ipc/ai-vault/ai-vault-local-scan.ts index dae8d79cfec8..c284c74ae2a9 100644 --- a/src/main/ipc/ai-vault/ai-vault-local-scan.ts +++ b/src/main/ipc/ai-vault/ai-vault-local-scan.ts @@ -1,4 +1,7 @@ -import { AiVaultLocalScanError, listAiVaultSessions } from '../../ai-vault/listing/cached-session-list' +import { + AiVaultLocalScanError, + listAiVaultSessions +} from '../../ai-vault/listing/cached-session-list' import { aiVaultScanIssueResult } from '../../ai-vault/listing/session-list-results' import { classifyAiVaultScanError } from '../../../shared/ai-vault/scanning/ai-vault-scan-error-message' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' diff --git a/src/main/ipc/ai-vault/ai-vault.ts b/src/main/ipc/ai-vault/ai-vault.ts index da4aad0a9d31..bf3e9b85172e 100644 --- a/src/main/ipc/ai-vault/ai-vault.ts +++ b/src/main/ipc/ai-vault/ai-vault.ts @@ -4,9 +4,7 @@ import { } from './ai-vault-projection-dependency' import { app, ipcMain } from 'electron' import { configureAiVaultSessionSources } from '../../ai-vault/discovery/ai-vault-scan-roots' -import { - resetAiVaultSessionListCacheForTests, -} from '../../ai-vault/listing/cached-session-list' +import { resetAiVaultSessionListCacheForTests } from '../../ai-vault/listing/cached-session-list' import type { AiVaultSessionSources } from '../../ai-vault/discovery/ai-vault-scan-roots' import { deleteAiVaultSession, registerAiVaultDeleteHandler } from './ai-vault-delete' import { listAiVaultSubagentSessions } from './ai-vault-subagent-list' From 8f9a4f6c27aa9ae2b26d77b11e253b4a7cda80e3 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Thu, 19 Nov 2026 04:09:03 +0700 Subject: [PATCH 16/17] test(mobile): open the workspace list before checking the host's bots The host screen now opens on project conversations, so the bots render check waited for workspace rows that only the advanced workspace view draws. Each case opens that view through More options first, and the page pins an English locale because the conversation copy follows the browser locale. Co-Authored-By: Claude Opus 5.5 --- .../mobile-web-app/mobile-web-app-bots-render.test.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/config/scripts/mobile-web-app/mobile-web-app-bots-render.test.mjs b/config/scripts/mobile-web-app/mobile-web-app-bots-render.test.mjs index c0092df3df94..2d49c367cf94 100644 --- a/config/scripts/mobile-web-app/mobile-web-app-bots-render.test.mjs +++ b/config/scripts/mobile-web-app/mobile-web-app-bots-render.test.mjs @@ -191,7 +191,8 @@ afterAll(async () => { async function openHostList(capabilities, botsEnabled, extraWorkers, scene) { const page = await browser.newPage({ viewport: scene?.viewport ?? { width: 390, height: 844 }, - colorScheme: scene?.theme ?? 'light' + colorScheme: scene?.theme ?? 'light', + locale: 'en-US' }) await page.addInitScript(installShellDouble, { version: bridgeVersion, @@ -225,6 +226,9 @@ async function openHostList(capabilities, botsEnabled, extraWorkers, scene) { timeout: 30_000, polling: 250 }) + // The host opens on its conversations; the workspace list that draws the bots is an advanced view. + await page.getByRole('button', { name: 'More options', exact: true }).click() + await page.getByText('Advanced: workspaces', { exact: true }).click() await page.waitForFunction(() => document.body.innerText.includes('main-checkout'), { timeout: 30_000, polling: 250 From 9c238cd2babdc1972e8a062906c55d5764e2c8f8 Mon Sep 17 00:00:00 2001 From: Vyacheslav Scherbinin Date: Sat, 21 Nov 2026 10:38:06 +0700 Subject: [PATCH 17/17] Show History's empty-list states from one component Upstream's agent filter and bottom bar filled MobileAgentSessionHistoryPanel.tsx past its 400-line limit beside this branch's single-conversation history. Co-Authored-By: Claude Opus 5.5 --- .../agent-history/AgentHistoryLoadState.tsx | 54 +++++++++++++++++++ .../MobileAgentSessionHistoryPanel.tsx | 40 ++++---------- 2 files changed, 64 insertions(+), 30 deletions(-) diff --git a/mobile/src/agent-history/AgentHistoryLoadState.tsx b/mobile/src/agent-history/AgentHistoryLoadState.tsx index 1c7d459a05c2..976ce05141e1 100644 --- a/mobile/src/agent-history/AgentHistoryLoadState.tsx +++ b/mobile/src/agent-history/AgentHistoryLoadState.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from 'react' import { History } from 'lucide-react-native' import { MobileLoadErrorState, + MobileNoMatchState, MobileOfflineState, MobileStateView } from '../components/feedback/MobileStateView' @@ -46,3 +47,56 @@ export function AgentHistoryLoadState({ } 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/MobileAgentSessionHistoryPanel.tsx b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx index 1881661941b3..7ef8a63eb8d3 100644 --- a/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx +++ b/mobile/src/agent-history/MobileAgentSessionHistoryPanel.tsx @@ -1,4 +1,4 @@ -import { AgentHistoryLoadState } from './AgentHistoryLoadState' +import { AgentHistoryEmptyList, AgentHistoryLoadState } from './AgentHistoryLoadState' import { scopeSegments } from './agent-history-scope-segments' import { openMobileAgentHistoryChat } from './open-mobile-agent-history-chat' import { mobileStructuredSessionOpenMessage } from '../session/native-chat/agent-session/mobile-structured-session-open-message' @@ -7,7 +7,7 @@ import { useResumedHistoryTerminalOpener } from './open-resumed-history-terminal import { useCallback, useMemo, useRef, useState } from 'react' import { View } from 'react-native' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' -import { ChevronLeft, History, RefreshCw } from 'lucide-react-native' +import { ChevronLeft, RefreshCw } from 'lucide-react-native' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { MobileSegmentedControl } from '../components/controls/MobileSegmentedControl' import { NavBar } from '../components/nav-bar/NavBar' @@ -39,7 +39,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 { MobileNoMatchState, MobileStateView } from '../components/feedback/MobileStateView' import { AgentHistoryInterruptedNotice, AgentHistoryResumeNotice, @@ -354,33 +353,14 @@ function MobileAgentSessionHistoryPanelContent({ onDismiss={() => setResumeMessage(null)} /> {sections.length === 0 ? ( - effectiveQuery ? ( - setQuery('')} - bottomInset={searchBarHeight} - /> - ) : !agentHistoryShowsEveryAgent(agents) ? ( - setAgents(AiVault.AI_VAULT_AGENTS)} - clearLabel={t('agentHistory.panel.showAllAgents', 'Show all agents')} - bottomInset={searchBarHeight} - /> - ) : ( - - ) + setQuery('')} + onShowAllAgents={() => setAgents(AiVault.AI_VAULT_AGENTS)} + /> ) : (