From 0d8d60aa13311b6fbbae224acf331fe1ccd0f0c3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:20:53 -0800 Subject: [PATCH] fix(mobile): folder summary skips restored and cached reads that could undo newer ones Persisted status is marked restored before anyone hears of it, so a child screen never hands an earlier launch's status to the folder list. A cached read caught up on opening writes only an idle summary and never cancels one in flight. Perf contracts count real lineage serializations, committed row renders and summary publications. --- .../src/query/host-query-persistence.test.ts | 31 +- mobile/src/query/host-query-persistence.ts | 5 +- .../folder/folder-lineage-serialization.ts | 19 ++ .../mobile-folder-attached-worktrees.ts | 18 +- .../use-folder-worktree-status.perf.test.ts | 15 +- ...ile-folder-attached-worktrees.perf.test.ts | 72 +++-- .../source-control/mobile-git-status-query.ts | 12 +- .../use-mobile-source-control-loaders.test.ts | 286 +++++++++++++++--- .../use-mobile-source-control-loaders.ts | 15 +- 9 files changed, 387 insertions(+), 86 deletions(-) create mode 100644 mobile/src/source-control/folder/folder-lineage-serialization.ts diff --git a/mobile/src/query/host-query-persistence.test.ts b/mobile/src/query/host-query-persistence.test.ts index 2095297f0c4..b3013f6c8ae 100644 --- a/mobile/src/query/host-query-persistence.test.ts +++ b/mobile/src/query/host-query-persistence.test.ts @@ -2,7 +2,12 @@ import { QueryClient } from '@tanstack/react-query' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcaQueryStoreBackend } from '../device-store/query-storage' import { hostWorktreeCatalogKey, hostWorktreeCatalogQuery } from '../host-screen/host-list-queries' -import { createHostQueryPersistence, persistedHostQueryKey } from './host-query-persistence' +import { + createHostQueryPersistence, + holdsRestoredHostQueryData, + persistedHostQueryKey +} from './host-query-persistence' +import { hashKey } from '@tanstack/react-query' vi.mock('react-native', () => ({ AppState: {} })) @@ -119,4 +124,28 @@ describe('createHostQueryPersistence', () => { expect(relaunched.getQueryData(key)).toBe(live) }) + + it("marks restored data as an earlier launch's before anyone hears of it, until a newer answer", async () => { + const store = memoryStore('host-a') + await storeFromEarlierLaunch(store, [liveRow]) + + const relaunched = new QueryClient() + const persistence = createHostQueryPersistence(relaunched, store.backend) + relaunched.getQueryCache().build(relaunched, { + queryKey: key, + meta: { persist: hostWorktreeCatalogQuery.persist } + }) + const heard: boolean[] = [] + relaunched.getQueryCache().subscribe((event) => { + if (event.type === 'updated' && event.action.type === 'success') { + heard.push(holdsRestoredHostQueryData(relaunched, hashKey(key))) + } + }) + const restoring = persistence.restore(firstPaint) + await vi.runAllTimersAsync() + await restoring + relaunched.setQueryData(key, { snapshotId: 'snap-8', worktrees: [liveRow] }) + + expect(heard).toEqual([true, false]) + }) }) diff --git a/mobile/src/query/host-query-persistence.ts b/mobile/src/query/host-query-persistence.ts index 9edf0f556df..a11a8cdc6bf 100644 --- a/mobile/src/query/host-query-persistence.ts +++ b/mobile/src/query/host-query-persistence.ts @@ -204,8 +204,9 @@ export function createHostQueryPersistence( if (queryClient.getQueryData(queryKey) === undefined) { const { data, dataUpdatedAt } = record.state settledAt.set(queryHash, dataUpdatedAt) - queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) + // Marked first: listeners told of this write must already see it as an earlier launch's. restored.add(queryHash) + queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) } settle() }) @@ -252,12 +253,12 @@ export function createHostQueryPersistence( if (event.type !== 'updated' || event.action.type !== 'success') { return } - restored.delete(query.queryHash) const family = familyOf(query.queryKey) const at = query.state.dataUpdatedAt if (family === null || at <= (settledAt.get(query.queryHash) ?? 0)) { return } + restored.delete(query.queryHash) settledAt.set(query.queryHash, at) void persisterFor(family, persist).persistQuery(query) }) diff --git a/mobile/src/source-control/folder/folder-lineage-serialization.ts b/mobile/src/source-control/folder/folder-lineage-serialization.ts new file mode 100644 index 00000000000..fc4a7f686bb --- /dev/null +++ b/mobile/src/source-control/folder/folder-lineage-serialization.ts @@ -0,0 +1,19 @@ +import type { Worktree } from '../../worktree/workspace-list-types' + +/** The fields folder membership and order depend on; labels and agent state are left out so their churn rebuilds nothing. */ +export function serializeFolderLineage(row: Worktree): string { + return 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 + ]) +} 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 a153ac8f342..5fbae1707b5 100644 --- a/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts +++ b/mobile/src/source-control/folder/mobile-folder-attached-worktrees.ts @@ -6,6 +6,7 @@ import { type MobileLineageStores } from '../../worktree/mobile-workspace-lineage' import { getWorktreeRowIdentity } from '../../worktree/worktree-host-row-identity' +import { serializeFolderLineage } from './folder-lineage-serialization' /** What a folder list row shows of a host row. */ export type FolderListRow = Pick< @@ -19,24 +20,11 @@ type FolderLineageRow = MobileLineageRow & Pick 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. */ +/** A row's lineage key, serialized once per row object. */ 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 - ]) + key = serializeFolderLineage(row) lineageKeys.set(row, key) } return key 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 f94eb4509ab..d6e9e942e12 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 @@ -194,10 +194,19 @@ describe.each([ status: { ...listed.data.status, branch: 'after' } } const target = { exec: opened.routeHost!, worktree: opened.worktreeId } - await act(() => publishGitStatusSummary(queryClient!, 'host-1', target, after, Date.now())) + await act(() => + publishGitStatusSummary(queryClient!, 'host-1', target, after, Date.now(), true) + ) // A detailed read older than the summary changes nothing. await act(() => - publishGitStatusSummary(queryClient!, 'host-1', target, listed.data!, listed.updatedAt - 1) + publishGitStatusSummary( + queryClient!, + 'host-1', + target, + listed.data!, + listed.updatedAt - 1, + true + ) ) // Back within three seconds, then well past them with no focus or signal. @@ -232,7 +241,7 @@ describe.each([ ) await act(() => - publishGitStatusSummary(queryClient!, 'host-1', target, listed.data!, cachedDetailAt) + publishGitStatusSummary(queryClient!, 'host-1', target, listed.data!, cachedDetailAt, true) ) expect(queryClient!.getQueryState(key)?.error).toBe(failure) }) 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 6b5482c6ad8..e57c5382c35 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 @@ -1,4 +1,4 @@ -import { createElement } from 'react' +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' @@ -18,6 +18,7 @@ import { useMobileFolderAttachedWorktrees, type MobileFolderAttachedWorktrees } from './use-mobile-folder-attached-worktrees' +import { MobileFolderWorktreeRow } from './MobileFolderWorktreeRow' vi.mock('react-native', () => ({ AppState: {} })) const gates = vi.hoisted(() => ({ hostCapabilities: [] as string[] })) @@ -28,7 +29,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, keyed: 0, seen: new WeakSet() })) +const lineage = vi.hoisted(() => ({ resolutions: 0, serialized: 0, rowCommits: 0 })) vi.mock('../../worktree/mobile-workspace-lineage', async (importOriginal) => { const actual = await importOriginal() return { @@ -41,20 +42,32 @@ vi.mock('../../worktree/mobile-workspace-lineage', async (importOriginal) => { } } }) -vi.mock('./mobile-folder-attached-worktrees', async (importOriginal) => { - const actual = await importOriginal() +// Runs behind the production key cache, so each call is a row serialized. +vi.mock('./folder-lineage-serialization', 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) + serializeFolderLineage: (row: Worktree) => { + lineage.serialized += 1 + return actual.serializeFolderLineage(row) } } }) +// Inside the production row's memo boundary: each call is a committed row render. +vi.mock('../../components/list/ListGroup', () => ({ + ListRow: () => { + lineage.rowCommits += 1 + return null + } +})) +vi.mock('./use-folder-worktree-status', () => ({ + useFolderWorktreeStatus: () => NO_STATUS +})) +vi.mock('../../i18n/use-mobile-translation', () => ({ + useMobileTranslation: () => (_key: string, fallback: string) => fallback +})) +const NO_STATUS = vi.hoisted(() => ({ data: undefined, error: null })) +const REFRESHERS = new Set<() => void>() +const NOOP = (): void => {} function row(worktreeId: string, overrides: Partial = {}): Worktree { return { @@ -131,10 +144,26 @@ afterEach(async () => { let queryClient: QueryClient | null = null async function mount(read: { current: MobileFolderAttachedWorktrees | null }) { - function Harness(): null { + function Harness() { queryClient = useQueryClient() - read.current = useMobileFolderAttachedWorktrees('host-1', 'folder:f-1', true) - return null + const folder = useMobileFolderAttachedWorktrees('host-1', 'folder:f-1', true) + read.current = folder + return createElement( + Fragment, + null, + folder.worktrees.map((worktree) => + createElement(MobileFolderWorktreeRow, { + key: worktree.worktreeId, + hostId: 'host-1', + desktopCapabilities: folder.desktopCapabilities, + worktree, + unreachable: false, + subscribed: true, + refreshers: REFRESHERS, + onOpen: NOOP + }) + ) + ) } await act(async () => { renderer = create(queries.wrap(createElement(Harness))) @@ -165,7 +194,7 @@ describe.each([ { h: 750, n: 30 }, { h: 7_500, n: 300 } ])('folder membership over H=$h host rows, N=$n attached', ({ h, n }) => { - it('resolves lineage again only for lineage changes, keying only changed rows', async () => { + it('resolves lineage only for lineage changes, serializing and committing only changed rows', async () => { vi.useFakeTimers({ toFake: ['Date'] }) const fake = catalogHost(catalog(h, n)) host.client = fake.client @@ -176,16 +205,18 @@ describe.each([ expect(read.current?.worktrees).toHaveLength(n) const members = read.current!.worktrees lineage.resolutions = 0 - lineage.keyed = 0 + lineage.serialized = 0 + lineage.rowCommits = 0 // 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(lineage.serialized).toBe(3) + expect(lineage.rowCommits).toBe(0) expect(read.current?.worktrees).toBe(members) // A member renamed: shown at once, without resolving lineage or touching the other members. - lineage.keyed = 0 + lineage.serialized = 0 await rowsChanged( fake, catalog(h, n, (rows) => { @@ -194,7 +225,8 @@ describe.each([ }) ) expect(lineage.resolutions).toBe(0) - expect(lineage.keyed).toBe(1) + expect(lineage.serialized).toBe(1) + expect(lineage.rowCommits).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) diff --git a/mobile/src/source-control/mobile-git-status-query.ts b/mobile/src/source-control/mobile-git-status-query.ts index a6c65d468fa..986a262e7f1 100644 --- a/mobile/src/source-control/mobile-git-status-query.ts +++ b/mobile/src/source-control/mobile-git-status-query.ts @@ -128,7 +128,9 @@ export async function publishGitStatusSummary( hostId: string, target: HostQueryTarget, read: GitStatusRead, - readAt: number + readAt: number, + /** A read accepted now; otherwise a cached one, which can't tell whether a summary read out started before it. */ + accepted: boolean ): Promise { // An earlier launch's copy is unconfirmed; the summary's own read decides. if ( @@ -150,8 +152,12 @@ export async function publishGitStatusSummary( if (!supersedes()) { return } - // A summary read already out started before this answer; landing later, it would undo it. - if (queryClient.getQueryState(queryKey)?.fetchStatus === 'fetching') { + if (queryClient.getQueryState(queryKey)?.fetchStatus !== 'idle') { + // A cached read leaves a summary read out to answer for itself. + if (!accepted) { + return + } + // A summary read out started before this answer; landing later, it would undo it. await queryClient.cancelQueries({ queryKey, exact: true }, { silent: true }) } if (supersedes()) { diff --git a/mobile/src/source-control/use-mobile-source-control-loaders.test.ts b/mobile/src/source-control/use-mobile-source-control-loaders.test.ts index 45a30be6bc3..329733196d4 100644 --- a/mobile/src/source-control/use-mobile-source-control-loaders.test.ts +++ b/mobile/src/source-control/use-mobile-source-control-loaders.test.ts @@ -1,5 +1,5 @@ import { createElement } from 'react' -import { useQueryClient, type QueryClient } from '@tanstack/react-query' +import { hashKey, QueryClientProvider, type QueryClient } from '@tanstack/react-query' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' @@ -10,7 +10,16 @@ import { useMobileSourceControlLoaders } from './use-mobile-source-control-loade import { stubRpcClient } from '../transport/rpc/rpc-client-test-stub' import { prefetchHostQuery } from '../query/host-query' import { hostQueryKey } from '../query/host-query-key' -import { gitStatusSummaryQuery, serverGitStatusSummaryQuery } from './mobile-git-status-query' +import { + gitStatusQuery, + gitStatusSummaryQuery, + serverGitStatusSummaryQuery, + type GitStatusRead +} from './mobile-git-status-query' +import { gitStatusHostPayloadSchema } from './git-status-reply-schema' +import { createOrcaQueryClient } from '../query/orca-query-client' +import { createHostQueryPersistence } from '../query/host-query-persistence' +import type { OrcaQueryStoreBackend } from '../device-store/query-storage' import { documentQueryClient, @@ -185,29 +194,69 @@ describe('useMobileSourceControlLoaders branch compare', () => { describe('useMobileSourceControlLoaders status summary', () => { let renderer: ReactTestRenderer | null = null - const queries = documentQueryClient() + let queryClient: QueryClient | null = null afterEach(async () => { act(() => renderer?.unmount()) renderer = null - await queries.end() + await queryClient?.cancelQueries() + queryClient?.clear() + queryClient = null vi.useRealTimers() }) + const local = { exec: 'local' as const, worktree: WORKTREE } + const summaryKey = hostQueryKey('host-1', gitStatusSummaryQuery.family, local, {}) + const detailKey = hostQueryKey('host-1', gitStatusQuery.family, local, {}) + function statusReply(branch: string): RpcResponse { return success({ branch, head: `${branch}-oid`, entries: [] }) } - it("hands each status read to the folder list's summary of the same worktree, and only that one", async () => { - vi.useFakeTimers({ toFake: ['Date'] }) - const calls: PendingCall[] = [] + function readOf(branch: string): GitStatusRead { + return { + kind: 'ready', + status: gitStatusHostPayloadSchema.parse({ branch, head: `${branch}-oid`, entries: [] }) + } + } + + // Summary reads skip line stats; the screen's own read asks for them. + function takeRead(calls: PendingCall[], summary: boolean): PendingCall { + const index = calls.findIndex( + (call) => + call.method === 'git.status' && + ((call.params as { includeLineStats?: boolean }).includeLineStats === false) === summary + ) + if (index === -1) { + throw new Error(`The schedule expected a pending ${summary ? 'summary' : 'status'} read`) + } + return calls.splice(index, 1)[0] + } + + function setup(calls: PendingCall[]) { const client = fakeClient(calls) + const documentClient = createOrcaQueryClient() + queryClient = documentClient + // Successful writes to each summary entry: its own reads and publications. + const summaryWrites = new Map() + documentClient.getQueryCache().subscribe((event) => { + const family = event.query.queryKey[2] + if ( + event.type === 'updated' && + event.action.type === 'success' && + typeof family === 'string' && + family.startsWith('git.statusSummary') + ) { + summaryWrites.set( + event.query.queryHash, + (summaryWrites.get(event.query.queryHash) ?? 0) + 1 + ) + } + }) const read: { loaders: ReturnType | null } = { loaders: null } - let queryClient: QueryClient | null = null function Harness(): null { - queryClient = useQueryClient() read.loaders = useMobileSourceControlLoaders({ hostId: 'host-1', client, @@ -218,35 +267,50 @@ describe('useMobileSourceControlLoaders status summary', () => { }) return null } - await act(async () => { - renderer = create(queries.wrap(createElement(Harness))) - }) - const local = { exec: 'local' as const, worktree: WORKTREE } - const summaryKey = hostQueryKey('host-1', gitStatusSummaryQuery.family, local, {}) + return { + client, + queryClient: documentClient, + read, + writesTo: (key: readonly unknown[]) => summaryWrites.get(hashKey(key)) ?? 0, + clearWrites: () => summaryWrites.clear(), + readSummary: () => + void prefetchHostQuery( + documentClient, + gitStatusSummaryQuery, + { hostId: 'host-1', client }, + local, + {} + ), + mount: async () => { + await act(async () => { + renderer = create( + createElement(QueryClientProvider, { client: documentClient }, createElement(Harness)) + ) + }) + } + } + } + + it('hands each accepted status read to the matching summary once, over an earlier summary read', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const calls: PendingCall[] = [] + const child = setup(calls) // The same worktree id on a relayed server keeps its own summary. - const elsewhere = { exec: 'runtime:env-1' as const, worktree: WORKTREE } - const elsewhereKey = hostQueryKey('host-1', serverGitStatusSummaryQuery.family, elsewhere, {}) - const elsewhereData = { kind: 'unavailable' as const } - queryClient!.setQueryData(elsewhereKey, elsewhereData) - // The folder list's summary read is out when the screen's own read lands. - void prefetchHostQuery( - queryClient!, - gitStatusSummaryQuery, - { hostId: 'host-1', client }, - local, + const elsewhereKey = hostQueryKey( + 'host-1', + serverGitStatusSummaryQuery.family, + { exec: 'runtime:env-1', worktree: WORKTREE }, {} ) - // Summary reads skip line stats. - const summaryRead = calls.findIndex( - (call) => - call.method === 'git.status' && - (call.params as { includeLineStats?: boolean }).includeLineStats === false - ) - const [stale] = calls.splice(summaryRead, 1) + const elsewhereData = { kind: 'unavailable' as const } + child.queryClient.setQueryData(elsewhereKey, elsewhereData) + child.clearWrites() + await child.mount() + child.readSummary() + const stale = takeRead(calls, true) + const screenRead = takeRead(calls, false) // Landing just after the screen's read, the earlier summary read must not undo it. - const opened = calls.findIndex((call) => call.method === 'git.status') - const [screenRead] = calls.splice(opened, 1) await act(async () => { screenRead.settle(statusReply('opened')) for (let i = 0; i < 20; i++) { @@ -256,18 +320,164 @@ describe('useMobileSourceControlLoaders status summary', () => { stale.settle(statusReply('before')) }) await settleQueryNotifications() - expect(queryClient!.getQueryData(summaryKey)).toMatchObject({ status: { branch: 'opened' } }) + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'opened' } + }) + expect(child.writesTo(summaryKey)).toBe(1) // An action's forced reread. - const reread = read.loaders!.loadStatus({ force: true }) + const reread = child.read.loaders!.loadStatus({ force: true }) await settleQueryNotifications() - await settleOldest(calls, 'git.status', statusReply('after')) + await act(async () => takeRead(calls, false).settle(statusReply('after'))) await act(async () => { await reread }) await settleQueryNotifications() - expect(queryClient!.getQueryData(summaryKey)).toMatchObject({ status: { branch: 'after' } }) - expect(queryClient!.getQueryData(elsewhereKey)).toBe(elsewhereData) + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'after' } + }) + expect(child.writesTo(summaryKey)).toBe(2) + expect(child.queryClient.getQueryData(elsewhereKey)).toBe(elsewhereData) + expect(child.writesTo(elsewhereKey)).toBe(0) + expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) + }) + + // Summary read at 100, detail cached at 200, child opened at 400. + async function cachedDetailOpened(refreshAt300: boolean) { + vi.useFakeTimers({ toFake: ['Date'], now: 100 }) + const calls: PendingCall[] = [] + const child = setup(calls) + child.queryClient.setQueryData(summaryKey, readOf('first'), { updatedAt: 100 }) + vi.setSystemTime(200) + child.queryClient.setQueryData(detailKey, readOf('cached'), { updatedAt: 200 }) + vi.setSystemTime(300) + if (refreshAt300) { + await child.queryClient.invalidateQueries({ queryKey: summaryKey }, { cancelRefetch: false }) + child.readSummary() + } + child.clearWrites() + vi.setSystemTime(400) + await child.mount() + await settleQueryNotifications() + return { calls, child } + } + + it('leaves a summary read out to answer when the child opens over an older cached read', async () => { + const { calls, child } = await cachedDetailOpened(true) + expect(child.writesTo(summaryKey)).toBe(0) + await act(async () => takeRead(calls, true).settle(statusReply('refresh'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'refresh' } + }) + }) + + it('catches an idle older summary up to the cached read once, keeping its time', async () => { + const { calls, child } = await cachedDetailOpened(false) + expect(child.writesTo(summaryKey)).toBe(1) + expect(child.queryClient.getQueryData(summaryKey)).toEqual(readOf('cached')) + expect(child.queryClient.getQueryState(summaryKey)?.dataUpdatedAt).toBe(200) + expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) + }) + + it("never hands an earlier launch's status to the summary, nor cancels its live read", async () => { + const store = memoryStore() + const earlier = createOrcaQueryClient() + const earlierPersistence = createHostQueryPersistence(earlier, store.backend) + earlier.getQueryCache().build(earlier, { + queryKey: detailKey, + meta: { persist: gitStatusQuery.persist } + }) + earlier.setQueryData(detailKey, readOf('saved'), { updatedAt: Date.now() - 86_400_000 }) + await settleQueryNotifications() + await earlierPersistence.flush() + expect(store.rows.size).toBe(1) + earlier.clear() + + const calls: PendingCall[] = [] + const child = setup(calls) + createHostQueryPersistence(child.queryClient, store.backend) + child.readSummary() + const release = store.holdReads() + await child.mount() + release() + await settleQueryNotifications() + expect(child.queryClient.getQueryData(detailKey)).toEqual(readOf('saved')) + expect(child.writesTo(summaryKey)).toBe(0) + + await act(async () => takeRead(calls, true).settle(statusReply('live'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ status: { branch: 'live' } }) + + await act(async () => takeRead(calls, false).settle(statusReply('newer'))) + await settleQueryNotifications() + expect(child.queryClient.getQueryData(summaryKey)).toMatchObject({ + status: { branch: 'newer' } + }) + expect(child.writesTo(summaryKey)).toBe(2) + }) + + it.each([10, 100])('touches one summary of N=%i listed beside it', async (n) => { + vi.useFakeTimers({ toFake: ['Date'] }) + const calls: PendingCall[] = [] + const child = setup(calls) + const others = Array.from({ length: n }, (_, i) => [ + hostQueryKey( + 'host-1', + gitStatusSummaryQuery.family, + { exec: 'local', worktree: `repo42::/o${i}` }, + {} + ), + hostQueryKey( + 'host-1', + serverGitStatusSummaryQuery.family, + { exec: `runtime:env-${i}`, worktree: WORKTREE }, + {} + ) + ]).flat() + for (const key of [summaryKey, ...others]) { + child.queryClient.setQueryData(key, readOf('first')) + } + child.clearWrites() + vi.setSystemTime(Date.now() + 1) + await child.mount() + await act(async () => takeRead(calls, false).settle(statusReply('opened'))) + await settleQueryNotifications() + expect(child.writesTo(summaryKey)).toBe(1) + expect(others.filter((key) => child.writesTo(key) > 0)).toHaveLength(0) expect(calls.filter((call) => call.method === 'git.status')).toHaveLength(0) }) }) + +function memoryStore() { + const rows = new Map() + let readGate: Promise = Promise.resolve() + const backend: OrcaQueryStoreBackend = { + hostId: 'host-1', + read: async (keys) => { + await readGate + return { status: 'ok', values: keys.map((storeKey) => rows.get(storeKey) ?? null) } + }, + write: async (ops) => { + for (const op of ops) { + if (op.value === null) { + rows.delete(op.key) + } else { + rows.set(op.key, op.value) + } + } + return { written: true } + } + } + return { + backend, + rows, + holdReads: () => { + let release = (): void => {} + readGate = new Promise((resolve) => { + release = resolve + }) + return release + } + } +} 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 3b2986fbd37..48a36a09c1b 100644 --- a/mobile/src/source-control/use-mobile-source-control-loaders.ts +++ b/mobile/src/source-control/use-mobile-source-control-loaders.ts @@ -112,20 +112,27 @@ export function useMobileSourceControlLoaders(params: Params): MobileSourceContr useEffect(() => { const statusKey = hostQueryKey(hostId, gitStatusQuery.family, target, NO_INPUT) const statusHash = hashKey(statusKey) - const publish = () => { + const publish = (accepted: boolean) => { const state = queryClient.getQueryState(statusKey) if (state?.data) { - void publishGitStatusSummary(queryClient, hostId, target, state.data, state.dataUpdatedAt) + void publishGitStatusSummary( + queryClient, + hostId, + target, + state.data, + state.dataUpdatedAt, + accepted + ) } } - publish() + publish(false) return queryClient.getQueryCache().subscribe((event) => { if ( event.type === 'updated' && event.action.type === 'success' && event.query.queryHash === statusHash ) { - publish() + publish(true) } }) }, [hostId, queryClient, target])