From 6d9f30201d2876e1db415ce9a4bfbc2b5f0b2fa8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 15:50:05 -0800 Subject: [PATCH] perf(mobile): folder membership keys on lineage only; child status reads update the folder list Membership resolves again only when a row's lineage fields change, keying only rows the catalog replaced; labels come from the current rows. A child Source Control's newer status read is handed to the folder list's summary, so Back shows what an action did without another read. --- .../mobile-folder-attached-worktrees.ts | 68 ++++++++++----- .../use-folder-worktree-status.perf.test.ts | 56 +++++++++++- ...ile-folder-attached-worktrees.perf.test.ts | 61 ++++++++++--- .../use-mobile-folder-attached-worktrees.ts | 85 +++++++++++++++---- .../source-control/mobile-git-status-query.ts | 38 ++++++++- .../use-mobile-source-control-loaders.ts | 10 ++- 6 files changed, 266 insertions(+), 52 deletions(-) diff --git a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts index d88c8619063..a153ac8f342 100644 --- a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts +++ b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts @@ -7,32 +7,58 @@ import { } from '../../worktree/mobile-workspace-lineage' import { getWorktreeRowIdentity } from '../../worktree/worktree-host-row-identity' -/** What the folder list reads of a host row: lineage, then what a row shows. Agent and terminal fields churn, so they're left out. */ -export type FolderListRow = MobileLineageRow & - Pick +/** What a folder list row shows of a host row. */ +export type FolderListRow = Pick< + Worktree, + 'worktreeId' | 'hostId' | 'repo' | 'displayName' | 'branch' +> + +type FolderLineageRow = MobileLineageRow & Pick + +// Keyed by row object: the catalog query keeps an unchanged row's identity, so only changed rows are read again. +const lineageKeys = new WeakMap() +const listRows = new WeakMap() + +/** The fields membership and order depend on; labels and agent state are left out so their churn rebuilds nothing. */ +export function folderLineageKey(row: Worktree): string { + let key = lineageKeys.get(row) + if (key === undefined) { + key = JSON.stringify([ + row.worktreeId, + row.hostId, + row.repoId, + row.workspaceKind, + row.isArchived, + row.parentWorktreeId, + row.worktreeInstanceId, + row.lineageWorktreeInstanceId, + row.parentWorktreeInstanceId, + row.crossStoreParent, + row.workspaceLineage, + row.createdAt + ]) + lineageKeys.set(row, key) + } + return key +} export function toFolderListRow(row: Worktree): FolderListRow { - return { - worktreeId: row.worktreeId, - hostId: row.hostId, - repoId: row.repoId, - workspaceKind: row.workspaceKind, - isArchived: row.isArchived, - parentWorktreeId: row.parentWorktreeId, - worktreeInstanceId: row.worktreeInstanceId, - lineageWorktreeInstanceId: row.lineageWorktreeInstanceId, - parentWorktreeInstanceId: row.parentWorktreeInstanceId, - crossStoreParent: row.crossStoreParent, - workspaceLineage: row.workspaceLineage, - repo: row.repo, - displayName: row.displayName, - branch: row.branch, - createdAt: row.createdAt + let listRow = listRows.get(row) + if (listRow === undefined) { + listRow = { + worktreeId: row.worktreeId, + hostId: row.hostId, + repo: row.repo, + displayName: row.displayName, + branch: row.branch + } + listRows.set(row, listRow) } + return listRow } /** The folder workspace row a Source Control route names; a route without a server means the paired desktop's own. */ -export function findFolderWorkspaceRow( +export function findFolderWorkspaceRow( rows: readonly Row[], folderWorktreeId: string, executionHost: ExecutionHostId | undefined @@ -46,7 +72,7 @@ export function findFolderWorkspaceRow( } /** Worktrees attached to the folder, as the host list nests them, with their worktree descendants; oldest first, like desktop. */ -export function getFolderAttachedWorktrees( +export function getFolderAttachedWorktrees( rows: readonly Row[], folder: Row, stores?: MobileLineageStores diff --git a/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts b/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts index 784d0ff6db4..ee93a66a4c3 100644 --- a/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts +++ b/mobile/src/source-control/folder/use-folder-worktree-status.perf.test.ts @@ -1,4 +1,5 @@ import { createElement, Fragment } from 'react' +import { useQueryClient, type QueryClient } from '@tanstack/react-query' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { ExecutionHostId } from '../../../../src/shared/execution-host' @@ -9,6 +10,7 @@ import { documentQueryClient, settleQueryNotifications } from '../../test-support/rpc-recording/hook-mount' +import { publishGitStatusSummary, type GitStatusRead } from '../mobile-git-status-query' import { useFolderWorktreeStatus } from './use-folder-worktree-status' const STATUS = { branch: 'feature', entries: [] } @@ -54,6 +56,9 @@ afterEach(async () => { }) const REFRESHERS = new Set<() => void>() +const shown = new Map() +let queryClient: QueryClient | null = null +const rowKey = (row: RowSpec) => `${row.routeHost ?? 'local'}|${row.worktreeId}` function Row(props: { client: RpcClient @@ -61,7 +66,8 @@ function Row(props: { routeHost: ExecutionHostId | undefined subscribed: boolean }): null { - useFolderWorktreeStatus({ + queryClient = useQueryClient() + const status = useFolderWorktreeStatus({ hostId: 'host-1', client: props.client, routeHost: props.routeHost, @@ -69,6 +75,7 @@ function Row(props: { subscribed: props.subscribed, refreshers: REFRESHERS }) + shown.set(rowKey(props), { data: status.data, updatedAt: status.dataUpdatedAt }) return null } @@ -92,7 +99,7 @@ async function mountFolder(rows: RowSpec[], client: RpcClient) { createElement( Fragment, null, - rows.map((row) => createElement(Row, { key: row.worktreeId, client, ...row, subscribed })) + rows.map((row) => createElement(Row, { key: rowKey(row), client, ...row, subscribed })) ) ) await act(async () => { @@ -155,4 +162,49 @@ describe.each([ await settleQueryNotifications() expect(host.reads).toHaveLength(0) }) + + it("shows a child's detailed read on Back with no read of its own", async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const host = countingClient() + // The same worktree id on another server and on the desktop must keep their own summaries. + const opened: RowSpec = { worktreeId: 'repo-s::/w0', routeHost: 'runtime:env-0' } + const rows = [ + ...folderRows(n, servers), + { worktreeId: 'repo-s::/w0', routeHost: 'runtime:env-x' as ExecutionHostId }, + { worktreeId: 'repo-s::/w0', routeHost: undefined } + ] + const setSubscribed = await mountFolder(rows, host.client) + const before = new Map(shown) + const listed = before.get(rowKey(opened))! + if (listed.data?.kind !== 'ready') { + throw new Error('summary not read') + } + + // The child opens over the list, commits, and its forced reread lands. + await setSubscribed(false) + host.reads.length = 0 + vi.setSystemTime(Date.now() + 1_000) + const after: GitStatusRead = { + kind: 'ready', + status: { ...listed.data.status, branch: 'after' } + } + const target = { exec: opened.routeHost!, worktree: opened.worktreeId } + await act(() => publishGitStatusSummary(queryClient!, 'host-1', target, after, Date.now())) + // A detailed read older than the summary changes nothing. + await act(() => + publishGitStatusSummary(queryClient!, 'host-1', target, listed.data!, listed.updatedAt - 1) + ) + + // Back within three seconds, then well past them with no focus or signal. + vi.setSystemTime(Date.now() + 1_000) + await setSubscribed(true) + vi.setSystemTime(Date.now() + 10_000) + await setSubscribed(true) + expect(host.reads).toHaveLength(0) + expect(shown.get(rowKey(opened))?.data).toEqual(after) + const changed = rows.filter( + (row) => shown.get(rowKey(row))?.data !== before.get(rowKey(row))?.data + ) + expect(changed).toEqual([opened]) + }) }) diff --git a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts index 8ef009b908b..2293f5f84ac 100644 --- a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts +++ b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.perf.test.ts @@ -19,7 +19,7 @@ const host = vi.hoisted(() => ({ client: null as unknown })) vi.mock('../../transport/connection/host-client-hooks', () => ({ useHostClient: () => ({ client: host.client, clientId: 'client-1', state: 'connected' }) })) -const lineage = vi.hoisted(() => ({ resolutions: 0 })) +const lineage = vi.hoisted(() => ({ resolutions: 0, keyed: 0, seen: new WeakSet() })) vi.mock('../../worktree/mobile-workspace-lineage', async (importOriginal) => { const actual = await importOriginal() return { @@ -32,6 +32,20 @@ vi.mock('../../worktree/mobile-workspace-lineage', async (importOriginal) => { } } }) +vi.mock('./mobile-folder-attached-worktrees', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + // Counts rows keyed for the first time: the per-row lineage work an update costs. + folderLineageKey: (row: Worktree) => { + if (!lineage.seen.has(row)) { + lineage.seen.add(row) + lineage.keyed += 1 + } + return actual.folderLineageKey(row) + } + } +}) function row(worktreeId: string, overrides: Partial = {}): Worktree { return { @@ -123,11 +137,22 @@ async function rowsChanged(fake: ReturnType, next: Worktree[ await settleQueryNotifications() } +function churn(rows: Worktree[]): void { + const h = rows.length + rows[1] = { ...rows[1], liveTerminalCount: 3, unread: true } + rows[h - 1] = { ...rows[h - 1], status: 'working' } + rows[h - 2] = { ...rows[h - 2], displayName: 'elsewhere', branch: 'other' } +} + +function rename(rows: Worktree[]): void { + rows[2] = { ...rows[2], displayName: 'renamed', branch: 'renamed-branch' } +} + describe.each([ { h: 750, n: 30 }, { h: 7_500, n: 300 } ])('folder membership over H=$h host rows, N=$n attached', ({ h, n }) => { - it('rebuilds lineage only when lineage or a shown label changes', async () => { + it('resolves lineage again only for lineage changes, keying only changed rows', async () => { vi.useFakeTimers({ toFake: ['Date'] }) const fake = catalogHost(catalog(h, n)) host.client = fake.client @@ -136,28 +161,44 @@ describe.each([ fake.emit({ type: 'ready' } as RuntimeClientEventStreamMessage) await settleQueryNotifications() expect(read.current?.worktrees).toHaveLength(n) - const members = read.current?.worktrees + const members = read.current!.worktrees lineage.resolutions = 0 + lineage.keyed = 0 - // Agent attention and terminal counts on unrelated rows and on members. + // Agent attention and terminal counts on a member and an unrelated row, and an unrelated rename. + await rowsChanged(fake, catalog(h, n, churn)) + expect(lineage.resolutions).toBe(0) + expect(lineage.keyed).toBe(3) + expect(read.current?.worktrees).toBe(members) + + // A member renamed: shown at once, without resolving lineage or touching the other members. + lineage.keyed = 0 await rowsChanged( fake, catalog(h, n, (rows) => { - rows[1] = { ...rows[1], liveTerminalCount: 3, unread: true } - rows[h - 1] = { ...rows[h - 1], status: 'working' } + churn(rows) + rename(rows) }) ) expect(lineage.resolutions).toBe(0) - expect(read.current?.worktrees).toBe(members) + expect(lineage.keyed).toBe(1) + const renamed = read.current!.worktrees + expect(renamed[1]).toMatchObject({ displayName: 'renamed', branch: 'renamed-branch' }) + expect(renamed.filter((member, index) => member !== members[index])).toHaveLength(1) - // A member renamed: the list must show it. + // A worktree attached: membership follows. await rowsChanged( fake, catalog(h, n, (rows) => { - rows[1] = { ...rows[1], displayName: 'renamed' } + churn(rows) + rename(rows) + rows[h - 1] = { + ...rows[h - 1], + workspaceLineage: { parentWorkspaceKey: 'folder:f-1', parentInstanceId: null } + } }) ) expect(lineage.resolutions).toBe(1) - expect(read.current?.worktrees.some((member) => member.displayName === 'renamed')).toBe(true) + expect(read.current?.worktrees).toHaveLength(n + 1) }) }) diff --git a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts index fb20466c610..65c918f077d 100644 --- a/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts +++ b/mobile/src/source-control/folder/use-mobile-folder-attached-worktrees.ts @@ -19,10 +19,30 @@ import type { ConnectionState } from '../../transport/connection/connection-stat import type { MobileRelayHost } from '../../../../src/shared/remote-runtime/relay/mobile-relay-hosts-contract' import { findFolderWorkspaceRow, + folderLineageKey, getFolderAttachedWorktrees, toFolderListRow, type FolderListRow } from './mobile-folder-attached-worktrees' +import type { Worktree } from '../../worktree/workspace-list-types' + +type FolderLineage = { + /** The catalog rows last seen. */ + source: readonly Worktree[] + /** The rows membership was resolved over; same lineage keys as `source`, in the same order. */ + rows: readonly Worktree[] + keys: readonly string[] +} + +const NO_ROWS: FolderListRow[] = [] + +// Reads each row's cached key: only rows the catalog replaced are keyed again. +function sameLineage(held: FolderLineage | null, rows: readonly Worktree[]): held is FolderLineage { + if (!held || held.keys.length !== rows.length) { + return false + } + return rows.every((row, index) => folderLineageKey(row) === held.keys[index]) +} const NO_CAPABILITIES: readonly string[] = [] const NO_SERVER_HOSTS: readonly MobileRelayHost[] = [] @@ -30,7 +50,7 @@ const NO_SERVER_HOSTS: readonly MobileRelayHost[] = [] export type MobileFolderAttachedWorktrees = { /** Undefined until the host's list is read; null when the list has no such folder. */ folder: FolderListRow | null | undefined - worktrees: FolderListRow[] + worktrees: readonly FolderListRow[] desktopCapabilities: readonly string[] /** The servers the desktop relays to, for rows it can't open. */ serverHosts: readonly MobileRelayHost[] @@ -75,31 +95,40 @@ export function useMobileFolderAttachedWorktrees( const ownRows = catalog.data?.worktrees const serverRows = servers.data?.worktrees const serverHosts = servers.data?.hosts - const projected = useMemo( - () => ownRows && [...ownRows, ...(serverRows ?? [])].map(toFolderListRow), + const allRows = useMemo( + () => ownRows && (serverRows?.length ? [...ownRows, ...serverRows] : ownRows), [ownRows, serverRows] ) - // Agent, terminal and badge updates rewrite rows constantly; keep the last projection while lineage and labels are unchanged. - const [held, setHeld] = useState({ source: projected, rows: projected }) - let rows = held.rows - if (held.source !== projected) { - rows = replaceEqualDeep(held.rows, projected) - setHeld({ source: projected, rows }) + // Agent, terminal and label updates rewrite rows constantly; membership is resolved again only when lineage moves. + const [lineage, setLineage] = useState(null) + let held = lineage + if (allRows && held?.source !== allRows) { + held = sameLineage(held, allRows) + ? { ...held, source: allRows } + : { source: allRows, rows: allRows, keys: allRows.map(folderLineageKey) } + setLineage(held) } + const lineageRows = held?.rows const serverRowsRead = serverRows !== undefined - const resolved = useMemo(() => { + const membership = useMemo(() => { // A server's folder is unknown, not missing, until its rows are read. - if (!rows || (executionHost && relays && !serverRowsRead)) { - return { folder: undefined, worktrees: [] } + if (!lineageRows || (executionHost && relays && !serverRowsRead)) { + return undefined + } + const folder = findFolderWorkspaceRow(lineageRows, folderWorktreeId, executionHost) + if (!folder) { + return null } - const folder = findFolderWorkspaceRow(rows, folderWorktreeId, executionHost) const stores: MobileLineageStores = { ownInstallationId, servers: serverHosts ?? [] } + const indexOf = new Map(lineageRows.map((row, index) => [row, index])) return { - folder: folder ?? null, - worktrees: folder ? getFolderAttachedWorktrees(rows, folder, stores) : [] + folderIndex: indexOf.get(folder)!, + memberIndexes: getFolderAttachedWorktrees(lineageRows, folder, stores).map((row) => + indexOf.get(row)! + ) } }, [ - rows, + lineageRows, serverRowsRead, serverHosts, folderWorktreeId, @@ -107,6 +136,30 @@ export function useMobileFolderAttachedWorktrees( ownInstallationId, relays ]) + // Same lineage means same row order, so the current rows supply the labels shown. + const currentRows = held?.source + const shown = useMemo( + () => + membership && currentRows + ? { + folder: toFolderListRow(currentRows[membership.folderIndex]), + worktrees: membership.memberIndexes.map((index) => toFolderListRow(currentRows[index])) + } + : null, + [membership, currentRows] + ) + const [heldShown, setHeldShown] = useState({ from: shown, value: shown }) + let stableShown = heldShown.value + if (heldShown.from !== shown) { + stableShown = replaceEqualDeep(heldShown.value, shown) + setHeldShown({ from: shown, value: stableShown }) + } + const resolved = + membership === undefined + ? { folder: undefined, worktrees: NO_ROWS } + : stableShown + ? stableShown + : { folder: null, worktrees: NO_ROWS } const refetchCatalog = catalog.refetch const refetchServers = servers.refetch return { diff --git a/mobile/src/source-control/mobile-git-status-query.ts b/mobile/src/source-control/mobile-git-status-query.ts index e7a852fbaa0..4ff40a1d89a 100644 --- a/mobile/src/source-control/mobile-git-status-query.ts +++ b/mobile/src/source-control/mobile-git-status-query.ts @@ -1,15 +1,17 @@ import * as z from 'zod' +import { hashKey, type QueryClient } from '@tanstack/react-query' import { translate } from '../i18n/mobile-i18n' import { LOCAL_EXECUTION_HOST_ID } from '../../../src/shared/execution-host' import { getRepoIdFromWorktreeId, worktreeIdsEqual } from '../../../src/shared/worktree/id' import { defineHostQuery, type HostSignalEvent } from '../query/host-query' -import type { HostQueryTarget } from '../query/host-query-key' +import { hostQueryKey, type HostQueryTarget } from '../query/host-query-key' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { gitStatusHostPayloadSchema, type MobileGitStatusHostPayload } from './git-status-reply-schema' import { gitStatusHostPayloadRead } from './mobile-git-read-operations' +import { holdsRestoredHostQueryData } from '../query/host-query-persistence' import { isMobileGitTransientRefreshError, isMobileGitUnavailableReply, @@ -119,3 +121,37 @@ export const serverGitStatusSummaryQuery = defineHostQuery({ refetchOnWindowFocus: true, fetch: fetchStatusSummary }) + +/** Hands a detailed read to the summary a folder list shows for the same worktree, so Back shows what an action just did. */ +export async function publishGitStatusSummary( + queryClient: QueryClient, + hostId: string, + target: HostQueryTarget, + read: GitStatusRead, + readAt: number +): Promise { + // An earlier launch's copy is unconfirmed; the summary's own read decides. + if ( + holdsRestoredHostQueryData( + queryClient, + hashKey(hostQueryKey(hostId, gitStatusQuery.family, target, {})) + ) + ) { + return + } + const summary = + target.exec === LOCAL_EXECUTION_HOST_ID ? gitStatusSummaryQuery : serverGitStatusSummaryQuery + const queryKey = hostQueryKey(hostId, summary.family, target, {}) + const state = queryClient.getQueryState(queryKey) + // No list reads this worktree, or its summary is newer than this read. + if (!state || state.dataUpdatedAt >= readAt) { + return + } + // A summary read already out started before this answer; landing later, it would undo it. + if (state.fetchStatus === 'fetching') { + await queryClient.cancelQueries({ queryKey, exact: true }, { silent: true }) + } + if ((queryClient.getQueryState(queryKey)?.dataUpdatedAt ?? 0) < readAt) { + queryClient.setQueryData(queryKey, read, { updatedAt: readAt }) + } +} diff --git a/mobile/src/source-control/use-mobile-source-control-loaders.ts b/mobile/src/source-control/use-mobile-source-control-loaders.ts index 26dca818647..ce2a82debfb 100644 --- a/mobile/src/source-control/use-mobile-source-control-loaders.ts +++ b/mobile/src/source-control/use-mobile-source-control-loaders.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef, useState, type MutableRefObject } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react' import { useQueryClient } from '@tanstack/react-query' import { useMobileTranslation } from '../i18n/use-mobile-translation' import type { MobileSourceControlSettings } from './mobile-source-control-settings-operations' @@ -16,7 +16,7 @@ import { readBranchCompareOutcome, type BranchCompareAttempt } from './mobile-branch-compare-outcome' -import { gitStatusQuery } from './mobile-git-status-query' +import { gitStatusQuery, publishGitStatusSummary } from './mobile-git-status-query' import type { LoadStatusOptions, MobileBranchCompareState, @@ -103,6 +103,12 @@ export function useMobileSourceControlLoaders(params: Params): MobileSourceContr enabled: statusEnabled, subscribed: focused }) + const { data: publishedRead, dataUpdatedAt: publishedAt } = statusQuery + useEffect(() => { + if (publishedRead) { + void publishGitStatusSummary(queryClient, hostId, target, publishedRead, publishedAt) + } + }, [hostId, publishedAt, publishedRead, queryClient, target]) const mountedRef = useRef(true) const setRootRef = useCallback((node: View | null): void => { // Invalidate route-detached RPC writes without waiting for passive cleanup.