diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx index e0d6d830c49..f83a4a3cdaf 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.fixture.tsx @@ -237,24 +237,26 @@ function stubWithRoutineRuns(): void { }) stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) Object.assign(window.api.cloudWorkspaces, { - list: (query: { routines?: string }) => + list: (query: { routines?: string; archived?: string }) => Promise.resolve( - query.routines === 'include' - ? { - ok: true as const, - value: [run, ...rows], - routineRuns: { routines: 2, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 } - } - : { - ok: true as const, - value: rows, - routineRuns: { - routines: 2, - hidden: 1, - hiddenRunning: 1, - hiddenComputeMs: run.cost.computeMs + query.archived === 'only' + ? { ok: true as const, value: [] } + : query.routines === 'include' + ? { + ok: true as const, + value: [run, ...rows], + routineRuns: { routines: 2, hidden: 0, hiddenRunning: 0, hiddenComputeMs: 0 } + } + : { + ok: true as const, + value: rows, + routineRuns: { + routines: 2, + hidden: 1, + hiddenRunning: 1, + hiddenComputeMs: run.cost.computeMs + } } - } ) }) } @@ -330,8 +332,11 @@ export const emptyMine = defineFixture({ const rows = teamWorkspaces() stubCloudWorkspacesApi(() => Promise.resolve({ ok: true, value: rows })) Object.assign(window.api.cloudWorkspaces, { - list: (query: { scope?: string }) => - Promise.resolve({ ok: true as const, value: query.scope === 'mine' ? [] : rows }) + list: (query: { scope?: string; archived?: string }) => + Promise.resolve({ + ok: true as const, + value: query.scope === 'mine' || query.archived === 'only' ? [] : rows + }) }) }, render: () => , @@ -344,3 +349,64 @@ export const emptyMine = defineFixture({ await waitFor(() => (document.querySelector('section')?.textContent ?? '').includes('yet.')) } }) + +/** ARCHIVE-REACH: n archived workspaces for Home's archived count and the Archived switch. */ +function archivedRows(n: number) { + return Array.from({ length: n }, (_, i) => + workspace({ + title: [ + 'fix-auth-redirect', + 'billing-retries', + 'docs-refresh', + 'perf-trace', + 'flaky-ci', + 'old-spike' + ][i % 6], + status: 'suspended', + archivedAt: Date.now() - (i + 1) * 86_400_000, + section: null + }) + ) +} + +function homeWith(active: number, archived: number, showArchived = false) { + return defineFixture({ + width: WIDTH, + store: { orcaProfileAuthStatus: AUTH_STATUS }, + setup: () => { + writeHomeSwitches(FIXTURE_ACCOUNT, { + running: false, + archived: showArchived, + routines: false + }) + const rows = [...teamWorkspaces(), workspace({ title: 'Release notes' })].slice(0, active) + stubCloudWorkspacesApi( + () => Promise.resolve({ ok: true, value: rows }), + archivedRows(archived) + ) + }, + render: () => , + interact: async () => { + await waitFor(() => document.querySelector('[data-cloud-workspace-row], section p') !== null) + // The archived count lands just after the list. + await new Promise((resolve) => setTimeout(resolve, 300)) + } + }) +} + +/** Archived your only workspace: Home says so and offers Show archived (2). */ +export const allArchived = homeWith(0, 2) +/** Nothing at all: the first-run invitation, no archived link. */ +export const noneAtAll = homeWith(0, 0) +/** 3 active, 2 archived: JA-30's minimal row plus the Archived (2) switch on its own. */ +export const fewWithArchived = homeWith(3, 2) +/** 3 active, none archived: JA-30 unchanged, no switch. */ +export const fewNoArchived = homeWith(3, 0) +/** 5+ active, 2 archived: the full filter row; the switch shows its count. */ +export const manyWithArchived = homeWith(7, 2) +/** 5+ active, none archived: the full filter row, plain Archived. */ +export const manyNoArchived = homeWith(7, 0) +/** The switch on with 2 archived: the rows, and the minimal row keeps only the switch. */ +export const archivedShown = homeWith(3, 2, true) +/** The switch on with 6 archived: 5+ rows shown, so the full filter row (JA-30's rule, same as active). */ +export const manyArchivedShown = homeWith(3, 6, true) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx index 4bb5d8d56db..ff37f5a6924 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesHome.tsx @@ -17,7 +17,13 @@ import { CloudWorkspaceRow } from './CloudWorkspaceRow' import { CloudWorkspaceGroupView, rowDragProps } from './CloudWorkspaceGroup' import { useCloudWorkspaceArrangement } from './use-cloud-workspace-arrangement' import { NEW_SECTION } from './CloudWorkspaceRowMenu' -import { ANY, CloudWorkspacesToolbar, shouldShowCloudHomeFilters } from './CloudWorkspacesToolbar' +import { + ANY, + CloudWorkspacesToolbar, + shouldShowCloudHomeArchivedOnly, + shouldShowCloudHomeFilters +} from './CloudWorkspacesToolbar' +import { useHomeArchivedCount } from './use-cloud-archived-count' import { EmptyState, ErrorState, NewSectionDialog, SkeletonRows } from './CloudWorkspacesStates' import { useCloudHomeFilters } from './use-cloud-home-filters' import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog' @@ -107,6 +113,15 @@ export function CloudWorkspacesHome({ // A workspace being deleted (or gone) is not something to open or manage; Home leaves it out. const all = useHomeWorkspaces(state.status === 'ready' ? state.workspaces : null) + // ARCHIVE-REACH: archived ones are always reachable, however few workspaces are active. + const { archivedRead, archivedCount } = useHomeArchivedCount({ + account, + scope, + shown: state.status === 'ready' && !stale ? all : null, + archivedOn: filters.archived, + enabled: Boolean(cloud) + }) + const showFilters = shouldShowCloudHomeFilters(all.length, filters, Boolean(orgId)) const { directory, canAdmin } = useMemberDirectory(orgId, all) const repos = useMemo( () => [...new Set(all.flatMap((w) => (w.repo ? [w.repo.url] : [])))].sort(), @@ -277,7 +292,14 @@ export function CloudWorkspacesHome({ reading={reading} onRefresh={refresh} routineRuns={routineRuns} - showFilters={shouldShowCloudHomeFilters(all.length, filters, Boolean(orgId))} + showFilters={showFilters} + archivedOnly={shouldShowCloudHomeArchivedOnly({ + showFilters, + archivedCount, + archivedOn: filters.archived, + activeCount: all.length + })} + archivedCount={archivedCount} />
changeFilters({ archived: true })} /> )} {state.status === 'ready' && diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx index 6bbaa0fa414..8f9dd84d3e1 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.test.tsx @@ -75,7 +75,9 @@ it('shows the filters from 5 workspaces, or whenever a filter is on so it can be expect(shouldShowCloudHomeFilters(0, DEFAULTS, true)).toBe(false) expect(shouldShowCloudHomeFilters(4, DEFAULTS, true)).toBe(false) expect(shouldShowCloudHomeFilters(5, DEFAULTS, true)).toBe(true) - expect(shouldShowCloudHomeFilters(0, { ...DEFAULTS, archived: true }, true)).toBe(true) + // The Archived switch alone doesn't bring the full row (ARCHIVE-REACH): the list's size does. + expect(shouldShowCloudHomeFilters(2, { ...DEFAULTS, archived: true }, true)).toBe(false) + expect(shouldShowCloudHomeFilters(5, { ...DEFAULTS, archived: true }, true)).toBe(true) expect(shouldShowCloudHomeFilters(1, { ...DEFAULTS, scope: 'mine' }, true)).toBe(true) expect(shouldShowCloudHomeFilters(1, { ...DEFAULTS, repo: 'https://x/y' }, true)).toBe(true) expect(shouldShowCloudHomeFilters(1, { ...DEFAULTS, running: true }, true)).toBe(true) diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx index e51a4a69d6c..1c22c2985f8 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesStates.tsx @@ -144,13 +144,18 @@ export function EmptyState({ scope, archived, filtered, - hasOrg = true + hasOrg = true, + archivedCount = 0, + onShowArchived }: { scope: 'team' | 'mine' archived: boolean filtered: boolean /** On a team: an empty Mine list says it's yours that's empty, not that nobody has started one. */ hasOrg?: boolean + /** Archived workspaces in this scope: an empty list then says so and offers them (ARCHIVE-REACH). */ + archivedCount?: number + onShowArchived?: () => void }): React.JSX.Element { const t = useTranslate() // Nothing to filter or share yet: say how to start one (JA-30), in the glossary's own words. @@ -171,18 +176,29 @@ export function EmptyState({ 'Archived cloud workspaces show up here.' ) ] - : scope === 'mine' && hasOrg + : archivedCount > 0 ? [ t( - 'components.cloudWorkspaces.emptyMineYoursTitle', - 'You don’t have any cloud workspaces yet.' + 'components.cloudWorkspaces.emptyAllArchivedTitle', + 'All your cloud workspaces are archived' ), - startBody - ] - : [ - t('components.cloudWorkspaces.emptyFirstTitle', 'Start your first cloud workspace'), - startBody + t( + 'components.cloudWorkspaces.emptyAllArchivedBody', + 'Unarchive one to keep working, or start a new one.' + ) ] + : scope === 'mine' && hasOrg + ? [ + t( + 'components.cloudWorkspaces.emptyMineYoursTitle', + 'You don’t have any cloud workspaces yet.' + ), + startBody + ] + : [ + t('components.cloudWorkspaces.emptyFirstTitle', 'Start your first cloud workspace'), + startBody + ] // Spec E3: an empty Mine or Team list offers a real button, not just copy. const offerCreate = !filtered && !archived return ( @@ -200,6 +216,13 @@ export function EmptyState({ {t('components.cloudWorkspaces.newCloudWorkspace', 'New cloud workspace')} ) : null} + {offerCreate && archivedCount > 0 && onShowArchived ? ( + + ) : null}
) } diff --git a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx index 07948138d30..6f0caf88e7c 100644 --- a/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx +++ b/src/renderer/src/components/cloud-workspaces/CloudWorkspacesToolbar.tsx @@ -63,12 +63,37 @@ export function shouldShowCloudHomeFilters( (hasOrg && filters.scope !== INITIAL_CLOUD_WORKSPACE_FILTERS.scope) || filters.by !== ANY || filters.repo !== ANY || - filters.archived || + // The Archived switch is not a reason for the full row: the row follows the list it shows + // (5+ archived rows: full row; fewer: the switch on its own), so turning it on never floods. filters.running === true || filters.routines === true return active || count >= CLOUD_HOME_FILTERS_MIN } +/** + * ARCHIVE-REACH: with the filter row hidden (few workspaces, JA-30), archived workspaces still get + * their Archived switch on its own, so archiving your only workspace never leaves Home without a way + * back to it. + */ +export function shouldShowCloudHomeArchivedOnly({ + showFilters, + archivedCount, + archivedOn, + activeCount +}: { + showFilters: boolean + archivedCount: number | null + /** The switch is on: it stays, so the active list is one click back. */ + archivedOn: boolean + /** With nothing active, the empty state's "Show archived (N)" is the one way in (no second control). */ + activeCount: number +}): boolean { + if (showFilters) { + return false + } + return archivedOn || ((archivedCount ?? 0) > 0 && activeCount > 0) +} + /** Row 1: title, count and cost, refresh. Row 2: whose, by whom, which repo, running, routine runs, archived. */ export function CloudWorkspacesToolbar({ filters, @@ -83,7 +108,9 @@ export function CloudWorkspacesToolbar({ reading, onRefresh, routineRuns, - showFilters = true + showFilters = true, + archivedOnly = false, + archivedCount = null }: { filters: CloudWorkspacesFilters onFiltersChange: (next: Partial) => void @@ -101,11 +128,30 @@ export function CloudWorkspacesToolbar({ routineRuns?: CloudWorkspaceRoutineRuns /** False with only a few workspaces and no filter on: title and count only (JA-30). */ showFilters?: boolean + /** With the filters hidden: still show the Archived switch, because archived ones exist. */ + archivedOnly?: boolean + /** How many archived workspaces the switch shows; null while unknown. */ + archivedCount?: number | null }): React.JSX.Element { const t = useTranslate() // Routines start cloud workspaces on their own, so they sit next to the list they fill. // Routines are parked (cloud-routines-ui.ts): no Routines entry and no Routine runs switch. const routinesAvailable = useOrcaCloudApiAvailable() && CLOUD_ROUTINES_UI_ENABLED + // The count says why the switch is there and what turning it on shows. + const archivedSwitch = ( + + ) return (
@@ -248,16 +294,15 @@ export function CloudWorkspacesToolbar({ )} ) : null} - + {/* One Archived switch at a time: here, or on its own row below. */} + {showFilters ? archivedSwitch : null}
+ {!showFilters && archivedOnly ? ( +
+ {archivedSwitch} +
+ ) : null} {/* T4: the team's trial ran out; running sandboxes sleep until a plan starts. */} diff --git a/src/renderer/src/components/cloud-workspaces/cloud-archive-reach.test.tsx b/src/renderer/src/components/cloud-workspaces/cloud-archive-reach.test.tsx new file mode 100644 index 00000000000..6f07b1b2bb7 --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/cloud-archive-reach.test.tsx @@ -0,0 +1,211 @@ +// @vitest-environment happy-dom +// ARCHIVE-REACH: Home always reaches archived workspaces, however few are active. +import { cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { EmptyState } from './CloudWorkspacesStates' +import { + CloudWorkspacesToolbar, + INITIAL_CLOUD_WORKSPACE_FILTERS as DEFAULTS, + shouldShowCloudHomeArchivedOnly, + shouldShowCloudHomeFilters +} from './CloudWorkspacesToolbar' +import { resetCloudArchivedCountCache, useCloudArchivedCount } from './use-cloud-archived-count' + +vi.mock('../new-workspace/run-on/OrcaCloudTrialUsedUpNotice', () => ({ + OrcaCloudTrialUsedUpBanner: () => null +})) +vi.mock('@/hooks/useOrcaCloudApiAvailability', () => ({ useOrcaCloudApiAvailable: () => false })) + +afterEach(cleanup) + +/** What Home decides for `active` workspaces, `archived` archived ones, and the switch on or off. */ +function homeRow(active: number, archived: number, archivedOn = false) { + // With the switch on, Home lists the archived ones: the row follows that list's size. + const shown = archivedOn ? archived : active + const showFilters = shouldShowCloudHomeFilters(shown, { ...DEFAULTS, archived: archivedOn }, true) + return { + showFilters, + archivedOnly: shouldShowCloudHomeArchivedOnly({ + showFilters, + archivedCount: archived, + archivedOn, + activeCount: active + }) + } +} + +describe('which filter row Home shows', () => { + it.each([ + // Nothing active: the empty state's "Show archived (N)" is the way in, not a second control. + [0, 0, false, { showFilters: false, archivedOnly: false }], + [0, 2, false, { showFilters: false, archivedOnly: false }], + [3, 0, false, { showFilters: false, archivedOnly: false }], + [3, 2, false, { showFilters: false, archivedOnly: true }], + [5, 0, false, { showFilters: true, archivedOnly: false }], + [5, 4, false, { showFilters: true, archivedOnly: false }], + // Switch on: a few archived rows keep the minimal row with the switch; 5+ get the full row. + [0, 2, true, { showFilters: false, archivedOnly: true }], + [3, 2, true, { showFilters: false, archivedOnly: true }], + [3, 6, true, { showFilters: true, archivedOnly: false }] + ])('%i active, %i archived, switch on: %s', (active, archived, on, expected) => { + expect(homeRow(active, archived, on)).toEqual(expected) + }) + + it('an unknown count (read failed or loading) keeps today’s row', () => { + expect( + shouldShowCloudHomeArchivedOnly({ + showFilters: false, + archivedCount: null, + archivedOn: false, + activeCount: 3 + }) + ).toBe(false) + }) +}) + +function toolbar(props: { + showFilters: boolean + archivedOnly: boolean + archivedCount: number | null + archived?: boolean +}) { + const onFiltersChange = vi.fn() + render( + + + + ) + return onFiltersChange +} + +describe('the Archived switch', () => { + it('below 5 active with archived ones: only the switch, with its count, and it turns on', () => { + const onFiltersChange = toolbar({ showFilters: false, archivedOnly: true, archivedCount: 3 }) + expect(screen.getByText('Archived (3)')).toBeTruthy() + // JA-30's minimal row otherwise: no owner/repo filters, no Running switch. + const own = document.querySelector('[data-cloud-home-archived-only]') + expect(own?.contains(screen.getByRole('switch', { name: 'Show archived' }))).toBe(true) + // JA-30's filter row (owner/repo, Running) stays hidden. + const running = screen.getByRole('switch', { name: 'Show running only' }) + expect(running.closest('.hidden')).not.toBeNull() + fireEvent.click(screen.getByRole('switch', { name: 'Show archived' })) + expect(onFiltersChange).toHaveBeenCalledWith({ archived: true }) + }) + + it('below 5 active with none archived: no switch at all (JA-30 unchanged)', () => { + toolbar({ showFilters: false, archivedOnly: false, archivedCount: 0 }) + expect(screen.queryByRole('switch', { name: 'Show archived' })).toBeNull() + }) + + it('at 5+ active: the full row, and the switch shows the count too', () => { + toolbar({ showFilters: true, archivedOnly: false, archivedCount: 4 }) + expect(screen.getByRole('switch', { name: 'Show running only' })).toBeTruthy() + expect(screen.getAllByRole('switch', { name: 'Show archived' })).toHaveLength(1) + expect(screen.getByText('Archived (4)')).toBeTruthy() + }) + + it('at 5+ active with none archived: plain "Archived"', () => { + toolbar({ showFilters: true, archivedOnly: false, archivedCount: 0 }) + expect(screen.getByText('Archived')).toBeTruthy() + }) +}) + +describe('the empty state', () => { + it('every workspace archived: says so, keeps New, and offers Show archived (N)', () => { + const onShowArchived = vi.fn() + render( + + ) + expect(screen.getByText('All your cloud workspaces are archived')).toBeTruthy() + expect(screen.queryByText('You don’t have any cloud workspaces yet.')).toBeNull() + expect(screen.getByText('Unarchive one to keep working, or start a new one.')).toBeTruthy() + // The first-run pitch isn't for someone who already has workspaces. + expect(screen.queryByText(/It runs in a sandbox/)).toBeNull() + expect(screen.getByRole('button', { name: 'New cloud workspace' })).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Show archived (2)' })) + expect(onShowArchived).toHaveBeenCalledOnce() + }) + + it('nothing archived: the first-run invitation, no Show archived link', () => { + render( + + ) + expect(screen.getByText('Start your first cloud workspace')).toBeTruthy() + expect(screen.queryByRole('button', { name: /Show archived/ })).toBeNull() + }) +}) + +describe('useCloudArchivedCount', () => { + const list = vi.fn() + beforeEach(() => { + resetCloudArchivedCountCache() + list.mockReset() + Object.defineProperty(window, 'api', { + configurable: true, + value: { cloudWorkspaces: { list } } + }) + }) + + it('reads archived=only once per active list, and again when the active list changes', async () => { + list.mockResolvedValue({ ok: true, value: [{ id: 'a' }, { id: 'b' }] }) + const { result, rerender } = renderHook( + (ids: string[]) => + useCloudArchivedCount({ account: 'u:o', scope: 'mine', activeIds: ids, enabled: true }), + { initialProps: ['w1'] } + ) + await waitFor(() => expect(result.current).toBe(2)) + expect(list).toHaveBeenCalledWith({ scope: 'mine', archived: 'only' }) + // Home polls: the same active list reuses the cached count. + rerender(['w1']) + renderHook(() => + useCloudArchivedCount({ account: 'u:o', scope: 'mine', activeIds: ['w1'], enabled: true }) + ) + expect(list).toHaveBeenCalledTimes(1) + // Archiving the only workspace empties the active list: read again. + list.mockResolvedValue({ ok: true, value: [{ id: 'a' }, { id: 'b' }, { id: 'w1' }] }) + rerender([]) + await waitFor(() => expect(result.current).toBe(3)) + expect(list).toHaveBeenCalledTimes(2) + }) + + it('stays null on a failed read or while the active list loads, so Home keeps today’s row', async () => { + list.mockResolvedValue({ ok: false, error: 'unavailable' }) + const failed = renderHook(() => + useCloudArchivedCount({ account: 'u:o', scope: 'team', activeIds: [], enabled: true }) + ) + await waitFor(() => expect(list).toHaveBeenCalled()) + expect(failed.result.current).toBeNull() + const loading = renderHook(() => + useCloudArchivedCount({ account: 'u:o', scope: 'team', activeIds: null, enabled: true }) + ) + expect(loading.result.current).toBeNull() + }) +}) diff --git a/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts b/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts index 7685f70f93d..cec0afee85a 100644 --- a/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts +++ b/src/renderer/src/components/cloud-workspaces/cloud-workspaces.test-fixture.ts @@ -1,4 +1,5 @@ // Static team, workspaces and API stubs shared by the cloud workspaces component fixtures. +import { resetCloudArchivedCountCache } from './use-cloud-archived-count' import type { CloudWorkspace, CloudWorkspacePresence @@ -150,10 +151,19 @@ export function teamWorkspaces(): CloudWorkspace[] { type ListResult = Awaited> /** Replaces the web build's "not configured" cloud workspaces bridge with static answers. */ -export function stubCloudWorkspacesApi(list: () => Promise): void { +/** + * `archived` is what the Archived switch (and Home's archived count, ARCHIVE-REACH) reads with + * `archived=only`; every other query gets `list`. + */ +export function stubCloudWorkspacesApi( + list: () => Promise, + archived: CloudWorkspace[] = [] +): void { + resetCloudArchivedCountCache() Object.assign(window.api.cloudWorkspaces, { available: () => Promise.resolve(true), - list, + list: (query?: { archived?: string }) => + query?.archived === 'only' ? Promise.resolve({ ok: true as const, value: archived }) : list(), localWorkspaces: () => Promise.resolve([]), environmentBindings: () => Promise.resolve({}) } satisfies Partial) diff --git a/src/renderer/src/components/cloud-workspaces/use-cloud-archived-count.ts b/src/renderer/src/components/cloud-workspaces/use-cloud-archived-count.ts new file mode 100644 index 00000000000..01e00cba6ad --- /dev/null +++ b/src/renderer/src/components/cloud-workspaces/use-cloud-archived-count.ts @@ -0,0 +1,116 @@ +// How many archived cloud workspaces Home's scope has, so Home can always reach them (ARCHIVE-REACH): +// with only a few active workspaces Home hides its filter row (JA-30), and that row holds the only +// Archived switch, so archiving your only workspace used to leave nothing on Home to get it back. +// +// One `archived=only` read per account, scope and active list. When the active list changes (a +// workspace archived or unarchived, here or elsewhere), the count is read again. Otherwise a cached +// answer is reused for a few minutes, so Home's polling never doubles its reads. +import { useEffect, useState } from 'react' + +const TTL_MS = 5 * 60_000 + +type Cached = { count: number; at: number } +const cache = new Map() +const inflight = new Map>() + +async function readArchivedCount(scope: 'team' | 'mine'): Promise { + try { + const result = await window.api.cloudWorkspaces.list({ scope, archived: 'only' }) + return result.ok ? result.value.length : null + } catch { + return null + } +} + +function load(key: string, scope: 'team' | 'mine', now: number): Promise { + const hit = cache.get(key) + if (hit && now - hit.at < TTL_MS) { + return Promise.resolve(hit.count) + } + const pending = inflight.get(key) + if (pending) { + return pending + } + const request = readArchivedCount(scope).then((count) => { + inflight.delete(key) + if (count !== null) { + cache.set(key, { count, at: Date.now() }) + } + return count + }) + inflight.set(key, request) + return request +} + +/** + * Null until known (or when the read failed): callers then keep today's behavior. `activeIds` is the + * active list Home shows; null while it loads. Disabled while the Archived switch is already on. + */ +export function useCloudArchivedCount({ + account, + scope, + activeIds, + enabled +}: { + account: string + scope: 'team' | 'mine' + activeIds: readonly string[] | null + enabled: boolean +}): number | null { + const signature = activeIds ? [...activeIds].sort().join(',') : null + const key = JSON.stringify({ account, scope, active: signature }) + const [state, setState] = useState<{ key: string; count: number | null }>({ key, count: null }) + useEffect(() => { + if (!enabled || signature === null) { + return + } + let disposed = false + void load(key, scope, Date.now()).then((count) => { + if (!disposed) { + setState({ key, count }) + } + }) + return () => { + disposed = true + } + }, [enabled, key, scope, signature]) + if (!enabled) { + return null + } + // A count read for an earlier active list still says whether archived ones exist; keep it until + // the new read lands so the switch doesn't flicker off and on. + return state.count +} + +/** + * Home's two numbers: `archivedRead` (the count while the active list shows, for the empty state) + * and `archivedCount` (the switch's label: with the switch on, the archived rows shown). + */ +export function useHomeArchivedCount({ + account, + scope, + shown, + archivedOn, + enabled +}: { + account: string + scope: 'team' | 'mine' + /** The rows Home shows now; null while they load. */ + shown: readonly { id: string }[] | null + archivedOn: boolean + enabled: boolean +}): { archivedRead: number | null; archivedCount: number | null } { + const archivedRead = useCloudArchivedCount({ + account, + scope, + activeIds: shown ? shown.map((w) => w.id) : null, + enabled: enabled && !archivedOn + }) + return { archivedRead, archivedCount: archivedOn ? (shown?.length ?? null) : archivedRead } +} + +/** Tests: forget every cached count. */ +export function resetCloudArchivedCountCache(): void { + cache.clear() + inflight.clear() +} diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c0333586ed0..fc04b55fb15 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21122,7 +21122,8 @@ "copyLinkToTerminal": "Copy link to this terminal", "copyLinkToChat": "Copy link to this chat", "linkToNumber": "Link to {{number}}", - "archiveConfirmStops": "{{owner}}'s agents in this workspace will stop." + "archiveConfirmStops": "{{owner}}'s agents in this workspace will stop.", + "archivedCount": "Archived ({{count}})" }, "orcaCloud": { "QueuedPrompt": { @@ -23705,7 +23706,10 @@ "newCloudWorkspace": "New cloud workspace", "emptyStartBody": "It runs in a sandbox, so your agents keep working even when this computer is off.", "emptyMineYoursTitle": "You don’t have any cloud workspaces yet.", - "emptyFirstTitle": "Start your first cloud workspace" + "emptyFirstTitle": "Start your first cloud workspace", + "emptyAllArchivedTitle": "All your cloud workspaces are archived", + "showArchivedCount": "Show archived ({{count}})", + "emptyAllArchivedBody": "Unarchive one to keep working, or start a new one." }, "worktreeCreation": { "pendingNativeChat": {