From c463effa5aaf1a3167aba656a3e8d7872732d25b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:34:29 -0800 Subject: [PATCH] test(perf): render and identity contracts for agent status, sidebar, tab strip and chat (#39954) * test(perf): render and identity contracts for agent status, sidebar, tab strip and chat Twelve operation, render and identity contracts at the production seams of the hottest UI paths, each driven at N and 10N with one hardcoded bound and shown to fail with its regression restored. Registers them in the contract list and fixes the perf workflow's path filter, which had drifted to 12 of 19 contracts. Removes test-only production exports nothing reads. * test(perf): prove composer typing lands; drop dead rebuild counter Review: the composer contract never checked the draft reached the composer, and its transcript control could not fail; the live-index rebuild counter and a bucket constant had no readers after the test exports went. --- .github/workflows/performance-contracts.yml | 17 +- .../agent-status-hot-path-benchmark.ts | 74 ++------ config/vitest.performance.config.ts | 15 +- ...se-runtime-graph-sync.performance.test.tsx | 58 ++++++ ...se-agent-pane-threads.performance.test.tsx | 98 +++++++++++ ...hatMarkdown.streaming.performance.test.tsx | 66 +++++++ ...ssion.composer-typing.performance.test.tsx | 166 ++++++++++++++++++ ...tiveChatStructuredSession.test-harness.tsx | 3 + ...MessageList.windowing.performance.test.tsx | 50 ++++++ .../markdown-parse-meter.test-fixture.ts | 51 ------ ...wn-top-level-blocks-legacy.test-fixture.ts | 103 ----------- ...ktree-activity-status.performance.test.tsx | 76 ++++++++ ...e-worktree-agent-rows.performance.test.tsx | 63 +++++++ .../worktree-agent-live-index-patch.ts | 9 - .../activity/worktree-agent-row-selectors.ts | 4 +- ...use-visible-worktrees.performance.test.tsx | 97 ++++++++++ ...-agent-types-by-tab-id.performance.test.ts | 63 +++++++ ...terminal-tab-activity.performance.test.tsx | 77 ++++++++ .../agent-status-projection.ts | 13 -- .../agent-status-batch.performance.test.ts | 34 ++++ .../agent-status-scale.test-fixture.ts | 91 ++++++++++ 21 files changed, 980 insertions(+), 248 deletions(-) create mode 100644 src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx create mode 100644 src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx delete mode 100644 src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts delete mode 100644 src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx create mode 100644 src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts create mode 100644 src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx create mode 100644 src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts create mode 100644 src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index 8af9f5342b2..cd3ba1dfa3a 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -12,22 +12,29 @@ on: - 'config/oxlint-performance-audit.json' - 'config/oxlint-plugins/*performance.mjs' - 'config/oxlint-plugins/quadratic-buffer-concat.mjs' - - 'config/scripts/*-plugin.test.mjs' - - '!config/scripts/static-analysis/oxlint-contracts/renderer-scrollbar-style-plugin.test.mjs' - # Keep in sync with the contract list in config/vitest.performance.config.ts; + - 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs' + - 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs' + - '**/*.performance.test.ts' + - '**/*.performance.test.tsx' + # Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts; # without these a rename lands green and only breaks the next nightly. - - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts' + - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts' + - 'src/main/runtime/rpc/methods/projects/repo.test.ts' + - 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx' - 'src/main/sqlite/sync-database.test.ts' - 'src/main/runtime/orchestration/db/row-column-lists.test.ts' - - 'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts' - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' - 'src/main/usage/jsonl-file-reader.test.ts' - 'src/main/usage/jsonl-file-snapshot.test.ts' - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' + - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' permissions: contents: read diff --git a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts index dd2ddb8fa18..774c2411787 100644 --- a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts +++ b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts @@ -9,23 +9,17 @@ import type { AppState } from '@/store/types' import type { AgentStatusBatchUpdate } from '@/store/slices/agent-status/agent-status-contract' import '@/store/slices/agent-status/agent-status' import { MAX_LIVE_AGENT_STATUSES } from '@/store/slices/agent-status/agent-status-capacity-eviction' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' -import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { makePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' -import { getDefaultSettings } from '../../../../src/shared/constants' +import type { createTestStore } from '@/store/testing/app-store-test-fixture' import { createAgentStatusPaneRoutingIndex, resolvePaneKeyFromRoutingIndex } from '@/hooks/ipc-events/agent-status-pane-routing-index' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' import { resolvePaneKey } from '@/hooks/ipc-events/agent-status-routing' const WORKTREES = 423 const EVENTS = 1_000 const BATCH_SIZE = 8 -const LEAF_ID = '11111111-1111-4111-8111-111111111111' const BASE_TIME = 2_000_000_000 const counters = { maps: 0, sets: 0, tabComparisons: 0 } @@ -58,62 +52,16 @@ function withAllocationCounting(run: () => T): T { } } -/** Tab list whose iteration is observable, so the nested-loop resolver's comparisons are countable. */ -class CountingTabList extends Array { - [Symbol.iterator](): ArrayIterator { - const iterator = super[Symbol.iterator]() - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - counters.tabComparisons += 1 - } - return result - } - return iterator - } -} - function buildFixture(countTabIteration: boolean) { - const store = createTestStore() - const settings = store.getState().settings ?? getDefaultSettings(tmpdir()) - const tabsByWorktree: AppState['tabsByWorktree'] = {} - const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {} - const worktrees: ReturnType[] = [] - const paneKeys: string[] = [] - const owners: { tabId: string; worktreeId: string }[] = [] - for (let index = 0; index < WORKTREES; index += 1) { - const worktreeId = `wt-${index}` - worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id })) - const tabs: ReturnType[] = [] - const unified: ReturnType[] = [] - for (let tab = 0; tab < (index % 2 === 0 ? 1 : 2); tab += 1) { - const tabId = `tab-${index}-${tab}` - tabs.push(makeTab({ id: tabId, worktreeId, title: `Terminal ${index}-${tab}` })) - unified.push( - makeUnifiedTab({ - id: tabId, - worktreeId, - groupId: `group-${index}`, - label: `Label ${index}` - }) - ) - paneKeys.push(makePaneKey(tabId, LEAF_ID)) - owners.push({ tabId, worktreeId }) - } - tabsByWorktree[worktreeId] = countTabIteration ? CountingTabList.from(tabs) : tabs - unifiedTabsByWorktree[worktreeId] = unified - } - store.setState({ - repos: [TEST_REPO], - worktreesByRepo: { [TEST_REPO.id]: worktrees }, - tabsByWorktree, - unifiedTabsByWorktree, - terminalLayoutsByTabId: {}, - setGeneratedTabTitlesFromAgentPrompts: () => {}, - settings: { ...settings, tabAutoGenerateTitle: false } - }) - return { store, paneKeys, owners } + const fixture = buildAgentStatusScaleFixture( + countTabIteration + ? () => { + counters.tabComparisons += 1 + } + : undefined + ) + fixture.store.setState({ setGeneratedTabTitlesFromAgentPrompts: () => {} }) + return fixture } function measure(run: () => void): number { diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 764857f9fe3..3d058e384c9 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -23,7 +23,20 @@ const contracts = [ 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + 'src/main/claude-usage/store-checkpoint-persistence.test.ts', + // Renderer hot paths: render, identity and publication counts at N and 10N (agent status, sidebar, tab strip, chat). + 'src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts', + 'src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx', + 'src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx', + 'src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx', + 'src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx', + 'src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts', + 'src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx', + 'src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx', + 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx', + 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx', + 'src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx', + 'src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx b/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx new file mode 100644 index 00000000000..4e34214bf13 --- /dev/null +++ b/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx @@ -0,0 +1,58 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '../store' +import { makeAgentStatusEntry } from '../runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness' +import { scheduleRuntimeGraphSync } from '../runtime/sync-runtime-graph/graph-sync-scheduler' +import { useRuntimeGraphSync } from './use-runtime-graph-sync' + +vi.mock('../runtime/sync-runtime-graph/graph-sync-scheduler', () => ({ + scheduleRuntimeGraphSync: vi.fn(), + setRuntimeGraphStoreStateGetter: vi.fn(), + setRuntimeGraphSyncEnabled: vi.fn() +})) +const initialState = useAppStore.getInitialState() +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.clearAllMocks() +}) +// Same-bucket heartbeats change no mobile data; a state transition requires one publication. +describe('runtime graph heartbeat publication contract', () => { + it.each([50, 500])('does not schedule heartbeats at %i panes', (count) => { + useAppStore.setState(initialState, true) + const entries = Object.fromEntries( + Array.from({ length: count }, (_, index) => { + const paneKey = `tab-${index}:11111111-1111-4111-8111-111111111111` + return [ + paneKey, + makeAgentStatusEntry({ paneKey, updatedAt: 1_800_000, stateStartedAt: 1_800_000 }) + ] + }) + ) + useAppStore.setState({ agentStatusByPaneKey: entries }) + renderHook(() => useRuntimeGraphSync()) + vi.mocked(scheduleRuntimeGraphSync).mockClear() + const key = Object.keys(entries)[9] + for (let tick = 1; tick <= 20; tick += 1) { + act(() => + useAppStore.setState({ + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [key]: { ...entries[key], updatedAt: 1_800_000 + tick * 1_000 } + } + }) + ) + expect(scheduleRuntimeGraphSync).toHaveBeenCalledTimes(0) + } + act(() => + useAppStore.setState({ + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [key]: { ...useAppStore.getState().agentStatusByPaneKey[key], state: 'blocked' } + } + }) + ) + expect(scheduleRuntimeGraphSync).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx b/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx new file mode 100644 index 00000000000..16b9950055c --- /dev/null +++ b/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx @@ -0,0 +1,98 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { useAppStore } from '@/store' +import { + LEAF_ID, + makeRepo, + makeTabWithIds, + makeWorktree +} from './ActivityPrototypePage-test-fixtures' + +import { useAgentPaneThreads } from './use-agent-pane-threads' + +vi.mock('@/store', async () => { + const { createTestStore } = await import('@/store/testing/app-store-test-fixture') + return { useAppStore: createTestStore() } +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +function installPanes(count: number): string[] { + vi.spyOn(Date, 'now').mockReturnValue(100_000) + const repo = makeRepo() + const worktree = makeWorktree() + const tabs = Array.from({ length: count }, (_, index) => + makeTabWithIds(`tab-${index}`, worktree.id) + ) + const entries: Record = {} + for (const tab of tabs) { + const paneKey = makePaneKey(tab.id, LEAF_ID) + entries[paneKey] = { + paneKey, + state: 'working', + prompt: `Task ${tab.id}`, + agentType: 'claude', + updatedAt: 100_000, + stateStartedAt: 99_000, + stateHistory: [] + } + } + useAppStore.setState({ + agentStatusByPaneKey: entries, + retainedAgentsByPaneKey: {}, + migrationUnsupportedByPtyId: {}, + runtimeAgentOrchestrationByPaneKey: {}, + acknowledgedAgentsByPaneKey: {}, + activityClearedAtByPaneKey: {}, + repos: [repo], + worktreesByRepo: { [repo.id]: [worktree] }, + folderWorkspaces: [], + detectedWorktreesByRepo: {}, + tabsByWorktree: { [worktree.id]: tabs }, + unifiedTabsByWorktree: {}, + agentsVisibleHostIds: null, + agentsFilterRepoIds: [] + }) + return Object.keys(entries) +} + +describe('agent thread list reuse', () => { + it.each([40, 400])('rebuilds only the pinged thread among %i panes', (count) => { + const panes = installPanes(count) + const activity = renderHook(() => + useAgentPaneThreads({ + query: '', + readFilter: 'all', + groupBy: 'none', + selectedPaneKey: null, + showChildAgents: true + }) + ) + const before = activity.result.current.allThreads + expect(before).toHaveLength(count) + const pinged = panes[9] + + act(() => { + const entries = useAppStore.getState().agentStatusByPaneKey + useAppStore.setState({ + agentStatusByPaneKey: { + ...entries, + [pinged]: { ...entries[pinged], prompt: 'Follow-up prompt' } + } + }) + }) + + const after = activity.result.current.allThreads + expect(after.map((thread) => thread.paneKey)).toEqual(before.map((thread) => thread.paneKey)) + // Memoized rows compare thread identity; only the pinged pane's row may see a new object. + const rebuilt = after.filter((thread, index) => thread !== before[index]) + expect(rebuilt.map((thread) => thread.paneKey)).toEqual([pinged]) + expect(rebuilt[0]?.currentAgentEntry?.prompt).toBe('Follow-up prompt') + }) +}) diff --git a/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx new file mode 100644 index 00000000000..809968ac7ce --- /dev/null +++ b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx @@ -0,0 +1,66 @@ +// @vitest-environment happy-dom +import { cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type * as ReactMarkdownModule from 'react-markdown' + +const markdownInput = vi.hoisted(() => ({ chars: 0 })) +vi.mock('react-markdown', async (importOriginal) => { + const actual = await importOriginal() + const { createElement } = await import('react') + return { + ...actual, + default: (props: Parameters[0]) => { + markdownInput.chars += typeof props.children === 'string' ? props.children.length : 0 + return createElement(actual.default, props) + } + } +}) +vi.mock('@/store/index', () => ({ + useAppStore: (selector: (state: { settings: { theme: string } }) => unknown) => + selector({ settings: { theme: 'light' } }) +})) + +import { NativeChatMarkdown } from './NativeChatMarkdown' +import { TooltipProvider } from '@/components/ui/tooltip' + +const BLOCK_CHARS = 200 +const TOKEN = ' tick' + +function paragraphs(count: number): string { + return Array.from({ length: count }, (_, index) => + `Paragraph ${index} ${'lorem '.repeat(BLOCK_CHARS)}`.slice(0, BLOCK_CHARS) + ).join('\n\n') +} + +function reply(content: string): React.JSX.Element { + return ( + + + + ) +} + +afterEach(cleanup) + +describe('streaming native chat markdown parse budget', () => { + it.each([10, 100])( + 'hands react-markdown only the tail of a %i-block reply per append', + (blocks) => { + let content = paragraphs(blocks) + const { container, rerender } = render(reply(content)) + const firstParagraph = container.querySelector('p') + expect(firstParagraph).not.toBeNull() + let widestAppend = 0 + for (let tick = 0; tick < 20; tick += 1) { + content += TOKEN + markdownInput.chars = 0 + rerender(reply(content)) + widestAppend = Math.max(widestAppend, markdownInput.chars) + } + // Only the unsettled tail: two 200-char blocks, the last grown by 20 x 5-char tokens, plus a separator. + expect(widestAppend).toBeLessThanOrEqual(505) + expect(container.querySelector('p')).toBe(firstParagraph) + expect(container.textContent).toContain(TOKEN.repeat(20).trim()) + } + ) +}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx new file mode 100644 index 00000000000..45c9f87c2d2 --- /dev/null +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx @@ -0,0 +1,166 @@ +// @vitest-environment happy-dom + +import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry' +import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' + +const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted( + async () => { + const setup = ( + await import('./NativeChatStructuredSession.test-harness') + ).createStructuredSessionMocks() + return { + ...setup, + launchModule: setup.moduleFactories.structuredAgentSessionLaunch() + } + } +) + +vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({ + retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch, + relaunchFailedStructuredAgentSessionForMessage: + launchModule.relaunchFailedStructuredAgentSessionForMessage +})) +vi.mock( + '@/lib/agent-session/launch/structured-agent-session-launch-registry', + async (importOriginal) => ({ + ...(await importOriginal()), + getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle, + getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes, + useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle, + useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure + }) +) +vi.mock( + '@/lib/agent-session/launch/structured-agent-session-launch-options', + async (importOriginal) => ({ + ...(await importOriginal()), + useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection + }) +) +vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-message', () => + moduleFactories.structuredAgentSessionLaunchMessage() +) +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => + moduleFactories.structuredAgentSessionCall() +) +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => + moduleFactories.structuredAgentSessionSubscriptions() +) +vi.mock('@/components/machine-identity/use-published-machine-name', () => ({ + usePublishedMachineName: () => null +})) +vi.mock('../../session/structured/use-structured-agent-session', () => + moduleFactories.useStructuredAgentSession() +) +vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize()) +vi.mock('../../links/actions/use-native-chat-file-link-context', () => + moduleFactories.useNativeChatFileLinkContext() +) +vi.mock('../../pane/ownership/use-native-chat-tab-owner', () => + moduleFactories.useNativeChatTabOwner() +) +vi.mock('../../links/actions/use-native-chat-file-link-click', () => + moduleFactories.useNativeChatFileLinkClick() +) +vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) +vi.mock('../../host-access/NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState()) +vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) +vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) +vi.mock('@/runtime/hosts/installation/use-managed-runtime-install', () => ({ + useManagedRuntimeInstall: () => ({ kind: 'inactive' }) +})) + +import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' +import { clearNativeChatComposerDraftsForTests } from '../../drafts/native-chat-draft-reset' +import { hydrateNativeChatComposerDrafts } from '../../drafts/native-chat-composer-draft-load' +import { updateNativeChatComposerDraft } from '../../drafts/native-chat-composer-draft-store' +import { structuredAgentSessionDraftScopeKey } from '../../drafts/native-chat-draft-scope' +import { TooltipProvider } from '@/components/ui/tooltip' +import { promptTextContent } from '../../composer/editor/native-chat-prompt-document-text' +import { + createMemoryNativeChatComposerDraftStorage, + setNativeChatComposerDraftStorageForTests +} from '../../drafts/native-chat-composer-draft-storage' +import { useAppStore } from '@/store' + +afterEach(() => { + cleanup() + resetStructuredSessionMocks() + clearNativeChatComposerDraftsForTests() +}) + +function journalMessage(index: number): AgentJournalRenderItem { + return { + itemId: `message-${index}`, + revision: 1, + sequence: index + 1, + observedAt: index + 1, + body: { + kind: 'message', + role: index % 2 === 0 ? 'user' : 'assistant', + blocks: [{ type: 'text', text: `Message ${index}` }] + } + } +} + +function session(): React.JSX.Element { + return ( + + + + ) +} + +describe('structured session composer typing', () => { + it.each([50, 500])( + 'renders no transcript while typing beside %i journal items', + async (count) => { + clearNativeChatComposerDraftsForTests() + setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage()) + await hydrateNativeChatComposerDrafts() + mocks.journalItems = Array.from({ length: count }, (_, index) => journalMessage(index)) + mocks.messages = mocks.journalItems.map((item) => ({ + id: item.itemId, + role: 'assistant', + source: 'transcript', + timestamp: item.observedAt, + blocks: [{ type: 'text', text: item.itemId }] + })) + render(session()) + await screen.findByRole('textbox') + const scopeKey = structuredAgentSessionDraftScopeKey('session-1') + let storePublications = 0 + const unsubscribe = useAppStore.subscribe(() => { + storePublications += 1 + }) + const rendersBefore = mocks.messageListRenders + expect(rendersBefore).toBeGreaterThan(0) + let text = '' + for (let keystroke = 0; keystroke < 20; keystroke += 1) { + text += 'a' + act(() => { + updateNativeChatComposerDraft( + scopeKey, + { text, document: promptTextContent(text) }, + 'deferred' + ) + }) + } + unsubscribe() + // Typing reached the composer, through its own scope store; the transcript never heard it. + expect(screen.getByRole('textbox').textContent).toContain('a'.repeat(20)) + expect(mocks.messageListRenders - rendersBefore).toBe(0) + expect(storePublications).toBe(0) + } + ) +}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx index 26cee219bc9..3d014c8deaa 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx @@ -93,6 +93,7 @@ export function createStructuredSessionMocks() { readRefusal: absent(), messages: null as null | unknown[], messageListProps: initialMessageListProps, + messageListRenders: 0, composerProps: nullable<{ launchSeed?: NativeChatLaunchSeed structuredTransport?: Record & { @@ -308,6 +309,7 @@ export function createStructuredSessionMocks() { nativeChatMessageList: () => ({ NativeChatMessageList: (props: typeof mocks.messageListProps) => { mocks.messageListProps = props + mocks.messageListRenders += 1 useImperativeHandle(props?.ref, () => ({ revealLatest: mocks.revealLatest, readerAtEnd: () => true, @@ -352,6 +354,7 @@ export function createStructuredSessionMocks() { mocks.readRefusal = undefined mocks.messages = null mocks.messageListProps = null + mocks.messageListRenders = 0 mocks.composerProps = null mocks.approvalCardProps = null mocks.questionCardProps = null diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx new file mode 100644 index 00000000000..be16ba53a87 --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx @@ -0,0 +1,50 @@ +// @vitest-environment happy-dom + +import { cleanup } from '@testing-library/react' +import { render } from '../../messages/actions/native-chat-tooltip-test-harness' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { list, marker, stubLayout, windowState } from './native-chat-windowing-test-harness' + +let restoreLayout = (): void => {} +beforeEach(() => { + restoreLayout = stubLayout() +}) +afterEach(() => { + cleanup() + restoreLayout() +}) + +function mountedRows(container: HTMLElement): Map { + return new Map( + Array.from(container.querySelectorAll('[data-index]'), (row) => [ + Number(row.dataset.index), + row + ]) + ) +} + +// ceil(600px viewport / 44px row pitch) = 14 visible, 2 x 6 overscan, and the pinned latest row. +const MOUNTED_ROW_BOUND = 27 + +describe('windowed transcript row budget', () => { + it.each([200, 2_000])('mounts a bounded row set from a %i-message transcript', (count) => { + const transcript = Array.from({ length: count }, (_, index) => marker(index)) + const { container, rerender } = render(list(transcript)) + const opened = windowState(container) + expect(opened.indexes.length).toBeLessThanOrEqual(MOUNTED_ROW_BOUND) + expect(opened.indexes).toContain(count - 1) + const before = mountedRows(container) + + rerender(list([...transcript, marker(count)])) + const appended = windowState(container) + expect(appended.indexes.length).toBeLessThanOrEqual(MOUNTED_ROW_BOUND) + expect(appended.indexes).toContain(count) + expect(container.textContent).toContain(`marker-${count}`) + const after = mountedRows(container) + const kept = [...before].filter(([index]) => after.has(index)) + expect(kept.length).toBeGreaterThan(0) + for (const [index, row] of kept) { + expect(after.get(index)).toBe(row) + } + }) +}) diff --git a/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts b/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts deleted file mode 100644 index 8c4d72be00e..00000000000 --- a/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { Nodes, Root } from 'mdast' - -type ParseWork = { - discovery: string[] - render: string[] - shifts: number - cloneNodes: number - cloneBytes: number - scans: { source: string; marker: string }[] - blocks: number -} - -export function createParseWork(): ParseWork { - return { - discovery: [], - render: [], - shifts: 0, - cloneNodes: 0, - cloneBytes: 0, - scans: [], - blocks: 0 - } -} - -export function nodeCount(node: Nodes): number { - return 1 + ('children' in node ? node.children.reduce((n, child) => n + nodeCount(child), 0) : 0) -} - -// Meter actual coordinate writes, leaving the parser's values and clone semantics unchanged. -export function meterPositions(tree: Root, onWrite: () => void): void { - function visit(node: Nodes): void { - if (node.position) { - for (const point of [node.position.start, node.position.end]) { - let offset = point.offset - Object.defineProperty(point, 'offset', { - enumerable: true, - configurable: true, - get: () => offset, - set: (value: number) => { - onWrite() - offset = value - } - }) - } - } - if ('children' in node) { - node.children.forEach(visit) - } - } - visit(tree) -} diff --git a/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts b/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts deleted file mode 100644 index fb50574b17a..00000000000 --- a/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Frozen splitter: differential tests compare every streaming prefix with the previous renderer. -// Reparse the last two blocks on append; cross-block definitions or HTML fall back to the whole document. - -import type { Nodes } from 'mdast' -import remarkGfm from 'remark-gfm' -import remarkParse from 'remark-parse' -import { remarkChatMath } from './chat-markdown-math' -import { chatMathCodeFences } from './chat-markdown-math-nodes' -import { unified } from 'unified' - -export type MarkdownBlock = { - /** Source offset, retained for settled blocks on append. */ - start: number - /** One-based source line. */ - line: number - text: string - literalMath?: boolean - /** Parser-owned end, excluding separators held for the next block. */ - end?: number -} - -export type MarkdownBlockSplit = { - source: string - blocks: readonly MarkdownBlock[] - /** Cross-block content requires whole-document rendering. */ - whole: boolean -} - -/** The last block, which is still growing, and the one it may yet join. */ -const UNSETTLED_BLOCKS = 2 - -const blockParser = unified().use(remarkParse).use(remarkGfm) -const mathBlockParser = blockParser().use(remarkChatMath) - -/** Tags that cannot hold anything, so cannot hold a later block. */ -const VOID_TAG_PATTERN = /^<(?:br|hr|wbr|img)\b[^>]*>$/i - -/** References and non-void HTML can affect other blocks and require whole-document parsing. */ -function reachesAcrossBlocks(node: Nodes): boolean { - if (node.type === 'definition' || node.type === 'footnoteDefinition') { - return true - } - if (node.type === 'html') { - return !VOID_TAG_PATTERN.test(node.value.trim()) - } - return 'children' in node && node.children.some(reachesAcrossBlocks) -} - -function hasLiteralMath(node: Nodes | undefined): boolean { - if (!node) { - return false - } - return ( - node.data?.mathComplete === false || - node.data?.mathLiteral === true || - ('children' in node && node.children.some(hasLiteralMath)) - ) -} - -function wholeDocument(source: string, literalMath = false): MarkdownBlockSplit { - return { source, blocks: [{ start: 0, line: 1, text: source, literalMath }], whole: true } -} - -export function splitMarkdownTopLevelBlocks( - source: string, - previous: MarkdownBlockSplit | null, - math = false -): MarkdownBlockSplit { - const grewFromPrevious = previous !== null && source.startsWith(previous.source) - if (grewFromPrevious && previous.whole && !math) { - return wholeDocument(source) - } - const settled = grewFromPrevious ? previous.blocks.slice(0, -UNSETTLED_BLOCKS) : [] - const reparsed = grewFromPrevious ? previous.blocks.at(-UNSETTLED_BLOCKS) : undefined - const base = reparsed?.start ?? 0 - const baseLine = reparsed?.line ?? 1 - const tail = source.slice(base) - const tree = (math ? mathBlockParser : blockParser).parse(tail) - if (math) { - chatMathCodeFences(tree, tail) - } - if (reachesAcrossBlocks(tree)) { - return wholeDocument(source, math && hasLiteralMath(tree)) - } - // Each block runs to the next one's start, so the blank lines between stay in the source. - const points = tree.children.map((child) => - 'position' in child ? child.position?.start : undefined - ) - const starts = points.map((point) => point?.offset ?? 0) - starts[0] = 0 - const blocks = starts.map((start, index) => ({ - start: base + start, - line: baseLine + (index === 0 ? 0 : (points[index]?.line ?? 1) - 1), - text: tail.slice(start, starts[index + 1]), - ...(math - ? { - literalMath: hasLiteralMath(tree.children[index]), - end: base + (tree.children[index]?.position?.end.offset ?? tail.length) - } - : {}) - })) - return { source, blocks: [...settled, ...blocks], whole: false } -} diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx new file mode 100644 index 00000000000..d7ecad94d71 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx @@ -0,0 +1,76 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { useWorktreeActivityStatus } from './use-worktree-activity-status' +import { useWorktreeActivityStatuses } from './use-worktree-activity-statuses' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// One permission transition changes one card; sidebar sizing changes no status output. +describe('sidebar activity status subscription contract', () => { + it.each([40, 400])('isolates a status transition among %i cards', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ + ...fixture.state, + agentStatusByPaneKey: fixture.agentStatusByPaneKey, + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined) + }) + const ids = Object.keys(fixture.state.tabsByWorktree) + let commits = 0 + let picker: ReturnType | undefined + const statuses = new Map() + function Probe({ worktreeId }: { worktreeId: string }) { + const status = useWorktreeActivityStatus(worktreeId) + useEffect(() => { + commits += 1 + statuses.set(worktreeId, status) + }) + return null + } + function Picker() { + picker = useWorktreeActivityStatuses(ids) + return null + } + render( + <> + + {ids.map((id) => ( + + ))} + + ) + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-17') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'blocked', agentType: 'claude', prompt: 'permission requested' }, + undefined, + { updatedAt: 2_000_000_001 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(statuses.get('wt-17')).toBe('permission') + expect(picker?.get('wt-17')).toBe('permission') + const previousPicker = picker + commits = 0 + act(() => useAppStore.setState({ sidebarWidth: 333 })) + expect(commits).toBe(0) + expect(picker).toBe(previousPicker) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx new file mode 100644 index 00000000000..ef457c4dcf9 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { useWorktreeAgentRows } from './useWorktreeAgentRows' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Only the card owning the changed prompt has new rows; a same-freshness epoch changes none. +describe('worktree agent row subscription contract', () => { + it.each([40, 400])('isolates a status ping among %i cards', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ ...fixture.state, agentStatusByPaneKey: fixture.agentStatusByPaneKey }) + let commits = 0 + const prompts = new Map() + function Probe({ worktreeId }: { worktreeId: string }) { + const rows = useWorktreeAgentRows(worktreeId, true) + useEffect(() => { + commits += 1 + prompts.set(worktreeId, rows[0]?.entry.prompt ?? '') + }) + return null + } + render( + <> + {Object.keys(fixture.state.tabsByWorktree).map((id) => ( + + ))} + + ) + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-17') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'working', agentType: 'claude', prompt: 'changed prompt' }, + undefined, + { updatedAt: 2_000_000_001 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(prompts.get('wt-17')).toBe('changed prompt') + commits = 0 + act(() => + useAppStore.setState({ agentStatusEpoch: useAppStore.getState().agentStatusEpoch + 1 }) + ) + expect(commits).toBe(0) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts index ca86090a00a..fbcac1c47c0 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts @@ -14,15 +14,6 @@ export type LiveEntriesByWorktreeCache = { entriesByWorktree: Map } -// Count full rebuilds to verify same-key status pings take the incremental path. -let liveEntriesFullRebuildCount = 0 -export function getLiveEntriesFullRebuildCountForTests(): number { - return liveEntriesFullRebuildCount -} -export function recordLiveEntriesFullRebuild(): void { - liveEntriesFullRebuildCount += 1 -} - // Local completed orphans stay hidden; remote rows await host retraction, not tab hydration. export function liveEntryWorktreeId( paneKey: string, diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts index ea6312970a3..12b6f915d6c 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts @@ -7,8 +7,7 @@ import { parsePaneKey } from '../../../../../../shared/workspace-layout/stable-p import { type LiveEntriesByWorktreeCache, liveEntryWorktreeId, - patchLiveEntriesByWorktree, - recordLiveEntriesFullRebuild + patchLiveEntriesByWorktree } from './worktree-agent-live-index-patch' import './worktree-agent-orchestration-index' import { createWorktreeRecordSelector } from '@/store/terminals/worktree-terminal-record-selector' @@ -150,7 +149,6 @@ function getLiveEntriesByWorktree(state: WorktreeAgentRowsState): Map() for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) { diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx new file mode 100644 index 00000000000..30c2a8cf139 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx @@ -0,0 +1,97 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { forgetWorktreeSleepIntent, markWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' +import { useVisibleSidebarWorktrees } from './use-visible-worktrees' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + forgetWorktreeSleepIntent('wt-18') + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Heartbeats change no visible membership; ending the deliberately slept row's last agent removes one row. +describe('visible sidebar worktree subscription contract', () => { + it.each([40, 400])('retains the visible list through heartbeats at %i worktrees', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ + ...fixture.state, + agentStatusByPaneKey: fixture.agentStatusByPaneKey, + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined) + }) + const args: Parameters[0] = { + filterState: { + showSleepingWorkspaces: false, + filterRepoIds: [], + hideDefaultBranchWorkspace: false, + hideAutomationGeneratedWorkspaces: false, + hideCliCreatedWorkspaces: false, + hideDetachedHeadWorkspaces: false, + hideWorkspacesFromOtherDevices: false, + alwaysShowDefaultBranchWorkspace: false, + visibleWorkspaceHostIds: null, + workspaceHostScope: 'all' + }, + sortBy: 'recent', + sortedIds: Object.keys(fixture.state.tabsByWorktree), + repoMap: new Map(fixture.state.repos.map((repo) => [repo.id, repo])), + worktreeLineageById: {}, + defaultHostId: LOCAL_EXECUTION_HOST_ID, + agentSendTargetWorktreeId: null + } + let commits = 0 + let visible: ReturnType['visibleWorktrees'] = [] + function Probe() { + const result = useVisibleSidebarWorktrees(args) + useEffect(() => { + commits += 1 + visible = result.visibleWorktrees + }) + return null + } + render() + expect(visible).toHaveLength(count) + const baseline = visible + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-18') + for (let tick = 1; tick <= 20; tick += 1) { + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'working', agentType: 'claude', prompt: 'initial prompt' }, + undefined, + { updatedAt: 2_000_000_000 + tick }, + fixture.owners[index] + ) + ) + expect(commits).toBe(0) + expect(visible).toBe(baseline) + } + markWorktreeSleepIntent('wt-18') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'done', agentType: 'claude', prompt: 'initial prompt' }, + undefined, + { updatedAt: 2_000_000_021 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(visible.some((worktree) => worktree.id === 'wt-18')).toBe(false) + }) +}) diff --git a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts new file mode 100644 index 00000000000..66aca792cf7 --- /dev/null +++ b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import { + makeAgentEntry, + makeManyTabState, + LEAF_ID +} from '../worktree-jump/worktree-jump-palette-test-fixtures' +import { createTabBarAgentProjectionSelector } from './tab-agent-types-by-tab-id' + +// Same-agent pings change neither strip projection; a different agent must update the owning tab. +describe('tab bar agent projection identity contract', () => { + it.each([20, 200])('retains projection identities through pings at %i tabs', (count) => { + const tabs = makeManyTabState(count).tabsByWorktree!['wt-many'] + let statuses: Record = Object.fromEntries( + tabs.map((tab) => { + const entry = makeAgentEntry(tab.id, 'working', 2_000_000_000, { agentType: 'claude' }) + return [entry.paneKey, entry] + }) + ) + const layouts: Record = Object.fromEntries( + tabs.map((tab) => [ + tab.id, + { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: LEAF_ID }, + second: { type: 'leaf', leafId: '22222222-2222-4222-8222-222222222222' } + }, + activeLeafId: LEAF_ID, + expandedLeafId: null + } satisfies TerminalLayoutSnapshot + ]) + ) + const select = createTabBarAgentProjectionSelector() + const baseline = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + for (let ping = 1; ping <= 50; ping += 1) { + statuses = Object.fromEntries( + Object.entries(statuses).map(([key, entry]) => [ + key, + { ...entry, updatedAt: 2_000_000_000 + ping } + ]) + ) + const next = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + expect(next.tabAgentTypesByTabId).toBe(baseline.tabAgentTypesByTabId) + expect(next.nativeChatTabWideFallbackUnsafeTabsById).toBe( + baseline.nativeChatTabWideFallbackUnsafeTabsById + ) + } + const changedKey = `term-5:${LEAF_ID}` + statuses = { ...statuses, [changedKey]: { ...statuses[changedKey], agentType: 'codex' } } + const changed = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + expect(changed.tabAgentTypesByTabId).not.toBe(baseline.tabAgentTypesByTabId) + expect(changed.tabAgentTypesByTabId).toEqual({ + ...baseline.tabAgentTypesByTabId, + 'term-5': 'codex' + }) + expect(changed.nativeChatTabWideFallbackUnsafeTabsById).toBe( + baseline.nativeChatTabWideFallbackUnsafeTabsById + ) + }) +}) diff --git a/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx b/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx new file mode 100644 index 00000000000..3f4e5ed56f5 --- /dev/null +++ b/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { + makeAgentEntry, + makeManyTabState +} from '../worktree-jump/worktree-jump-palette-test-fixtures' +import { useTerminalTabActivity } from './use-terminal-tab-activity' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Only the completed tab's glyph changes; other workspaces' titles and sidebar sizing change none. +describe('terminal tab activity subscription contract', () => { + it.each([20, 200])('isolates one completion among %i tabs', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + useAppStore.setState(initialState, true) + useAppStore.setState(makeManyTabState(count)) + const tabs = useAppStore.getState().tabsByWorktree['wt-many'] + const entries = tabs.map((tab) => + makeAgentEntry(tab.id, 'working', 2_000_000_000, { agentType: 'claude' }) + ) + useAppStore.setState({ + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined), + agentStatusByPaneKey: Object.fromEntries(entries.map((entry) => [entry.paneKey, entry])) + }) + let commits = 0 + const statuses = new Map() + function Probe({ tab }: { tab: (typeof tabs)[number] }) { + const activity = useTerminalTabActivity(tab) + useEffect(() => { + commits += 1 + statuses.set(tab.id, activity.activityStatus) + }) + return null + } + render( + <> + {tabs.map((tab) => ( + + ))} + + ) + commits = 0 + act(() => + useAppStore + .getState() + .setAgentStatus( + entries[5].paneKey, + { state: 'done', agentType: 'claude', prompt: '' }, + undefined, + { updatedAt: 2_000_000_001 }, + { tabId: tabs[5].id, worktreeId: 'wt-many' } + ) + ) + expect(commits).toBe(1) + expect(statuses.get('term-5')).toBe('done') + commits = 0 + for (let tick = 0; tick < 20; tick += 1) { + act(() => + useAppStore.setState({ + runtimePaneTitlesByTabId: { 'other-worktree-tab': { 0: `title ${tick}` } }, + sidebarWidth: 300 + tick + }) + ) + expect(commits).toBe(0) + } + }) +}) diff --git a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts index 727ccf8df3e..c2b40336453 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts @@ -103,16 +103,3 @@ export function buildRuntimeMobileAgentStatusProjection( } return projection } - -export function buildRuntimeMobileAgentStatusProjectionForTests( - agentStatusByPaneKey: AppState['agentStatusByPaneKey'] -): string { - return buildRuntimeMobileAgentStatusProjection(agentStatusByPaneKey) -} - -export const AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS_FOR_TESTS = - AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS - -export function resetRuntimeMobileAgentStatusProjectionCacheForTests(): void { - cachedAgentStatusProjection = null -} diff --git a/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts new file mode 100644 index 00000000000..64f0e56110f --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusBatchUpdate } from './agent-status-contract' +import { buildAgentStatusScaleFixture } from './agent-status-scale.test-fixture' + +// One burst has one externally visible snapshot, irrespective of how many panes it changes. +describe('agent status burst publication contract', () => { + afterEach(() => vi.useRealTimers()) + + it.each([8, 80])('publishes %i updates once and retains untouched entries', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const { store, paneKeys, owners, agentStatusByPaneKey } = buildAgentStatusScaleFixture() + store.setState({ agentStatusByPaneKey }) + const before = store.getState().agentStatusByPaneKey + const published = vi.fn() + const stop = store.subscribe(published) + const updates: AgentStatusBatchUpdate[] = paneKeys.slice(0, count).map((paneKey, index) => ({ + paneKey, + payload: { state: 'working', agentType: 'claude', prompt: 'new prompt' }, + timing: { updatedAt: 2_000_000_001 }, + routing: owners[index] + })) + store.getState().setAgentStatuses(updates) + stop() + expect(published).toHaveBeenCalledTimes(1) + const after = store.getState().agentStatusByPaneKey + for (const paneKey of paneKeys.slice(0, count)) { + expect(after[paneKey].prompt).toBe('new prompt') + } + for (const paneKey of paneKeys.slice(count)) { + expect(after[paneKey]).toBe(before[paneKey]) + } + }) +}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts b/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts new file mode 100644 index 00000000000..76cd7f36a36 --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts @@ -0,0 +1,91 @@ +import { tmpdir } from 'node:os' +import type { AppState } from '@/store/types' +import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' +import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture' +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' +import { TEST_REPO } from '@/store/repos/repo.test-fixture' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { getDefaultSettings } from '../../../../../shared/constants' + +const LEAF_ID = '11111111-1111-4111-8111-111111111111' + +export function buildAgentStatusScaleFixture( + onTabVisit: (() => void) | undefined = undefined, + worktreeCount = 423 +) { + /** Tab list whose iteration is observable, so the nested-loop resolver's comparisons are countable. */ + class CountingTabList extends Array { + [Symbol.iterator](): ArrayIterator { + const iterator = super[Symbol.iterator]() + const next = iterator.next.bind(iterator) + iterator.next = (...args) => { + const result = next(...args) + if (!result.done) { + onTabVisit?.() + } + return result + } + return iterator + } + } + + const store = createTestStore() + const settings = store.getState().settings ?? getDefaultSettings(tmpdir()) + const tabsByWorktree: AppState['tabsByWorktree'] = {} + const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {} + const worktrees: ReturnType[] = [] + const paneKeys: string[] = [] + const owners: { tabId: string; worktreeId: string }[] = [] + for (let index = 0; index < worktreeCount; index += 1) { + const worktreeId = `wt-${index}` + worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id })) + const tabs: ReturnType[] = [] + const unified: ReturnType[] = [] + for (let tab = 0; tab < (index % 2 === 0 ? 1 : 2); tab += 1) { + const tabId = `tab-${index}-${tab}` + tabs.push(makeTab({ id: tabId, worktreeId, title: `Terminal ${index}-${tab}` })) + unified.push( + makeUnifiedTab({ + id: tabId, + worktreeId, + groupId: `group-${index}`, + label: `Label ${index}` + }) + ) + paneKeys.push(makePaneKey(tabId, LEAF_ID)) + owners.push({ tabId, worktreeId }) + } + tabsByWorktree[worktreeId] = onTabVisit ? CountingTabList.from(tabs) : tabs + unifiedTabsByWorktree[worktreeId] = unified + } + const state = { + repos: [TEST_REPO], + worktreesByRepo: { [TEST_REPO.id]: worktrees }, + tabsByWorktree, + unifiedTabsByWorktree, + terminalLayoutsByTabId: {}, + settings: { ...settings, tabAutoGenerateTitle: false } + } satisfies Partial + store.setState(state) + const agentStatusByPaneKey = Object.fromEntries( + paneKeys + .map((paneKey, index): [string, AgentStatusEntry] => [ + paneKey, + { + paneKey, + ...owners[index], + state: 'working', + agentType: 'claude', + prompt: 'initial prompt', + updatedAt: 2_000_000_000, + stateStartedAt: 2_000_000_000, + firstStateStartedAt: 2_000_000_000, + stateHistory: [] + } satisfies AgentStatusEntry + ]) + .filter((_, index) => owners[index].tabId.endsWith('-0')) + ) + return { store, state, paneKeys, owners, agentStatusByPaneKey } +}