From b426f32e5a1d3d3bf7cf82905c82dcd50bd3fac8 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:40:40 -0800 Subject: [PATCH] Fix offline evidence, deadline admission, clipping, keyset paging and focus revalidation --- .../first-work-branch-changes.test.ts | 75 ++++++++++++- .../first-work/first-work-branch-changes.ts | 27 ++++- .../first-work-native-first-message.ts | 38 +++++-- .../first-work-rename-attempts.test.ts | 41 +++++++ .../first-work-rename-retry.test.ts | 51 ++++++++- ...rnal-domain-first-submitted-prompt.test.ts | 32 +++++- .../journal-domain-first-submitted-prompt.ts | 42 +++++-- .../identity/AutoRenameFailedDialog.test.tsx | 105 ++++++++++++++++-- .../identity/AutoRenameFailedDialog.tsx | 26 ++++- 9 files changed, 389 insertions(+), 48 deletions(-) diff --git a/src/main/agent-hooks/first-work/first-work-branch-changes.test.ts b/src/main/agent-hooks/first-work/first-work-branch-changes.test.ts index 5039293821a..65a38bc557f 100644 --- a/src/main/agent-hooks/first-work/first-work-branch-changes.test.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-changes.test.ts @@ -1,8 +1,9 @@ import { mkdtemp, rm, unlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import type { GitExecOptions } from '../../git/command-runner/git-exec-options' import { readBranchChangesForNaming } from './first-work-branch-changes' const roots: string[] = [] @@ -153,3 +154,75 @@ describe('readBranchChangesForNaming', () => { ).resolves.toEqual({ kind: 'unreadable' }) }) }) + +describe('readBranchChangesForNaming with an injected runner', () => { + type Call = { args: string[]; options: GitExecOptions } + const ok = (stdout: string) => Promise.resolve({ stdout }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('runs every Git read with the offline environment', async () => { + const calls: Call[] = [] + await readBranchChangesForNaming({ + cwd: '/repo', + baseRef: 'main', + signal: new AbortController().signal, + deadlineAt: Number.MAX_SAFE_INTEGER, + runGit: (args, options) => { + calls.push({ args, options }) + return ok(args[0] === 'rev-parse' || args[0] === 'merge-base' ? 'sha\n' : '') + } + }) + expect(calls).toHaveLength(6) + for (const { options } of calls) { + expect(options.env).toMatchObject({ GIT_NO_LAZY_FETCH: '1', GIT_ALLOW_PROTOCOL: 'none' }) + } + }) + + it('launches no Git work once the deadline has passed, including routed retries', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(1_000) + const calls: Call[] = [] + const result = await readBranchChangesForNaming({ + cwd: '/repo', + baseRef: 'main', + signal: new AbortController().signal, + deadlineAt: 2_000, + runGit: (args, options) => { + calls.push({ args, options }) + // The deadline passes while the first read runs. + vi.setSystemTime(2_500) + return ok('sha\n') + } + }) + expect(result).toEqual({ kind: 'unreadable' }) + expect(calls.map(({ args }) => args[0])).toEqual(['rev-parse']) + expect(calls[0]?.options.canStart?.()).toBe(false) + }) + + it('does not count clipped diagnostics as work when stdout is complete', async () => { + const clipped = (stdout: string) => + Promise.reject( + Object.assign(new Error('git produced more than 262144 bytes of output.'), { + code: 0, + killed: false, + signal: null, + outputTruncated: true, + stdout + }) + ) + const read = (stdout: string) => + readBranchChangesForNaming({ + cwd: '/repo', + baseRef: undefined, + signal: new AbortController().signal, + deadlineAt: Number.MAX_SAFE_INTEGER, + runGit: (args) => (args[0] === 'ls-files' ? ok('') : clipped(stdout)) + }) + await expect(read('')).resolves.toEqual({ kind: 'nothing-yet' }) + const atCap = await read('x'.repeat(256 * 1024)) + expect(atCap.kind === 'changes' && atCap.changes.workingStat.endsWith('…')).toBe(true) + }) +}) diff --git a/src/main/agent-hooks/first-work/first-work-branch-changes.ts b/src/main/agent-hooks/first-work/first-work-branch-changes.ts index cb00b2ace14..c895c5010c4 100644 --- a/src/main/agent-hooks/first-work/first-work-branch-changes.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-changes.ts @@ -6,6 +6,10 @@ import { import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' import type { GitExecOptions } from '../../git/command-runner/git-exec-options' import { isQuietGitControlFlowExit } from '../../git/command-runner/host-routing/git-command-resolution' +import { + gitOptionalLocksDisabledEnv, + offlineGitEnv +} from '../../git/command-runner/git-environment/git-process-env' export type BranchChangesLookup = | { kind: 'changes'; changes: BranchNameChanges } @@ -52,7 +56,8 @@ function parseGitExitFields(error: unknown): GitExitFields { /** Abort and timeout outrank clipping; clipping counts only with a clean exit the route observed. */ export function classifyGitCaptureError( error: unknown, - signal: AbortSignal | undefined + signal: AbortSignal | undefined, + maxBuffer: number ): GitCapture { if (signal?.aborted || error instanceof GitCommandTimeoutError) { return { kind: 'failed' } @@ -60,7 +65,11 @@ export function classifyGitCaptureError( const exit = parseGitExitFields(error) const truncated = exit.outputTruncated === true if (truncated && exit.code === 0 && exit.killed !== true && (exit.signal ?? null) === null) { - return { kind: 'truncated', stdout: typeof exit.stdout === 'string' ? exit.stdout : '' } + const stdout = typeof exit.stdout === 'string' ? exit.stdout : '' + // The flag also covers stderr; below the cap, stdout is complete and only diagnostics were clipped. + return stdoutReachedCap(stdout, maxBuffer) + ? { kind: 'truncated', stdout } + : { kind: 'ok', stdout } } if (!truncated && isQuietGitControlFlowExit(error)) { return { kind: 'quiet-exit' } @@ -68,6 +77,11 @@ export function classifyGitCaptureError( return { kind: 'failed' } } +// A clipped UTF-8 stream may stop up to one partial character short of the byte cap. +function stdoutReachedCap(stdout: string, maxBuffer: number): boolean { + return Buffer.byteLength(stdout) >= maxBuffer - 3 +} + function evidenceText(capture: GitCapture): string | null { if (capture.kind === 'ok') { return capture.stdout.trim() @@ -89,21 +103,26 @@ export async function readBranchChangesForNaming(args: { }): Promise { const runGit = args.runGit ?? gitExecFileAsync const capture = async (gitArgs: string[], maxBuffer = EVIDENCE_MAX_BUFFER) => { - if (args.signal.aborted || Date.now() >= args.deadlineAt) { + const live = () => !args.signal.aborted && Date.now() < args.deadlineAt + if (!live()) { return { kind: 'failed' } as const } try { const { stdout } = await runGit(gitArgs, { cwd: args.cwd, + // Evidence is local by contract: no lazy partial-clone fetch, no transport, no index refresh. + env: gitOptionalLocksDisabledEnv(offlineGitEnv()), maxBuffer, timeout: Math.min(GIT_READ_TIMEOUT_MS, Math.max(1, args.deadlineAt - Date.now())), signal: args.signal, + // Rechecked after admission and before any routed fallback, so expiry never launches a child. + canStart: live, // The barrier route reports exit status alongside clipping, so precedence is observable. terminationBarrier: true }) return { kind: 'ok', stdout } as const } catch (error) { - return classifyGitCaptureError(error, args.signal) + return classifyGitCaptureError(error, args.signal, maxBuffer) } } diff --git a/src/main/agent-hooks/first-work/first-work-native-first-message.ts b/src/main/agent-hooks/first-work/first-work-native-first-message.ts index 6ae66d9e392..a6533067210 100644 --- a/src/main/agent-hooks/first-work/first-work-native-first-message.ts +++ b/src/main/agent-hooks/first-work/first-work-native-first-message.ts @@ -1,15 +1,14 @@ +import type { JournalFirstSubmittedPrompt } from '../../native-chat/agent-session-journal/journal-domain-first-submitted-prompt' + export type NativeFirstMessageLookup = | { kind: 'found'; prompt: string; submittedAt: number } | { kind: 'none' } - /** Read failed or the feature's read capacity is full: retryable. */ + /** Read failed, a scan was incomplete, or the feature's read capacity is full: retryable. */ | { kind: 'unreadable' } export type NativeFirstMessageReads = { listSessionIds: () => Promise - readFirst: ( - sessionId: string, - sinceMs: number - ) => Promise<{ prompt: string; submittedAt: number } | null> + readFirst: (sessionId: string, sinceMs: number) => Promise } // Leases outlive a logical timeout until the physical read settles, so expiries cannot pile up reads. @@ -42,17 +41,38 @@ export function leaseNativeFirstMessageRead( return physical } +type Candidate = { prompt: string; submittedAt: number; sequence: number; sessionId: string } + +/** D4 order: submission time, then item sequence; session id only makes an exact tie deterministic. */ +function precedes(left: Candidate, right: Candidate): boolean { + if (left.submittedAt !== right.submittedAt) { + return left.submittedAt < right.submittedAt + } + if (left.sequence !== right.sequence) { + return left.sequence < right.sequence + } + return left.sessionId < right.sessionId +} + /** The earliest qualifying native-chat message of the workspace, one point read at a time. */ export async function readNativeFirstMessage( reads: NativeFirstMessageReads, sinceMs: number ): Promise { - let earliest: { prompt: string; submittedAt: number } | null = null + let earliest: Candidate | null = null for (const sessionId of await reads.listSessionIds()) { const first = await reads.readFirst(sessionId, sinceMs) - if (first && (!earliest || first.submittedAt < earliest.submittedAt)) { - earliest = first + if (first.kind === 'incomplete') { + return { kind: 'unreadable' } + } + if (first.kind === 'found') { + const candidate = { ...first, sessionId } + if (!earliest || precedes(candidate, earliest)) { + earliest = candidate + } } } - return earliest ? { kind: 'found', ...earliest } : { kind: 'none' } + return earliest + ? { kind: 'found', prompt: earliest.prompt, submittedAt: earliest.submittedAt } + : { kind: 'none' } } diff --git a/src/main/agent-hooks/first-work/first-work-rename-attempts.test.ts b/src/main/agent-hooks/first-work/first-work-rename-attempts.test.ts index 0c106757d5e..3a1a66bfd92 100644 --- a/src/main/agent-hooks/first-work/first-work-rename-attempts.test.ts +++ b/src/main/agent-hooks/first-work/first-work-rename-attempts.test.ts @@ -9,10 +9,13 @@ import { import { isFirstWorkGenerationBackingOff } from './first-work-generation-backoff' import { leaseNativeFirstMessageRead, + readNativeFirstMessage, resetNativeFirstMessageReads, type NativeFirstMessageLookup } from './first-work-native-first-message' +import type { JournalFirstSubmittedPrompt } from '../../native-chat/agent-session-journal/journal-domain-first-submitted-prompt' + const ID = 'repo::/repo/wt' function deferred() { @@ -107,3 +110,41 @@ describe('native first-message read lease', () => { }) }) }) + +describe('native first-message ordering', () => { + const found = (prompt: string, submittedAt: number, sequence: number) => + ({ kind: 'found', prompt, submittedAt, sequence }) as const + + it('breaks an equal submission time by sequence, whatever the session order', async () => { + const firsts: Record = { + a: found('Later in sequence', 100, 7), + b: found('Earlier in sequence', 100, 3) + } + for (const order of [ + ['a', 'b'], + ['b', 'a'] + ] as const) { + await expect( + readNativeFirstMessage( + { + listSessionIds: async () => [...order], + readFirst: async (id) => firsts[id] ?? { kind: 'none' } + }, + 0 + ) + ).resolves.toMatchObject({ prompt: 'Earlier in sequence' }) + } + }) + + it('treats an incomplete session scan as unreadable rather than a miss', async () => { + await expect( + readNativeFirstMessage( + { + listSessionIds: async () => ['a', 'b'], + readFirst: async (id) => (id === 'a' ? found('Found', 100, 1) : { kind: 'incomplete' }) + }, + 0 + ) + ).resolves.toEqual({ kind: 'unreadable' }) + }) +}) diff --git a/src/main/agent-hooks/first-work/first-work-rename-retry.test.ts b/src/main/agent-hooks/first-work/first-work-rename-retry.test.ts index 0e5f9e27432..9121e014a1a 100644 --- a/src/main/agent-hooks/first-work/first-work-rename-retry.test.ts +++ b/src/main/agent-hooks/first-work/first-work-rename-retry.test.ts @@ -51,7 +51,10 @@ function deferred() { return { promise, resolve } } -const noNativeChat: Reads = () => ({ listSessionIds: async () => [], readFirst: async () => null }) +const noNativeChat: Reads = () => ({ + listSessionIds: async () => [], + readFirst: async () => ({ kind: 'none' }) +}) function changesGit(stat: string) { return async (args: string[]) => { @@ -101,8 +104,8 @@ describe('retryFirstWorkRename', () => { listSessionIds: async () => ['later', 'earlier'], readFirst: async (sessionId) => sessionId === 'earlier' - ? { prompt: 'Fix the login form', submittedAt: 110 } - : { prompt: 'Polish the README', submittedAt: 120 } + ? { kind: 'found', prompt: 'Fix the login form', submittedAt: 110, sequence: 9 } + : { kind: 'found', prompt: 'Polish the README', submittedAt: 120, sequence: 1 } }) }) const result = await retryFirstWorkRename(WORKTREE_ID, deps) @@ -148,7 +151,12 @@ describe('retryFirstWorkRename', () => { const { deps } = makeRetryDeps({ nativeReads: () => ({ listSessionIds, - readFirst: async () => ({ prompt: 'Late message', submittedAt: 200 }) + readFirst: async () => ({ + kind: 'found', + prompt: 'Late message', + submittedAt: 200, + sequence: 1 + }) }) }) const first = retryFirstWorkRename(WORKTREE_ID, deps) @@ -186,6 +194,41 @@ describe('retryFirstWorkRename', () => { ) }) + it.each([ + ['setting turned off', 'setting-off'], + ['branch ownership lost', 'name-chosen'] + ])('renames nothing when the %s during the final upstream probe', async (_label, reason) => { + generateBranchNameMock.mockResolvedValue({ success: true, slug: 'fix-auth' }) + let eligible = true + const probe = deferred() + let probes = 0 + const respond = gitResponder({ currentBranch: 'Nautilus-8', hasUpstream: false }) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + // The second upstream probe is the one inside the final recheck. + if (args.some((arg) => arg.includes('@{u}')) && ++probes === 2) { + await probe.promise + } + return respond(args) + }) + const { deps } = makeRetryDeps({ + runGit: changesGit(' a.ts | 1 +\n'), + canRenameOrcaCreatedBranch: () => eligible + }) + const result = retryFirstWorkRename(WORKTREE_ID, deps) + await vi.waitFor(() => expect(probes).toBe(2)) + if (reason === 'setting-off') { + deps.getSettings().autoRenameBranchFromWork = false + } else { + eligible = false + } + probe.resolve() + await expect(result).resolves.toMatchObject({ outcome: { kind: 'ineligible', reason } }) + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + expect.arrayContaining(['branch', '-m']), + expect.anything() + ) + }) + it('drops a replaced workspace’s late failure instead of writing it to the new row', async () => { const generation = deferred<{ success: false; error: string }>() generateBranchNameMock.mockReturnValue(generation.promise) diff --git a/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.test.ts b/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.test.ts index de2899bf491..ee61eb8d80c 100644 --- a/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.test.ts @@ -1,6 +1,7 @@ import { afterEach, expect, it } from 'vitest' import { domainLifecycleFixture } from './journal-domain-lifecycle.test-fixture' import { readJournalSqlPoint } from './journal-sql-point-read' +import { FIRST_SUBMITTED_PROMPT_SCAN_LIMIT } from './journal-domain-first-submitted-prompt' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' const cleanup: (() => void)[] = [] @@ -39,7 +40,11 @@ it('applies the creation bound before taking the earliest submission', async () const f = domainLifecycleFixture(cleanup) await send(f, 'opener', 'Pre-creation opener', 50) await send(f, 'qualifying', 'Fix the login form', 110) - expect(first(f, 100)).toEqual({ prompt: 'Fix the login form', submittedAt: 110 }) + expect(first(f, 100)).toMatchObject({ + kind: 'found', + prompt: 'Fix the login form', + submittedAt: 110 + }) }) it('orders by submission time, not journal sequence, and ignores context clears', async () => { @@ -49,12 +54,33 @@ it('orders by submission time, not journal sequence, and ignores context clears' f.db .prepare("UPDATE journal_items SET context_clear=1 WHERE item_id LIKE '%sequenced-second%'") .run() - expect(first(f, 100)).toEqual({ prompt: 'Submitted earlier', submittedAt: 200 }) + expect(first(f, 100)).toMatchObject({ + kind: 'found', + prompt: 'Submitted earlier', + submittedAt: 200 + }) +}) + +it('pages past text-less candidates to the first message with text', async () => { + const f = domainLifecycleFixture(cleanup) + for (let index = 0; index < 40; index++) { + await send(f, `blank-${index}`, '', 200 + index) + } + await send(f, 'named', 'Add password reset', 300) + expect(first(f, 100)).toMatchObject({ kind: 'found', prompt: 'Add password reset' }) +}) + +it('reports an incomplete scan instead of a miss once the bound is reached', async () => { + const f = domainLifecycleFixture(cleanup) + for (let index = 0; index <= FIRST_SUBMITTED_PROMPT_SCAN_LIMIT; index++) { + await send(f, `blank-${index}`, '', 200 + index) + } + expect(first(f, 100)).toEqual({ kind: 'incomplete' }) }) it('never treats a message without a submission row as a candidate', async () => { const f = domainLifecycleFixture(cleanup) await send(f, 'orphaned', 'No submission', 150) f.db.prepare("DELETE FROM journal_submission_attempts WHERE message_id='orphaned'").run() - expect(first(f, 100)).toBeNull() + expect(first(f, 100)).toEqual({ kind: 'none' }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.ts b/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.ts index 477ed4dea0f..d7aa2750017 100644 --- a/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.ts +++ b/src/main/native-chat/agent-session-journal/journal-domain-first-submitted-prompt.ts @@ -2,20 +2,29 @@ import type { AgentJournalRenderItem } from '../../../shared/agent-session/journ import { firstStructuredAgentSessionPrompt } from '../../../shared/agent-session/requests/structured-agent-session-first-prompt' import type { JournalSqlScope } from './journal-sql-scope' -export type JournalFirstSubmittedPrompt = { prompt: string; submittedAt: number } | null +export type JournalFirstSubmittedPrompt = + | { kind: 'found'; prompt: string; submittedAt: number; sequence: number } + | { kind: 'none' } + /** The scan bound was reached before a qualifying message: not proof that none exists. */ + | { kind: 'incomplete' } const CANDIDATE_PAGE = 32 +export const FIRST_SUBMITTED_PROMPT_SCAN_LIMIT = 512 + +type Cursor = [submittedAt: number, sequence: number, sequenceIndex: number, ordinal: number] /** The earliest user message submitted at/after `sinceMs`, by submission time across context clears. - * Unlike the naming prompt this ignores the latest-clear floor; items without a submission row never qualify. */ + * Unlike the naming prompt this ignores the latest-clear floor; items without a submission row never qualify. + * Keyset pages keep a long run of text-less candidates linear, and the scan is bounded. */ export function readJournalDomainFirstSubmittedPrompt( scope: JournalSqlScope, sinceMs: number ): JournalFirstSubmittedPrompt { - let offset = 0 - for (;;) { + let after: Cursor = [sinceMs, -1, -1, -1] + for (let scanned = 0; scanned < FIRST_SUBMITTED_PROMPT_SCAN_LIMIT;) { const rows = scope.db - .prepare(`SELECT i.payload_json AS payload_json, s.submitted_at AS submitted_at + .prepare(`SELECT i.payload_json AS payload_json, s.submitted_at AS submitted_at, + i.sequence AS sequence, i.sequence_index AS sequence_index, i.ordinal AS ordinal FROM journal_items i JOIN journal_submission_attempts s ON s.session_id=i.session_id AND s.epoch=i.epoch AND s.current=1 @@ -25,19 +34,32 @@ export function readJournalDomainFirstSubmittedPrompt( i.item_id) WHERE i.session_id=? AND i.epoch=? AND i.hidden=0 AND i.root=1 AND i.kind='message' AND i.message_role='user' AND i.command_entry=0 - ORDER BY s.submitted_at, i.sequence, i.sequence_index, i.ordinal LIMIT ? OFFSET ?`) - .all(sinceMs, ...scope.prefix, CANDIDATE_PAGE, offset) + AND (s.submitted_at, i.sequence, i.sequence_index, i.ordinal) > (?, ?, ?, ?) + ORDER BY s.submitted_at, i.sequence, i.sequence_index, i.ordinal LIMIT ?`) + .all(sinceMs, ...scope.prefix, ...after, CANDIDATE_PAGE) for (const row of rows) { const examined = scope.examined(row) + scanned++ const item = scope.decode(examined.payload_json) const prompt = firstStructuredAgentSessionPrompt([item]) if (prompt) { - return { prompt, submittedAt: Number(examined.submitted_at) } + return { + kind: 'found', + prompt, + submittedAt: Number(examined.submitted_at), + sequence: Number(examined.sequence) + } } + after = [ + Number(examined.submitted_at), + Number(examined.sequence), + Number(examined.sequence_index), + Number(examined.ordinal) + ] } if (rows.length < CANDIDATE_PAGE) { - return null + return { kind: 'none' } } - offset += CANDIDATE_PAGE } + return { kind: 'incomplete' } } diff --git a/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx b/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx index c24554d7a97..d1bc20fe5f2 100644 --- a/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.test.tsx @@ -96,17 +96,19 @@ beforeEach(() => { runningAttemptId: null }) useAppStore.setState({ updateWorktreeMeta }) - ;(window as unknown as { api: unknown }).api = { - worktrees: { - getBranchRenameFailureOutput, - updateMeta, - getBranchAutoRenameRetryAvailability, - retryBranchAutoRename, - onBranchAutoRenameAttempt - }, - nativeChat: { getConversationNameFailureOutput: getBranchRenameFailureOutput }, - ui: { writeClipboardText } - } + Object.assign(window, { + api: { + worktrees: { + getBranchRenameFailureOutput, + updateMeta, + getBranchAutoRenameRetryAvailability, + retryBranchAutoRename, + onBranchAutoRenameAttempt + }, + nativeChat: { getConversationNameFailureOutput: getBranchRenameFailureOutput }, + ui: { writeClipboardText } + } + }) container = document.createElement('div') document.body.appendChild(container) root = createRoot(container) @@ -316,3 +318,84 @@ describe('AutoRenameFailedDialog retry', () => { expect(button('Dismiss')?.disabled).toBe(false) }) }) + +describe('AutoRenameFailedDialog sessions and focus', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + function Controlled({ open }: { open: boolean }) { + return ( + {}} + worktreeId="repo1::/path/wt1" + executionHostId="local" + worktreeName="Nautilus" + error={EXCERPT_ERROR} + /> + ) + } + + it('ignores an availability reply from a closed session after reopening', async () => { + getBranchRenameFailureOutput.mockResolvedValue(null) + const stale = Promise.withResolvers<{ available: boolean; runningAttemptId: number | null }>() + getBranchAutoRenameRetryAvailability.mockReturnValueOnce(stale.promise) + getBranchAutoRenameRetryAvailability.mockResolvedValueOnce({ + available: true, + runningAttemptId: null + }) + await act(async () => root.render()) + await act(async () => root.render()) + await act(async () => root.render()) + await act(async () => stale.resolve({ available: true, runningAttemptId: 5 })) + expect(button('Dismiss')?.disabled).toBe(false) + expect(button('Try again')).toBeDefined() + }) + + function queueFrames(): FrameRequestCallback[] { + const frames: FrameRequestCallback[] = [] + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((frame) => { + frames.push(frame) + return frames.length + }) + return frames + } + + it('does not take back focus the user moved before the queued focus runs', async () => { + const frames = queueFrames() + await renderFailure() + retryBranchAutoRename.mockResolvedValue({ + attemptId: 1, + outcome: { kind: 'nothing-yet' }, + finishedAt: 1 + }) + button('Try again')?.focus() + await act(async () => button('Try again')?.click()) + button('Dismiss')?.focus() + await act(async () => frames.splice(0).forEach((frame) => frame(0))) + expect(document.activeElement?.getAttribute('aria-label')).toBe('Dismiss') + }) + + it('does not focus a reopened dialog from the previous session’s queued focus', async () => { + const frames = queueFrames() + getBranchRenameFailureOutput.mockResolvedValue(null) + getBranchAutoRenameRetryAvailability.mockResolvedValue({ + available: true, + runningAttemptId: null + }) + retryBranchAutoRename.mockResolvedValue({ + attemptId: 1, + outcome: { kind: 'nothing-yet' }, + finishedAt: 1 + }) + await act(async () => root.render()) + button('Try again')?.focus() + await act(async () => button('Try again')?.click()) + await act(async () => root.render()) + await act(async () => root.render()) + button('Dismiss')?.focus() + await act(async () => frames.splice(0).forEach((frame) => frame(0))) + expect(document.activeElement?.getAttribute('aria-label')).toBe('Dismiss') + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.tsx b/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.tsx index ee9146f11aa..b7d572f825c 100644 --- a/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.tsx +++ b/src/renderer/src/components/sidebar/workspace-card/identity/AutoRenameFailedDialog.tsx @@ -83,7 +83,21 @@ export function AutoRenameFailedDialog({ return } const target = outcome.kind === 'ineligible' ? dismissRef : tryAgainRef - requestAnimationFrame(() => target.current?.focus()) + const focusedAtFinish = document.activeElement + requestAnimationFrame(() => { + // Re-validate at run time: the dialog may have closed or reopened, or the user moved focus. + const button = target.current + const active = document.activeElement + if ( + button && + dialog.isConnected && + button.closest('[role="dialog"]') === dialog && + // Unchanged, or dropped to because the focused Try again just unmounted. + (active === focusedAtFinish || active === document.body) + ) { + button.focus() + } + }) } }) const dismissLabel = t('auto.components.sidebar.AutoRenameFailedDialog.dismiss', 'Dismiss') @@ -306,11 +320,11 @@ export function NameGenerationFailedDialog({ - - {tone === 'error' ? : null} - {title} + + + {tone === 'error' ? : null} + {title} +

{reason ?? description}