TypeScript
fix(web,mobile): list database space for all machines in one notice (#22575)
Julius Marminge8cd561ef6f8d
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsxindex 140e92505ef..e33f1b8d5cb 100644--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx@@ -434,15 +434,14 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {{props.page === "maintenance" ? (<>- {!projectSelected &&- selectedTargets- .filter(+ {!projectSelected ? (+ <DatabaseStorageNotice+ targets={selectedTargets.filter((target) =>target.serverConfig.environment.capabilities.databaseStorage === true,- )- .map((target) => (- <DatabaseStorageNotice key={target.environmentId} target={target} />- ))}+ )}+ />+ ) : null}{!projectSelected ? (<SettingsSection title="Manage environments">{selectedTargets.map((target) => (diff --git a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsxindex 2c21e5125bf..1e7e6693103 100644--- a/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx+++ b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx@@ -1,9 +1,6 @@import { useAtomSet, useAtomValue } from "@effect/atom-react";-import { shouldRecommendDatabaseCompaction } from "@t3tools/contracts";import { AsyncResult } from "effect/reactivity";-import { View } from "react-native";-import { AppText as Text } from "../../../components/ui/AppText";import { copyTextWithHaptic } from "../../../lib/copyTextWithHaptic";import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";import { serverEnvironment } from "../../../state/server";@@ -11,36 +8,41 @@ import type { SettingsTarget } from "../settings-environment-filter";import { SettingsActionRow } from "./SettingsActionRow";import { SettingsSection } from "./SettingsSection";-/** Suggests `t3 doctor` for a database that still holds at least 1 GiB of freed pages. */-export function DatabaseStorageNotice({ target }: { readonly target: SettingsTarget }) {- const result = useAtomValue(- serverEnvironment.databaseStorage({ environmentId: target.environmentId, input: {} }),+/** Suggests `t3 doctor` on every machine whose database still holds at least 1 GiB of freed pages. */+export function DatabaseStorageNotice({+ targets,+}: {+ readonly targets: readonly SettingsTarget[];+}) {+ const recommendations = useAtomValue(+ serverEnvironment.databaseCompactionRecommendations(+ JSON.stringify(targets.map((target) => target.environmentId)),+ ),);const preferences = useAtomValue(mobilePreferencesAtom);const updatePreferences = useAtomSet(updateMobilePreferencesAtom);- const dismissed =- AsyncResult.isSuccess(preferences) &&- preferences.value.dismissedDatabaseStorageNotices?.includes(target.environmentId) === true;- const status = result._tag === "Success" ? result.value : null;- if (dismissed || status === null || !shouldRecommendDatabaseCompaction(status)) return null;- const gib = (status.reclaimableBytes / 1024 ** 3).toFixed(1);+ const dismissed = AsyncResult.isSuccess(preferences)+ ? (preferences.value.dismissedDatabaseStorageNotices ?? [])+ : [];+ const visible = recommendations.filter(+ (recommendation) => !dismissed.includes(recommendation.environmentId),+ );+ if (visible.length === 0) return null;return (- <SettingsSection title={`Reclaim ${gib} GiB on ${target.label}`}>- <View className="gap-3 p-4">- <Text className="text-sm text-muted-foreground">- Old history is cleaned up automatically, but this database still holds the freed space.- Run this command on {target.label} to return it to disk; it pauses and restarts the- background service. Quit the desktop app first if it hosts this environment.- </Text>- <Text selectable className="font-mono text-sm text-foreground">- {status.compactCommand}- </Text>- </View>- <SettingsActionRow- icon="doc.on.doc"- label="Copy command"- onPress={() => copyTextWithHaptic(status.compactCommand, { target: "command" })}- />+ <SettingsSection+ title="Reclaim database space"+ footer="Old history is cleaned up automatically, but these databases still hold the freed space. Run the command on each machine to return it to disk; it pauses and restarts the background service. Quit the desktop app first if it hosts the environment."+ >+ {visible.map(({ environmentId, status }) => (+ <SettingsActionRow+ key={environmentId}+ icon="doc.on.doc"+ label={targets.find((target) => target.environmentId === environmentId)?.label ?? ""}+ description={status.compactCommand}+ detail={`${(status.reclaimableBytes / 1024 ** 3).toFixed(1)} GiB`}+ onPress={() => copyTextWithHaptic(status.compactCommand, { target: "command" })}+ />+ ))}<SettingsActionRowicon="xmark"label="Dismiss"@@ -50,7 +52,7 @@ export function DatabaseStorageNotice({ target }: { readonly target: SettingsTardismissedDatabaseStorageNotices: [...new Set([...(current.dismissedDatabaseStorageNotices ?? []),- target.environmentId,+ ...visible.map((recommendation) => recommendation.environmentId),]),],}),diff --git a/apps/web/src/components/settings/DatabaseStorageNotice.tsx b/apps/web/src/components/settings/DatabaseStorageNotice.tsxindex 637c920f5ed..08ccf816a9e 100644--- a/apps/web/src/components/settings/DatabaseStorageNotice.tsx+++ b/apps/web/src/components/settings/DatabaseStorageNotice.tsx@@ -1,60 +1,70 @@import { useAtomValue } from "@effect/atom-react";-import { shouldRecommendDatabaseCompaction, type EnvironmentId } from "@t3tools/contracts";+import type { EnvironmentId } from "@t3tools/contracts";import * as Schema from "effect/Schema";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";import { useLocalStorage } from "../../hooks/useLocalStorage";import { serverEnvironment } from "../../state/server";import { Button } from "../ui/button";-import { SettingsGroup } from "./SettingsGroup";import { SettingsRow, SettingsSection } from "./settingsLayout";-/** Suggests `t3 doctor` for a database that still holds at least 1 GiB of freed pages. */+const DismissedEnvironmentIds = Schema.Array(Schema.String);++/** Suggests `t3 doctor` on every machine whose database still holds at least 1 GiB of freed pages. */export function DatabaseStorageNotice({- environmentId,- label,+ environments,}: {- environmentId: EnvironmentId;- label: string;+ environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>;}) {- const result = useAtomValue(serverEnvironment.databaseStorage({ environmentId, input: {} }));+ const recommendations = useAtomValue(+ serverEnvironment.databaseCompactionRecommendations(+ JSON.stringify(environments.map((environment) => environment.environmentId)),+ ),+ );const [dismissed, setDismissed] = useLocalStorage(- `database-storage-notice-dismissed:${environmentId}`,- false,- Schema.Boolean,+ "database-storage-notice-dismissed",+ [],+ DismissedEnvironmentIds,);const { copyToClipboard } = useCopyToClipboard({ target: "command" });- const status = result._tag === "Success" ? result.value : null;- if (dismissed || status === null || !shouldRecommendDatabaseCompaction(status)) return null;+ const visible = recommendations.filter(+ (recommendation) => !dismissed.includes(recommendation.environmentId),+ );+ if (visible.length === 0) return null;return (- <SettingsSection id={`storage-database-${environmentId}`} title="Database">- <SettingsGroup>+ <SettingsSection id="storage-database" title="Database">+ <SettingsRow+ title="Reclaim freed database space"+ description="Old history is cleaned up automatically, but these databases still hold the freed space. Run the command on each machine to return it to disk; it pauses and restarts the background service. Quit the desktop app first if it hosts the environment."+ />+ {visible.map(({ environmentId, status }) => (<SettingsRow- title={`Reclaim ${(status.reclaimableBytes / 1024 ** 3).toFixed(1)} GiB on ${label}`}- description={- <>- Old history is cleaned up automatically, but this database still holds the freed- space. Run the command on {label} to return it to disk; it pauses and restarts the- background service. Quit the desktop app first if it hosts this environment.- <code className="mt-2 block select-text break-all">{status.compactCommand}</code>- </>- }+ key={environmentId}+ title={`${(status.reclaimableBytes / 1024 ** 3).toFixed(1)} GiB on ${+ environments.find((environment) => environment.environmentId === environmentId)+ ?.label ?? environmentId+ }`}+ description={<code className="select-text break-all">{status.compactCommand}</code>}control={<div className="flex flex-wrap items-center gap-1.5"><Buttonvariant="outline"- size="sm"+ size="xs"onClick={() => copyToClipboard(status.compactCommand, undefined)}>Copy command</Button>- <Button variant="ghost" size="sm" onClick={() => setDismissed(true)}>+ <Button+ variant="ghost"+ size="xs"+ onClick={() => setDismissed((current) => [...current, environmentId])}+ >Dismiss</Button></div>}/>- </SettingsGroup>+ ))}</SettingsSection>);}diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsxindex 78dd750109a..643e0864dc9 100644--- a/apps/web/src/components/settings/StorageSettings.tsx+++ b/apps/web/src/components/settings/StorageSettings.tsx@@ -491,19 +491,14 @@ export function StorageSettingsPanel() {return (<SettingsPageContainer>- {!isProjectScope &&- connectedEnvironments- .filter(+ {!isProjectScope && (+ <DatabaseStorageNotice+ environments={connectedEnvironments.filter((environment) =>environment.serverConfig?.environment.capabilities.databaseStorage === true,- )- .map((environment) => (- <DatabaseStorageNotice- key={environment.environmentId}- environmentId={environment.environmentId}- label={environment.label}- />- ))}+ )}+ />+ )}<SettingsSection id="storage-worktrees" title="Worktrees">{!isProjectScope && <WorktreesDirectoryRow />}{isProjectScope && (diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex a38c28db629..4361592601f 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -6,6 +6,7 @@ import {type ServerLifecycleStreamReadyEvent,type ServerSelfUpdateProgressEvent,type ServerSelfUpdateResult,+ shouldRecommendDatabaseCompaction,WS_METHODS,} from "@t3tools/contracts";import * as Cause from "effect/Cause";@@ -954,6 +955,34 @@ export function createServerEnvironmentAtoms<R, E>(: AsyncResult.success(result.value, result);}).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),);+ const databaseStorage = createEnvironmentRpcSubscriptionAtomFamily(runtime, {+ label: "environment-data:server:database-storage",+ tag: WS_METHODS.serverGetDatabaseStorage,+ idleTtlMs: 0,+ });+ // Keyed by a JSON array of environment ids so one notice can list every machine.+ const databaseCompactionRecommendations = Atom.family((environmentIdsKey: string) => {+ const sources = (JSON.parse(environmentIdsKey) as EnvironmentId[]).map((environmentId) => ({+ environmentId,+ atom: databaseStorage({ environmentId, input: {} }),+ }));+ return Atom.make((get) =>+ sources+ .flatMap(({ environmentId, atom }) => {+ const result = get(atom);+ return result._tag === "Success" &&+ result.value !== null &&+ shouldRecommendDatabaseCompaction(result.value)+ ? [{ environmentId, status: result.value }]+ : [];+ })+ .sort((left, right) => right.status.reclaimableBytes - left.status.reclaimableBytes),+ ).pipe(+ Atom.withLabel(+ `environment-data:server:database-compaction-recommendations:${environmentIdsKey}`,+ ),+ );+ });const welcome = (target: {readonly environmentId: EnvironmentId;readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;@@ -972,11 +1001,8 @@ export function createServerEnvironmentAtoms<R, E>(tag: WS_METHODS.serverRunStorageCleanup,concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },}),- databaseStorage: createEnvironmentRpcSubscriptionAtomFamily(runtime, {- label: "environment-data:server:database-storage",- tag: WS_METHODS.serverGetDatabaseStorage,- idleTtlMs: 0,- }),+ databaseStorage,+ databaseCompactionRecommendations,storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {label: "environment-data:server:storage-cleanup-report",tag: WS_METHODS.serverGetStorageCleanupReport,