diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts new file mode 100644 index 00000000000..2b3a2722aef --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.test.ts @@ -0,0 +1,105 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { createGitStatusRefreshScheduler } from './git-status-refresh-scheduler' + +const options = { + safetyIntervalMs: 60_000, + activityDebounceMs: 125, + activityMinGapMs: 3000, + slowTaskBackoff: { idleMultiplier: 1, changeSignalMultiplier: 1, maxIntervalMs: 300_000 } +} +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) +}) +afterEach(() => vi.useRealTimers()) + +it('rejects late hidden signals and catches up after an aborted read settles', async () => { + const reads: AbortSignal[] = [] + let finish: (() => void) | undefined + const scheduler = createGitStatusRefreshScheduler(({ signal }) => { + reads.push(signal) + return reads.length === 1 + ? new Promise((resolve) => { + finish = resolve + }) + : Promise.resolve() + }, options) + scheduler.resumeSafety() + scheduler.pause() + expect(reads[0].aborted).toBe(true) + scheduler.signal() + scheduler.refreshNow() + scheduler.retime() + await vi.advanceTimersByTimeAsync(60_000) + expect(reads).toHaveLength(1) + scheduler.resumeSafety() + finish?.() + await vi.advanceTimersByTimeAsync(3000) + expect(reads).toHaveLength(2) + scheduler.pause() + scheduler.signal() + scheduler.refreshNow() + await vi.advanceTimersByTimeAsync(300_000) + expect(reads).toHaveLength(2) + scheduler.resumeSafety() + await vi.advanceTimersByTimeAsync(0) + expect(reads).toHaveLength(3) + scheduler.dispose() +}) + +it('paces visible unfocused edits at 60s while retaining 240s safety and focused catch-up', async () => { + let focused = false + const reads: number[] = [] + const scheduler = createGitStatusRefreshScheduler( + async () => { + reads.push(Date.now()) + }, + { + ...options, + cadenceScale: () => (focused ? 1 : 4), + activityCadenceScale: () => (focused ? 1 : 20) + } + ) + scheduler.resumeSafety() + await vi.advanceTimersByTimeAsync(0) + for (let i = 0; i < 5; i++) { + scheduler.signal() + await vi.advanceTimersByTimeAsync(12_000) + } + expect(reads).toEqual([0, 60_000]) + await vi.advanceTimersByTimeAsync(240_000) + expect(reads).toEqual([0, 60_000, 300_000]) + scheduler.signal() + await vi.advanceTimersByTimeAsync(10_000) + focused = true + scheduler.retime() + await vi.advanceTimersByTimeAsync(125) + expect(reads).toEqual([0, 60_000, 300_000, 310_125]) + scheduler.dispose() +}) + +it('retains quiet-failure safety retry and one trailing read for an in-flight wake', async () => { + const reads: number[] = [] + let finish: (() => void) | undefined + const scheduler = createGitStatusRefreshScheduler(() => { + reads.push(Date.now()) + if (reads.length === 1) { + return Promise.reject(new Error('offline')) + } + if (reads.length === 2) { + return new Promise((resolve) => { + finish = resolve + }) + } + return Promise.resolve() + }, options) + scheduler.resumeSafety() + await vi.advanceTimersByTimeAsync(60_000) + expect(reads).toEqual([0, 60_000]) + scheduler.refreshNow() + scheduler.signal() + finish?.() + await vi.advanceTimersByTimeAsync(3000) + expect(reads).toEqual([0, 60_000, 63_000]) + scheduler.dispose() +}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.ts b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.ts index 106f981cad9..782bbe27e42 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.ts +++ b/src/renderer/src/components/right-sidebar/source-control/sync/git-status-refresh-scheduler.ts @@ -55,9 +55,11 @@ export function createGitStatusRefreshScheduler( pacing?: GitStatusRefreshPacing // Multiplies the activity floor and safety interval at schedule time (e.g. while unfocused). cadenceScale?: () => number + activityCadenceScale?: () => number } ): GitStatusRefreshScheduler { let disposed = false + let paused = false let safetyEnabled = false let inFlight = false let pendingActivity = false @@ -89,7 +91,7 @@ export function createGitStatusRefreshScheduler( slowTaskRequiredIdleMs( pacing.lastRunDurationMs, options.slowTaskBackoff.changeSignalMultiplier, - options.activityMinGapMs * cadenceScale(), + options.activityMinGapMs * (options.activityCadenceScale?.() ?? cadenceScale()), options.slowTaskBackoff.maxIntervalMs ) @@ -119,7 +121,7 @@ export function createGitStatusRefreshScheduler( } const scheduleActivityRun = (minDelayMs: number): void => { - if (disposed) { + if (disposed || paused) { return } if (inFlight) { @@ -150,7 +152,7 @@ export function createGitStatusRefreshScheduler( } const startRun = (reason: GitStatusRefreshReason): void => { - if (disposed || inFlight) { + if (disposed || paused || inFlight) { return } clearActivityTimer() @@ -183,7 +185,7 @@ export function createGitStatusRefreshScheduler( activeController = null } inFlight = false - if (disposed) { + if (disposed || paused) { return } if (pendingActivity) { @@ -202,6 +204,7 @@ export function createGitStatusRefreshScheduler( if (disposed) { return } + paused = false const wasEnabled = safetyEnabled safetyEnabled = true if (wasEnabled) { @@ -216,6 +219,7 @@ export function createGitStatusRefreshScheduler( scheduleActivityRun(0) }, pause: () => { + paused = true safetyEnabled = false pendingActivity = false clearActivityTimer() @@ -223,25 +227,26 @@ export function createGitStatusRefreshScheduler( activeController?.abort() }, suspendSafety: () => { + paused = false safetyEnabled = false clearSafetyTimer() }, signal: () => { - if (disposed) { + if (disposed || paused) { return } clearSafetyTimer() scheduleActivityRun(options.activityDebounceMs) }, refreshNow: () => { - if (disposed) { + if (disposed || paused) { return } clearSafetyTimer() scheduleActivityRun(0) }, retime: () => { - if (disposed || inFlight) { + if (disposed || paused || inFlight) { return } if (activityTimer !== null) { diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.test.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.test.tsx new file mode 100644 index 00000000000..0557e9e680c --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.test.tsx @@ -0,0 +1,275 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { useGitStatusWindowPresence } from './use-git-status-window-presence' +import { useGitStatusTurnCompletion } from './use-git-status-turn-completion' +import { createGitStatusRefreshScheduler } from './git-status-refresh-scheduler' +import { resetStructuredAgentSessionTurnCompletionFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-turn-completion-feed' +import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import type { AgentSessionTurnCompletionEvent } from '../../../../../../shared/agent-session/view/agent-session-turn-completion-wire' +import type { Tab } from '../../../../../../shared/tab-types' + +const transport = vi.hoisted(() => ({ open: vi.fn(), supports: vi.fn() })) +vi.mock('@/runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ + subscribeStructuredAgentSessionTurnCompletions: transport.open +})) +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', () => ({ + runtimeEnvironmentSupportsCapability: transport.supports +})) +let root: Root +let visibility: DocumentVisibilityState +const leaf = '11111111-1111-4111-8111-111111111111' +const signals: string[] = [] +const renders = new Map() +const stops: string[] = [] +const sends = new Map void>() +const schedulers = new Map>() +const target: RuntimeClientTarget = { kind: 'local' } +function Observer({ + id, + host, + structured = false +}: { + id: string + host: ExecutionHostId + structured?: boolean +}) { + renders.set(id, (renders.get(id) ?? 0) + 1) + let scheduler = schedulers.get(id) + if (!scheduler) { + scheduler = createGitStatusRefreshScheduler( + async () => { + signals.push(id) + }, + { + safetyIntervalMs: 60_000, + activityDebounceMs: 125, + activityMinGapMs: 3000, + slowTaskBackoff: { idleMultiplier: 1, changeSignalMultiplier: 1, maxIntervalMs: 300_000 } + } + ) + schedulers.set(id, scheduler) + } + useGitStatusTurnCompletion(structured ? target : null, host, id, true, { current: scheduler }) + return null +} +function tab(id: string, worktreeId: string, executionHostId?: ExecutionHostId): Tab { + return { + id, + entityId: id, + groupId: 'group', + worktreeId, + executionHostId, + contentType: 'terminal', + label: 'agent', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} +function write(id: string, worktreeId: string, done: boolean) { + useAppStore.getState().setAgentStatus( + `${id}:${leaf}`, + { state: done ? 'done' : 'working', prompt: 'implement fix', agentType: 'codex' }, + undefined, + { + updatedAt: Date.now(), + stateStartedAt: Date.now(), + ...(done ? { turnEndedAt: Date.now() } : {}) + }, + { tabId: id, worktreeId } + ) +} +beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000) + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) + visibility = 'visible' + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }) + useAppStore.setState(useAppStore.getInitialState(), true) + signals.length = 0 + stops.length = 0 + sends.clear() + renders.clear() + transport.open.mockClear() + transport.supports.mockResolvedValue(true) + transport.open.mockImplementation( + async (owner: RuntimeClientTarget, send: (event: AgentSessionTurnCompletionEvent) => void) => { + const key = owner.kind === 'local' ? 'local' : owner.environmentId + sends.set(key, send) + return { + unsubscribe: () => { + stops.push(key) + sends.delete(key) + } + } + } + ) + root = createRoot(document.createElement('div')) +}) +afterEach(async () => { + await act(async () => root.unmount()) + for (const scheduler of schedulers.values()) { + scheduler.dispose() + } + schedulers.clear() + resetStructuredAgentSessionTurnCompletionFeedsForTests() + Reflect.deleteProperty(document, 'visibilityState') + vi.unstubAllGlobals() + vi.useRealTimers() +}) + +it('routes accepted terminal turn ends to local, runtime and SSH copies, including legacy local tabs', async () => { + const specs = [ + { id: 'folder', host: 'local' as const, pty: 'local-pty' }, + { id: 'runtime', host: 'runtime:env' as const, pty: 'remote:env@@pty' }, + { id: 'ssh', host: 'ssh:server' as const, pty: 'ssh:server@@pty' } + ] + useAppStore.setState({ + unifiedTabsByWorktree: Object.fromEntries(specs.map((s) => [s.id, [tab(s.id, s.id)]])), + ptyIdsByTabId: Object.fromEntries(specs.map((s) => [s.id, [s.pty]])) + }) + await act(async () => + root.render( + <> + {specs.map((s) => ( + + ))} + + + ) + ) + for (const spec of specs) { + write(spec.id, spec.id, false) + } + await vi.advanceTimersByTimeAsync(1) + for (const spec of specs) { + write(spec.id, spec.id, true) + } + await vi.advanceTimersByTimeAsync(125) + expect(signals.sort()).toEqual(['folder', 'runtime', 'ssh']) + signals.length = 0 + visibility = 'hidden' + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(4000) + for (const spec of specs) { + write(spec.id, spec.id, false) + write(spec.id, spec.id, true) + } + await vi.advanceTimersByTimeAsync(125) + expect(signals).toEqual([]) +}) + +it.each([10, 100])( + 'shares the producer and scopes updates for %i interested observers', + async (count) => { + await act(async () => + root.render( + <> + {Array.from({ length: count }, (_, i) => ( + + ))} + + ) + ) + expect(transport.open).toHaveBeenCalledTimes(1) + const settledRenders = [...renders] + await act(async () => useAppStore.setState({ rightSidebarOpen: true })) + expect([...renders]).toEqual(settledRenders) + const send = sends.get('local')! + send({ + type: 'completion', + completion: { + scope: { + executionHostId: 'local', + workspaceId: 'observer-1', + workspaceKind: 'folder', + wslDistro: null + }, + sessionId: 'session', + turnId: 'turn', + outcome: 'success', + completedAt: Date.now() + } + }) + await vi.advanceTimersByTimeAsync(125) + expect(signals).toEqual(['observer-1']) + expect([...renders]).toEqual(settledRenders) + visibility = 'hidden' + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(10_000) + expect(stops).toEqual(['local']) + expect(sends.size).toBe(0) + signals.length = 0 + send({ + type: 'completion', + completion: { + scope: { + executionHostId: 'local', + workspaceId: 'observer-0', + workspaceKind: 'folder', + wslDistro: null + }, + sessionId: 'session', + turnId: 'late', + outcome: 'success', + completedAt: Date.now() + } + }) + await vi.advanceTimersByTimeAsync(125) + expect(signals).toEqual([]) + } +) + +it('catches up on system wake and reveal, but adds no idle read on focus', async () => { + let wake: (() => void) | undefined + vi.stubGlobal('api', { + ui: { + onSystemResumed: (listener: () => void) => { + wake = listener + return () => { + wake = undefined + } + } + } + }) + const reads: number[] = [] + const scheduler = createGitStatusRefreshScheduler( + async () => { + reads.push(Date.now()) + }, + { + safetyIntervalMs: 60_000, + activityDebounceMs: 125, + activityMinGapMs: 3000, + slowTaskBackoff: { idleMultiplier: 1, changeSignalMultiplier: 1, maxIntervalMs: 300_000 } + } + ) + schedulers.set('presence', scheduler) + const ref = { current: scheduler } + function Presence() { + useGitStatusWindowPresence(ref, true, 'local/folder') + return null + } + await act(async () => root.render()) + await vi.advanceTimersByTimeAsync(10_000) + window.dispatchEvent(new Event('focus')) + await vi.advanceTimersByTimeAsync(0) + expect(reads).toEqual([2_000_000]) + wake?.() + await vi.advanceTimersByTimeAsync(0) + expect(reads).toEqual([2_000_000, 2_010_000]) + visibility = 'hidden' + document.dispatchEvent(new Event('visibilitychange')) + wake?.() + await vi.advanceTimersByTimeAsync(10_000) + expect(reads).toEqual([2_000_000, 2_010_000]) + visibility = 'visible' + document.dispatchEvent(new Event('visibilitychange')) + await vi.advanceTimersByTimeAsync(0) + expect(reads).toEqual([2_000_000, 2_010_000, 2_020_000]) +}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.ts b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.ts new file mode 100644 index 00000000000..f4ed50b706f --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-turn-completion.ts @@ -0,0 +1,134 @@ +import { useEffect } from 'react' +import { useAppStore } from '@/store' +import { getStructuredAgentSessionTurnCompletionFeed } from '@/runtime/native-chat/status/structured-agent-session-turn-completion-feed' +import { + isRemoteRuntimePtyId, + parseRemoteRuntimePtyId +} from '../../../../../../shared/remote-runtime/remote-runtime-pty-id' +import { getPtyIdForPaneKey } from '@/hooks/pane-key-pty-id' +import { isWindowVisible } from '@/lib/window-activity/window-visibility-interval' +import { mainAgentDoneAt } from '../../../../../../shared/agent-status/lifecycle/main-agent-status' +import { + type ExecutionHostId, + getConnectionExecutionHostId, + toRuntimeExecutionHostId, + toSshExecutionHostId +} from '../../../../../../shared/execution-host' +import { parsePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' +import { parseAppSshPtyId } from '../../../../../../shared/ssh-pty-id' +import type { AgentStatusChange } from '@/store/slices/agent-status/agent-status-contract' +import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' +import type { GitStatusRefreshScheduler } from './git-status-refresh-scheduler' + +export function isNewTerminalTurnEnd({ previous, current }: AgentStatusChange): boolean { + if ( + !current || + current.structuredHostOwned || + current.sessionBoundary || + current.restoredUnconfirmed + ) { + return false + } + if (current.turnEndedAt !== undefined && current.turnEndedAt !== previous?.turnEndedAt) { + return true + } + return ( + previous !== undefined && + mainAgentDoneAt(current) !== undefined && + mainAgentDoneAt(current) !== mainAgentDoneAt(previous) + ) +} + +export function useGitStatusTurnCompletion( + target: RuntimeClientTarget | null, + expectedHost: ExecutionHostId, + worktreeId: string | null, + enabled: boolean, + scheduler: { readonly current: GitStatusRefreshScheduler | null } +): void { + useEffect(() => { + if (!worktreeId || !enabled) { + return + } + let releaseVisible: (() => void) | undefined + const reconcile = (): void => { + if (!isWindowVisible()) { + releaseVisible?.() + releaseVisible = undefined + return + } + if (releaseVisible) { + return + } + const feed = target ? getStructuredAgentSessionTurnCompletionFeed(target) : null + const stopFeed = feed?.subscribe((edge) => { + if (edge.type !== 'completion' || !isWindowVisible()) { + return + } + const { scope, sessionId } = edge.completion + if (scope.executionHostId !== expectedHost) { + return + } + const tabs = useAppStore.getState().unifiedTabsByWorktree[worktreeId] ?? [] + if ( + scope.workspaceId === worktreeId || + tabs.some((tab) => tab.contentType === 'agent-session' && tab.entityId === sessionId) + ) { + scheduler.current?.signal() + } + }) + const releaseFeed = feed?.activate() + const stopTerminal = useAppStore.getState().subscribeAgentStatusChanges((changes) => { + if (!isWindowVisible()) { + return + } + for (const change of changes) { + if (!isNewTerminalTurnEnd(change)) { + continue + } + const row = change.current! + if (row.worktreeId !== undefined && row.worktreeId !== worktreeId) { + continue + } + const tabId = parsePaneKey(change.paneKey)?.tabId + const tabs = useAppStore.getState().unifiedTabsByWorktree[worktreeId] ?? [] + const tab = tabs.find( + (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId + ) + if (row.worktreeId !== worktreeId && !tab) { + continue + } + const ptyId = getPtyIdForPaneKey(change.paneKey) ?? '' + const runtimeId = parseRemoteRuntimePtyId(ptyId)?.environmentId + const ssh = parseAppSshPtyId(ptyId) + const host = + tab?.executionHostId ?? + (runtimeId + ? toRuntimeExecutionHostId(runtimeId) + : ssh + ? toSshExecutionHostId(ssh.connectionId) + : isRemoteRuntimePtyId(ptyId) || ptyId.startsWith('ssh:') + ? null + : row.connectionId !== undefined || ptyId + ? getConnectionExecutionHostId(row.connectionId) + : null) + if (host === expectedHost) { + scheduler.current?.signal() + break + } + } + }) + releaseVisible = () => { + stopTerminal() + stopFeed?.() + releaseFeed?.() + } + } + reconcile() + document.addEventListener('visibilitychange', reconcile) + return () => { + document.removeEventListener('visibilitychange', reconcile) + releaseVisible?.() + } + }, [target, expectedHost, worktreeId, enabled, scheduler]) +} diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-window-presence.ts b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-window-presence.ts index aaba1a9c06d..3929e5af68c 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-window-presence.ts +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-git-status-window-presence.ts @@ -40,9 +40,15 @@ export function useGitStatusWindowPresence( } document.addEventListener('visibilitychange', handleVisibilityChange) window.addEventListener('focus', handleWindowFocus) + const stopResume = window.api?.ui?.onSystemResumed?.(() => { + if (canFetch && isWindowVisible()) { + schedulerRef.current?.refreshNow() + } + }) return () => { document.removeEventListener('visibilitychange', handleVisibilityChange) window.removeEventListener('focus', handleWindowFocus) + stopResume?.() } }, [schedulerRef, canFetch, pollScope]) } diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-worktree-git-status-observation.ts b/src/renderer/src/components/right-sidebar/source-control/sync/use-worktree-git-status-observation.ts index 97b6759de8f..087e0964426 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/use-worktree-git-status-observation.ts +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-worktree-git-status-observation.ts @@ -23,6 +23,8 @@ import { resolveWorktreeGitCopyNow } from '@/lib/workspace/ownership/worktree-gi import { useGitStatusFileWatchRefresh } from './git-status-file-watch-refresh' import { useGitStatusPushSignalRefresh } from './git-status-push-signal-refresh' import { useGitStatusUpstreamRefWatch } from './use-git-status-upstream-ref-watch' +import { useWorktreeGitOwnerTarget } from './worktree-git-owner-target' +import { useGitStatusTurnCompletion } from './use-git-status-turn-completion' import { admissionTierForGitStatusRefreshReason, createGitStatusRefreshPacing, @@ -228,7 +230,8 @@ export function useWorktreeGitStatusObservation( slowTaskBackoff: SLOW_GIT_POLL_BACKOFF, pacing, // Agents editing files behind another app must not drive (remote) git status every 3s. - cadenceScale: windowPollSlowdown + cadenceScale: windowPollSlowdown, + activityCadenceScale: () => (windowPollSlowdown() === 1 ? 1 : 20) } ) statusSchedulerRef.current = scheduler @@ -250,6 +253,15 @@ export function useWorktreeGitStatusObservation( useRefreshOnHostContact(activeExecutionHostId, statusSchedulerRef, canApplyScheduledStatusRef) + const ownerTarget = useWorktreeGitOwnerTarget(activeWorktreeId, activeExecutionHostId) + useGitStatusTurnCompletion( + ownerTarget, + activeExecutionHostId, + activeWorktreeId, + canFetchActiveWorktreeGitStatus, + statusSchedulerRef + ) + const previousConsumerVisibilityRef = useRef({ worktreeId: activeWorktreeId, visible: interactiveConsumerVisible,