fix(launcher): keep copy maintenance progress across tab switches

This commit is contained in:
N0VAN0M4LY committed 2026-12-02 20:24:30 +08:00
1 parent fa7f68b942
commit be772c0cea
6 files changed
+112 -50

No files matched your search

+2 -1
View File
@@ -5,7 +5,7 @@ import { appUpdatesSupported, checkAppUpdate, downloadAppUpdate, installAppUpdat
import { listBackgroundPictures } from '../services/background-art/art-catalog.ts';
import { getCopyTuning, updateCopyTuning } from '../services/config/copy-tuning.ts';
import { getSettings, updateSettings } from '../services/config/settings-store.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress } from '../services/copies/copy-maintenance.ts';
import { cancelMaintenance, maintainCopy, maintenanceInfo, maintenanceInProgress, maintenanceState } from '../services/copies/copy-maintenance.ts';
import { relocateCopy } from '../services/copies/relocate-copy.ts';
import { exportDiagnostics, openLogsFolder } from '../services/diagnostics/diagnostics.ts';
import { measureFolder } from '../services/game-folder/folder-size.ts';
@@ -135,6 +135,7 @@ export function registerIpcHandlers(): void {
return updated;
});
handle('copies:maintenanceInfo', ({ id }) => maintenanceInfo(id));
handle('copies:maintenanceState', () => maintenanceState());
handle('copies:maintain', async (request) => {
if (saveWriteInProgress() || decalImportInProgress()) throw new AppError('maintenance_busy');
const updated = await hydrateCopiesStatus(await maintainCopy(request, (progress) => broadcast('event:copy-maintenance', progress)));
@@ -15,12 +15,20 @@ import { localServerReady } from '../launch/local-server.ts';
import { fileInfo } from './change-copy-files.ts';
import { compactCopy, convertibleCopy, isNewer, readSource, repair, updateFromSource, updatePreservesSpaceSaving, type Report } from './copy-file-maintenance.ts';
let current: { stop: AbortController; interruptible: boolean } | null = null;
let current: {
stop: AbortController;
interruptible: boolean;
progress: MaintenanceProgress;
} | null = null;
export function maintenanceInProgress(): boolean {
return current !== null;
}
export function maintenanceState(): MaintenanceProgress | null {
return current ? { ...current.progress } : null;
}
export function cancelMaintenance(): void {
if (current?.interruptible) current.stop.abort();
}
@@ -43,18 +51,28 @@ export async function maintenanceInfo(id: string): Promise<MaintenanceInfo> {
export async function maintainCopy(
request: MaintenanceRequest,
publish: (progress: MaintenanceProgress) => void,
publish: (progress: MaintenanceProgress | null) => void,
): Promise<Copies> {
if (current || launchInProgress() || installationInProgress()) throw new AppError('maintenance_busy');
const initial: MaintenanceProgress = {
id: request.id,
operation: request.operation,
phase: 'checking',
doneBytes: 0,
totalBytes: 0,
};
const job = {
stop: new AbortController(),
interruptible: request.operation === 'update' || request.operation === 'compact',
progress: initial,
};
current = job;
const signal = job.stop.signal;
const report: Report = (phase, doneBytes = 0, totalBytes = 0) => {
if (phase === 'applying') job.interruptible = false;
publish({ id: request.id, operation: request.operation, phase, doneBytes, totalBytes });
const next: MaintenanceProgress = { id: request.id, operation: request.operation, phase, doneBytes, totalBytes };
job.progress = next;
publish(next);
};
try {
@@ -67,6 +85,7 @@ export async function maintainCopy(
throw new AppError('maintenance_failed');
} finally {
current = null;
publish(null);
}
}
+3 -1
View File
@@ -10,6 +10,7 @@ import { applyLanguage, resolveLanguage } from './i18n/index.ts';
import { ipcInvoke, ipcOn } from './ipc.ts';
import { AboutPage } from './pages/about/AboutPage.tsx';
import { CopyMaintenance } from './pages/copies/CopyMaintenance.tsx';
import { useCopyMaintenance } from './pages/copies/useCopyMaintenance.ts';
import { CopyList } from './pages/copies/CopyList.tsx';
import { CopySummary } from './pages/copies/CopySummary.tsx';
import { FeatureStatus } from './pages/copies/FeatureStatus.tsx';
@@ -68,6 +69,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
// The setting as the window opened: turning it on later does not check right away.
const patchPack = usePatchPack(initialSettings.checkPatchPacksOnStart, report);
const appUpdate = useAppUpdate(info.appUpdatesSupported, initialSettings.checkLauncherUpdatesOnStart, report);
const maintenance = useCopyMaintenance(report);
const supported = patchPack.active?.gameVersions ?? info.supportedGameVersions;
const wizard = useInstallWizard({ onInstalled: () => setRoute(START_ROUTE) });
@@ -223,7 +225,7 @@ export function App({ info, initialSettings, initialCopies }: AppProps) {
};
}
if (route.copies === 'maintain') {
return { side, main: <CopyMaintenance key={record.id} record={record} onError={report} />, bar: home };
return { side, main: <CopyMaintenance key={record.id} record={record} maintenance={maintenance} onError={report} />, bar: home };
}
const main = route.copies === 'features'
? <FeatureStatus record={record} supportedVersions={supported} onError={report} />
@@ -1,29 +1,24 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { MaintenanceInfo, MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import type { MaintenanceInfo, MaintenanceProgress } from '@shared/schemas/maintenance.ts';
import { ProgressBar } from '../../components/ProgressBar.tsx';
import { Sheet } from '../../components/Sheet.tsx';
import { formatBytes } from '../../format.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
import { ipcInvoke } from '../../ipc.ts';
import { CopyMaintenanceActions, CopyRemoval, type CopyRemovalOptions } from './CopyMaintenanceControls.tsx';
import type { CopyMaintenanceState, MaintenanceOperation, MaintenanceOptions } from './useCopyMaintenance.ts';
interface CopyMaintenanceProps {
readonly record: InstallRecord;
readonly maintenance: CopyMaintenanceState;
readonly onError: (error: unknown) => void;
}
type Operation = MaintenanceRequest['operation'];
type OperationOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
export function CopyMaintenance({ record, maintenance, onError }: CopyMaintenanceProps) {
const { t } = useTranslation();
const [info, setInfo] = useState<MaintenanceInfo | null>(null);
const [working, setWorking] = useState<Operation | null>(null);
const [progress, setProgress] = useState<MaintenanceProgress | null>(null);
const [removal, setRemoval] = useState<CopyRemovalOptions | null>(null);
const [result, setResult] = useState<Operation | 'cancelled' | null>(null);
useEffect(() => {
let mounted = true;
@@ -31,29 +26,17 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
if (mounted) setInfo(value);
}).catch(onError);
return () => { mounted = false; };
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, onError]);
}, [record.id, record.gameVersion, record.steamLibraryConfirmation, maintenance.revision, onError]);
useEffect(() => ipcOn('event:copy-maintenance', (event) => {
if (event.id === record.id) setProgress(event);
}), [record.id]);
const run = (operation: Operation, options: OperationOptions = {}): void => {
setResult(null);
setWorking(operation);
setProgress(null);
ipcInvoke('copies:maintain', { id: record.id, operation, ...options })
.then(() => {
setResult(operation);
setRemoval(null);
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') setResult('cancelled');
else onError(error);
})
.finally(() => setWorking(null));
const run = (operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
if (operation === 'delete') setRemoval(null);
maintenance.run(record.id, operation, options);
};
const busy = working !== null;
const active = maintenance.active;
const busy = active !== null;
const result = maintenance.lastResult?.copyId === record.id ? maintenance.lastResult.outcome : null;
return (
<Sheet title={t('copies.sections.maintain')} aside={record.name}>
<CopyMaintenanceActions
@@ -71,32 +54,25 @@ export function CopyMaintenance({ record, onError }: CopyMaintenanceProps) {
onOptionsChange={setRemoval}
onRemove={(deleteData) => run('delete', { deleteData })}
/>
{working && (
<MaintenanceStatus
operation={working}
progress={progress}
onCancel={() => ipcInvoke('copies:cancelMaintenance').catch(onError)}
/>
)}
{active && <MaintenanceStatus progress={active} onCancel={maintenance.cancel} />}
{result && <p className="small" role="status">{t(`copies.maintenance.result.${result}`)}</p>}
</Sheet>
);
}
interface MaintenanceStatusProps {
readonly operation: Operation;
readonly progress: MaintenanceProgress | null;
readonly progress: MaintenanceProgress;
readonly onCancel: () => void;
}
function MaintenanceStatus({ operation, progress, onCancel }: MaintenanceStatusProps) {
function MaintenanceStatus({ progress, onCancel }: MaintenanceStatusProps) {
const { t } = useTranslation();
return (
<div className="maintenance-progress" role="status">
<p>{t(`copies.maintenance.phase.${progress?.phase ?? 'checking'}`)}</p>
<ProgressBar value={progress?.doneBytes ?? 0} max={progress?.totalBytes || null} />
{progress?.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(operation === 'update' || operation === 'compact') && progress?.phase !== 'applying' && (
<p>{t(`copies.maintenance.phase.${progress.phase}`)}</p>
<ProgressBar value={progress.doneBytes} max={progress.totalBytes || null} />
{progress.totalBytes ? <p className="small">{formatBytes(progress.doneBytes)} / {formatBytes(progress.totalBytes)}</p> : null}
{(progress.operation === 'update' || progress.operation === 'compact') && progress.phase !== 'applying' && (
<button type="button" className="button" onClick={onCancel}>
{t('wizard.cancel')}
</button>
@@ -0,0 +1,60 @@
import { useCallback, useEffect, useState } from 'react';
import type { IpcInput } from '@shared/ipc/contract.ts';
import type { MaintenanceProgress, MaintenanceRequest } from '@shared/schemas/maintenance.ts';
import { AppIpcError, ipcInvoke, ipcOn } from '../../ipc.ts';
export type MaintenanceOperation = MaintenanceRequest['operation'];
export type MaintenanceOptions = Pick<IpcInput<'copies:maintain'>, 'deleteData' | 'steamLocations'>;
export interface MaintenanceOutcome {
readonly copyId: string;
readonly outcome: MaintenanceOperation | 'cancelled';
}
/** Tracks copy maintenance across tab switches so progress and busy state survive unmounting the maintenance page. */
export function useCopyMaintenance(onError: (error: unknown) => void) {
const [active, setActive] = useState<MaintenanceProgress | null>(null);
const [lastResult, setLastResult] = useState<MaintenanceOutcome | null>(null);
const [revision, setRevision] = useState(0);
useEffect(() => {
let mounted = true;
let receivedEvent = false;
const dispose = ipcOn('event:copy-maintenance', (event) => {
receivedEvent = true;
setActive(event);
if (event === null) setRevision((value) => value + 1);
});
ipcInvoke('copies:maintenanceState').then((state) => {
if (mounted && !receivedEvent) setActive(state);
}).catch(onError);
return () => { mounted = false; dispose(); };
}, [onError]);
const run = useCallback((id: string, operation: MaintenanceOperation, options: MaintenanceOptions = {}): void => {
setLastResult(null);
setActive({ id, operation, phase: 'checking', doneBytes: 0, totalBytes: 0 });
ipcInvoke('copies:maintain', { id, operation, ...options })
.then(() => {
setLastResult({ copyId: id, outcome: operation });
})
.catch((error: unknown) => {
if (error instanceof AppIpcError && error.code === 'maintenance_cancelled') {
setLastResult({ copyId: id, outcome: 'cancelled' });
} else {
onError(error);
}
})
.finally(() => {
setActive((current) => (current?.id === id && current.operation === operation ? null : current));
});
}, [onError]);
const cancel = useCallback((): void => {
ipcInvoke('copies:cancelMaintenance').catch(onError);
}, [onError]);
return { active, lastResult, revision, run, cancel };
}
export type CopyMaintenanceState = ReturnType<typeof useCopyMaintenance>;
+5 -1
View File
@@ -154,6 +154,10 @@ export const ipcContract = {
input: z.object({ id: CopyIdSchema }),
output: MaintenanceInfoSchema,
},
'copies:maintenanceState': {
input: z.void(),
output: MaintenanceProgressSchema.nullable(),
},
'copies:maintain': {
input: MaintenanceRequestSchema,
output: CopiesSchema,
@@ -334,7 +338,7 @@ export const ipcEvents = {
'event:app-update-progress': AppUpdateProgressSchema,
'event:launch-state': LaunchStateSchema,
'event:copies-changed': CopiesSchema,
'event:copy-maintenance': MaintenanceProgressSchema,
'event:copy-maintenance': MaintenanceProgressSchema.nullable(),
/** Another patch set became active (a pack was installed, or the bundled set restored). */
'event:patch-set-changed': ActivePatchSetSchema,
} as const;