fix(build-sheet): review: build clock state lives on the entry (no setState in render), no flicker on resume, resumes after Open anyway; shortcut can't flip the hidden sidebar; hours keep minutes; matching non-Intl fallback; min-width timers; locale-pinned and clock/config/toggle tests

This commit is contained in:
Neil
2026-11-09 17:36:28 -08:00
parent 1876a91d1a
commit 54299a9412
14 changed files with 260 additions and 54 deletions
@@ -35,6 +35,22 @@ it('opens only a github.com page for Connect GitHub', async () => {
expect(openExternal).toHaveBeenCalledOnce()
})
it('re-reads the config after 5 minutes so a new build sheet sees a fresh median', async () => {
vi.useFakeTimers({ now: 0 })
try {
const config = register('https://github.com/x')
await handlers.get(CH.getConfig)?.()
vi.setSystemTime(4 * 60_000)
await handlers.get(CH.getConfig)?.()
expect(config).toHaveBeenCalledTimes(1)
vi.setSystemTime(5 * 60_000)
await handlers.get(CH.getConfig)?.()
expect(config).toHaveBeenCalledTimes(2)
} finally {
vi.useRealTimers()
}
})
it('reads the config once, and again after a failed read', async () => {
let fail = true
const config = vi.fn(async () => {
@@ -0,0 +1,53 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, expect, it } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import { useAppStore } from '@/store'
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
import { RightSidebarToggle } from './TitlebarMainStrip'
afterEach(cleanup)
function showCloudBuild(): void {
useAppStore.setState({
activeView: 'terminal',
activePendingCreationId: 'c1',
rightSidebarOpen: false,
pendingWorktreeCreations: {
c1: {
creationId: 'c1',
status: 'creating',
loaderVisible: true,
request: {
name: 'fix-login',
ephemeralVmRecipe: {
sourceRepoId: 'r',
recipeId: 'cloud',
projectId: 'p',
provider: 'orca-cloud'
}
}
} as PendingWorktreeCreation
}
})
}
it('explains itself instead of toggling a hidden sidebar during a build, by click or shortcut', () => {
showCloudBuild()
render(
<TooltipProvider>
<RightSidebarToggle />
</TooltipProvider>
)
const button = screen.getByRole('button', { name: 'Toggle right sidebar' })
expect(button.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(button)
// The shortcut path calls the store action directly.
act(() => useAppStore.getState().toggleRightSidebar())
expect(useAppStore.getState().rightSidebarOpen).toBe(false)
act(() => {
fireEvent.focus(button)
})
expect(document.body.textContent).toContain('Available when the workspace is ready')
})
@@ -77,7 +77,7 @@ export function VmBuildStepRow({
</span>
) : null}
{step.elapsedMs !== null && step.state !== 'pending' ? (
<span className="w-12 text-right text-xs tabular-nums text-muted-foreground">
<span className="min-w-12 shrink-0 whitespace-nowrap text-right text-xs tabular-nums text-muted-foreground">
{formatElapsedTime(step.elapsedMs)}
</span>
) : null}
@@ -9,7 +9,11 @@ import {
import { Progress } from '@/components/ui/progress'
import { useTranslate } from '@/i18n/use-translate'
import WorktreeCreationTabStrip from './WorktreeCreationTabStrip'
import { formatElapsedTime, useWorktreeCreationClock } from './worktree-creation-clock'
import {
buildClockElapsedMs,
formatElapsedTime,
useWorktreeCreationClock
} from './worktree-creation-clock'
import { VmBuildSheet } from './VmBuildSheet'
import { VmDeleteConfirmDialog } from './VmDeleteConfirmDialog'
@@ -25,38 +29,11 @@ export default function WorktreeCreationPanel({
const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId])
const progressLabelId = React.useId()
const [confirmingDelete, setConfirmingDelete] = React.useState(false)
const checksFinishedAt =
entry?.environmentCheck?.status === 'failed' ? entry.environmentCheck.finishedAt : undefined
// Depend on primitives so stderr’s fresh entry objects cannot continuously reset the interval;
// a build paused on failed checks waits on the user, so its clock stops.
const now = useWorktreeCreationClock(
entry?.status === 'creating' && entry.environmentCheck?.status !== 'failed'
entry?.status === 'creating' && entry.waitingSince === undefined
)
// Time spent waiting on the user after failed checks: Retry checks resumes the clock from where it
// stopped instead of jumping ahead by the wait.
const [paused, setPaused] = React.useState<{
run: number | undefined
ms: number
waitingSince: number | undefined
}>({ run: entry?.startedAt, ms: 0, waitingSince: undefined })
const restartedChecksAt =
entry?.environmentCheck?.status === 'running' ? entry.environmentCheck.startedAt : undefined
if (paused.run !== entry?.startedAt) {
// Try again starts a new run with its own clock.
setPaused({ run: entry?.startedAt, ms: 0, waitingSince: checksFinishedAt })
} else if (checksFinishedAt !== undefined && paused.waitingSince !== checksFinishedAt) {
setPaused({ ...paused, waitingSince: checksFinishedAt })
} else if (
checksFinishedAt === undefined &&
paused.waitingSince !== undefined &&
restartedChecksAt !== undefined
) {
setPaused({
...paused,
ms: paused.ms + Math.max(0, restartedChecksAt - paused.waitingSince),
waitingSince: undefined
})
}
if (!entry) {
return null
}
@@ -71,8 +48,7 @@ export default function WorktreeCreationPanel({
// A VM build keeps its sheet through fetch and checkout, so it never drops to the one-line status.
const isVmCreation = Boolean(entry.request.ephemeralVmRecipe) || entry.phase === 'provisioning-vm'
const title = entry.request.displayName || entry.request.name
const stoppedAt = checksFinishedAt ?? (isError ? entry.errorAt : undefined)
const elapsedLabel = formatElapsedTime((stoppedAt ?? now) - entry.startedAt - paused.ms)
const elapsedLabel = formatElapsedTime(buildClockElapsedMs(entry, now))
const checkoutProgress = getVisibleCheckoutProgress(entry)
return (
@@ -82,7 +82,7 @@ export function WorktreeSetupSteps({
<span className="text-xs tabular-nums text-muted-foreground">{step.percent}%</span>
) : null}
{step.elapsedMs !== null ? (
<span className="w-12 text-right text-xs tabular-nums text-muted-foreground">
<span className="min-w-12 shrink-0 whitespace-nowrap text-right text-xs tabular-nums text-muted-foreground">
{formatElapsedTime(step.elapsedMs)}
</span>
) : null}
@@ -0,0 +1,37 @@
// @vitest-environment happy-dom
import { cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import { useVmBuildStepTimings } from './vm-build-timing'
afterEach(() => {
cleanup()
vi.unstubAllGlobals()
})
it('asks for the measured timing on every new build sheet, never for VM recipes', async () => {
const getConfig = vi
.fn()
.mockResolvedValueOnce({
idleSleepMinutes: 15,
createTiming: { p50Ms: 3000, p95Ms: 9000, samples: 40 }
})
.mockResolvedValueOnce({
idleSleepMinutes: 15,
createTiming: { p50Ms: 5000, p95Ms: 9000, samples: 41 }
})
vi.stubGlobal('window', Object.assign(window, { api: { orcaCloudWorkspace: { getConfig } } }))
const first = renderHook(() => useVmBuildStepTimings(true))
await waitFor(() => expect(first.result.current.provision?.p50Ms).toBe(3000))
first.unmount()
const second = renderHook(() => useVmBuildStepTimings(true))
// The last answer shows at once, then the fresh one replaces it.
expect(second.result.current.provision?.p50Ms).toBe(3000)
await waitFor(() => expect(second.result.current.provision?.p50Ms).toBe(5000))
expect(getConfig).toHaveBeenCalledTimes(2)
renderHook(() => useVmBuildStepTimings(false))
expect(getConfig).toHaveBeenCalledTimes(2)
})
@@ -20,7 +20,7 @@ function loadMeasuredTimings(): Promise<VmBuildStepTimings> {
if (!config) {
// Unreachable now says nothing about later: the next sheet asks again.
pending = null
return NONE
return measured ?? NONE
}
// Only "Start sandbox" is measured. Without a measurement there is no hint, never a guess.
measured = config.createTiming ? { provision: config.createTiming } : NONE
@@ -29,7 +29,7 @@ function loadMeasuredTimings(): Promise<VmBuildStepTimings> {
})
.catch(() => {
pending = null
return NONE
return measured ?? NONE
})
return pending
}
@@ -0,0 +1,54 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/i18n/i18n', () => ({ getIntlLocale: () => 'en' }))
import { buildClockElapsedMs, formatElapsedTime } from './worktree-creation-clock'
afterEach(() => {
vi.unstubAllGlobals()
})
describe('formatElapsedTime', () => {
it('formats with Intl in the given locale and keeps minutes once past an hour', () => {
expect(formatElapsedTime(5_000, 'en')).toBe('5s')
expect(formatElapsedTime(125_000, 'en')).toBe('2m 5s')
expect(formatElapsedTime(3_605_000, 'en')).toBe('1h 0m 5s')
expect(formatElapsedTime(125_000, 'de')).toBe('2 Min., 5 Sek.')
})
it('falls back to the same English shape where Intl.DurationFormat is missing', () => {
vi.stubGlobal('Intl', { ...Intl, DurationFormat: undefined })
// A locale no earlier call cached, so the stub decides.
expect(formatElapsedTime(5_000, 'en-x-fallback')).toBe('5s')
expect(formatElapsedTime(125_000, 'en-x-fallback')).toBe('2m 5s')
expect(formatElapsedTime(3_605_000, 'en-x-fallback')).toBe('1h 0m 5s')
})
})
describe('buildClockElapsedMs', () => {
const T0 = 1_000_000
const base = { startedAt: T0, status: 'creating' as const }
it('stops while failed checks wait, resumes where it stopped, and starts over on Try again', () => {
// Checks fail 10s in; the user waits 50s.
const waiting = { ...base, waitingSince: T0 + 10_000 }
expect(buildClockElapsedMs(waiting, T0 + 60_000)).toBe(10_000)
// Retry checks at 60s: the wait is folded away.
const resumed = { ...base, pausedMs: 50_000, resumedAt: T0 + 60_000 }
// A stale tick from before the resume never reads below the frozen value.
expect(buildClockElapsedMs(resumed, T0 + 30_000)).toBe(10_000)
expect(buildClockElapsedMs(resumed, T0 + 65_000)).toBe(15_000)
// Checks fail again 5s later; another 100s wait stays frozen at 15s.
const waitingAgain = { ...resumed, waitingSince: T0 + 65_000 }
expect(buildClockElapsedMs(waitingAgain, T0 + 165_000)).toBe(15_000)
// Try again starts a new run with its own clock.
const retried = { startedAt: T0 + 200_000, status: 'creating' as const }
expect(buildClockElapsedMs(retried, T0 + 203_000)).toBe(3_000)
})
it('stops at an error', () => {
expect(
buildClockElapsedMs({ ...base, status: 'error', errorAt: T0 + 7_000 }, T0 + 99_000)
).toBe(7_000)
})
})
@@ -1,4 +1,5 @@
import { getIntlLocale } from '@/i18n/i18n'
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
import { useEffect, useState } from 'react'
import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval'
@@ -9,32 +10,66 @@ export function useWorktreeCreationClock(running: boolean): number {
if (!running) {
return
}
// A resumed clock reads the time at once rather than a tick later.
setNow(Date.now())
return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 })
}, [running])
return now
}
/**
* The build's own time: stopped while failed checks wait on the user (and at an error), with the
* waits left out, and never reading earlier than the last resume, so a stale tick cannot flicker back.
*/
export function buildClockElapsedMs(
entry: Pick<
PendingWorktreeCreation,
'startedAt' | 'status' | 'errorAt' | 'waitingSince' | 'pausedMs' | 'resumedAt'
>,
now: number
): number {
const end =
entry.waitingSince ??
(entry.status === 'error' ? entry.errorAt : undefined) ??
Math.max(now, entry.resumedAt ?? 0)
return Math.max(0, end - entry.startedAt - (entry.pausedMs ?? 0))
}
type DurationFormatter = { format: (duration: Record<string, number>) => string }
type DurationFormatOptions = {
style: 'narrow'
secondsDisplay: 'always'
minutesDisplay: 'always' | 'auto'
}
type DurationFormatConstructor = new (
locale: string,
options: { style: 'narrow'; secondsDisplay: 'always' }
options: DurationFormatOptions
) => DurationFormatter
const durationFormatters = new Map<string, DurationFormatter | null>()
// Intl.DurationFormat localizes units ("1m 5s", "1 Min., 5 Sek."); older runtimes keep the English form.
function durationFormatter(locale: string): DurationFormatter | null {
if (!durationFormatters.has(locale)) {
// Intl.DurationFormat localizes units ("1m 5s", "1 Min., 5 Sek."); runtimes without it get the same
// English shape. Past an hour the minutes always show ("1h 0m 5s"), so a glance never misreads it.
function durationFormatter(locale: string, withHours: boolean): DurationFormatter | null {
const key = `${locale}|${withHours}`
if (!durationFormatters.has(key)) {
const DurationFormat = (Intl as unknown as { DurationFormat?: DurationFormatConstructor })
.DurationFormat
durationFormatters.set(
locale,
DurationFormat
? new DurationFormat(locale, { style: 'narrow', secondsDisplay: 'always' })
let formatter: DurationFormatter | null = null
try {
formatter = DurationFormat
? new DurationFormat(locale, {
style: 'narrow',
secondsDisplay: 'always',
minutesDisplay: withHours ? 'always' : 'auto'
})
: null
)
} catch {
// An unsupported locale tag falls back to the English shape below.
}
durationFormatters.set(key, formatter)
}
return durationFormatters.get(locale) ?? null
return durationFormatters.get(key) ?? null
}
export function formatElapsedTime(elapsedMs: number, locale: string = getIntlLocale()): string {
@@ -42,13 +77,12 @@ export function formatElapsedTime(elapsedMs: number, locale: string = getIntlLoc
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds % 60
const formatter = durationFormatter(locale)
const formatter = durationFormatter(locale, hours > 0)
if (formatter) {
return formatter.format({ hours, minutes, seconds })
}
const totalMinutes = Math.floor(totalSeconds / 60)
if (totalMinutes === 0) {
return `${seconds}s`
if (hours > 0) {
return `${hours}h ${minutes}m ${seconds}s`
}
return `${totalMinutes}m ${seconds.toString().padStart(2, '0')}s`
return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`
}
@@ -70,6 +70,20 @@ async function runVmEnvironmentCheck(
* build sheet; it resolves true to continue (passed, unsupported, or "Open anyway") and false to cancel.
* Nothing here tears the VM down: only cancelling does, so a degraded open keeps the VM that provisioned.
*/
/** The user decided: fold the wait into pausedMs so the clock resumes where it stopped. */
export function resumeBuildClock(creationId: string, now = Date.now()): void {
const state = useAppStore.getState()
const entry = state.pendingWorktreeCreations[creationId]
if (entry?.waitingSince === undefined) {
return
}
state.updatePendingWorktreeCreation(creationId, {
pausedMs: (entry.pausedMs ?? 0) + Math.max(0, now - entry.waitingSince),
waitingSince: undefined,
resumedAt: now
})
}
export async function gateVmCreateOnEnvironmentCheck(
creationId: string,
environmentId: string,
@@ -105,13 +119,15 @@ export async function gateVmCreateOnEnvironmentCheck(
})
return true
}
const failedAt = Date.now()
update(creationId, {
environmentCheck: {
status: 'failed',
checks: result.checks,
startedAt,
finishedAt: Date.now()
}
finishedAt: failedAt
},
waitingSince: failedAt
})
if (useAppStore.getState().activePendingCreationId !== creationId) {
// The paused build keeps its VM running, so a background create must say it needs the user.
@@ -126,6 +142,7 @@ export async function gateVmCreateOnEnvironmentCheck(
if (decision === 'cancel' || !isPending()) {
return false
}
resumeBuildClock(creationId)
if (decision === 'open-anyway') {
toast.warning(
translate(
@@ -176,6 +176,12 @@ export type PendingWorktreeCreation = {
provisioningLogStamps?: readonly number[]
/** VM creates: the provisioned VM's environment checks, run before the workspace is created. */
environmentCheck?: PendingVmEnvironmentCheck
/** VM creates: since when failed checks have waited on the user; the build clock stops meanwhile. */
waitingSince?: number
/** VM creates: time already spent waiting on the user this run, left out of the build clock. */
pausedMs?: number
/** VM creates: when the user last resumed the build; the clock never reads earlier than this. */
resumedAt?: number
/** VM creates: the provisioned VM's runtime environment, known once it answers. */
vmEnvironmentId?: string
// Local git checkout meter; absent when git emits none or creation runs over SSH/runtime.
@@ -198,6 +198,9 @@ export function retryBackgroundWorktreeCreation(creationId: string): void {
provisioningLog: undefined,
provisioningLogStamps: undefined,
environmentCheck: undefined,
waitingSince: undefined,
pausedMs: undefined,
resumedAt: undefined,
checkoutProgress: undefined,
worktreeId: undefined
})
@@ -1,3 +1,4 @@
import { selectVmBuildSurfaceShown } from '@/lib/workspace/creation/worktree-creation-surface'
import type { EditorGet, EditorSet } from '../editor/types/editor-set-get'
import type { ActivityBarPosition } from '../editor/types/open-file'
import type {
@@ -35,7 +36,7 @@ export type RightSidebarState = {
setActivityBarPosition: (position: ActivityBarPosition) => void
}
export function createRightSidebarState(set: EditorSet, _get: EditorGet): RightSidebarState {
export function createRightSidebarState(set: EditorSet, get: EditorGet): RightSidebarState {
return {
rightSidebarOpen: false,
rightSidebarWidth: 280,
@@ -47,7 +48,13 @@ export function createRightSidebarState(set: EditorSet, _get: EditorGet): RightS
rightSidebarExplorerViewByWorktree: {},
rightSidebarEffectiveTab: null,
activityBarPosition: 'top',
toggleRightSidebar: () => set((s) => ({ rightSidebarOpen: !s.rightSidebarOpen })),
toggleRightSidebar: () => {
// A build sheet keeps the sidebar closed; flipping the hidden preference would surprise later.
if (selectVmBuildSurfaceShown(get())) {
return
}
set((s) => ({ rightSidebarOpen: !s.rightSidebarOpen }))
},
setRightSidebarOpen: (open) => set({ rightSidebarOpen: open }),
setRightSidebarWidth: (width) => set({ rightSidebarWidth: width }),
setRightSidebarTab: (tab) =>
@@ -182,6 +182,9 @@ export type WorktreeSlice = {
provisioningLog?: string
provisioningLogStamps?: PendingWorktreeCreation['provisioningLogStamps']
environmentCheck?: PendingWorktreeCreation['environmentCheck']
waitingSince?: number
pausedMs?: number
resumedAt?: number
vmEnvironmentId?: string
checkoutProgress?: PendingWorktreeCreation['checkoutProgress']
worktreeId?: string