TypeScript
feat: suggest t3 doctor when the database has space to reclaim (#19437)
Julius Marminge65d390fc52fe
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsxindex 7ab14c10df8..b92111c0418 100644--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx@@ -26,6 +26,7 @@ import {SettingsEnvironmentFilterHeader,} from "./components/SettingsEnvironmentFilterHeader";import { BranchNamingSettings } from "./components/BranchNamingSettings";+import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";import { SettingsChoiceRow } from "./components/SettingsChoiceRow";import { SettingsSection } from "./components/SettingsSection";import { SettingsSwitchRow } from "./components/SettingsSwitchRow";@@ -428,6 +429,15 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {{props.page === "maintenance" ? (<>+ {!projectSelected &&+ selectedTargets+ .filter(+ (target) =>+ target.serverConfig.environment.capabilities.databaseStorage === true,+ )+ .map((target) => (+ <DatabaseStorageNotice key={target.environmentId} target={target} />+ ))}{!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.tsxnew file mode 100644index 00000000000..2c21e5125bf--- /dev/null+++ b/apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx@@ -0,0 +1,62 @@+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";+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: {} }),+ );+ 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);+ 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" })}+ />+ <SettingsActionRow+ icon="xmark"+ label="Dismiss"+ onPress={() =>+ updatePreferences({+ transform: (current) => ({+ dismissedDatabaseStorageNotices: [+ ...new Set([+ ...(current.dismissedDatabaseStorageNotices ?? []),+ target.environmentId,+ ]),+ ],+ }),+ })+ }+ />+ </SettingsSection>+ );+}diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.tsindex 808383183e4..72e163c747d 100644--- a/apps/mobile/src/persistence/mobile-preferences.ts+++ b/apps/mobile/src/persistence/mobile-preferences.ts@@ -67,6 +67,8 @@ export interface Preferences {readonly codeWordBreak?: boolean;readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;readonly collapsedProjectGroups?: readonly string[];+ /** Environments whose "reclaim database space" notice was dismissed. */+ readonly dismissedDatabaseStorageNotices?: readonly string[];/** What the Return key does in the composer on a hardware keyboard. iOS only. */readonly composerEnterBehavior?: ComposerEnterBehavior;/**@@ -150,6 +152,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {codeWordBreak?: boolean;connectOnboardingOptOutAccounts?: ReadonlyArray<string>;collapsedProjectGroups?: readonly string[];+ dismissedDatabaseStorageNotices?: readonly string[];composerEnterBehavior?: ComposerEnterBehavior;followUpBehavior?: FollowUpBehavior;microphones?: ReadonlyArray<MicrophoneEntry>;@@ -226,6 +229,11 @@ function sanitizePreferences(parsed: Preferences): Preferences {(key): key is string => typeof key === "string",);}+ if (Array.isArray(parsed.dismissedDatabaseStorageNotices)) {+ preferences.dismissedDatabaseStorageNotices = parsed.dismissedDatabaseStorageNotices.filter(+ (value): value is string => typeof value === "string",+ );+ }if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {preferences.composerEnterBehavior = parsed.composerEnterBehavior;}diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 5b8d483dc10..986a8c05f43 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -85,6 +85,7 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.serverUpsertKeybinding]: AuthSettingsWriteScope,[WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,[WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope,+ [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,[WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,[WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,[WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.tsindex 5cd89a1457b..6579335ee7c 100644--- a/apps/server/src/cli/invocation.test.ts+++ b/apps/server/src/cli/invocation.test.ts@@ -7,6 +7,7 @@ import * as Path from "effect/Path";import {formatCliCommand,+ resolveHostCliCommand,resolveRootCliCommand,resolveServerInstallation,} from "./invocation.ts";@@ -179,6 +180,53 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => {);});+it.layer(NodeServices.layer)("host CLI commands", (it) => {+ it.effect("renders a PowerShell command line on Windows", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const home = yield* fs.makeTempDirectoryScoped();+ const shim = path.join(home, "t3.cmd");+ yield* fs.writeFileString(shim, "@echo off\r\n");+ const hostCommand = (platform: NodeJS.Platform, env: Record<string, string>) =>+ resolveHostCliCommand("doctor", ["--base-dir", "C:\\Users\\Jane Doe\\.t3"]).pipe(+ Effect.provideService(HostProcess.ExecutablePath, "C:\\Program Files\\T3 Code\\t3.exe"),+ Effect.provideService(HostProcess.Arguments, [+ "C:\\Program Files\\T3 Code\\t3.exe",+ "C:\\Program Files\\T3 Code\\resources\\app.asar\\apps\\server\\dist\\bin.mjs",+ ]),+ Effect.provideService(HostProcess.IsExecutable, false),+ Effect.provideService(HostProcess.Platform, platform),+ Effect.provideService(HostProcess.Environment, { PATH: "", ...env }),+ );+ // The desktop shim is called through `&`, and each argument is quoted+ // the PowerShell way: no POSIX single quotes anywhere.+ expect((yield* hostCommand("win32", { T3CODE_CLI_PATH: shim })).command).toBe(+ `& "${shim}" doctor "--base-dir" "C:\\Users\\Jane Doe\\.t3"`,+ );+ // Without a launcher, plain `t3` with PowerShell-quoted arguments.+ expect((yield* hostCommand("win32", {})).command).toBe(+ 't3 doctor "--base-dir" "C:\\Users\\Jane Doe\\.t3"',+ );+ // Typographic quotes also delimit PowerShell strings; doubling keeps them.+ expect(+ (yield* resolveHostCliCommand("doctor", ["--base-dir", "C:\\T3\\\u201CArchive\u201D"]).pipe(+ Effect.provideService(HostProcess.Platform, "win32"),+ Effect.provideService(HostProcess.Environment, { PATH: "" }),+ Effect.provideService(HostProcess.ExecutablePath, "C:\\t3.exe"),+ Effect.provideService(HostProcess.Arguments, ["C:\\t3.exe", "C:\\bin.mjs"]),+ Effect.provideService(HostProcess.IsExecutable, false),+ )).command,+ ).toBe('t3 doctor "--base-dir" "C:\\T3\\\u201C\u201CArchive\u201D\u201D"');+ // POSIX hosts keep single quotes for the same input. The shim prefix is+ // a host path, so only the arguments are asserted.+ expect((yield* hostCommand("linux", { T3CODE_CLI_PATH: shim })).command).toMatch(+ / doctor --base-dir 'C:\\Users\\Jane Doe\\\.t3'$/,+ );+ }).pipe(Effect.scoped),+ );+});+it.layer(NodeServices.layer)("manual server installation ownership", (it) => {it.effect("recognizes runner caches for both script and executable packages", () =>Effect.gen(function* () {diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.tsindex ff5cb9d8f9c..686efbdafb1 100644--- a/apps/server/src/cli/invocation.ts+++ b/apps/server/src/cli/invocation.ts@@ -147,6 +147,22 @@ export const resolveCliCommand = (subcommand: string) =>const shellWord = (value: string) =>/^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;+/**+ * Quotes `value` for PowerShell, the default Windows terminal. Always quoted,+ * so a path reads the same whether or not it holds a space. Inside double+ * quotes `"` and its typographic forms (which also end the string) double,+ * and `$` and the backtick are escaped so nothing expands.+ */+const powershellWord = (value: string) =>+ `"${value+ .replaceAll("`", "``")+ .replaceAll("$", "`$")+ .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;++/** Quotes a word for the host's shell: POSIX, or PowerShell on Windows. */+const hostShellWord = (platform: NodeJS.Platform, value: string) =>+ platform === "win32" ? powershellWord(value) : shellWord(value);+/*** The launcher a person can type to run this install when `t3` is not on* PATH: the desktop app's `t3` shim, which the app and the shim itself name in@@ -165,19 +181,26 @@ const resolveInstallLauncher = Effect.gen(function* () {});/**- * `t3 <subcommand>` for a person to run on this host: `t3` when it is on PATH,- * the package runner this process came from, or else the absolute path of the- * launcher for this install, such as the one the desktop app installs.+ * `t3 <subcommand> <args>` for a person to run on this host: `t3` when it is+ * on PATH, the package runner this process came from, or else the absolute+ * path of the launcher for this install, such as the one the desktop app+ * installs. `args` are quoted for the host's shell: POSIX, or PowerShell on+ * Windows.*/-const resolveHostCliCommand = (subcommand: string) =>+export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>Effect.gen(function* () {+ const platform = yield* HostProcess.Platform;+ const withArgs = (prefix: string) =>+ [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");const command = yield* resolveCliCommand(subcommand);- if (command !== `t3 ${subcommand}`) return { command, launcher: false };- if (yield* isCommandAvailable("t3")) return { command, launcher: false };+ if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };+ if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };const launcher = yield* resolveInstallLauncher;- return Option.isSome(launcher)- ? { command: `${shellWord(launcher.value)} ${subcommand}`, launcher: true }- : { command, launcher: false };+ if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };+ // PowerShell runs a quoted path only through the call operator.+ const quoted = hostShellWord(platform, launcher.value);+ const call = platform === "win32" ? `& ${quoted}` : quoted;+ return { command: withArgs(`${call} ${subcommand}`), launcher: true };});/**diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex 8e635f9814b..71464911d6f 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -229,6 +229,7 @@ export const make = Effect.gen(function* () {threadAutoSettlement: true,storageCleanup: true,storageCleanupRun: true,+ databaseStorage: true,otlpEndpointCheck: true,projectWorktreeCleanup: true,settledWorktreeCleanup: true,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 167ce8d11ff..00009c59eca 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -57,6 +57,7 @@ const RPC_AGGREGATES = {[WS_METHODS.serverRemoveKeybinding]: "server",[WS_METHODS.serverRunStorageCleanup]: "server",[WS_METHODS.serverGetStorageCleanupReport]: "server",+ [WS_METHODS.serverGetDatabaseStorage]: "server",[WS_METHODS.serverGetSettings]: "server",[WS_METHODS.serverUpdateSettings]: "server",[WS_METHODS.serverSearchAcpRegistry]: "server",diff --git a/apps/server/src/persistence/DatabaseStorage.test.ts b/apps/server/src/persistence/DatabaseStorage.test.tsindex 59f9bf8b530..7196f18f40e 100644--- a/apps/server/src/persistence/DatabaseStorage.test.ts+++ b/apps/server/src/persistence/DatabaseStorage.test.ts@@ -1,8 +1,15 @@+import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as Stream from "effect/Stream";+import * as TestClock from "effect/testing/TestClock";import * as SqlClient from "effect/sql/SqlClient";+import * as ServerConfig from "../config.ts";import * as EventStore from "../orchestration-v2/EventStore.ts";import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";@@ -17,6 +24,23 @@ const freePages = Effect.map((rows) => rows[0]?.freelist_count ?? 0,);+const storageLayer = <E>(+ config: Layer.Layer<ServerConfig.ServerConfig, E, FileSystem.FileSystem | Path.Path>,+) =>+ DatabaseStorage.layer.pipe(+ Layer.provide(ProjectionMaintenance.layer),+ Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),+ Layer.provideMerge(Sqlite.layerMemory),+ Layer.provideMerge(config),+ Layer.provide(NodeServices.layer),+ );++const testConfig = ServerConfig.layerTest(process.cwd(), { prefix: "database-storage-" });++const currentStatus = Effect.flatMap(DatabaseStorage.DatabaseStorage, (storage) =>+ storage.status.pipe(Stream.take(1), Stream.runHead),+);+it.effect("a new database returns freed pages online without losing data", () =>Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;@@ -31,12 +55,55 @@ it.effect("a new database returns freed pages online without losing data", () =>yield* storage.reclaim;assert.equal(yield* freePages, 0);assert.deepEqual(yield* sql`SELECT value FROM retained`, [{ value: "keep" }]);+ }).pipe(Effect.provide(storageLayer(testConfig))),+);++it.effect("publishes file accounting and the doctor command after each pass", () =>+ Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;+ const config = yield* ServerConfig.ServerConfig;+ yield* sql`CREATE TABLE discarded (value BLOB)`;+ yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;+ yield* TestClock.adjust("1 minute");+ const before = (yield* currentStatus).pipe(Option.getOrThrow);+ assert.isNotNull(before);+ assert.isAbove(before!.databaseBytes, 1048576);+ assert.isTrue(before!.incrementalVacuumEnabled);+ // Quoting follows the host shell, so check each word on its own.+ assert.include(before!.compactCommand, "doctor");+ assert.include(before!.compactCommand, "--base-dir");+ assert.include(before!.compactCommand, config.baseDir);++ // The next reclaim pass frees the dropped table and republishes.+ yield* sql`DROP TABLE discarded`;+ yield* TestClock.adjust("1 minute");+ const storage = yield* DatabaseStorage.DatabaseStorage;+ const after = yield* storage.status.pipe(+ Stream.filter((status) => status !== null && status.databaseBytes < before!.databaseBytes),+ Stream.runHead,+ Effect.map(Option.getOrThrow),+ );+ assert.isAtMost(after!.databaseBytes, before!.databaseBytes - 1048576);+ assert.equal(after!.reclaimableBytes, 0);+ }).pipe(Effect.provide(storageLayer(testConfig))),+);++it.effect("publishes nothing when doctor would repair a different database", () =>+ Effect.gen(function* () {+ yield* TestClock.adjust("1 minute");+ assert.deepEqual(yield* currentStatus, Option.some(null));}).pipe(Effect.provide(- DatabaseStorage.layer.pipe(- Layer.provide(ProjectionMaintenance.layer),- Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),- Layer.provideMerge(Sqlite.layerMemory),+ storageLayer(+ // A dev server without an explicit home keeps state in <baseDir>/dev,+ // while `doctor --base-dir` targets <baseDir>/userdata.+ Layer.effect(+ ServerConfig.ServerConfig,+ Effect.gen(function* () {+ const config = yield* ServerConfig.ServerConfig;+ return { ...config, dbPath: `${config.baseDir}/dev/statev2.sqlite` };+ }),+ ).pipe(Layer.provide(testConfig)),),),),diff --git a/apps/server/src/persistence/DatabaseStorage.ts b/apps/server/src/persistence/DatabaseStorage.tsindex 914ca51fa45..3866020c1c1 100644--- a/apps/server/src/persistence/DatabaseStorage.ts+++ b/apps/server/src/persistence/DatabaseStorage.ts@@ -1,9 +1,16 @@+import type { DatabaseStorageStatus } from "@t3tools/contracts";import * as Context from "effect/Context";import * as Effect from "effect/Effect";+import * as Equal from "effect/Equal";import * as Layer from "effect/Layer";+import * as Path from "effect/Path";import * as Schedule from "effect/Schedule";+import * as Stream from "effect/Stream";+import * as SubscriptionRef from "effect/SubscriptionRef";import * as SqlClient from "effect/sql/SqlClient";+import { resolveHostCliCommand } from "../cli/invocation.ts";+import * as ServerConfig from "../config.ts";import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";import { forkParked } from "../serverActivation.ts";@@ -15,6 +22,8 @@ export class DatabaseStorage extends Context.Service<{/** Return free pages to the filesystem on databases with incremental auto_vacuum. */readonly reclaim: Effect.Effect<void>;+ /** Current file accounting, re-published after each maintenance pass. Null until first read. */+ readonly status: Stream.Stream<DatabaseStorageStatus | null>;}>()("t3/persistence/DatabaseStorage") {}@@ -27,6 +36,42 @@ export class DatabaseStorage extends Context.Service<const make = Effect.gen(function* () {const sql = yield* SqlClient.SqlClient;const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;+ const config = yield* ServerConfig.ServerConfig;+ const path = yield* Path.Path;+ const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);++ // The notice shows this verbatim; quote for the host's shell. Desktop+ // installs have no `t3` on PATH, so the command names their launcher.+ const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [+ "--base-dir",+ config.baseDir,+ ]);+ // `t3 doctor --base-dir` repairs <baseDir>/userdata. A dev server without+ // an explicit home keeps its state in <baseDir>/dev instead, so there the+ // command would target the live install; publish no status at all.+ const doctorTargetsThisDatabase =+ path.resolve(config.dbPath) ===+ path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));+ const publishStatus = Effect.gen(function* () {+ if (!doctorTargetsThisDatabase) return;+ const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;+ const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;+ const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;+ const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;+ const pageSize = size[0]?.page_size ?? 0;+ const next: DatabaseStorageStatus = {+ databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,+ reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,+ incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,+ compactCommand,+ };+ // Every set reaches each open Storage page; most passes change nothing.+ if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {+ yield* SubscriptionRef.set(statusRef, next);+ }+ }).pipe(+ Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),+ );const reclaim = Effect.gen(function* () {const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;@@ -57,16 +102,21 @@ const make = Effect.gen(function* () {yield* forkParked(Effect.sleep("1 minute").pipe(- Effect.andThen(compact.pipe(Effect.repeat(Schedule.spaced("6 hours")))),+ Effect.andThen(+ compact.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("6 hours"))),+ ),),);yield* forkParked(- Effect.sleep("1 minute").pipe(- Effect.andThen(reclaim.pipe(Effect.repeat(Schedule.spaced("1 minute")))),+ publishStatus.pipe(+ Effect.andThen(Effect.sleep("1 minute")),+ Effect.andThen(+ reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),+ ),),);- return DatabaseStorage.of({ reclaim });+ return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });});export const layer = Layer.effect(DatabaseStorage, make);diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 96994ee37c1..d3878ef8beb 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -176,6 +176,7 @@ import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";import * as ServerSettings from "./serverSettings.ts";+import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";import * as StorageCleanup from "./storageCleanup.ts";import * as TerminalManager from "./terminal/Manager.ts";import { withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";@@ -1299,6 +1300,7 @@ const layerWsRpc = (const config = yield* ServerConfig.ServerConfig;const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;const storageCleanup = yield* StorageCleanup.StorageCleanup;+ const databaseStorage = yield* DatabaseStorage.DatabaseStorage;const serverSettings = yield* ServerSettings.ServerSettingsService;const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;@@ -2414,6 +2416,7 @@ const layerWsRpc = (}),[WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,[WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,+ [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,[WS_METHODS.serverGetSettings]: (_input) =>serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),[WS_METHODS.serverUpdateSettings]: ({ patch, providerInstanceMutation }) =>diff --git a/apps/web/src/components/settings/DatabaseStorageNotice.tsx b/apps/web/src/components/settings/DatabaseStorageNotice.tsxnew file mode 100644index 00000000000..637c920f5ed--- /dev/null+++ b/apps/web/src/components/settings/DatabaseStorageNotice.tsx@@ -0,0 +1,60 @@+import { useAtomValue } from "@effect/atom-react";+import { shouldRecommendDatabaseCompaction, 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. */+export function DatabaseStorageNotice({+ environmentId,+ label,+}: {+ environmentId: EnvironmentId;+ label: string;+}) {+ const result = useAtomValue(serverEnvironment.databaseStorage({ environmentId, input: {} }));+ const [dismissed, setDismissed] = useLocalStorage(+ `database-storage-notice-dismissed:${environmentId}`,+ false,+ Schema.Boolean,+ );+ const { copyToClipboard } = useCopyToClipboard({ target: "command" });+ const status = result._tag === "Success" ? result.value : null;+ if (dismissed || status === null || !shouldRecommendDatabaseCompaction(status)) return null;+ return (+ <SettingsSection id={`storage-database-${environmentId}`} title="Database">+ <SettingsGroup>+ <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>+ </>+ }+ control={+ <div className="flex flex-wrap items-center gap-1.5">+ <Button+ variant="outline"+ size="sm"+ onClick={() => copyToClipboard(status.compactCommand, undefined)}+ >+ Copy command+ </Button>+ <Button variant="ghost" size="sm" onClick={() => setDismissed(true)}>+ Dismiss+ </Button>+ </div>+ }+ />+ </SettingsGroup>+ </SettingsSection>+ );+}diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsxindex baae21bc77d..0c54d27755a 100644--- a/apps/web/src/components/settings/StorageSettings.tsx+++ b/apps/web/src/components/settings/StorageSettings.tsx@@ -35,6 +35,7 @@ import {SettingsSection,useRelativeTimeTick,} from "./settingsLayout";+import { DatabaseStorageNotice } from "./DatabaseStorageNotice";import { SettingsScopeNotice } from "./SettingsScopeNotice";import { FoldedSettingsSection } from "./FoldedSettingsSection";import { SettingsGroup } from "./SettingsGroup";@@ -483,6 +484,19 @@ export function StorageSettingsPanel() {return (<SettingsPageContainer>+ {!isProjectScope &&+ 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/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex c11a49897b8..c3cd2967feb 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -59,6 +59,7 @@ export type EnvironmentSubscriptionRpcTag =| typeof WS_METHODS.subscribeServerLifecycle| typeof WS_METHODS.scheduledTasksSubscribe| typeof WS_METHODS.serverGetStorageCleanupReport+ | typeof WS_METHODS.serverGetDatabaseStorage| typeof WS_METHODS.subscribeTerminalEvents| typeof WS_METHODS.subscribeTerminalMetadata| typeof WS_METHODS.subscribePreviewEventsdiff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 243d88c11dc..c896f43c64f 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -1000,6 +1000,11 @@ 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,+ }),storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {label: "environment-data:server:storage-cleanup-report",tag: WS_METHODS.serverGetStorageCleanupReport,diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 53170883dd5..8086603afca 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -126,6 +126,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({threadAutoSettlement: Schema.optionalKey(Schema.Boolean),storageCleanup: Schema.optionalKey(Schema.Boolean),storageCleanupRun: Schema.optionalKey(Schema.Boolean),+ /** Server streams database size and reclaimable space for the Storage settings notice. */+ databaseStorage: Schema.optionalKey(Schema.Boolean),/** Server checks OTLP endpoints for the telemetry export settings. */otlpEndpointCheck: Schema.optionalKey(Schema.Boolean),projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean),diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 61304c52f86..08d08609e57 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -326,6 +326,7 @@ import {import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";import {StorageCleanupReport,+ DatabaseStorageStatus,ServerSettings,ServerSettingsError,ServerSettingsPatch,@@ -483,6 +484,7 @@ export const WS_METHODS = {serverRemoveKeybinding: "server.removeKeybinding",serverRunStorageCleanup: "server.runStorageCleanup",serverGetStorageCleanupReport: "server.getStorageCleanupReport",+ serverGetDatabaseStorage: "server.getDatabaseStorage",serverGetSettings: "server.getSettings",serverUpdateSettings: "server.updateSettings",serverDiscoverSourceControl: "server.discoverSourceControl",@@ -761,6 +763,13 @@ const WsServerGetStorageCleanupReportRpc = Rpc.make(WS_METHODS.serverGetStorageCerror: EnvironmentAuthorizationError,});+const WsServerGetDatabaseStorageRpc = Rpc.make(WS_METHODS.serverGetDatabaseStorage, {+ payload: Schema.Struct({}),+ success: Schema.NullOr(DatabaseStorageStatus),+ stream: true,+ error: EnvironmentAuthorizationError,+});+const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {payload: Schema.Struct({}),success: ServerSettings,@@ -1902,6 +1911,7 @@ export const WsRpcGroup = RpcGroup.make(WsServerRemoveKeybindingRpc,WsServerRunStorageCleanupRpc,WsServerGetStorageCleanupReportRpc,+ WsServerGetDatabaseStorageRpc,WsServerGetSettingsRpc,WsServerUpdateSettingsRpc,WsServerDiscoverSourceControlRpc,diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex ea5185b4028..3ddbe726612 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1077,6 +1077,26 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettin/** Reclaimable bytes from which the offline `t3 doctor` repair is worth suggesting. */export const DATABASE_COMPACTION_RECOMMENDED_BYTES = 1024 ** 3;+/** Live SQLite file accounting for the environment's state database. */+export const DatabaseStorageStatus = Schema.Struct({+ databaseBytes: Schema.Number,+ /** Free pages inside the file that an offline VACUUM (or incremental auto_vacuum) returns to disk. */+ reclaimableBytes: Schema.Number,+ /** False on databases created before incremental auto_vacuum; `t3 doctor` converts them. */+ incrementalVacuumEnabled: Schema.Boolean,+ /** Command to run on the host to reclaim the space offline. */+ compactCommand: Schema.String,+});+export type DatabaseStorageStatus = typeof DatabaseStorageStatus.Type;++/** Only suggest the offline conversion when it can reclaim enough to matter. */+export function shouldRecommendDatabaseCompaction(status: DatabaseStorageStatus): boolean {+ return (+ !status.incrementalVacuumEnabled &&+ status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES+ );+}+export const StorageCleanupReportEntry = Schema.Struct({kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),outcome: Schema.Literals(["removed", "kept", "failed"]),