diff --git a/config/oxlint-plugins/app-store-performance.mjs b/config/oxlint-plugins/app-store-performance.mjs index d8bfe4131d9e..263e8b04ac0c 100644 --- a/config/oxlint-plugins/app-store-performance.mjs +++ b/config/oxlint-plugins/app-store-performance.mjs @@ -78,11 +78,11 @@ function returnedExpressions(selector) { return expressions } -function unwrapShallowSelector(selector, shallowHooks) { +function unwrapShallowSelector(selector, state) { if ( selector?.type === 'CallExpression' && selector.callee.type === 'Identifier' && - shallowHooks.has(selector.callee.name) + state.shallowHooks.has(variableFor(selector.callee, state)) ) { return { selector: selector.arguments[0], shallow: true } } @@ -157,26 +157,37 @@ function isModuleScope(node) { ) } -/** Records module-scope `const selectX = (state) => ...` so identifier selectors resolve. */ -function recordNamedSelector(node, state) { - if (!isModuleScope(node)) { - return - } - const declared = - node.type === 'FunctionDeclaration' - ? [[node.id, node]] - : node.declarations.map((declarator) => [declarator.id, declarator.init]) - for (const [id, initializer] of declared) { - const name = identifierName(id) - if (name && functionNode(initializer)) { - state.namedSelectors.set(name, initializer) +/** Resolve the binding at the use site, including nested lexical shadows. */ +function variableFor(node, state) { + const name = identifierName(node) + for (let scope = name && state.sourceCode.getScope(node); scope; scope = scope.upper) { + const variable = scope.set.get(name) + if (variable) { + return variable } } + return null } -/** Inline function, or a module-scope selector referenced by name. */ +/** Inline function, or a module-scope selector referenced by its lexical binding. */ function resolveSelector(argument, state) { - return functionNode(argument) ?? state.namedSelectors.get(identifierName(argument)) ?? null + if (functionNode(argument)) { + return argument + } + const definition = variableFor(argument, state)?.defs[0] + const declaration = definition?.node + if ( + definition?.type === 'FunctionName' && + declaration.type === 'FunctionDeclaration' && + isModuleScope(declaration) + ) { + return declaration + } + return definition?.type === 'Variable' && + declaration.type === 'VariableDeclarator' && + isModuleScope(declaration.parent) + ? functionNode(declaration.init) + : null } /** @@ -186,8 +197,8 @@ function resolveSelector(argument, state) { */ function expandThroughNamedHelper(expression, state) { const helper = - expression?.type === 'CallExpression' - ? state.namedSelectors.get(identifierName(expression.callee)) + expression?.type === 'CallExpression' && expression.callee.type === 'Identifier' + ? resolveSelector(expression.callee, state) : undefined const returned = helper ? returnedExpressions(helper) : [] return returned.length > 0 && returned.every((entry) => allocates(entry, true)) @@ -195,11 +206,11 @@ function expandThroughNamedHelper(expression, state) { : [expression] } -function createRuleState() { +function createRuleState(sourceCode) { return { appStoreHooks: new Set(), shallowHooks: new Set(), - namedSelectors: new Map(), + sourceCode, deferredCalls: [] } } @@ -211,12 +222,12 @@ function recordImports(node, state) { continue } const imported = identifierName(specifier.imported) - const localName = identifierName(specifier.local) - if (!imported || !localName) { + const variable = variableFor(specifier.local, state) + if (!imported || !variable) { continue } if (source === 'zustand/react/shallow' && imported === 'useShallow') { - state.shallowHooks.add(localName) + state.shallowHooks.add(variable) } // useAppStore is the app store wherever it is re-exported from; sibling // stores are trusted by naming convention only when they come from this codebase. @@ -225,7 +236,7 @@ function recordImports(node, state) { !NON_STORE_HOOKS.has(imported) && (imported === 'useAppStore' || isLocalModuleSource(source)) ) { - state.appStoreHooks.add(localName) + state.appStoreHooks.add(variable) } } } @@ -233,13 +244,13 @@ function recordImports(node, state) { function isAppStoreCall(node, state) { return ( node.callee.type === 'Identifier' && - state.appStoreHooks.has(node.callee.name) && + state.appStoreHooks.has(variableFor(node.callee, state)) && node.optional !== true ) } -function requireSelectorRule() { - const state = createRuleState() +function requireSelectorRule(sourceCode) { + const state = createRuleState(sourceCode) return { ImportDeclaration(node) { recordImports(node, state) @@ -260,18 +271,12 @@ function requireSelectorRule() { * Selector arguments are collected during traversal and judged at Program:exit so a * selector hoisted below its call site still resolves. */ -function deferredSelectorRule(inspect) { - const state = createRuleState() +function deferredSelectorRule(sourceCode, inspect) { + const state = createRuleState(sourceCode) return { ImportDeclaration(node) { recordImports(node, state) }, - FunctionDeclaration(node) { - recordNamedSelector(node, state) - }, - VariableDeclaration(node) { - recordNamedSelector(node, state) - }, CallExpression(node) { if (isAppStoreCall(node, state)) { state.deferredCalls.push(node) @@ -279,10 +284,7 @@ function deferredSelectorRule(inspect) { }, 'Program:exit'() { for (const node of state.deferredCalls) { - const { selector: argument, shallow } = unwrapShallowSelector( - node.arguments[0], - state.shallowHooks - ) + const { selector: argument, shallow } = unwrapShallowSelector(node.arguments[0], state) const report = inspect({ selector: resolveSelector(argument, state), shallow, @@ -296,8 +298,8 @@ function deferredSelectorRule(inspect) { } } -function noIdentitySelectorRule() { - return deferredSelectorRule(({ selector }) => +function noIdentitySelectorRule(sourceCode) { + return deferredSelectorRule(sourceCode, ({ selector }) => isIdentitySelector(selector) ? { node: selector, @@ -308,8 +310,8 @@ function noIdentitySelectorRule() { ) } -function noFreshSelectorResultRule() { - return deferredSelectorRule(({ selector, shallow, state }) => { +function noFreshSelectorResultRule(sourceCode) { + return deferredSelectorRule(sourceCode, ({ selector, shallow, state }) => { if (shallow || !selector) { return null } @@ -339,8 +341,8 @@ function nestedFreshValues(expression) { return [] } -function noNestedFreshUnderShallowRule() { - return deferredSelectorRule(({ selector, shallow, state }) => { +function noNestedFreshUnderShallowRule(sourceCode) { + return deferredSelectorRule(sourceCode, ({ selector, shallow, state }) => { if (!shallow || !selector) { return null } @@ -361,7 +363,7 @@ function noNestedFreshUnderShallowRule() { function bindContext(createVisitors) { return (context) => { - const visitors = createVisitors() + const visitors = createVisitors(context.sourceCode) for (const [nodeType, visit] of Object.entries(visitors)) { visitors[nodeType] = visit.bind(context) } diff --git a/config/scripts/app-store-performance-plugin.test.mjs b/config/scripts/app-store-performance-plugin.test.mjs index b07f07c26b1d..5e4df531cb47 100644 --- a/config/scripts/app-store-performance-plugin.test.mjs +++ b/config/scripts/app-store-performance-plugin.test.mjs @@ -41,7 +41,7 @@ const sources = { namedSelectors: ` import { useAppStore } from '@/store' const EarlyFresh = () => useAppStore(selectFreshRows) - const selectFreshRows = (state) => state.rows.filter(Boolean) + function selectFreshRows(state) { return state.rows.filter(Boolean) } const Stable = () => useAppStore(selectActiveId) const selectActiveId = (state) => state.activeId `, @@ -75,10 +75,31 @@ const sources = { const Delegating = () => useAppStore((state) => buildRows(state)) const NestedDelegating = () => useAppStore(useShallow((state) => ({ ids: buildRows(state) }))) `, + lexicalBindings: ` + import { useAppStore } from '@/store' + const select = s => ({ active: s.active }) + const build = s => s.rows.map(row => row.id) + function View() { + const select = s => s.active, build = s => s.rows + useAppStore(select) + return useAppStore(s => build(s)) + } + export function useTargetState(options) { useAppStore(options); return { options } } + `, + shadowedImports: ` + import { useAppStore, useAppStore as useStore } from '@/store' + import { usePluginPanelsStore as usePanels } from '@/store/plugin-panels' + import { useShallow as shallow } from 'zustand/react/shallow' + function View(useStore, usePanels, shallow) { + useStore(); usePanels() + return useAppStore(shallow(s => ({ ids: s.rows.map(row => row.id) }))) + } + `, cachedHelpers: ` import { useAppStore } from '@/store' import { useShallow } from 'zustand/react/shallow' // The identity-caching shape: fresh only on a miss, cached otherwise. + const cache = new WeakMap() const selectCachedRows = (state) => cache.get(state.key) ?? state.rows.filter(Boolean) const Cached = () => useAppStore((state) => selectCachedRows(state)) const CachedNested = () => useAppStore(useShallow((state) => ({ rows: selectCachedRows(state) }))) @@ -96,6 +117,10 @@ beforeAll(() => { }) describe('app store performance Oxlint plugin', () => { + it.each(['lexicalBindings', 'shadowedImports'])('respects lexical bindings in %s', (name) => { + expect(diagnosticsBySource.get(sources[name])).toEqual([]) + }) + it('reports whole-store and fresh-reference subscriptions', () => { const diagnostics = diagnosticsBySource.get(sources.subscriptions) diff --git a/src/renderer/src/components/native-chat/native-chat-agent-message-sender-label.ts b/src/renderer/src/components/native-chat/native-chat-agent-message-sender-label.ts index 14559acef253..8c0a3a1b9247 100644 --- a/src/renderer/src/components/native-chat/native-chat-agent-message-sender-label.ts +++ b/src/renderer/src/components/native-chat/native-chat-agent-message-sender-label.ts @@ -1,7 +1,10 @@ import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' -import { structuredChatTabBySessionId } from '@/lib/structured-chat-tab-index' +import { + structuredChatTabBySessionId, + structuredChatWorkspacesBySessionId +} from '@/lib/structured-chat-tab-index' import { useStructuredChatTabConversationName } from '@/runtime/structured-conversation-name' import { structuredAgentSessionOwnerForTab, @@ -23,7 +26,7 @@ function findChatTab( executionHostId: string | null ): Tab | undefined { const tabsByWorktree = state.unifiedTabsByWorktree - for (const worktreeId in tabsByWorktree) { + for (const worktreeId of structuredChatWorkspacesBySessionId(tabsByWorktree, sessionId)) { const tab = structuredChatTabBySessionId(tabsByWorktree, worktreeId, sessionId) if (tab && structuredAgentSessionOwnerForTab(state, tab) === executionHostId) { return tab diff --git a/src/renderer/src/components/native-chat/native-chat-composer-draft-image-check.ts b/src/renderer/src/components/native-chat/native-chat-composer-draft-image-check.ts index 45ef3ab0bf66..ac69ccfd81fd 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-draft-image-check.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-draft-image-check.ts @@ -2,6 +2,8 @@ import { useEffect, useMemo, useSyncExternalStore } from 'react' import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import { resolveNativeChatDraftOwner } from '@/lib/native-chat-draft-owner' import { chatImageAccess } from '@/lib/local-file-access' import { isAgentSessionAttachmentStorePath } from '../../../../shared/agent-session-attachments' import { @@ -15,7 +17,6 @@ import { import type { NativeChatComposerDraftImage } from './native-chat-composer-draft-storage' import { isKeptLocalPaste, - resolveNativeChatComposerDraftOwner, structuredAgentSessionIdOfDraftScope, readNativeChatComposerDraft, unavailableNativeChatComposerDraftImage, @@ -65,7 +66,11 @@ export async function findMissingNativeChatComposerDraftImages( return missing } -function localStoreAuthority(scopeKey: string, checks: readonly DraftImageCheck[]): string | null { +function localStoreAuthority( + state: AppState, + scopeKey: string, + checks: readonly DraftImageCheck[] +): string | null { if ( structuredAgentSessionIdOfDraftScope(scopeKey) === null || !checks.some( @@ -75,7 +80,7 @@ function localStoreAuthority(scopeKey: string, checks: readonly DraftImageCheck[ return null } const stored = readNativeChatComposerDraft(scopeKey).owner - const current = resolveNativeChatComposerDraftOwner(scopeKey) + const current = resolveNativeChatDraftOwner(state, scopeKey) return (stored ?? current)?.executionHostId === 'local' && (!current || current.executionHostId === 'local') ? JSON.stringify([stored, current]) @@ -112,7 +117,8 @@ function attemptIsCurrent(scopeKey: string, entry: DraftImageCheck): boolean { readNativeChatComposerDraft(scopeKey).images.some( (image) => restoredImageKey(image) === restoredImageKey(entry.image) ) && - entry.attempt.authority === checkAuthority(entry.image, localStoreAuthority(scopeKey, [entry])) + entry.attempt.authority === + checkAuthority(entry.image, localStoreAuthority(useAppStore.getState(), scopeKey, [entry])) ) } @@ -142,7 +148,10 @@ async function runCheck(scopeKey: string, entry: DraftImageCheck): Promise export async function verifyRestoredNativeChatComposerDraftImages(scopeKey: string): Promise { await Promise.all( (restoredImageChecks.get(scopeKey) ?? NO_IMAGE_CHECKS).map(async (entry) => { - const authority = checkAuthority(entry.image, localStoreAuthority(scopeKey, [entry])) + const authority = checkAuthority( + entry.image, + localStoreAuthority(useAppStore.getState(), scopeKey, [entry]) + ) if (entry.attempt && entry.attempt.authority !== authority) { replaceCheck(scopeKey, entry, { image: entry.image }) } else if (!entry.attempt && authority !== null) { @@ -199,7 +208,7 @@ export function useRestoredNativeChatComposerDraftImageCheck( subscribe, () => restoredImageChecks.get(scopeKey) ?? NO_IMAGE_CHECKS ) - const local = useAppStore(() => localStoreAuthority(scopeKey, checks)) + const local = useAppStore((state) => localStoreAuthority(state, scopeKey, checks)) const pending = useMemo( () => new Set( diff --git a/src/renderer/src/components/native-chat/native-chat-file-link.ts b/src/renderer/src/components/native-chat/native-chat-file-link.ts index b7aeea15717c..fc00a456cdb0 100644 --- a/src/renderer/src/components/native-chat/native-chat-file-link.ts +++ b/src/renderer/src/components/native-chat/native-chat-file-link.ts @@ -1,3 +1,4 @@ +import { chatWorkspaceByTabId } from '@/lib/structured-chat-tab-index' import { routeNativeChatHref } from '../../../../shared/native-chat-href-routing' import { parseExplicitFileLinkTarget, @@ -41,26 +42,7 @@ export function findTerminalTabWorktreeId( tabsByWorktree: NativeChatFileLinkState['tabsByWorktree'], terminalTabId: string ): string | null { - for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { - // Why: tabsByWorktree stores TerminalTab records; unified tabs carry - // entityId, but the terminal owner lookup must use the backing tab id. - if (tabs.some((tab) => tab.id === terminalTabId)) { - return worktreeId - } - } - return null -} - -function findStructuredTabWorktreeId( - unifiedTabsByWorktree: NativeChatFileLinkState['unifiedTabsByWorktree'], - tabId: string -): string | null { - for (const [worktreeId, tabs] of Object.entries(unifiedTabsByWorktree ?? {})) { - if (tabs.some((tab) => tab.id === tabId && tab.contentType === 'agent-session')) { - return worktreeId - } - } - return null + return chatWorkspaceByTabId(tabsByWorktree, terminalTabId) } /** The workspace that owns a native chat tab, independent of whether its directory is known. */ @@ -70,7 +52,7 @@ export function findNativeChatTabOwnerWorktreeId( ): string | null { return ( findTerminalTabWorktreeId(state.tabsByWorktree, tabId) ?? - findStructuredTabWorktreeId(state.unifiedTabsByWorktree, tabId) + chatWorkspaceByTabId(state.unifiedTabsByWorktree, tabId) ) } diff --git a/src/renderer/src/components/native-chat/native-chat-store-fanout.perf.test.tsx b/src/renderer/src/components/native-chat/native-chat-store-fanout.perf.test.tsx new file mode 100644 index 000000000000..32cb2f731f54 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-store-fanout.perf.test.tsx @@ -0,0 +1,214 @@ +// @vitest-environment happy-dom +import { act, cleanup, render } from '@testing-library/react' +import { useCallback } from 'react' +import { afterEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { resolveNativeChatDraftOwner } from '@/lib/native-chat-draft-owner' +import type { Tab } from '../../../../shared/tab-types' +import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' +import type { TerminalTab } from '../../../../shared/terminal-tab-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspace-types' +import { useAgentMessageSenderLabel } from './native-chat-agent-message-sender-label' +import { useNativeChatFileLinkContext } from './use-native-chat-file-link-context' +import { useRestoredNativeChatComposerDraftImageCheck } from './native-chat-composer-draft-image-check' +import * as drafts from './native-chat-composer-draft-store' +import * as storage from './native-chat-composer-draft-storage' +import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/structured-agent-session-status-feed' + +const initial = useAppStore.getInitialState() +const originalApi = window.api +const reads = { terminal: 0, unified: 0 } +let renders = 0 +const workspace = (index: number) => `folder:workspace-${index}` +const scope = (index: number) => `agent-session:session-${index}` +function counted(map: T, kind: keyof typeof reads): T { + return new Proxy(map, { ownKeys: (target) => (reads[kind]++, Reflect.ownKeys(target)) }) +} +function tab(index: number, workspaces: number): Tab { + return { + id: `chat-${index}`, + entityId: `session-${index}`, + worktreeId: workspace(index % workspaces), + groupId: 'group', + contentType: 'agent-session', + executionHostId: 'local', + label: `Chat ${index}`, + customLabel: `Name ${index}`, + color: null, + sortOrder: index, + createdAt: 0 + } +} +function seed(chats: number, workspaces: number, terminalsPerWorkspace: number) { + const tabsByWorktree: Record = {} + const unifiedTabsByWorktree: Record = {} + const folderWorkspaces: FolderWorkspace[] = [] + for (let index = 0; index < workspaces; index++) { + const id = workspace(index) + tabsByWorktree[id] = Array.from({ length: terminalsPerWorkspace }, (_, slot) => ({ + id: `terminal-${index}-${slot}`, + worktreeId: id, + ptyId: null, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: slot, + createdAt: 0 + })) + unifiedTabsByWorktree[id] = [] + folderWorkspaces.push({ + id: `workspace-${index}`, + projectGroupId: 'group', + name: id, + folderPath: `/repo/${index}`, + executionHostId: 'local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: index, + lastActivityAt: 0, + createdAt: 0, + updatedAt: 0 + }) + } + for (let index = 0; index < chats; index++) { + unifiedTabsByWorktree[workspace(index % workspaces)].push(tab(index, workspaces)) + } + useAppStore.setState( + { + ...initial, + folderWorkspaces, + tabsByWorktree: counted(tabsByWorktree, 'terminal'), + unifiedTabsByWorktree: counted(unifiedTabsByWorktree, 'unified') + }, + true + ) +} + +type Population = { chats: number; workspaces: number; terminalsPerWorkspace: number } +type SubscriberProps = { index: number; population: Population } +function Sender({ index, population: { workspaces } }: SubscriberProps) { + renders++ + const name = useAgentMessageSenderLabel( + { + party: { + address: `orca_session_id:session-${index}`, + terminalHandle: null, + orcaSessionId: testOrcaSessionId(`session-${index}`) + }, + name: 'Recorded' + }, + workspace(index % workspaces), + { kind: 'local' } + ) + return {name} +} +function FileLink({ index }: SubscriberProps) { + renders++ + const context = useNativeChatFileLinkContext(`chat-${index}`) + return {context?.worktreeId} +} +function Composer({ index }: SubscriberProps) { + renders++ + const subscribe = useCallback( + (listener: () => void) => drafts.subscribeToNativeChatComposerDraft(scope(index), listener), + [index] + ) + const pending = useRestoredNativeChatComposerDraftImageCheck(scope(index), subscribe) + return {pending.size} +} + +afterEach(() => { + cleanup() + drafts.clearNativeChatComposerDraftsForTests() + resetStructuredAgentSessionStatusFeedsForTests() + useAppStore.setState(initial, true) + Object.assign(window, { api: originalApi }) +}) + +it.each( + [ + { chats: 10, workspaces: 6, terminalsPerWorkspace: 16 }, + { chats: 100, workspaces: 60, terminalsPerWorkspace: 16 } + ].flatMap((population) => [ + { name: 'sender', Subscriber: Sender, population }, + { name: 'file link', Subscriber: FileLink, population }, + { name: 'composer', Subscriber: Composer, population } + ]) +)('$name scan budget at $population.chats chats', async (testCase) => { + const { name, Subscriber, population } = testCase + seed(population.chats, population.workspaces, population.terminalsPerWorkspace) + const resolveOwner = vi.fn((key: string) => + resolveNativeChatDraftOwner(useAppStore.getState(), key) + ) + drafts.setNativeChatComposerDraftOwnerResolver(resolveOwner) + const saved = storage.createMemoryNativeChatComposerDraftStorage() + saved.drafts.set(scope(0), { + text: '', + owner: { workspaceId: workspace(0), executionHostId: 'local' }, + savedAt: 1, + images: [{ id: 'image', path: '/state/agent-session-attachments/upload/shot.png' }] + }) + storage.setNativeChatComposerDraftStorageForTests(saved) + const validation = Promise.withResolvers() + const pathExists = vi.fn(() => validation.promise) + Object.assign(window, { api: { fs: { pathExists } } }) + await drafts.hydrateNativeChatComposerDrafts() + const view = render( + <> + {Array.from({ length: population.chats }, (_, index) => ( + + ))} + + ) + if (name === 'composer') { + expect(pathExists).toHaveBeenCalledTimes(1) + expect(view.container.querySelector('[data-index="0"]')?.textContent).toBe('1') + } + reads.terminal = reads.unified = renders = 0 + resolveOwner.mockClear() + act(() => { + for (let tick = 0; tick < 50; tick++) { + useAppStore.setState({ lastTerminalInputAtByPaneKey: { 'other:pane': tick } }) + } + }) + expect(reads).toEqual({ terminal: 0, unified: 0 }) + expect(renders).toBe(0) + expect(resolveOwner).not.toHaveBeenCalled() + + // Build the focus/relabel publication before counting subscriber work on the new snapshot. + const state = useAppStore.getState() + const moved = { + ...tab(0, population.workspaces), + worktreeId: workspace(1), + customLabel: 'Renamed' + } + const replacement = counted( + { + ...state.unifiedTabsByWorktree, + [workspace(0)]: state.unifiedTabsByWorktree[workspace(0)].filter(({ id }) => id !== moved.id), + [workspace(1)]: [...state.unifiedTabsByWorktree[workspace(1)], moved] + }, + 'unified' + ) + const terminals = counted({ ...state.tabsByWorktree }, 'terminal') + reads.terminal = reads.unified = 0 + await act(async () => + useAppStore.setState({ + unifiedTabsByWorktree: replacement, + tabsByWorktree: terminals, + activeWorktreeId: workspace(1) + }) + ) + expect(reads.terminal).toBeLessThanOrEqual(1) + expect(reads.unified).toBeLessThanOrEqual(1) + expect(resolveNativeChatDraftOwner(useAppStore.getState(), scope(0))?.workspaceId).toBe( + workspace(1) + ) + expect(view.container.querySelector('[data-index="0"]')?.textContent).toBe( + name === 'sender' ? 'Renamed' : name === 'file link' ? workspace(1) : '1' + ) + await act(async () => validation.resolve(true)) +}) diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.test.tsx index 0c3d6f10d648..a113ee33c6e5 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.test.tsx @@ -15,6 +15,34 @@ import { imageReferenceToken } from '../../../../shared/native-chat-image-refere import type * as RemoteRuntimePtyIdModule from '../../../../shared/remote-runtime-pty-id' import { useAppStore } from '@/store' +import { resolveNativeChatDraftOwner } from '@/lib/native-chat-draft-owner' +import type { Tab } from '../../../../shared/tab-types' + +const initialStoreState = useAppStore.getInitialState() +function publishOwner( + scopeKey: string, + owner: draftStorage.NativeChatComposerDraftOwner | undefined +): void { + const sessionId = draftStore.structuredAgentSessionIdOfDraftScope(scopeKey) + const tab: Tab = { + id: scopeKey, + entityId: sessionId ?? scopeKey, + worktreeId: owner?.workspaceId ?? 'unknown', + groupId: 'group', + contentType: 'agent-session', + label: 'Chat', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } + useAppStore.setState({ + unifiedTabsByWorktree: owner ? { [owner.workspaceId]: [tab] } : {}, + activeWorktreeId: owner?.workspaceId ?? null, + activeWorkspaceExecutionHostId: owner?.executionHostId ?? null + }) +} + import * as draftStore from './native-chat-composer-draft-store' import * as draftStorage from './native-chat-composer-draft-storage' import { nativeChatImagesHoldSend } from './native-chat-image-reattach' @@ -55,6 +83,7 @@ function publishUnrelatedStatuses(): void { describe('useNativeChatComposerAttachments', () => { afterEach(() => { + useAppStore.setState(initialStoreState, true) runtimeTarget.remote = false clearNativeChatAttachmentCacheForTests() document.body.replaceChildren() @@ -167,8 +196,10 @@ describe('useNativeChatComposerAttachments', () => { const storage = draftStorage.createMemoryNativeChatComposerDraftStorage() storage.drafts.set(scope, { text: '', images: [image], owner: storedOwner, savedAt: 1 }) draftStorage.setNativeChatComposerDraftStorageForTests(storage) - let owner = storedOwner - const resolveOwner = vi.fn(() => owner) + publishOwner(scope, storedOwner) + const resolveOwner = vi.fn((key: string) => + resolveNativeChatDraftOwner(useAppStore.getState(), key) + ) draftStore.setNativeChatComposerDraftOwnerResolver(resolveOwner) const old = Promise.withResolvers() const next = Promise.withResolvers() @@ -182,12 +213,12 @@ describe('useNativeChatComposerAttachments', () => { probe = await renderProbe(scope, true) expect(nativeChatImagesHoldSend(probe.latest().imageAttachments)).toBe(true) expect(pathExists).toHaveBeenCalledTimes(1) - owner = { ...storedOwner, executionHostId: 'runtime:remote' } + publishOwner(scope, { ...storedOwner, executionHostId: 'runtime:remote' }) await act(async () => old.resolve(false)) expect(draftStore.readNativeChatComposerDraft(scope).images).toEqual([image]) await act(async () => useAppStore.setState({})) expect(nativeChatImagesHoldSend(probe.latest().imageAttachments)).toBe(false) - owner = storedOwner + publishOwner(scope, storedOwner) await act(async () => useAppStore.setState({})) expect(pathExists).toHaveBeenCalledTimes(2) expect(nativeChatImagesHoldSend(probe.latest().imageAttachments)).toBe(true) @@ -217,8 +248,10 @@ describe('useNativeChatComposerAttachments', () => { const paste = { id: 'paste', path: '/state/native-chat-pastes/orca-paste-1-a.png' } storage.drafts.set('pty-1', { text: '', images: [image, paste], savedAt: 1 }) draftStorage.setNativeChatComposerDraftStorageForTests(storage) - let owner: draftStorage.NativeChatComposerDraftOwner | undefined - draftStore.setNativeChatComposerDraftOwnerResolver(() => owner) + publishOwner(scope, undefined) + draftStore.setNativeChatComposerDraftOwnerResolver((key) => + resolveNativeChatDraftOwner(useAppStore.getState(), key) + ) const exists = Promise.withResolvers() const pathExists = vi.fn(() => exists.promise) const originalApi = window.api @@ -237,16 +270,16 @@ describe('useNativeChatComposerAttachments', () => { expect(nativeChatImagesHoldSend(terminal.latest().imageAttachments)).toBe(false) act(() => terminal.root.unmount()) const probe = await renderProbe(scope, true) - owner = { workspaceId: 'wt', executionHostId: 'runtime:remote' } + publishOwner(scope, { workspaceId: 'wt', executionHostId: 'runtime:remote' }) act(() => useAppStore.setState({})) expect(pathExists).not.toHaveBeenCalled() - owner = { workspaceId: 'wt', executionHostId: 'local' } + publishOwner(scope, { workspaceId: 'wt', executionHostId: 'local' }) act(() => useAppStore.setState({})) expect(nativeChatImagesHoldSend(probe.latest().imageAttachments)).toBe(true) - owner = { workspaceId: 'wt', executionHostId: 'runtime:remote' } + publishOwner(scope, { workspaceId: 'wt', executionHostId: 'runtime:remote' }) await act(async () => useAppStore.setState({})) expect(nativeChatImagesHoldSend(probe.latest().imageAttachments)).toBe(false) - owner = { workspaceId: 'wt', executionHostId: 'local' } + publishOwner(scope, { workspaceId: 'wt', executionHostId: 'local' }) act(() => useAppStore.setState({})) const newer = { id: 'edit', path: '/repo/new.png' } await act(async () => { @@ -272,10 +305,10 @@ describe('useNativeChatComposerAttachments', () => { const storage = draftStorage.createMemoryNativeChatComposerDraftStorage() storage.drafts.set(scope, { text: 'hi', images: [image, other], savedAt: 1 }) draftStorage.setNativeChatComposerDraftStorageForTests(storage) - draftStore.setNativeChatComposerDraftOwnerResolver(() => ({ - workspaceId: 'wt', - executionHostId: 'local' - })) + publishOwner(scope, { workspaceId: 'wt', executionHostId: 'local' }) + draftStore.setNativeChatComposerDraftOwnerResolver((key) => + resolveNativeChatDraftOwner(useAppStore.getState(), key) + ) let present = true const pathExists = vi.fn(async () => present) const originalApi = window.api @@ -505,6 +538,7 @@ describe('useNativeChatComposerAttachments', () => { act(() => probe.latest().attachResolvedPaths(refused)) expect(probe.notice()).toBe('Local attachments are not available for remote sessions.') + useAppStore.setState(initialStoreState, true) runtimeTarget.remote = false act(() => probe.latest().attachResolvedPaths(['/local/allowed.txt'])) composing = false diff --git a/src/renderer/src/lib/native-chat-draft-owner.ts b/src/renderer/src/lib/native-chat-draft-owner.ts index 36923536669a..76a1e2ed9569 100644 --- a/src/renderer/src/lib/native-chat-draft-owner.ts +++ b/src/renderer/src/lib/native-chat-draft-owner.ts @@ -4,6 +4,10 @@ import { nativeChatDraftScopeTabId, structuredAgentSessionIdOfDraftScope } from '@/components/native-chat/native-chat-composer-draft-store' +import { + chatWorkspaceByTabId, + structuredChatWorkspacesBySessionId +} from './structured-chat-tab-index' import { resolveWorktreeOperationRoute } from './worktree-operation-route' function workspaceOfDraftScope( @@ -11,21 +15,9 @@ function workspaceOfDraftScope( scopeKey: string ): string | null { const sessionId = structuredAgentSessionIdOfDraftScope(scopeKey) - if (sessionId !== null) { - for (const [workspaceId, tabs] of Object.entries(state.unifiedTabsByWorktree)) { - if (tabs.some((tab) => tab.contentType === 'agent-session' && tab.entityId === sessionId)) { - return workspaceId - } - } - return null - } - const tabId = nativeChatDraftScopeTabId(scopeKey) - for (const [workspaceId, tabs] of Object.entries(state.tabsByWorktree)) { - if (tabs.some((tab) => tab.id === tabId)) { - return workspaceId - } - } - return null + return sessionId !== null + ? (structuredChatWorkspacesBySessionId(state.unifiedTabsByWorktree, sessionId)[0] ?? null) + : chatWorkspaceByTabId(state.tabsByWorktree, nativeChatDraftScopeTabId(scopeKey)) } /** The workspace, and the host it runs on, whose open chat a new draft is written in; the same diff --git a/src/renderer/src/lib/structured-chat-tab-index.test.ts b/src/renderer/src/lib/structured-chat-tab-index.test.ts index df13f1f6e7bf..4a602317c87e 100644 --- a/src/renderer/src/lib/structured-chat-tab-index.test.ts +++ b/src/renderer/src/lib/structured-chat-tab-index.test.ts @@ -1,6 +1,11 @@ import { describe, expect, it } from 'vitest' import type { Tab } from '../../../shared/tab-types' -import { structuredChatTabById, structuredChatTabBySessionId } from './structured-chat-tab-index' +import { + structuredChatTabById, + structuredChatTabBySessionId, + structuredChatWorkspacesBySessionId, + chatWorkspaceByTabId +} from './structured-chat-tab-index' function tab(id: string, contentType: Tab['contentType'] = 'agent-session'): Tab { return { @@ -57,3 +62,24 @@ describe('structured chat tab index', () => { } ) }) + +it('keeps own-key order, prototype-named ids, and separate session and tab keys across snapshots', () => { + const chat = { ...tab('__proto__'), entityId: '__proto__' } + const snapshot: Record = {} + Object.setPrototypeOf(snapshot, { inherited: [chat] }) + Object.assign(snapshot, { + constructor: [tab('terminal', 'terminal'), chat, chat], + second: [chat] + }) + expect(structuredChatWorkspacesBySessionId(snapshot, '__proto__')).toEqual([ + 'constructor', + 'second' + ]) + expect(chatWorkspaceByTabId(snapshot, '__proto__')).toBe('constructor') + expect(chatWorkspaceByTabId(snapshot, 'terminal')).toBeNull() + expect(structuredChatWorkspacesBySessionId({ second: [chat] }, '__proto__')).toEqual(['second']) + expect(structuredChatWorkspacesBySessionId(snapshot, '__proto__')).toEqual([ + 'constructor', + 'second' + ]) +}) diff --git a/src/renderer/src/lib/structured-chat-tab-index.ts b/src/renderer/src/lib/structured-chat-tab-index.ts index d672eb1a06e7..14da07f7b965 100644 --- a/src/renderer/src/lib/structured-chat-tab-index.ts +++ b/src/renderer/src/lib/structured-chat-tab-index.ts @@ -53,3 +53,56 @@ export function structuredChatTabBySessionId( ): Tab | undefined { return indexTabs(workspaceTabs(tabsByWorkspace, workspaceId))?.bySessionId.get(sessionId) } + +type WorkspaceTab = Pick & Partial> +type WorkspaceTabMap = Readonly> +const workspaceIndexes = new WeakMap< + WorkspaceTabMap, + { + byTabId: Map + bySessionId: Map + } +>() + +function indexWorkspaces(tabsByWorkspace: WorkspaceTabMap | undefined) { + if (!tabsByWorkspace) { + return undefined + } + let index = workspaceIndexes.get(tabsByWorkspace) + if (!index) { + const byTabId = new Map() + const bySessionId = new Map() + for (const [workspaceId, tabs] of Object.entries(tabsByWorkspace)) { + for (const { id, contentType, entityId } of tabs ?? []) { + if (contentType && contentType !== 'agent-session') { + continue + } + if (!byTabId.has(id)) { + byTabId.set(id, workspaceId) + } + if (entityId === undefined) { + continue + } + const candidates = bySessionId.get(entityId) ?? [] + if (candidates.at(-1) !== workspaceId) { + candidates.push(workspaceId) + } + bySessionId.set(entityId, candidates) + } + } + index = { byTabId, bySessionId } + workspaceIndexes.set(tabsByWorkspace, index) + } + return index +} + +export function structuredChatWorkspacesBySessionId( + tabsByWorkspace: TabsByWorkspace, + sessionId: string +): readonly string[] { + return indexWorkspaces(tabsByWorkspace)?.bySessionId.get(sessionId) ?? [] +} + +export function chatWorkspaceByTabId(tabsByWorkspace: WorkspaceTabMap | undefined, tabId: string) { + return indexWorkspaces(tabsByWorkspace)?.byTabId.get(tabId) ?? null +}