fix(cloud): the workspace menu is whole on first paint; asleep cloud rows show Wake, not Sleep and Wake

Neil: right-clicking a cloud workspace, some rows appeared about a second later, and an asleep
cloud workspace showed both "Sleep" (the local close-panels item) and "Wake".

First paint:
- The team's record (Share with team / Make private, Copy › Workspace link) is kept per row
  across menu openings and fetched on row hover (deduped; refreshed when older than 30 s). Before
  the first answer for a row, its rows show disabled in place instead of appearing late.
- Move to this computer reads the cloud workspace store (the same list main serves, loaded before
  any menu opens) instead of asking main when the menu mounts.
- Remote desktop, Sleep/Wake/Restart/Archive already read stores primed before the menu opens.

Sleep/Wake: this desktop's own cloud workspace gets exactly one lifecycle item: Sleep when running,
Wake when asleep (Try waking again after a failed wake), Waking… disabled while waking, nothing while
provisioning or failed. Never the local close-panels Sleep beside it. Paired cloud rows (no VM
record here) keep their Sleep, which reaches the sandbox. Local workspaces are unchanged.

Evidence: fixture sidebar/.../WorktreeContextMenuCloudFirstPaint (answers delayed 900 ms), frames
at first paint and after 2.5 s, before and after.
This commit is contained in:
Neil
2026-11-16 02:04:33 -08:00
parent e6267478f7
commit 4b1cd8fcc6
8 changed files with 443 additions and 52 deletions
@@ -59,7 +59,7 @@ function CloudMenuRows({
}): React.JSX.Element {
const t = useTranslate()
const actions = useCloudPanelActions(worktreeId, noop)
const { workspace, reload } = useCloudWorkspaceRecord(worktreeId, hostId)
const { workspace, loaded, reload } = useCloudWorkspaceRecord(worktreeId, hostId)
const confirm = useContext(ConfirmationDialogContext)
const busy = view.pending !== undefined
const archived = view.state === 'archived'
@@ -98,12 +98,17 @@ function CloudMenuRows({
{t('orcaCloudWorkspace.unarchive', 'Unarchive')}
</DropdownMenuItem>
) : null}
{workspace && (has('share') || has('makePrivate')) ? (
{/* Before the first answer for this row (it's fetched on row hover, so rarely), the rows
show disabled instead of appearing under the pointer a moment later. */}
{(workspace || !loaded) && (has('share') || has('makePrivate')) ? (
<>
<DropdownMenuSeparator />
{has('share') ? (
<DropdownMenuItem
onSelect={() => void setVisibility(workspace, 'team', { reload, t, confirm })}
disabled={!workspace}
onSelect={() =>
workspace && void setVisibility(workspace, 'team', { reload, t, confirm })
}
>
<Users className="size-3.5" />
{t('auto.components.cloudWorkspaces.shareWithTeam', 'Share with team')}
@@ -111,7 +116,10 @@ function CloudMenuRows({
) : null}
{has('makePrivate') ? (
<DropdownMenuItem
onSelect={() => void setVisibility(workspace, 'private', { reload, t, confirm })}
disabled={!workspace}
onSelect={() =>
workspace && void setVisibility(workspace, 'private', { reload, t, confirm })
}
>
<Lock className="size-3.5" />
{t('auto.components.cloudWorkspaces.makePrivate', 'Make private')}
@@ -183,16 +191,20 @@ export function CloudCopyWorkspaceLinkItem({
hostId?: string | null
}): React.JSX.Element | null {
const t = useTranslate()
const { workspace } = useCloudWorkspaceRecord(worktreeId, hostId ?? null)
const { workspace, loaded } = useCloudWorkspaceRecord(worktreeId, hostId ?? null)
// SHARE-LINKS-HOLD: no way to produce a share link while it's held.
const shareLinks = useCloudTeamSharingEnabled()
if (!workspace || !shareLinks) {
// Not asked yet: disabled in place rather than appearing a moment later.
if ((!workspace && loaded) || !shareLinks) {
return null
}
return (
<DropdownMenuItem onSelect={() => void copyCloudWorkspaceLink(workspace.id)}>
<DropdownMenuItem
disabled={!workspace}
onSelect={() => workspace && void copyCloudWorkspaceLink(workspace.id)}
>
<Link2 className="size-3.5" />
{workspace.number
{workspace?.number
? t('auto.components.cloudWorkspaces.linkToNumber', 'Link to {{number}}', {
number: formatWorkspaceNumber(workspace.number)
})
@@ -0,0 +1,63 @@
// @vitest-environment happy-dom
// Menu rows that need the team's record are there on the menu's first paint: the record is kept
// per row and fetched on row hover, not first asked for when the menu opens.
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
prefetchCloudWorkspaceRecord,
RECORD_FRESH_MS,
resetCloudWorkspaceRecordsForTests,
useCloudWorkspaceRecord
} from './use-cloud-workspace-record'
const bridge = {
localWorkspaces: vi.fn(async () => [{ worktreeId: 'w', sandboxId: 'sbx' }]),
environmentBindings: vi.fn(async () => ({})),
get: vi.fn(async () => ({ ok: true, value: { id: 'sbx', visibility: 'private' } }))
}
beforeEach(() => {
resetCloudWorkspaceRecordsForTests()
vi.clearAllMocks()
Object.assign(window, { api: { cloudWorkspaces: bridge } })
})
afterEach(() => {
Object.assign(window, { api: undefined })
})
async function settle(): Promise<void> {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
describe('useCloudWorkspaceRecord', () => {
it('a menu opened after row hover has the record on its first render', async () => {
prefetchCloudWorkspaceRecord('w', null)
await settle()
const { result } = renderHook(() => useCloudWorkspaceRecord('w', null))
expect(result.current.loaded).toBe(true)
expect(result.current.workspace?.id).toBe('sbx')
})
it('says not loaded until the first answer, then updates in place', async () => {
const { result } = renderHook(() => useCloudWorkspaceRecord('w', null))
expect(result.current.loaded).toBe(false)
await settle()
expect(result.current.loaded).toBe(true)
expect(result.current.workspace?.id).toBe('sbx')
})
it('hovering again while fresh asks nothing; a stale record is refreshed', async () => {
prefetchCloudWorkspaceRecord('w', null, 1_000)
prefetchCloudWorkspaceRecord('w', null, 1_000)
await settle()
expect(bridge.get).toHaveBeenCalledOnce()
prefetchCloudWorkspaceRecord('w', null, Date.now() + 1)
await settle()
expect(bridge.get).toHaveBeenCalledOnce()
prefetchCloudWorkspaceRecord('w', null, Date.now() + RECORD_FRESH_MS)
await settle()
expect(bridge.get).toHaveBeenCalledTimes(2)
})
})
@@ -1,37 +1,92 @@
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useSyncExternalStore } from 'react'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { toRuntimeExecutionHostId } from '../../../../shared/execution-host'
/**
* The team's record of the cloud workspace behind a sidebar row (visibility, access), so the
* sidebar menu can offer the same Share actions as Home. Owned workspaces are found through this
* desktop's runtime; paired ones through their pairing. Null until loaded or when there is none.
* desktop's runtime; paired ones through their pairing.
*
* Kept per row across menu openings (last known), and fetched before the menu opens (row hover),
* so the menu's rows are there on its first paint instead of appearing a second later. A record
* older than RECORD_FRESH_MS is shown and refreshed in the background.
*/
export const RECORD_FRESH_MS = 30_000
type Entry = { workspace: CloudWorkspace | null; at: number }
const records = new Map<string, Entry>()
const inFlight = new Map<string, Promise<void>>()
const listeners = new Set<() => void>()
function key(worktreeId: string, hostId: string | null | undefined): string {
return `${worktreeId}\0${hostId ?? ''}`
}
function api(): NonNullable<Window['api']>['cloudWorkspaces'] | undefined {
return typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined
}
function fetchRecord(worktreeId: string, hostId: string | null | undefined): Promise<void> {
const bridge = api()
const k = key(worktreeId, hostId)
if (!bridge) {
return Promise.resolve()
}
const running = inFlight.get(k)
if (running) {
return running
}
const run = (async () => {
const sandboxId = await resolveSandboxId(bridge, worktreeId, hostId)
const result = sandboxId ? await bridge.get(sandboxId).catch(() => null) : null
records.set(k, { workspace: result?.ok ? result.value : null, at: Date.now() })
for (const listener of listeners) {
listener()
}
})().finally(() => inFlight.delete(k))
inFlight.set(k, run)
return run
}
/** Loads the record unless a fresh one is known; for row hover, before any menu opens. */
export function prefetchCloudWorkspaceRecord(
worktreeId: string,
hostId: string | null | undefined,
now = Date.now()
): void {
const known = records.get(key(worktreeId, hostId))
if (!known || now - known.at >= RECORD_FRESH_MS) {
void fetchRecord(worktreeId, hostId)
}
}
/**
* `workspace`: the last known record, null when there is none. `loaded`: false only until the
* first answer for this row, the one time a caller can't yet tell "none" from "not asked".
*/
export function useCloudWorkspaceRecord(
worktreeId: string,
hostId: string | null | undefined
): { workspace: CloudWorkspace | null; reload: () => void } {
const [workspace, setWorkspace] = useState<CloudWorkspace | null>(null)
const [generation, setGeneration] = useState(0)
): { workspace: CloudWorkspace | null; loaded: boolean; reload: () => void } {
const entry = useSyncExternalStore(
(listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
() => records.get(key(worktreeId, hostId))
)
useEffect(() => {
const api = typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined
if (!api) {
return
}
let cancelled = false
void (async () => {
const sandboxId = await resolveSandboxId(api, worktreeId, hostId)
const result = sandboxId ? await api.get(sandboxId).catch(() => null) : null
if (!cancelled) {
setWorkspace(result?.ok ? result.value : null)
}
})()
return () => {
cancelled = true
}
}, [worktreeId, hostId, generation])
const reload = useCallback(() => setGeneration((value) => value + 1), [])
return { workspace, reload }
prefetchCloudWorkspaceRecord(worktreeId, hostId)
}, [worktreeId, hostId])
const reload = useCallback(() => void fetchRecord(worktreeId, hostId), [worktreeId, hostId])
return { workspace: entry?.workspace ?? null, loaded: entry !== undefined, reload }
}
/** Tests: forget every record. */
export function resetCloudWorkspaceRecordsForTests(): void {
records.clear()
inFlight.clear()
}
async function resolveSandboxId(
@@ -1,34 +1,25 @@
import React, { useEffect, useState } from 'react'
import React from 'react'
import { Monitor } from 'lucide-react'
import { DropdownMenuItem } from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
import { openMoveToThisComputer } from '@/lib/orca-cloud/orca-cloud-move-store'
import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store'
import { useAppStore } from '@/store'
import { findWorktreeById } from '@/store/github/refresh/worktree-refresh'
/** "Move to this computer" for Orca Cloud workspaces. Mounted only inside the open menu. */
/**
* "Move to this computer" for this desktop's own Orca Cloud workspaces. Reads the cloud workspace
* store (the same list main serves, loaded before any menu opens), so it is there on the menu's
* first paint instead of popping in after an IPC round trip.
*/
export function WorktreeCloudTransferMenuItem({
worktreeId
}: {
worktreeId: string
}): React.JSX.Element | null {
const t = useTranslate()
const [isCloud, setIsCloud] = useState(false)
useEffect(() => {
let live = true
const api = window.api?.orcaCloudWorkspace
if (!api?.prepareTransferToLocal) {
return
}
void api
.listCloudWorkspaceIds()
.then((ids) => live && setIsCloud(ids.includes(worktreeId)))
.catch(() => undefined)
return () => {
live = false
}
}, [worktreeId])
if (!isCloud) {
const isCloud = useIsCloudWorkspace(worktreeId)
if (!isCloud || !window.api?.orcaCloudWorkspace?.prepareTransferToLocal) {
return null
}
return (
@@ -0,0 +1,125 @@
// MENU-FIRST-PAINT (Neil): a cloud workspace's right-click menu is whole when it opens; nothing
// appears a second later. The answers this menu used to wait for take 900 ms here (a slow link):
// the cloud workspace list and the team's record. Running and asleep (one Sleep or Wake item).
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import type { Repo } from '../../../../../../shared/repo-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import type { HostedWorkspaceStatus } from '../../../../../../shared/hosted-sandbox/hosted-sandbox-wire'
import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store'
import WorktreeContextMenu from './WorktreeContextMenu'
const SLOW_MS = 900
const slow = <T,>(value: T): Promise<T> =>
new Promise((resolve) => setTimeout(() => resolve(value), SLOW_MS))
const repo: Repo = {
id: 'cloud-repo',
path: '/workspace/hello-world',
displayName: 'hello-world',
badgeColor: '',
addedAt: 1
}
function cloudWorktree(id: string, name: string): Worktree {
return {
id,
repoId: repo.id,
hostId: 'runtime:env-cloud',
instanceId: `${id}-instance`,
path: '/workspace/hello-world',
displayName: name,
branch: 'refs/heads/fix-login',
head: 'abc123',
isBare: false,
isMainWorktree: false,
comment: '',
linkedIssue: null,
linkedPR: null,
linkedLinearIssue: null,
isArchived: false,
isUnread: false,
isPinned: false,
sortOrder: 0,
lastActivityAt: 1
}
}
const status = (state: 'ready' | 'sleeping'): HostedWorkspaceStatus => ({
state,
metrics: null,
uptimeMs: null,
usage: { totalMs: 0, centsPerHour: 100, costCents: 0 },
archive: null,
checkedAt: 1
})
function firstPaint(asleep: boolean) {
const worktree = cloudWorktree(asleep ? 'cloud-asleep' : 'cloud-running', 'fix login')
return defineFixture({
width: 420,
store: {
repos: [repo],
worktreesByRepo: { [repo.id]: [worktree] },
// Team sharing on, so the Share row (which needs the team's record) is in the menu.
orcaProfileAuthStatus: {
activeProfileId: 'p',
configured: true,
state: 'connected',
persistence: 'encrypted',
cloud: { cloudProfileId: 'c', userId: 'u', email: 'e', activeOrgId: 'o', linkedAt: 0 },
organizations: [{ orgId: 'o', name: 'Team', role: 'Owner' }],
capabilities: { flags: { cloudTeamSharing: true }, refreshedAt: 0 }
},
ephemeralVmRuntimesByWorkspaceId: {
[worktree.id]: {
id: 'vm-1',
workspaceId: worktree.id,
status: asleep ? 'suspended' : 'running',
runtimeEnvironmentId: 'env-cloud',
canSuspend: true
}
},
// Restored panels on the asleep one: what made the local "Sleep" show beside Wake.
browserTabsByWorktree: asleep ? { [worktree.id]: [{ id: 'browser-1' }] } : {}
},
setup: () => {
seedCloudWorkspaceSnapshot({
ids: new Set([worktree.id]),
idsLoaded: true,
status: {
[worktree.id]: {
status: status(asleep ? 'sleeping' : 'ready'),
loading: false,
error: null,
fetchedAt: Date.now()
}
}
})
Object.assign(window.api.orcaCloudWorkspace, {
listCloudWorkspaceIds: () => slow([worktree.id]),
prepareTransferToLocal: () => slow(null)
})
Object.assign(window.api.cloudWorkspaces, {
localWorkspaces: () => slow([{ worktreeId: worktree.id, sandboxId: 'sbx_1' }]),
environmentBindings: () => slow({}),
get: () =>
slow({
ok: true,
value: { id: 'sbx_1', status: 'running', visibility: 'private', access: 'owner' }
})
})
},
render: () => (
<div className="h-[520px] bg-background p-4 text-foreground">
<WorktreeContextMenu worktree={worktree}>
<div className="text-sm" data-first-paint-row>
fix login
</div>
</WorktreeContextMenu>
</div>
)
})
}
export const running = firstPaint(false)
export const asleep = firstPaint(true)
@@ -15,6 +15,7 @@ import {
CloudCopyWorkspaceLinkItem,
CloudWorkspaceMenuItems
} from '@/components/orca-cloud/CloudWorkspaceMenuItems'
import { prefetchCloudWorkspaceRecord } from '@/components/orca-cloud/use-cloud-workspace-record'
import { useIsCloudHostRow, usePrimeCloudRowBindings } from '@/lib/orca-cloud/cloud-host-rows'
import { getWorktreeExecutionHostId } from '../../../../../../shared/execution-host'
import { WorktreeOpenInAndSshSubMenus } from '../cloud-ssh/WorktreeOpenInAndSshSubMenus'
@@ -104,6 +105,17 @@ export default function WorktreeContextMenuView({ model }: { model: WorktreeCont
ref={scopeRef}
className="relative"
{...{ [WORKTREE_CONTEXT_MENU_SCOPE_ATTR]: 'worktree' }}
// The cloud menu's Share and link rows need the team's record: fetch it while the pointer is
// on the row, so it's there when the menu opens (cached; a fresh one isn't fetched again).
onPointerEnter={
isCloud
? () =>
prefetchCloudWorkspaceRecord(
worktree.id,
getWorktreeExecutionHostId(worktree, repo ?? undefined)
)
: undefined
}
onContextMenuCapture={(event) => {
if (!isEventTargetInsideCurrentTarget(event.currentTarget, event.target)) {
return
@@ -0,0 +1,129 @@
// @vitest-environment happy-dom
// Neil: an asleep cloud workspace's menu showed "Sleep" (the local close-panels item) beside "Wake".
// A cloud row gets one lifecycle item for its state; local VM workspaces are unchanged.
import { cleanup, render, screen } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
type MenuState = {
runtime: null | { status: string; canSuspend?: boolean }
waking: boolean
ownedCloud: boolean
archived: boolean
}
const { state } = vi.hoisted(() => {
const initial: MenuState = { runtime: null, waking: false, ownedCloud: false, archived: false }
return { state: initial }
})
vi.mock('@/store', () => ({
useAppStore: (select: (s: unknown) => unknown) =>
select({
ephemeralVmRuntimesByWorkspaceId: state.runtime ? { w: state.runtime } : {},
wakingEphemeralVmWorkspaceIds: state.waking ? { w: true } : {}
})
}))
vi.mock('@/lib/orca-cloud/orca-cloud-workspace-store', () => ({
useIsCloudWorkspace: () => state.ownedCloud,
useCloudWorkspace: () => state.archived
}))
vi.mock('@/lib/workspace/activation/sidebar-worktree-activation', () => ({
resumeEphemeralVmWorkspace: vi.fn(),
suspendEphemeralVmWorkspace: vi.fn()
}))
vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuItem: ({ children, disabled }: { children: React.ReactNode; disabled?: boolean }) => (
<div role="menuitem" aria-disabled={disabled || undefined}>
{children}
</div>
)
}))
vi.mock('@/components/ui/tooltip', () => ({
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipContent: () => null
}))
import { WorkspaceVmLifecycleMenuItems } from './WorkspaceVmLifecycleMenuItems'
const PANEL_SLEEP = <div role="menuitem">Close panels sleep</div>
function items({ hasSleepableActivity = true } = {}): string[] {
render(
<WorkspaceVmLifecycleMenuItems
worktreeId="w"
hasSleepableActivity={hasSleepableActivity}
disabled={false}
onSleep={vi.fn()}
hasActiveDescendants={false}
onSleepSubtree={vi.fn()}
sleepItems={PANEL_SLEEP}
replacesSleep
/>
)
return screen.queryAllByRole('menuitem').map((item) => {
const label = item.textContent ?? ''
return item.getAttribute('aria-disabled') ? `${label} (disabled)` : label
})
}
function set(patch: Partial<MenuState>): void {
Object.assign(state, { runtime: null, waking: false, ownedCloud: false, archived: false }, patch)
}
afterEach(cleanup)
describe('a cloud workspace has one lifecycle item for its state', () => {
it('running: Sleep, without the local close-panels Sleep', () => {
set({ ownedCloud: true, runtime: { status: 'running' } })
expect(items()).toEqual(['Sleep'])
})
it('asleep with restored panels: Wake only (the bug: Sleep and Wake together)', () => {
set({ ownedCloud: true, runtime: { status: 'suspended' } })
expect(items()).toEqual(['Wake'])
})
it('waking: Waking…, disabled', () => {
set({ ownedCloud: true, runtime: { status: 'suspended' }, waking: true })
expect(items()).toEqual(['Waking… (disabled)'])
})
it('a wake that failed: Try waking again', () => {
set({ ownedCloud: true, runtime: { status: 'resume_failed' } })
expect(items()).toEqual(['Try waking again'])
})
it('transitioning (provisioning): no lifecycle item, not the local Sleep', () => {
set({ ownedCloud: true, runtime: { status: 'provisioning' } })
expect(items()).toEqual([])
})
it('paired (no VM record here): its Sleep is the one that reaches the sandbox', () => {
set({ runtime: null })
expect(items()).toEqual(['Close panels sleep'])
})
it('archived: nothing', () => {
set({ ownedCloud: true, runtime: { status: 'running' }, archived: true })
expect(items()).toEqual([])
})
})
describe('local workspaces are unchanged', () => {
it('no VM: the close-panels Sleep', () => {
set({})
expect(items()).toEqual(['Close panels sleep'])
})
it('a suspended local VM with restored panels keeps both Sleep and Resume VM', () => {
set({ runtime: { status: 'suspended' } })
expect(items()).toEqual(['Close panels sleep', 'Resume VM'])
})
it('a running local VM: Suspend VM in place of Sleep', () => {
set({ runtime: { status: 'running' } })
expect(items()).toEqual(['Suspend VM'])
})
})
@@ -111,7 +111,9 @@ export function WorkspaceVmLifecycleMenuItems({
return null
}
if (!action) {
return <>{sleepItems}</>
// This desktop's own cloud workspace mid-transition has no lifecycle item. (A paired one has no
// VM record here; its Sleep is `sleepItems`, which reaches the sandbox.)
return cloud ? null : <>{sleepItems}</>
}
const vmItem = (
<VmLifecycleMenuItem
@@ -134,8 +136,10 @@ export function WorkspaceVmLifecycleMenuItems({
/>
)
// Sleep and Suspend VM are one action on a running VM. A VM still asleep or waking keeps Sleep
// only while it has restored panels to close; otherwise Sleep would sit there disabled.
return replacesSleep && (action === 'suspend' || !hasSleepableActivity) ? (
// only while it has restored panels to close; otherwise Sleep would sit there disabled. Not on
// Orca Cloud (Neil): there that "Sleep" read as a second, contradictory item beside Wake; the
// cloud row has exactly one lifecycle item, Sleep or Wake.
return cloud || (replacesSleep && (action === 'suspend' || !hasSleepableActivity)) ? (
vmItem
) : (
<>