Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(sandbox-drive): say a usage refresh could not measure instead of a generic failure (#22309)

Rdmclin2b7c15746b94b
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 899152cf217..58d23429e33 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -669,6 +669,9 @@
"drive.tabs.public": "Public drive",
"drive.usage.enableOverage": "Turn on pay-as-you-go",
"drive.usage.manage": "Manage in Sandbox Storage",
+ "drive.usage.measuring": "Measuring · {{size}} counted so far",
+ "drive.usage.measuringHint": "This drive is large, so it is measured in several passes. The figure shown is the last finished measurement. Measuring carries on in the background — measure again later to see the new figure.",
+ "drive.usage.measuringShort": "Measuring…",
"drive.usage.memberUnmeasured": "Not measured",
"drive.usage.membersHint": "Usage only — contents stay private",
"drive.usage.membersTitle": "Members' personal drives",
@@ -680,6 +683,7 @@
"drive.usage.overageModalTitle": "Keep saving past the quota",
"drive.usage.poolTitle": "Workspace storage pool",
"drive.usage.refresh": "Measure again",
+ "drive.usage.refreshFailed": "Could not measure the drive right now. The figure shown is still the last measurement — try again in a moment.",
"drive.usage.remaining": "{{size}} left · {{percent}}% used",
"drive.usage.showAllMembers": "Show all {{count}} members",
"drive.usage.showFewerMembers": "Show fewer",
@@ -1938,7 +1942,6 @@
"subscriptionAccounts.calendar.desc": "Next 7 days, one square per 5-hour window: grey is unused, blue is in use.",
"subscriptionAccounts.calendar.failed": "Couldn't load",
"subscriptionAccounts.calendar.failedNote": "Couldn't load this account's quota",
- "subscriptionAccounts.calendar.summary.failed": "{{count}} couldn't load",
"subscriptionAccounts.calendar.idle": "Refilled · not started",
"subscriptionAccounts.calendar.latest": "by {{time}}",
"subscriptionAccounts.calendar.legend.blocked": "Used up",
@@ -1953,6 +1956,7 @@
"subscriptionAccounts.calendar.state.used": "{{percent}} used",
"subscriptionAccounts.calendar.summary.available": "{{count}} available",
"subscriptionAccounts.calendar.summary.exhausted": "{{count}} used up",
+ "subscriptionAccounts.calendar.summary.failed": "{{count}} couldn't load",
"subscriptionAccounts.calendar.summary.nextRecovery": "next one back {{time}}",
"subscriptionAccounts.calendar.summary.nextReset": "next reset {{time}}",
"subscriptionAccounts.calendar.teamCell": "{{count}} of {{total}} accounts available",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index c207883d289..7bc6a2d1a66 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -669,6 +669,9 @@
"drive.tabs.public": "公共网盘",
"drive.usage.enableOverage": "开启按量计费",
"drive.usage.manage": "在沙箱存储中管理",
+ "drive.usage.measuring": "统计中 · 已统计 {{size}}",
+ "drive.usage.measuringHint": "网盘较大,需要分几次统计。当前显示的是上次统计完成的结果;统计会在后台继续,稍后再点「重新统计」即可看到新结果。",
+ "drive.usage.measuringShort": "统计中…",
"drive.usage.memberUnmeasured": "未统计",
"drive.usage.membersHint": "只显示用量,看不到内容",
"drive.usage.membersTitle": "成员个人网盘",
@@ -680,6 +683,7 @@
"drive.usage.overageModalTitle": "超出额度后继续保存",
"drive.usage.poolTitle": "工作区存储配额",
"drive.usage.refresh": "重新统计",
+ "drive.usage.refreshFailed": "暂时无法重新统计用量,当前显示的仍是上次统计的结果,请稍后再试。",
"drive.usage.remaining": "剩余 {{size}} · 已用 {{percent}}%",
"drive.usage.showAllMembers": "显示全部 {{count}} 位成员",
"drive.usage.showFewerMembers": "收起",
@@ -1938,7 +1942,6 @@
"subscriptionAccounts.calendar.desc": "未来 7 天,每格是一个 5 小时窗口:灰色未使用,蓝色已占用。",
"subscriptionAccounts.calendar.failed": "读取失败",
"subscriptionAccounts.calendar.failedNote": "额度读取失败",
- "subscriptionAccounts.calendar.summary.failed": "{{count}} 个读取失败",
"subscriptionAccounts.calendar.idle": "已恢复 · 未开始计时",
"subscriptionAccounts.calendar.latest": "最晚{{time}}",
"subscriptionAccounts.calendar.legend.blocked": "已用尽",
@@ -1953,6 +1956,7 @@
"subscriptionAccounts.calendar.state.used": "已用 {{percent}}",
"subscriptionAccounts.calendar.summary.available": "{{count}} 个可用",
"subscriptionAccounts.calendar.summary.exhausted": "{{count}} 个已用尽",
+ "subscriptionAccounts.calendar.summary.failed": "{{count}} 个读取失败",
"subscriptionAccounts.calendar.summary.nextRecovery": "最早 {{time}}恢复",
"subscriptionAccounts.calendar.summary.nextReset": "下次 {{time}}重置",
"subscriptionAccounts.calendar.teamCell": "{{total}} 个账号中 {{count}} 个可用",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index ea3e6bc93c5..bbbbde76ed5 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -4832,6 +4832,12 @@ When I am ___, I need ___
'drive.usage.overBy': '{{size}} over the quota',
'drive.usage.others': 'Other members',
'drive.usage.refresh': 'Measure again',
+ 'drive.usage.measuring': 'Measuring · {{size}} counted so far',
+ 'drive.usage.measuringHint':
+ 'This drive is large, so it is measured in several passes. The figure shown is the last finished measurement. Measuring carries on in the background — measure again later to see the new figure.',
+ 'drive.usage.measuringShort': 'Measuring…',
+ 'drive.usage.refreshFailed':
+ 'Could not measure the drive right now. The figure shown is still the last measurement — try again in a moment.',
'drive.usage.membersTitle': "Members' personal drives",
'drive.usage.membersHint': 'Usage only — contents stay private',
'drive.usage.memberUnmeasured': 'Not measured',
diff --git a/src/features/SandboxDrive/UsageBreakdown.test.tsx b/src/features/SandboxDrive/UsageBreakdown.test.tsx
index 3c19ef73759..5ee35dd37d1 100644
--- a/src/features/SandboxDrive/UsageBreakdown.test.tsx
+++ b/src/features/SandboxDrive/UsageBreakdown.test.tsx
@@ -1,9 +1,35 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import type * as LobeUI from '@lobehub/ui';
+import { toast } from '@lobehub/ui';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { StrictMode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { UsageBreakdown } from './UsageBreakdown';
vi.mock('@/business/client/features/RetainedMemberDrives', () => ({ default: () => null }));
+const workspace = vi.hoisted(() => ({ id: 'ws-a' as string | null }));
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => workspace.id,
+}));
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof LobeUI>();
+ return {
+ ...actual,
+ // Real base-ui ActionIcon only surfaces its title via a hover Tooltip, so
+ // a plain button stands in to make the refresh clickable by its label.
+ ActionIcon: ({
+ loading,
+ onClick,
+ title,
+ }: {
+ loading?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => <button data-loading={!!loading} title={title} type="button" onClick={onClick} />,
+ toast: { ...actual.toast, error: vi.fn() },
+ Tooltip: ({ children }: { children: unknown }) => children,
+ };
+});
const overQuota = (overageAllowed: boolean) =>
({
@@ -30,4 +56,195 @@ describe('UsageBreakdown', () => {
expect(screen.getByText('drive.usage.overBilled')).toBeInTheDocument();
expect(screen.queryByText('drive.usage.over')).not.toBeInTheDocument();
});
+
+ // LOBE-15436: a refresh whose walk timed out used to answer with the old
+ // figure as if it had been re-measured.
+ it('should say the figure is the last measurement when the drive could not be measured', async () => {
+ const onRefresh = vi.fn().mockRejectedValue(new Error('STORAGE_USAGE_MEASURE_FAILED'));
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('drive.usage.refreshFailed'));
+ });
+
+ it('should keep the generic message for any other refresh failure', async () => {
+ const onRefresh = vi.fn().mockRejectedValue(new Error('BAD_GATEWAY'));
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith('workingDirectory.drive.actionFailed'),
+ );
+ });
+
+ // LOBE-15436: a drive too large to walk in one call is measured over several.
+ describe('a drive measured over several calls', () => {
+ beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['setTimeout'] });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+ const advance = () => vi.advanceTimersByTimeAsync(3000);
+
+ it('should keep measuring a large drive and show how much it has counted', async () => {
+ const onRefresh = vi
+ .fn()
+ .mockResolvedValueOnce({ measuring: { drives: ['personal'], scannedBytes: 1024 } })
+ .mockResolvedValueOnce({ measuring: { drives: ['personal'], scannedBytes: 2048 } })
+ .mockResolvedValueOnce({});
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ await waitFor(() => expect(screen.getByText('drive.usage.measuring')).toBeInTheDocument());
+ // Over the quota stays said while measuring.
+ expect(screen.getByText('drive.usage.overBy')).toBeInTheDocument();
+ await advance();
+ await advance();
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(3));
+ // The first call measures every drive; the rest only the one still walking.
+ expect(onRefresh.mock.calls[0][0]).toBeUndefined();
+ expect(onRefresh.mock.calls[1][0]).toEqual(['personal']);
+ // Done: back to the figures, with no "measuring" left behind.
+ await waitFor(() =>
+ expect(screen.queryByText('drive.usage.measuring')).not.toBeInTheDocument(),
+ );
+ expect(toast.error).not.toHaveBeenCalledWith('drive.usage.refreshFailed');
+ });
+
+ it('should pause between calls and stop after a bounded number', async () => {
+ const onRefresh = vi
+ .fn()
+ .mockResolvedValue({ measuring: { drives: ['personal'], scannedBytes: 1024 } });
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
+ // A call answered at once (another caller holds the walk) does not run on
+ // into the next one.
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ for (let i = 0; i < 15; i++) await advance();
+ // Bounded: the cron finishes a walk nobody is waiting on.
+ expect(onRefresh).toHaveBeenCalledTimes(12);
+ expect(screen.getByText('drive.usage.measuring')).toBeInTheDocument();
+ });
+
+ it('should say in the open that the figure is the last finished measurement', async () => {
+ const onRefresh = vi
+ .fn()
+ .mockResolvedValue({ measuring: { drives: ['personal'], scannedBytes: 1 } });
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ // Visible text, not a tooltip: touch screens cannot hover.
+ await waitFor(() =>
+ expect(screen.getByText('drive.usage.measuringHint')).toBeInTheDocument(),
+ );
+ });
+
+ it('should stop calling once the page is hidden', async () => {
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');
+ const onRefresh = vi
+ .fn()
+ .mockResolvedValue({ measuring: { drives: ['personal'], scannedBytes: 1 } });
+ render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
+ visibility.mockReturnValue('hidden');
+ for (let i = 0; i < 5; i++) await advance();
+
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ // Still says it is measuring: the walk goes on without this tab.
+ expect(screen.getByText('drive.usage.measuring')).toBeInTheDocument();
+ visibility.mockRestore();
+ });
+
+ it('should stop measuring when the active workspace changes', async () => {
+ workspace.id = 'ws-a';
+ const onRefresh = vi
+ .fn()
+ .mockResolvedValue({ measuring: { drives: ['personal'], scannedBytes: 1 } });
+ const { rerender } = render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+ await waitFor(() => expect(screen.getByText('drive.usage.measuring')).toBeInTheDocument());
+
+ // Same route, another workspace: requests would now go to it.
+ workspace.id = 'ws-b';
+ rerender(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+ for (let i = 0; i < 5; i++) await advance();
+
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText('drive.usage.measuring')).not.toBeInTheDocument();
+ workspace.id = 'ws-a';
+ });
+
+ it("should keep one workspace's refresh spinner out of another", async () => {
+ workspace.id = 'ws-a';
+ let finishA: (value: unknown) => void = () => {};
+ let finishB: (value: unknown) => void = () => {};
+ const onRefresh = vi
+ .fn()
+ .mockImplementationOnce(() => new Promise((resolve) => (finishA = resolve)))
+ .mockImplementationOnce(() => new Promise((resolve) => (finishB = resolve)));
+ const view = () => <UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />;
+ const { rerender } = render(view());
+ const button = () => screen.getByTitle('drive.usage.refresh');
+
+ fireEvent.click(button());
+ await waitFor(() => expect(button().dataset.loading).toBe('true'));
+
+ // A's request is still in flight; B is not refreshing.
+ workspace.id = 'ws-b';
+ rerender(view());
+ expect(button().dataset.loading).toBe('false');
+
+ // B starts its own; A finishing must not clear it.
+ fireEvent.click(button());
+ await waitFor(() => expect(button().dataset.loading).toBe('true'));
+ finishA({});
+ await advance();
+ expect(button().dataset.loading).toBe('true');
+ finishB({});
+ await waitFor(() => expect(button().dataset.loading).toBe('false'));
+ workspace.id = 'ws-a';
+ });
+
+ it('should still refresh under StrictMode, which replays effects', async () => {
+ const onRefresh = vi.fn().mockResolvedValue({});
+ render(
+ <StrictMode>
+ <UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />
+ </StrictMode>,
+ );
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+
+ await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
+ });
+
+ it('should stop measuring once the panel is closed', async () => {
+ let finish: (value: unknown) => void = () => {};
+ const onRefresh = vi
+ .fn()
+ .mockImplementationOnce(() => new Promise((resolve) => (finish = resolve)))
+ .mockResolvedValue({ measuring: { drives: ['personal'], scannedBytes: 1 } });
+ const { unmount } = render(<UsageBreakdown data={overQuota(false)} onRefresh={onRefresh} />);
+
+ fireEvent.click(screen.getByTitle('drive.usage.refresh'));
+ unmount();
+ finish({ measuring: { drives: ['personal'], scannedBytes: 1 } });
+ await advance();
+ await advance();
+
+ expect(onRefresh).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/src/features/SandboxDrive/UsageBreakdown.tsx b/src/features/SandboxDrive/UsageBreakdown.tsx
index cd788cd4a1c..3f0cc4b6134 100644
--- a/src/features/SandboxDrive/UsageBreakdown.tsx
+++ b/src/features/SandboxDrive/UsageBreakdown.tsx
@@ -1,22 +1,47 @@
'use client';
+import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
import { ActionIcon, Button, Flexbox, Icon, Text, toast, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import type { LucideIcon } from 'lucide-react';
import { LockIcon, RefreshCwIcon, UserRoundIcon, UsersIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import RetainedMemberDrives from '@/business/client/features/RetainedMemberDrives';
import SandboxStorageOverQuotaAction from '@/business/client/features/SandboxStorageOverQuotaAction';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import UserAvatar from '@/components/UserAvatar';
import { formatSize } from '@/utils/format';
-import type { useDriveUsage } from './useDriveData';
+import type { DriveUsageRefreshResult, useDriveUsage } from './useDriveData';
+
+/** The market's code for a usage refresh whose walk did not finish. */
+const USAGE_MEASURE_FAILED = 'STORAGE_USAGE_MEASURE_FAILED';
type DriveUsageData = NonNullable<ReturnType<typeof useDriveUsage>['data']>;
+/**
+ * How many refresh calls one click keeps going for while a large drive is
+ * still being measured. Each call walks for up to about half a minute on the
+ * server, so this follows a walk for several minutes; past it, the measurement
+ * cron finishes the walk and the next visit shows the result.
+ */
+const MAX_MEASURE_CALLS = 12;
+
+/**
+ * Pause between those calls. A call normally spends its time walking on the
+ * server; when another caller holds the walk it answers at once, and without
+ * a pause the loop would spend all its calls in a second.
+ */
+const MEASURE_CALL_GAP_MS = 3000;
+
+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Nobody is looking: the measurement cron finishes the walk without this tab. */
+const pageHidden = () => typeof document !== 'undefined' && document.visibilityState === 'hidden';
+
/** How many members the ranking shows before it folds the rest away. */
const MEMBERS_FOLDED = 5;
@@ -127,10 +152,41 @@ export const UsageBreakdown = memo<{
data: DriveUsageData;
/** In a popover: a smaller figure and bounded width. Embedded: the page's width. */
inPopover?: boolean;
- onRefresh: () => Promise<void>;
+ /** `drives`: only these, to continue walks still under way; all when omitted. */
+ onRefresh: (drives?: SandboxDrive[]) => Promise<DriveUsageRefreshResult | void>;
}>(({ data, inPopover, onRefresh }) => {
const { t } = useTranslation('setting');
- const [refreshing, setRefreshing] = useState(false);
+ // Which refresh is running, and in which workspace: the spinner belongs to
+ // that workspace, and only that refresh may clear it.
+ const [busy, setBusy] = useState<{ token: object; workspaceId: string | null } | null>(null);
+ // A drive too large to measure in one call (LOBE-15436): how much the walk
+ // has counted so far, shown beside the last finished figure.
+ const [measurement, setMeasurement] = useState<{
+ progress: NonNullable<DriveUsageRefreshResult['measuring']>;
+ workspaceId: string | null;
+ } | null>(null);
+ const mounted = useRef(true);
+ // The route stays mounted across a workspace switch, and every request goes
+ // to whichever workspace is active then: a loop started in one workspace
+ // must not carry on — or show its progress — in the next.
+ const workspaceId = useActiveWorkspaceId();
+ const activeWorkspace = useRef(workspaceId);
+ useEffect(() => {
+ activeWorkspace.current = workspaceId;
+ }, [workspaceId]);
+ const refreshing = busy?.workspaceId === workspaceId;
+ // Progress belongs to the workspace it was measured in.
+ const measuring = measurement?.workspaceId === workspaceId ? measurement.progress : null;
+ const setMeasuring = (progress: DriveUsageRefreshResult['measuring'] | null) =>
+ setMeasurement(progress ? { progress, workspaceId } : null);
+ useEffect(() => {
+ // Set here too: StrictMode replays effects, running the cleanup once
+ // before the component is really gone.
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
const [showAllMembers, setShowAllMembers] = useState(false);
const drives = data.drives ?? [];
@@ -182,13 +238,37 @@ export const UsageBreakdown = memo<{
const largestMember = Math.max(1, ...members.map((member) => member.usageBytes ?? 0));
const refresh = async () => {
- setRefreshing(true);
+ const started = activeWorkspace.current;
+ const current = () => mounted.current && activeWorkspace.current === started;
+ const token = {};
+ setBusy({ token, workspaceId: started });
try {
- await onRefresh();
- } catch {
- toast.error(t('workingDirectory.drive.actionFailed', { ns: 'device' }));
+ // Each call continues the walk where the last one stopped, so keep
+ // calling while it is still measuring and someone is looking.
+ let pending: DriveUsageRefreshResult['measuring'];
+ for (let call = 0; call < MAX_MEASURE_CALLS && current(); call++) {
+ if (pending) await wait(MEASURE_CALL_GAP_MS);
+ if (!current()) return;
+ if (pending && pageHidden()) break;
+ const result = await onRefresh(pending?.drives);
+ if (!current()) return;
+ pending = result?.measuring;
+ setMeasuring(pending ?? null);
+ if (!pending) break;
+ }
+ } catch (error) {
+ if (!current()) return;
+ setMeasuring(null);
+ // The execution plane could not walk the drive, so the figure on screen
+ // is the last one it measured — say so, rather than let a refresh that
+ // changed nothing pass for one that confirmed it (LOBE-15436).
+ toast.error(
+ (error as { message?: string } | undefined)?.message === USAGE_MEASURE_FAILED
+ ? t('drive.usage.refreshFailed')
+ : t('workingDirectory.drive.actionFailed', { ns: 'device' }),
+ );
} finally {
- setRefreshing(false);
+ if (mounted.current) setBusy((now) => (now?.token === token ? null : now));
}
};
@@ -214,16 +294,27 @@ export const UsageBreakdown = memo<{
</Flexbox>
</Flexbox>
<Flexbox horizontal align={'center'} flex={'none'} gap={4}>
- <Text fontSize={12} type={refused ? 'danger' : over ? 'warning' : 'secondary'}>
- {total === null
- ? t('drive.usage.unmeasuredShort')
- : over
- ? t('drive.usage.overBy', { size: formatSize(total - quotaBytes) })
- : t('drive.usage.remaining', {
- percent: formatPercent(percent(total, quotaBytes)),
- size: formatSize(quotaBytes - total),
- })}
- </Text>
+ {/* Over the quota stays said while a new measurement runs: those are
+ the drives most likely to be large, and writes may be refused. */}
+ {(over || !measuring) && (
+ <Text fontSize={12} type={refused ? 'danger' : over ? 'warning' : 'secondary'}>
+ {total === null
+ ? t('drive.usage.unmeasuredShort')
+ : over
+ ? t('drive.usage.overBy', { size: formatSize(total - quotaBytes) })
+ : t('drive.usage.remaining', {
+ percent: formatPercent(percent(total, quotaBytes)),
+ size: formatSize(quotaBytes - total),
+ })}
+ </Text>
+ )}
+ {measuring && (
+ <Text fontSize={12} type={'secondary'}>
+ {measuring.scannedBytes === null
+ ? t('drive.usage.measuringShort')
+ : t('drive.usage.measuring', { size: formatSize(measuring.scannedBytes) })}
+ </Text>
+ )}
<ActionIcon
icon={RefreshCwIcon}
loading={refreshing}
@@ -234,6 +325,14 @@ export const UsageBreakdown = memo<{
</Flexbox>
</Flexbox>
+ {/* The large figure is still the last finished measurement. Said in the
+ open, not in a tooltip: touch screens have no hover. */}
+ {measuring && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('drive.usage.measuringHint')}
+ </Text>
+ )}
+
<div
aria-label={t(isWorkspace ? 'drive.usage.poolTitle' : 'drive.usage.title')}
role={'img'}
diff --git a/src/features/SandboxDrive/useDriveData.test.ts b/src/features/SandboxDrive/useDriveData.test.ts
index f2188726d4e..ecb01ea00eb 100644
--- a/src/features/SandboxDrive/useDriveData.test.ts
+++ b/src/features/SandboxDrive/useDriveData.test.ts
@@ -48,7 +48,51 @@ describe('useDriveUsage refresh', () => {
const { result } = renderHook(() => useDriveUsage());
await act(async () => {
- await expect(result.current.refresh()).resolves.toBeUndefined();
+ await expect(result.current.refresh()).resolves.toEqual({});
});
});
+
+ // LOBE-15436: a drive too large to walk in one call answers "still measuring".
+ it('should report a drive still being measured with what has been counted', async () => {
+ vi.mocked(sandboxStorageService.refreshStorageUsage)
+ .mockResolvedValueOnce({
+ usageMeasurement: { scannedBytes: 300, startedAt: null, status: 'measuring' },
+ } as any)
+ .mockResolvedValueOnce({} as any);
+ const { result } = renderHook(() => useDriveUsage());
+ await waitFor(() => expect(result.current.data).toBeDefined());
+
+ await act(async () => {
+ await expect(result.current.refresh()).resolves.toEqual({
+ measuring: { drives: ['public'], scannedBytes: 300 },
+ });
+ });
+ });
+
+ it('should still say measuring when the walk has not reported a count yet', async () => {
+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue({
+ usageMeasurement: { scannedBytes: null, startedAt: null, status: 'measuring' },
+ } as any);
+ const { result } = renderHook(() => useDriveUsage());
+ await waitFor(() => expect(result.current.data).toBeDefined());
+
+ await act(async () => {
+ await expect(result.current.refresh()).resolves.toEqual({
+ measuring: { drives: ['public', 'personal'], scannedBytes: null },
+ });
+ });
+ });
+
+ it('should measure only the drives it is given', async () => {
+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue({} as any);
+ const { result } = renderHook(() => useDriveUsage());
+ await waitFor(() => expect(result.current.data).toBeDefined());
+
+ await act(async () => {
+ await result.current.refresh(['personal']);
+ });
+
+ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(1);
+ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledWith({ drive: 'personal' });
+ });
});
diff --git a/src/features/SandboxDrive/useDriveData.ts b/src/features/SandboxDrive/useDriveData.ts
index 186b61344df..e9acc25d0f9 100644
--- a/src/features/SandboxDrive/useDriveData.ts
+++ b/src/features/SandboxDrive/useDriveData.ts
@@ -6,6 +6,33 @@ import { useClientDataSWR } from '@/libs/swr';
import { sandboxStorageService } from '@/services/sandboxStorage';
const USAGE_KEY = 'sandbox-drive-usage';
+
+/**
+ * A refresh of a drive too large to measure in one go (LOBE-15436): the
+ * execution plane walks it over several calls and, until the walk ends, says
+ * how much it has counted so far beside the last finished figure.
+ */
+interface UsageMeasurement {
+ scannedBytes: number | null;
+ status: 'measuring';
+}
+
+const measurementOf = (info: unknown): UsageMeasurement | undefined => {
+ const measurement = (info as { usageMeasurement?: Partial<UsageMeasurement> } | null)
+ ?.usageMeasurement;
+ return measurement?.status === 'measuring'
+ ? { scannedBytes: measurement.scannedBytes ?? null, status: 'measuring' }
+ : undefined;
+};
+
+/** What a usage refresh found: still measuring, and how much it has counted so far. */
+export interface DriveUsageRefreshResult {
+ measuring?: {
+ /** The drives whose walk needs more calls: the only ones to call again. */
+ drives: SandboxDrive[];
+ scannedBytes: number | null;
+ };
+}
const FILES_KEY = 'sandbox-drive-files';
/**
@@ -23,19 +50,42 @@ export const useDriveUsage = () => {
// Measuring walks each of the caller's own drives; the members' figures are
// whatever was last measured for them. Every drive is measured even when one
// fails, and the figures are reloaded either way; then a failure is thrown,
- // so the caller can say the refresh did not fully work.
- const refresh = useCallback(async () => {
- const drives = swr.data?.drives.map((entry) => entry.drive) ?? [];
- const results = await Promise.allSettled(
- drives.map((drive) => sandboxStorageService.refreshStorageUsage({ drive })),
- );
- await swr.mutate();
-
- const failed = results.find(
- (result): result is PromiseRejectedResult => result.status === 'rejected',
- );
- if (failed) throw failed.reason;
- }, [swr.data, swr.mutate]);
+ // so the caller can say the refresh did not fully work. A drive whose walk
+ // needs more calls is reported as still measuring, with what it has counted;
+ // passing those drives back measures only them, not the finished ones again.
+ const refresh = useCallback(
+ async (only?: SandboxDrive[]): Promise<DriveUsageRefreshResult> => {
+ const drives = only ?? swr.data?.drives.map((entry) => entry.drive) ?? [];
+ const results = await Promise.allSettled(
+ drives.map((drive) => sandboxStorageService.refreshStorageUsage({ drive })),
+ );
+ await swr.mutate();
+
+ const failed = results.find(
+ (result): result is PromiseRejectedResult => result.status === 'rejected',
+ );
+ if (failed) throw failed.reason;
+
+ const measuring = results.flatMap((result, index) => {
+ const measurement = result.status === 'fulfilled' ? measurementOf(result.value) : undefined;
+ return measurement ? [{ drive: drives[index], measurement }] : [];
+ });
+ if (measuring.length === 0) return {};
+ const counted = measuring
+ .map(({ measurement }) => measurement)
+ .filter((measurement) => measurement.scannedBytes !== null);
+ return {
+ measuring: {
+ drives: measuring.map(({ drive }) => drive),
+ scannedBytes:
+ counted.length > 0
+ ? counted.reduce((sum, measurement) => sum + measurement.scannedBytes!, 0)
+ : null,
+ },
+ };
+ },
+ [swr.data, swr.mutate],
+ );
return { data: swr.data, error: swr.error, isLoading: swr.isLoading, refresh };
};