diff --git a/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.test.ts b/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.test.ts new file mode 100644 index 00000000000..ef107966f07 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.test.ts @@ -0,0 +1,126 @@ +import { EventEmitter } from 'node:events' +import type { IpcMainInvokeEvent } from 'electron' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createSenderScopedRequestCancellations } from '../sender-scoped-request-cancellation' +import type { FilesystemHandlerContext } from './filesystem-handler-context' + +const { handlers, readAtRiskMock } = vi.hoisted(() => ({ + handlers: new Map unknown>(), + readAtRiskMock: vi.fn() +})) + +vi.mock('electron', () => ({ + ipcMain: { + handle: (channel: string, handler: (event: IpcMainInvokeEvent, args: unknown) => unknown) => { + handlers.set(channel, handler) + } + } +})) +vi.mock('../../providers/execution-host-provider-dispatch', () => ({ + requireReachableGitRoute: vi.fn() +})) +vi.mock('./wsl-gated-worktree-git-read', () => ({ + readWorktreeGitUnlessWslStopped: ( + _store: unknown, + worktreePath: string, + _wake: unknown, + read: (path: string, gitOptions: { wslDistro?: string }) => Promise + ) => read(worktreePath, { wslDistro: undefined }) +})) +vi.mock('../local-worktree-runtime-options', () => ({ + getLocalRepoForRegisteredWorktree: vi.fn(() => ({ path: '/repo' })) +})) +vi.mock('../../git/worktrees/removal/worktree-at-risk-local-files', () => ({ + readWorktreeAtRiskLocalFiles: readAtRiskMock +})) + +import { registerFilesystemGitAtRiskLocalFilesHandlers } from './filesystem-git-at-risk-local-files-handlers' + +function requestEvent(id = 1): IpcMainInvokeEvent { + const sender = Object.assign(new EventEmitter(), { id }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the cancellation registry only reads sender.id and its EventEmitter lifetime methods. + return { sender } as unknown as IpcMainInvokeEvent +} + +function invoke(channel: string, event: IpcMainInvokeEvent, args: unknown): unknown { + const handler = handlers.get(channel) + if (!handler) { + throw new Error(`no handler for ${channel}`) + } + return handler(event, args) +} + +describe('git:atRiskLocalFiles cancellation', () => { + beforeEach(() => { + handlers.clear() + readAtRiskMock.mockReset() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these handlers only read store and the git status cancellation registry. + const context = { + store: {}, + gitStatusCancellations: createSenderScopedRequestCancellations() + } as unknown as FilesystemHandlerContext + registerFilesystemGitAtRiskLocalFilesHandlers(context) + }) + + it('aborts the scan when the renderer cancels its request token', async () => { + let scanSignal: AbortSignal | undefined + readAtRiskMock.mockImplementation( + (args: { gitOptions?: { signal?: AbortSignal } }) => + new Promise((_resolve, reject) => { + scanSignal = args.gitOptions?.signal + scanSignal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) + }) + ) + const event = requestEvent() + + const scan = invoke('git:atRiskLocalFiles', event, { + worktreePath: '/repo-feature', + requestToken: 'at-risk-1' + }) + await vi.waitFor(() => expect(readAtRiskMock).toHaveBeenCalled()) + expect(scanSignal?.aborted).toBe(false) + + await invoke('git:cancelAtRiskLocalFiles', event, { + requestToken: 'at-risk-1' + }) + + expect(scanSignal?.aborted).toBe(true) + await expect(scan).rejects.toThrow('aborted') + }) + + it('does not let another window cancel the scan', async () => { + let scanSignal: AbortSignal | undefined + let startScan!: () => void + const scanStarted = new Promise((resolve) => { + startScan = resolve + }) + readAtRiskMock.mockImplementation( + (args: { gitOptions?: { signal?: AbortSignal } }) => + new Promise((_resolve, reject) => { + scanSignal = args.gitOptions?.signal + scanSignal?.addEventListener('abort', () => reject(new Error('aborted')), { once: true }) + startScan() + }) + ) + const owner = requestEvent(1) + + const scan = invoke('git:atRiskLocalFiles', owner, { + worktreePath: '/repo-feature', + requestToken: 'at-risk-1' + }) + const cancelled = expect(scan).rejects.toThrow('aborted') + await scanStarted + await invoke('git:cancelAtRiskLocalFiles', requestEvent(2), { + requestToken: 'at-risk-1' + }) + + const abortedByOtherWindow = scanSignal?.aborted + await invoke('git:cancelAtRiskLocalFiles', owner, { + requestToken: 'at-risk-1' + }) + + expect(scanSignal?.aborted).toBe(true) + await cancelled + expect(abortedByOtherWindow).toBe(false) + }) +}) diff --git a/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.ts b/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.ts new file mode 100644 index 00000000000..d239eccb004 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-git-at-risk-local-files-handlers.ts @@ -0,0 +1,51 @@ +import { ipcMain } from 'electron' +import { readWorktreeAtRiskLocalFiles } from '../../git/worktrees/removal/worktree-at-risk-local-files' +import type { WorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files' +import { getLocalRepoForRegisteredWorktree } from '../local-worktree-runtime-options' +import { requireReachableGitRoute } from '../../providers/execution-host-provider-dispatch' +import { getConnectionExecutionHostId } from '../../../shared/execution-host' +import type { FilesystemHandlerContext } from './filesystem-handler-context' +import { readWorktreeGitUnlessWslStopped } from './wsl-gated-worktree-git-read' + +/** Delete-preview ignored-file scans; a closed or retargeted preview cancels its queued or running scan. */ +export function registerFilesystemGitAtRiskLocalFilesHandlers( + context: FilesystemHandlerContext +): void { + // Request tokens are unique per scan, so these share the sender-scoped status registry. + const { store, gitStatusCancellations: cancellations } = context + ipcMain.handle( + 'git:atRiskLocalFiles', + async ( + event, + args: { + worktreePath: string + connectionId?: string + requestToken?: string + } + ): Promise => { + const controller = cancellations.begin(event, args.requestToken) + try { + requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) + return await readWorktreeGitUnlessWslStopped( + store, + args.worktreePath, + false, + (worktreePath, gitOptions) => + readWorktreeAtRiskLocalFiles({ + worktreePath, + mainCheckoutPath: + getLocalRepoForRegisteredWorktree(store, args.worktreePath, worktreePath)?.path ?? + null, + gitOptions: controller ? { ...gitOptions, signal: controller.signal } : gitOptions + }) + ) + } finally { + cancellations.finish(event, args.requestToken, controller) + } + } + ) + + ipcMain.handle('git:cancelAtRiskLocalFiles', (event, args: { requestToken: string }): void => { + cancellations.cancel(event, args.requestToken) + }) +} diff --git a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts index 81779a5a33b..495556f449b 100644 --- a/src/main/ipc/filesystem/filesystem-git-status-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-git-status-handlers.ts @@ -16,11 +16,10 @@ import { } from '../../git/source-control/mutations/git-conflict-operation' import { getDiff } from '../../git/source-control/diffs/file-diff' import { registerFilesystemGitHistoryHandlers } from './filesystem-git-history-handlers' +import { registerFilesystemGitAtRiskLocalFilesHandlers } from './filesystem-git-at-risk-local-files-handlers' import { isGitWorktreeMutationInFlight } from '../../git/command-runner/git-worktree-mutation-state' import type { GitMutationInFlight } from '../../../shared/git/commands/git-mutation-in-flight' import { checkIgnoredPaths } from '../../git/source-control/ignores/check-ignored-paths' -import { readWorktreeAtRiskLocalFiles } from '../../git/worktrees/removal/worktree-at-risk-local-files' -import type { WorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files' import { appendFolderToGitignore, findKnownHugeFolderPathsToIgnore @@ -48,6 +47,7 @@ import { export function registerFilesystemGitStatusHandlers(context: FilesystemHandlerContext): void { const { store, gitStatusCancellations } = context registerFilesystemGitHistoryHandlers(context) + registerFilesystemGitAtRiskLocalFilesHandlers(context) ipcMain.handle( 'git:status', async ( @@ -173,29 +173,6 @@ export function registerFilesystemGitStatusHandlers(context: FilesystemHandlerCo } ) - ipcMain.handle( - 'git:atRiskLocalFiles', - async ( - _event, - args: { worktreePath: string; connectionId?: string } - ): Promise => { - requireReachableGitRoute(getConnectionExecutionHostId(args.connectionId)) - return readWorktreeGitUnlessWslStopped( - store, - args.worktreePath, - false, - (worktreePath, gitOptions) => - readWorktreeAtRiskLocalFiles({ - worktreePath, - mainCheckoutPath: - getLocalRepoForRegisteredWorktree(store, args.worktreePath, worktreePath)?.path ?? - null, - gitOptions - }) - ) - } - ) - ipcMain.handle( 'git:findHugeFoldersToIgnore', async (_event, args: { worktreePath: string }): Promise => diff --git a/src/preload/api/source-control/git-bridge.ts b/src/preload/api/source-control/git-bridge.ts index f3cd0546596..a421e77b9ee 100644 --- a/src/preload/api/source-control/git-bridge.ts +++ b/src/preload/api/source-control/git-bridge.ts @@ -54,7 +54,10 @@ export const gitApi = { atRiskLocalFiles: (args: { worktreePath: string connectionId?: string + requestToken?: string }): Promise => ipcRenderer.invoke('git:atRiskLocalFiles', args), + cancelAtRiskLocalFiles: (args: { requestToken: string }): Promise => + ipcRenderer.invoke('git:cancelAtRiskLocalFiles', args), findHugeFoldersToIgnore: (args: { worktreePath: string }): Promise => ipcRenderer.invoke('git:findHugeFoldersToIgnore', args), appendGitignore: (args: { worktreePath: string; folderName: string }): Promise => diff --git a/src/preload/api/source-control/git-inspection-api.ts b/src/preload/api/source-control/git-inspection-api.ts index 32fefdd910b..dbe0e49f0d3 100644 --- a/src/preload/api/source-control/git-inspection-api.ts +++ b/src/preload/api/source-control/git-inspection-api.ts @@ -60,7 +60,10 @@ export type GitInspectionApi = { atRiskLocalFiles: (args: { worktreePath: string connectionId?: string + /** Lets cancelAtRiskLocalFiles stop the scan once its preview closes. */ + requestToken?: string }) => Promise + cancelAtRiskLocalFiles: (args: { requestToken: string }) => Promise findHugeFoldersToIgnore: (args: { worktreePath: string }) => Promise refs: (args: { worktreePath: string diff --git a/src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts b/src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts index 36f2a88eaff..ee745b3a160 100644 --- a/src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts +++ b/src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts @@ -1,5 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getRuntimeGitStatus } from './runtime-git-status-client' +import { + getRuntimeGitStatus, + getRuntimeWorktreeAtRiskLocalFiles +} from './runtime-git-status-client' import { createCompatibleRuntimeStatusResponseIfNeeded, type RuntimeEnvironmentCallRequest @@ -9,6 +12,8 @@ import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTest const gitStatus = vi.fn() const gitCancelStatus = vi.fn() const gitCheckIgnored = vi.fn() +const gitAtRiskLocalFiles = vi.fn() +const gitCancelAtRiskLocalFiles = vi.fn() const gitSubmoduleStatus = vi.fn() const gitDiff = vi.fn() const gitBranchCompare = vi.fn() @@ -34,6 +39,9 @@ beforeEach(() => { gitCancelStatus.mockReset() gitCancelStatus.mockResolvedValue(undefined) gitCheckIgnored.mockReset() + gitAtRiskLocalFiles.mockReset() + gitCancelAtRiskLocalFiles.mockReset() + gitCancelAtRiskLocalFiles.mockResolvedValue(undefined) gitSubmoduleStatus.mockReset() gitDiff.mockReset() gitBranchCompare.mockReset() @@ -61,6 +69,8 @@ beforeEach(() => { status: gitStatus, cancelStatus: gitCancelStatus, checkIgnored: gitCheckIgnored, + atRiskLocalFiles: gitAtRiskLocalFiles, + cancelAtRiskLocalFiles: gitCancelAtRiskLocalFiles, submoduleStatus: gitSubmoduleStatus, diff: gitDiff, branchCompare: gitBranchCompare, @@ -108,4 +118,43 @@ describe('runtime git client', () => { // Best-effort main cancellation may still resolve status; aborted calls must reject rather than publish fresh results. await expect(request).rejects.toMatchObject({ name: 'AbortError' }) }) + + it('cancels a local at-risk file scan in main when its signal aborts', async () => { + const controller = new AbortController() + let resolveScan!: (value: { count: number; samplePaths: string[]; complete: boolean }) => void + gitAtRiskLocalFiles.mockImplementation( + () => + new Promise((resolve) => { + resolveScan = resolve + }) + ) + + const request = getRuntimeWorktreeAtRiskLocalFiles( + { target: { kind: 'local' as const }, worktreeId: 'wt-1', worktreePath: '/repo-feature' }, + controller.signal + ) + await vi.waitFor(() => expect(gitAtRiskLocalFiles).toHaveBeenCalled()) + const requestToken = gitAtRiskLocalFiles.mock.calls[0]?.[0]?.requestToken + expect(requestToken).toEqual(expect.any(String)) + expect(gitCancelAtRiskLocalFiles).not.toHaveBeenCalled() + + controller.abort() + + expect(gitCancelAtRiskLocalFiles).toHaveBeenCalledWith({ requestToken }) + resolveScan({ count: 1, samplePaths: ['.env'], complete: true }) + await expect(request).rejects.toMatchObject({ name: 'AbortError' }) + }) + + it('does not start a local at-risk file scan for an already aborted signal', async () => { + const controller = new AbortController() + controller.abort() + + await expect( + getRuntimeWorktreeAtRiskLocalFiles( + { target: { kind: 'local' as const }, worktreeId: 'wt-1', worktreePath: '/repo-feature' }, + controller.signal + ) + ).rejects.toMatchObject({ name: 'AbortError' }) + expect(gitAtRiskLocalFiles).not.toHaveBeenCalled() + }) }) diff --git a/src/renderer/src/runtime/source-control/git/runtime-git-status-client.ts b/src/renderer/src/runtime/source-control/git/runtime-git-status-client.ts index d50c29f00f6..8d6aff40daf 100644 --- a/src/renderer/src/runtime/source-control/git/runtime-git-status-client.ts +++ b/src/renderer/src/runtime/source-control/git/runtime-git-status-client.ts @@ -96,8 +96,8 @@ export async function setRuntimeGitStatusUpstreamRefWatch( let nextGitStatusRequestToken = 0 -function createGitStatusAbortError(): Error { - const error = new Error('Git status request aborted') +function createGitRequestAbortError(): Error { + const error = new Error('Git request aborted') error.name = 'AbortError' return error } @@ -110,7 +110,7 @@ async function callLocalGitStatus( return window.api.git.status(args) } if (signal.aborted) { - throw createGitStatusAbortError() + throw createGitRequestAbortError() } const requestToken = `git-status-${Date.now()}-${++nextGitStatusRequestToken}` const cancel = (): void => { @@ -121,7 +121,7 @@ async function callLocalGitStatus( const status = await window.api.git.status({ ...args, requestToken }) // Why: best-effort cancellation must not publish a late result as fresh. if (signal.aborted) { - throw createGitStatusAbortError() + throw createGitRequestAbortError() } return status } finally { @@ -179,10 +179,11 @@ export async function getRuntimeWorktreeAtRiskLocalFiles( signal?: AbortSignal ): Promise { if (context.target.kind === 'local' || !context.worktreeId) { - return window.api.git.atRiskLocalFiles({ + const args = { worktreePath: resolveLocalWorktreePath(context), connectionId: context.connectionId - }) + } + return signal ? callLocalAtRiskLocalFiles(args, signal) : window.api.git.atRiskLocalFiles(args) } return callRuntimeRpc( context.target, @@ -192,6 +193,32 @@ export async function getRuntimeWorktreeAtRiskLocalFiles( ) } +let nextAtRiskLocalFilesRequestToken = 0 + +async function callLocalAtRiskLocalFiles( + args: { worktreePath: string; connectionId?: string }, + signal: AbortSignal +): Promise { + if (signal.aborted) { + throw createGitRequestAbortError() + } + const requestToken = `git-at-risk-${Date.now()}-${++nextAtRiskLocalFilesRequestToken}` + // Why: a closed preview must stop main's queued git ls-files and file comparisons, not just drop the result. + const cancel = (): void => { + void window.api.git.cancelAtRiskLocalFiles({ requestToken }).catch(() => {}) + } + signal.addEventListener('abort', cancel, { once: true }) + try { + const files = await window.api.git.atRiskLocalFiles({ ...args, requestToken }) + if (signal.aborted) { + throw createGitRequestAbortError() + } + return files + } finally { + signal.removeEventListener('abort', cancel) + } +} + export async function getRuntimeGitRefs( context: RuntimeGitContext, query?: string diff --git a/src/renderer/src/web/preload-api/web-git-api.ts b/src/renderer/src/web/preload-api/web-git-api.ts index 7e9a5b5c5e6..3c859670d9b 100644 --- a/src/renderer/src/web/preload-api/web-git-api.ts +++ b/src/renderer/src/web/preload-api/web-git-api.ts @@ -5,6 +5,7 @@ import { callAbortableRuntimeEnvironment } from '../../runtime/rpc/calls/abortab import { toRuntimeWorktreeSelector } from '../../runtime/rpc/targets/runtime-worktree-selector' import { translate } from '@/i18n/i18n' import { callRuntimeResult } from './web-runtime-calls' +import { createWebGitAtRiskLocalFilesApi } from './web-git-at-risk-local-files-api' import { mutateGitPath, mutateGitPaths, resolveGitConflict } from './web-git-mutations' import { requireGitStageWorktreeScopeReceipt } from '../../../../shared/git/paths/git-stage-worktree-scope' import { requireActiveEnvironment, updateEnvironmentFromResponse } from './web-runtime-session' @@ -88,12 +89,7 @@ export function createGitApi(): NonNullable['git']> { paths }) }, - atRiskLocalFiles: async ({ worktreePath }) => { - const worktree = await resolveRuntimeWorktreeByPath(worktreePath) - return callRuntimeResult('git.atRiskLocalFiles', { - worktree: toRuntimeWorktreeSelector(worktree.id) - }) - }, + ...createWebGitAtRiskLocalFilesApi(), // Why: the "add huge folder to .gitignore" flow is desktop-only; the web runtime makes no offer, so return no candidates. findHugeFoldersToIgnore: async () => [], appendGitignore: async () => false, diff --git a/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.test.ts b/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.test.ts new file mode 100644 index 00000000000..b3580dd18e0 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.test.ts @@ -0,0 +1,84 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { RuntimeRpcCallError } from '../../runtime/rpc/calls/runtime-rpc-result' + +const { resolveWorktreeMock, abortableCallMock } = vi.hoisted(() => ({ + resolveWorktreeMock: vi.fn(), + abortableCallMock: vi.fn() +})) + +vi.mock('./web-runtime-worktree-catalog', () => ({ + resolveRuntimeWorktreeByPath: resolveWorktreeMock, + resolveRuntimeFilePath: vi.fn() +})) +vi.mock('./web-runtime-session', () => ({ + requireActiveEnvironment: () => ({ id: 'env-1' }), + updateEnvironmentFromResponse: vi.fn() +})) +vi.mock('../../runtime/rpc/calls/abortable-runtime-environment-call', async (importOriginal) => ({ + ...(await importOriginal>()), + callAbortableRuntimeEnvironment: abortableCallMock +})) + +import { createWebGitAtRiskLocalFilesApi } from './web-git-at-risk-local-files-api' + +describe('web git atRiskLocalFiles', () => { + beforeEach(() => { + resolveWorktreeMock.mockReset() + abortableCallMock.mockReset() + }) + + it('keeps a cancel that lands during the worktree lookup', async () => { + const api = createWebGitAtRiskLocalFilesApi() + let resolveWorktree!: (worktree: { id: string }) => void + resolveWorktreeMock.mockReturnValue( + new Promise((resolve) => { + resolveWorktree = resolve + }) + ) + let dispatchedSignal: AbortSignal | undefined + abortableCallMock.mockImplementation( + (_env: string, _method: string, _params: unknown, _timeout: unknown, signal: AbortSignal) => { + dispatchedSignal = signal + return signal.aborted + ? Promise.reject(Object.assign(new Error('aborted'), { name: 'AbortError' })) + : Promise.resolve({ + id: '1', + ok: true, + result: { count: 0, samplePaths: [], complete: true } + }) + } + ) + + const scan = api.atRiskLocalFiles({ + worktreePath: '/repo-feature', + requestToken: 'at-risk-1' + }) + await api.cancelAtRiskLocalFiles({ requestToken: 'at-risk-1' }) + resolveWorktree({ id: 'wt-1' }) + + await expect(scan).rejects.toMatchObject({ name: 'AbortError' }) + // The real call rejects an aborted signal before dispatching any RPC. + expect(dispatchedSignal?.aborted ?? true).toBe(true) + }) + + it('keeps method_not_found typed so older hosts fall back', async () => { + const api = createWebGitAtRiskLocalFilesApi() + resolveWorktreeMock.mockResolvedValue({ id: 'wt-1' }) + abortableCallMock.mockResolvedValue({ + id: '1', + ok: false, + error: { + code: 'method_not_found', + message: 'Unknown method: git.atRiskLocalFiles' + } + }) + + const scan = api.atRiskLocalFiles({ + worktreePath: '/repo-feature', + requestToken: 'at-risk-2' + }) + + await expect(scan).rejects.toBeInstanceOf(RuntimeRpcCallError) + await expect(scan).rejects.toMatchObject({ code: 'method_not_found' }) + }) +}) diff --git a/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.ts b/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.ts new file mode 100644 index 00000000000..17f8aea15d6 --- /dev/null +++ b/src/renderer/src/web/preload-api/web-git-at-risk-local-files-api.ts @@ -0,0 +1,62 @@ +import type { PreloadApi } from '../../../../preload/api-types' +import type { WorktreeAtRiskLocalFiles } from '../../../../shared/worktree/removal/at-risk-local-files' +import { callAbortableRuntimeEnvironment } from '../../runtime/rpc/calls/abortable-runtime-environment-call' +import { unwrapRuntimeRpcResult } from '../../runtime/rpc/calls/runtime-rpc-result' +import { toRuntimeWorktreeSelector } from '../../runtime/rpc/targets/runtime-worktree-selector' +import { callRuntimeResult } from './web-runtime-calls' +import { requireActiveEnvironment, updateEnvironmentFromResponse } from './web-runtime-session' +import { resolveRuntimeWorktreeByPath } from './web-runtime-worktree-catalog' + +type WebGitAtRiskLocalFilesApi = Pick< + PreloadApi['git'], + 'atRiskLocalFiles' | 'cancelAtRiskLocalFiles' +> + +const abortControllers = new Map() + +async function callAbortableAtRiskLocalFiles( + requestToken: string, + worktreePath: string +): Promise { + abortControllers.get(requestToken)?.abort() + // Registered before the worktree lookup so a cancel that lands during it still stops the scan. + const controller = new AbortController() + abortControllers.set(requestToken, controller) + try { + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + const environment = requireActiveEnvironment() + // Rejects without dispatching once aborted; unsubscribing closes the host request context. + const response = await callAbortableRuntimeEnvironment( + environment.id, + 'git.atRiskLocalFiles', + { worktree: toRuntimeWorktreeSelector(worktree.id) }, + 30_000, + controller.signal + ) + updateEnvironmentFromResponse(environment, response) + // Typed unwrap keeps method_not_found, which the delete dialog treats as an older host. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: git.atRiskLocalFiles resolves WorktreeAtRiskLocalFiles; the callRuntimeResult path trusts the same contract. + return unwrapRuntimeRpcResult(response) as WorktreeAtRiskLocalFiles + } finally { + if (abortControllers.get(requestToken) === controller) { + abortControllers.delete(requestToken) + } + } +} + +export function createWebGitAtRiskLocalFilesApi(): WebGitAtRiskLocalFilesApi { + return { + atRiskLocalFiles: async ({ worktreePath, requestToken }) => { + if (requestToken) { + return callAbortableAtRiskLocalFiles(requestToken, worktreePath) + } + const worktree = await resolveRuntimeWorktreeByPath(worktreePath) + return callRuntimeResult('git.atRiskLocalFiles', { + worktree: toRuntimeWorktreeSelector(worktree.id) + }) + }, + cancelAtRiskLocalFiles: async ({ requestToken }) => { + abortControllers.get(requestToken)?.abort() + } + } +}