π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(sandbox-drive): re-measure the drive after a delete so the quota figure drops (#23488)
Rdmclin230a5e19014c5
diff --git a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.tsindex 7462f1dff1f..9b6b9ccb247 100644--- a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts+++ b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.test.ts@@ -5,9 +5,18 @@ import { useStorageAnalysis } from './useStorageAnalysis';const service = vi.hoisted(() => ({ analyzeStorage: vi.fn(), deleteFiles: vi.fn() }));const refreshDrive = vi.hoisted(() => vi.fn());+const remeasureDrive = vi.hoisted(() => vi.fn());+const workspace = vi.hoisted(() => ({ id: 'ws_1' as string | null }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => workspace.id,+}));vi.mock('@/services/sandboxStorage', () => ({ sandboxStorageService: service }));-vi.mock('../useDriveData', () => ({ useRefreshDrive: () => refreshDrive }));+vi.mock('../useDriveData', () => ({+ useRefreshDrive: () => refreshDrive,+ useRemeasureDrive: () => remeasureDrive,+}));const items = [{@@ -39,6 +48,8 @@ beforeEach(() => {service.analyzeStorage.mockReset();service.deleteFiles.mockReset();refreshDrive.mockReset().mockResolvedValue(undefined);+ remeasureDrive.mockReset().mockResolvedValue(undefined);+ workspace.id = 'ws_1';});describe('useStorageAnalysis', () => {@@ -115,6 +126,9 @@ describe('useStorageAnalysis', () => {expect(result.current.analysis?.result?.totalBytes).toBe(0);// The usage figure and listings reload to show the space coming back.expect(refreshDrive).toHaveBeenCalled();+ // Reloading alone returns the figure measured before the delete+ // (T-14518): the drive is measured again.+ expect(remeasureDrive).toHaveBeenCalledWith('personal', 'ws_1');});it('should leave in the figures what could not be deleted in time', async () => {@@ -138,6 +152,8 @@ describe('useStorageAnalysis', () => {expect(result.current.analysis?.result?.items.map((item) => item.path)).toContain('app/data.bin',);+ // Nothing left the drive, so there is nothing to measure again.+ expect(remeasureDrive).not.toHaveBeenCalled();});});@@ -272,4 +288,21 @@ describe('useStorageAnalysis estimates', () => {expect(result.current.analysis?.result?.stale).toBe(true);});++ it('should tie the re-measure to the workspace the delete began in', async () => {+ service.analyzeStorage.mockResolvedValue(done);+ service.deleteFiles.mockImplementation(async () => {+ // The user switches workspace while the delete is running.+ workspace.id = 'ws_2';+ return { deleted: ['app/data.bin'], done: true, freedBytes: 300, missing: [], pending: [] };+ });+ const { result } = renderHook(() => useStorageAnalysis('personal'));+ await waitFor(() => expect(result.current.scanning).toBe(false));++ await act(async () => {+ await result.current.remove([items[1]]);+ });++ expect(remeasureDrive).toHaveBeenCalledWith('personal', 'ws_1');+ });});diff --git a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.tsindex 1d92217ac04..94fd4e64076 100644--- a/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts+++ b/src/features/SandboxDrive/Cleanup/useStorageAnalysis.ts@@ -1,9 +1,10 @@import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import { useCallback, useEffect, useRef, useState } from 'react';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { sandboxStorageService } from '@/services/sandboxStorage';-import { useRefreshDrive } from '../useDriveData';+import { useRefreshDrive, useRemeasureDrive } from '../useDriveData';import {type StorageAnalysis,type StorageAnalysisItem,@@ -45,6 +46,7 @@ export const useStorageAnalysis = (drive: SandboxDrive) => {const [scanning, setScanning] = useState(false);const generation = useRef(0);const refreshDrive = useRefreshDrive();+ const remeasureDrive = useRemeasureDrive();const scan = useCallback(async (restart = false) => {@@ -97,6 +99,8 @@ export const useStorageAnalysis = (drive: SandboxDrive) => {async (items: StorageAnalysisItem[], options: { regenerableOnly?: boolean } = {}) => {// Sent in batches the server accepts; what a batch could not finish in// time goes back to the front of the queue.+ // The workspace the delete is made in; see `useRemeasureDrive`.+ const workspaceId = getActiveWorkspaceId();let pending = [...new Set(items.map((item) => item.path))];let freedBytes = 0;const failed: string[] = [];@@ -132,11 +136,15 @@ export const useStorageAnalysis = (drive: SandboxDrive) => {};});await refreshDrive();+ // The usage read returns the figure measured before the delete until+ // the drive is measured again; not awaited, since a large drive takes+ // several calls and the delete's outcome is already known.+ if (gone.size > 0) void remeasureDrive(drive, workspaceId);}return { failed, freedBytes, pending } satisfies DeleteOutcome;},- [drive, refreshDrive],+ [drive, refreshDrive, remeasureDrive],);return { analysis, error, remove, rescan: () => scan(true), scanning };diff --git a/src/features/SandboxDrive/DriveExplorer.tsx b/src/features/SandboxDrive/DriveExplorer.tsxindex 9153712e37e..90007fcaf57 100644--- a/src/features/SandboxDrive/DriveExplorer.tsx+++ b/src/features/SandboxDrive/DriveExplorer.tsx@@ -29,6 +29,7 @@ import {import { memo, type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import FileIcon from '@/components/FileIcon';import { describeError } from '@/features/EnvironmentManager/errorMessage';import {@@ -49,7 +50,7 @@ import {entrySize,sortDriveEntries,} from './entryColumns';-import { useDriveFiles, useRefreshDrive } from './useDriveData';+import { useDriveFiles, useRefreshDrive, useRemeasureDrive } from './useDriveData';import { useDriveDownload } from './useDriveDownload';/**@@ -148,6 +149,7 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtconst [creating, setCreating] = useState(false);const files = useDriveFiles(drive, path);const refreshDrive = useRefreshDrive();+ const remeasureDrive = useRemeasureDrive();const download = useDriveDownload(drive);const tSetting = (key: string, options?: Record<string, unknown>) =>@@ -193,6 +195,8 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtokButtonProps: { danger: true },okText: t('drive.explorer.delete'),onOk: async () => {+ // The workspace the delete is made in; see `useRemeasureDrive`.+ const workspaceId = getActiveWorkspaceId();try {await sandboxStorageService.removeFile({drive,@@ -200,6 +204,9 @@ const DriveExplorer = memo<DriveExplorerProps>(({ drive, isWorkspace, toolbarExtrecursive: entry.isDirectory,});await refreshDrive();+ // See `useRemeasureDrive`: the usage figure would otherwise stay at+ // what was measured before the delete.+ void remeasureDrive(drive, workspaceId);} catch (error) {failed(error, t('workingDirectory.drive.actionFailed', { ns: 'device' }));}diff --git a/src/features/SandboxDrive/UsageBreakdown.tsx b/src/features/SandboxDrive/UsageBreakdown.tsxindex 4dd58d6bd7e..2e28364ffa7 100644--- a/src/features/SandboxDrive/UsageBreakdown.tsx+++ b/src/features/SandboxDrive/UsageBreakdown.tsx@@ -16,33 +16,20 @@ import UserAvatar from '@/components/UserAvatar';import { formatSize } from '@/utils/format';import CleanupEntryButton from './Cleanup/CleanupEntryButton';-import type { DriveUsageRefreshResult, useDriveUsage } from './useDriveData';+import {+ type DriveUsageRefreshResult,+ MAX_MEASURE_CALLS,+ MEASURE_CALL_GAP_MS,+ pageHidden,+ type useDriveUsage,+ wait,+} 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;diff --git a/src/features/SandboxDrive/useDriveData.test.ts b/src/features/SandboxDrive/useDriveData.test.tsindex fc1670b334c..8f57da161dd 100644--- a/src/features/SandboxDrive/useDriveData.test.ts+++ b/src/features/SandboxDrive/useDriveData.test.ts@@ -1,11 +1,19 @@import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { sandboxStorageService } from '@/services/sandboxStorage';-import { useDriveUsage } from './useDriveData';+import { useDriveUsage, useRemeasureDrive } from './useDriveData';const mutate = vi.hoisted(() => vi.fn());+const globalMutate = vi.hoisted(() => vi.fn());+const workspace = vi.hoisted(() => ({ id: 'ws_1' as string | null }));++vi.mock('swr', () => ({ useSWRConfig: () => ({ mutate: globalMutate }) }));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ getActiveWorkspaceId: () => workspace.id,+}));vi.mock('@/libs/swr', () => ({useClientDataSWR: () => ({@@ -96,3 +104,96 @@ describe('useDriveUsage refresh', () => {expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledWith({ drive: 'personal' });});});++// A delete only marks the stored figure stale (T-14518): the usage read keeps+// returning the figure measured before it, so the drive is measured again.+describe('useRemeasureDrive', () => {+ const measuring = {+ usageMeasurement: { scannedBytes: 300, startedAt: null, status: 'measuring' },+ } as any;++ beforeEach(() => {+ vi.useFakeTimers();+ globalMutate.mockReset().mockResolvedValue(undefined);+ workspace.id = 'ws_1';+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockReset();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('should measure the drive and reload the usage', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue({} as any);+ const { result } = renderHook(() => useRemeasureDrive());++ await result.current('public');++ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(1);+ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledWith({ drive: 'public' });+ expect(globalMutate).toHaveBeenCalledTimes(1);+ const matches = globalMutate.mock.calls[0][0] as (key: unknown) => boolean;+ expect(matches(['sandbox-drive-usage'])).toBe(true);+ expect(matches(['sandbox-drive-files', 'public', ''])).toBe(false);+ });++ it('should keep walking a large drive until the measurement finishes', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage)+ .mockResolvedValueOnce(measuring)+ .mockResolvedValueOnce(measuring)+ .mockResolvedValueOnce({} as any);+ const { result } = renderHook(() => useRemeasureDrive());++ const running = result.current('personal');+ await vi.runAllTimersAsync();+ await running;++ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(3);+ expect(globalMutate).toHaveBeenCalledTimes(3);+ });++ it('should stop after a bounded number of calls', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue(measuring);+ const { result } = renderHook(() => useRemeasureDrive());++ const running = result.current('personal');+ await vi.runAllTimersAsync();+ await running;++ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(12);+ });++ it('should not carry a walk into another workspace', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockImplementation(async () => {+ workspace.id = 'ws_2';+ return measuring;+ });+ const { result } = renderHook(() => useRemeasureDrive());++ const running = result.current('public');+ await vi.runAllTimersAsync();+ await running;++ expect(sandboxStorageService.refreshStorageUsage).toHaveBeenCalledTimes(1);+ expect(globalMutate).not.toHaveBeenCalled();+ });++ it('should not measure when the workspace changed before the delete finished', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockResolvedValue({} as any);+ const { result } = renderHook(() => useRemeasureDrive());++ // The delete began in ws_1; the user is in ws_2 by the time it ends.+ workspace.id = 'ws_2';+ await result.current('public', 'ws_1');++ expect(sandboxStorageService.refreshStorageUsage).not.toHaveBeenCalled();+ expect(globalMutate).not.toHaveBeenCalled();+ });++ it('should swallow a failed measurement', async () => {+ vi.mocked(sandboxStorageService.refreshStorageUsage).mockRejectedValue(new Error('down'));+ const { result } = renderHook(() => useRemeasureDrive());++ await expect(result.current('public')).resolves.toBeUndefined();+ });+});diff --git a/src/features/SandboxDrive/useDriveData.ts b/src/features/SandboxDrive/useDriveData.tsindex 6513fad158e..6009e41a27e 100644--- a/src/features/SandboxDrive/useDriveData.ts+++ b/src/features/SandboxDrive/useDriveData.ts@@ -2,11 +2,33 @@ import type { SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';import { useCallback } from 'react';import { useSWRConfig } from 'swr';+import { getActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useClientDataSWR } from '@/libs/swr';import { sandboxStorageService } from '@/services/sandboxStorage';const USAGE_KEY = 'sandbox-drive-usage';+/**+ * How many refresh calls one measurement keeps going for while a large drive+ * is still being walked. 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.+ */+export 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.+ */+export const MEASURE_CALL_GAP_MS = 3000;++export const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/** Nobody is looking: the measurement cron finishes the walk without this tab. */+export const pageHidden = () =>+ typeof document !== 'undefined' && document.visibilityState === 'hidden';+/*** A refresh of a drive too large to measure in one go: the* execution plane walks it over several calls and, until the walk ends, says@@ -107,3 +129,46 @@ export const useRefreshDrive = () => {[mutate],);};++/**+ * Measure a drive again after something was deleted from it, in the+ * background.+ *+ * A delete only marks the stored figure stale; the usage read keeps returning+ * the figure measured before it until something measures again. Reloading the+ * usage alone would show the space as still taken, so walk the drive β over+ * several calls when it is large β and reload the usage after each one. The+ * delete has already happened: a measurement that fails leaves the old figure,+ * and the user can still refresh it by hand.+ */+export const useRemeasureDrive = () => {+ const { mutate } = useSWRConfig();++ return useCallback(+ /**+ * `startedIn`: the workspace active when the delete began β capture it+ * before awaiting the delete, so a switch while it runs is noticed.+ */+ async (drive: SandboxDrive, startedIn: string | null = getActiveWorkspaceId()) => {+ // Requests go to whichever workspace is active: a walk for a delete made+ // in one must not run, or carry on, in the next.+ const workspaceId = startedIn;+ try {+ for (let call = 0; call < MAX_MEASURE_CALLS; call++) {+ if (call > 0) {+ await wait(MEASURE_CALL_GAP_MS);+ if (pageHidden()) return;+ }+ if (getActiveWorkspaceId() !== workspaceId) return;+ const result = await sandboxStorageService.refreshStorageUsage({ drive });+ if (getActiveWorkspaceId() !== workspaceId) return;+ await mutate((key) => Array.isArray(key) && key[0] === USAGE_KEY);+ if (!measurementOf(result)) return;+ }+ } catch {+ // Best-effort: see above.+ }+ },+ [mutate],+ );+};