@devries-cameron20 / t3code-1 / commits / 65d390fc52
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat: suggest t3 doctor when the database has space to reclaim (#19437)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>

Julius Marminge committed Oct 15, 2026 at 17:03 UTC 65d390fc52fe7cc4c481dede0e45cca6b7f5d365
18 files changed +403 -17
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+10
@@ -26,6 +26,7 @@ import {
26 SettingsEnvironmentFilterHeader,
27 } from "./components/SettingsEnvironmentFilterHeader";
28 import { BranchNamingSettings } from "./components/BranchNamingSettings";
29 +import { DatabaseStorageNotice } from "./components/DatabaseStorageNotice";
30 import { SettingsChoiceRow } from "./components/SettingsChoiceRow";
31 import { SettingsSection } from "./components/SettingsSection";
32 import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
@@ -428,6 +429,15 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
429
430 {props.page === "maintenance" ? (
431 <>
432 + {!projectSelected &&
433 + selectedTargets
434 + .filter(
435 + (target) =>
436 + target.serverConfig.environment.capabilities.databaseStorage === true,
437 + )
438 + .map((target) => (
439 + <DatabaseStorageNotice key={target.environmentId} target={target} />
440 + ))}
441 {!projectSelected ? (
442 <SettingsSection title="Manage environments">
443 {selectedTargets.map((target) => (
apps/mobile/src/features/settings/components/DatabaseStorageNotice.tsx new
+62
@@ -0,0 +1,62 @@
1 +import { useAtomSet, useAtomValue } from "@effect/atom-react";
2 +import { shouldRecommendDatabaseCompaction } from "@t3tools/contracts";
3 +import { AsyncResult } from "effect/reactivity";
4 +import { View } from "react-native";
5 +
6 +import { AppText as Text } from "../../../components/ui/AppText";
7 +import { copyTextWithHaptic } from "../../../lib/copyTextWithHaptic";
8 +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../../state/preferences";
9 +import { serverEnvironment } from "../../../state/server";
10 +import type { SettingsTarget } from "../settings-environment-filter";
11 +import { SettingsActionRow } from "./SettingsActionRow";
12 +import { SettingsSection } from "./SettingsSection";
13 +
14 +/** Suggests `t3 doctor` for a database that still holds at least 1 GiB of freed pages. */
15 +export function DatabaseStorageNotice({ target }: { readonly target: SettingsTarget }) {
16 + const result = useAtomValue(
17 + serverEnvironment.databaseStorage({ environmentId: target.environmentId, input: {} }),
18 + );
19 + const preferences = useAtomValue(mobilePreferencesAtom);
20 + const updatePreferences = useAtomSet(updateMobilePreferencesAtom);
21 + const dismissed =
22 + AsyncResult.isSuccess(preferences) &&
23 + preferences.value.dismissedDatabaseStorageNotices?.includes(target.environmentId) === true;
24 + const status = result._tag === "Success" ? result.value : null;
25 + if (dismissed || status === null || !shouldRecommendDatabaseCompaction(status)) return null;
26 + const gib = (status.reclaimableBytes / 1024 ** 3).toFixed(1);
27 + return (
28 + <SettingsSection title={`Reclaim ${gib} GiB on ${target.label}`}>
29 + <View className="gap-3 p-4">
30 + <Text className="text-sm text-muted-foreground">
31 + Old history is cleaned up automatically, but this database still holds the freed space.
32 + Run this command on {target.label} to return it to disk; it pauses and restarts the
33 + background service. Quit the desktop app first if it hosts this environment.
34 + </Text>
35 + <Text selectable className="font-mono text-sm text-foreground">
36 + {status.compactCommand}
37 + </Text>
38 + </View>
39 + <SettingsActionRow
40 + icon="doc.on.doc"
41 + label="Copy command"
42 + onPress={() => copyTextWithHaptic(status.compactCommand, { target: "command" })}
43 + />
44 + <SettingsActionRow
45 + icon="xmark"
46 + label="Dismiss"
47 + onPress={() =>
48 + updatePreferences({
49 + transform: (current) => ({
50 + dismissedDatabaseStorageNotices: [
51 + ...new Set([
52 + ...(current.dismissedDatabaseStorageNotices ?? []),
53 + target.environmentId,
54 + ]),
55 + ],
56 + }),
57 + })
58 + }
59 + />
60 + </SettingsSection>
61 + );
62 +}
apps/mobile/src/persistence/mobile-preferences.ts
+8
@@ -67,6 +67,8 @@ export interface Preferences {
67 readonly codeWordBreak?: boolean;
68 readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
69 readonly collapsedProjectGroups?: readonly string[];
70 + /** Environments whose "reclaim database space" notice was dismissed. */
71 + readonly dismissedDatabaseStorageNotices?: readonly string[];
72 /** What the Return key does in the composer on a hardware keyboard. iOS only. */
73 readonly composerEnterBehavior?: ComposerEnterBehavior;
74 /**
@@ -150,6 +152,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
152 codeWordBreak?: boolean;
153 connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
154 collapsedProjectGroups?: readonly string[];
155 + dismissedDatabaseStorageNotices?: readonly string[];
156 composerEnterBehavior?: ComposerEnterBehavior;
157 followUpBehavior?: FollowUpBehavior;
158 microphones?: ReadonlyArray<MicrophoneEntry>;
@@ -226,6 +229,11 @@ function sanitizePreferences(parsed: Preferences): Preferences {
229 (key): key is string => typeof key === "string",
230 );
231 }
232 + if (Array.isArray(parsed.dismissedDatabaseStorageNotices)) {
233 + preferences.dismissedDatabaseStorageNotices = parsed.dismissedDatabaseStorageNotices.filter(
234 + (value): value is string => typeof value === "string",
235 + );
236 + }
237 if (parsed.composerEnterBehavior === "send" || parsed.composerEnterBehavior === "newline") {
238 preferences.composerEnterBehavior = parsed.composerEnterBehavior;
239 }
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -85,6 +85,7 @@ export const RPC_REQUIRED_SCOPES = {
85 [WS_METHODS.serverUpsertKeybinding]: AuthSettingsWriteScope,
86 [WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,
87 [WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope,
88 + [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
89 [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
90 [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
91 [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
apps/server/src/cli/invocation.test.ts
+48
@@ -7,6 +7,7 @@ import * as Path from "effect/Path";
7
8 import {
9 formatCliCommand,
10 + resolveHostCliCommand,
11 resolveRootCliCommand,
12 resolveServerInstallation,
13 } from "./invocation.ts";
@@ -179,6 +180,53 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => {
180 );
181 });
182
183 +it.layer(NodeServices.layer)("host CLI commands", (it) => {
184 + it.effect("renders a PowerShell command line on Windows", () =>
185 + Effect.gen(function* () {
186 + const fs = yield* FileSystem.FileSystem;
187 + const path = yield* Path.Path;
188 + const home = yield* fs.makeTempDirectoryScoped();
189 + const shim = path.join(home, "t3.cmd");
190 + yield* fs.writeFileString(shim, "@echo off\r\n");
191 + const hostCommand = (platform: NodeJS.Platform, env: Record<string, string>) =>
192 + resolveHostCliCommand("doctor", ["--base-dir", "C:\\Users\\Jane Doe\\.t3"]).pipe(
193 + Effect.provideService(HostProcess.ExecutablePath, "C:\\Program Files\\T3 Code\\t3.exe"),
194 + Effect.provideService(HostProcess.Arguments, [
195 + "C:\\Program Files\\T3 Code\\t3.exe",
196 + "C:\\Program Files\\T3 Code\\resources\\app.asar\\apps\\server\\dist\\bin.mjs",
197 + ]),
198 + Effect.provideService(HostProcess.IsExecutable, false),
199 + Effect.provideService(HostProcess.Platform, platform),
200 + Effect.provideService(HostProcess.Environment, { PATH: "", ...env }),
201 + );
202 + // The desktop shim is called through `&`, and each argument is quoted
203 + // the PowerShell way: no POSIX single quotes anywhere.
204 + expect((yield* hostCommand("win32", { T3CODE_CLI_PATH: shim })).command).toBe(
205 + `& "${shim}" doctor "--base-dir" "C:\\Users\\Jane Doe\\.t3"`,
206 + );
207 + // Without a launcher, plain `t3` with PowerShell-quoted arguments.
208 + expect((yield* hostCommand("win32", {})).command).toBe(
209 + 't3 doctor "--base-dir" "C:\\Users\\Jane Doe\\.t3"',
210 + );
211 + // Typographic quotes also delimit PowerShell strings; doubling keeps them.
212 + expect(
213 + (yield* resolveHostCliCommand("doctor", ["--base-dir", "C:\\T3\\\u201CArchive\u201D"]).pipe(
214 + Effect.provideService(HostProcess.Platform, "win32"),
215 + Effect.provideService(HostProcess.Environment, { PATH: "" }),
216 + Effect.provideService(HostProcess.ExecutablePath, "C:\\t3.exe"),
217 + Effect.provideService(HostProcess.Arguments, ["C:\\t3.exe", "C:\\bin.mjs"]),
218 + Effect.provideService(HostProcess.IsExecutable, false),
219 + )).command,
220 + ).toBe('t3 doctor "--base-dir" "C:\\T3\\\u201C\u201CArchive\u201D\u201D"');
221 + // POSIX hosts keep single quotes for the same input. The shim prefix is
222 + // a host path, so only the arguments are asserted.
223 + expect((yield* hostCommand("linux", { T3CODE_CLI_PATH: shim })).command).toMatch(
224 + / doctor --base-dir 'C:\\Users\\Jane Doe\\\.t3'$/,
225 + );
226 + }).pipe(Effect.scoped),
227 + );
228 +});
229 +
230 it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
231 it.effect("recognizes runner caches for both script and executable packages", () =>
232 Effect.gen(function* () {
apps/server/src/cli/invocation.ts
+32 -9
@@ -147,6 +147,22 @@ export const resolveCliCommand = (subcommand: string) =>
147 const shellWord = (value: string) =>
148 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
149
150 +/**
151 + * Quotes `value` for PowerShell, the default Windows terminal. Always quoted,
152 + * so a path reads the same whether or not it holds a space. Inside double
153 + * quotes `"` and its typographic forms (which also end the string) double,
154 + * and `$` and the backtick are escaped so nothing expands.
155 + */
156 +const powershellWord = (value: string) =>
157 + `"${value
158 + .replaceAll("`", "``")
159 + .replaceAll("$", "`$")
160 + .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;
161 +
162 +/** Quotes a word for the host's shell: POSIX, or PowerShell on Windows. */
163 +const hostShellWord = (platform: NodeJS.Platform, value: string) =>
164 + platform === "win32" ? powershellWord(value) : shellWord(value);
165 +
166 /**
167 * The launcher a person can type to run this install when `t3` is not on
168 * 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* () {
181 });
182
183 /**
168 - * `t3 <subcommand>` for a person to run on this host: `t3` when it is on PATH,
169 - * the package runner this process came from, or else the absolute path of the
170 - * launcher for this install, such as the one the desktop app installs.
184 + * `t3 <subcommand> <args>` for a person to run on this host: `t3` when it is
185 + * on PATH, the package runner this process came from, or else the absolute
186 + * path of the launcher for this install, such as the one the desktop app
187 + * installs. `args` are quoted for the host's shell: POSIX, or PowerShell on
188 + * Windows.
189 */
172 -const resolveHostCliCommand = (subcommand: string) =>
190 +export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>
191 Effect.gen(function* () {
192 + const platform = yield* HostProcess.Platform;
193 + const withArgs = (prefix: string) =>
194 + [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
195 const command = yield* resolveCliCommand(subcommand);
175 - if (command !== `t3 ${subcommand}`) return { command, launcher: false };
176 - if (yield* isCommandAvailable("t3")) return { command, launcher: false };
196 + if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
197 + if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };
198 const launcher = yield* resolveInstallLauncher;
178 - return Option.isSome(launcher)
179 - ? { command: `${shellWord(launcher.value)} ${subcommand}`, launcher: true }
180 - : { command, launcher: false };
199 + if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
200 + // PowerShell runs a quoted path only through the call operator.
201 + const quoted = hostShellWord(platform, launcher.value);
202 + const call = platform === "win32" ? `& ${quoted}` : quoted;
203 + return { command: withArgs(`${call} ${subcommand}`), launcher: true };
204 });
205
206 /**
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -229,6 +229,7 @@ export const make = Effect.gen(function* () {
229 threadAutoSettlement: true,
230 storageCleanup: true,
231 storageCleanupRun: true,
232 + databaseStorage: true,
233 otlpEndpointCheck: true,
234 projectWorktreeCleanup: true,
235 settledWorktreeCleanup: true,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -57,6 +57,7 @@ const RPC_AGGREGATES = {
57 [WS_METHODS.serverRemoveKeybinding]: "server",
58 [WS_METHODS.serverRunStorageCleanup]: "server",
59 [WS_METHODS.serverGetStorageCleanupReport]: "server",
60 + [WS_METHODS.serverGetDatabaseStorage]: "server",
61 [WS_METHODS.serverGetSettings]: "server",
62 [WS_METHODS.serverUpdateSettings]: "server",
63 [WS_METHODS.serverSearchAcpRegistry]: "server",
apps/server/src/persistence/DatabaseStorage.test.ts
+71 -4
@@ -1,8 +1,15 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 +import * as Option from "effect/Option";
7 +import * as Path from "effect/Path";
8 +import * as Stream from "effect/Stream";
9 +import * as TestClock from "effect/testing/TestClock";
10 import * as SqlClient from "effect/sql/SqlClient";
11
12 +import * as ServerConfig from "../config.ts";
13 import * as EventStore from "../orchestration-v2/EventStore.ts";
14 import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
15 import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
@@ -17,6 +24,23 @@ const freePages = Effect.map(
24 (rows) => rows[0]?.freelist_count ?? 0,
25 );
26
27 +const storageLayer = <E>(
28 + config: Layer.Layer<ServerConfig.ServerConfig, E, FileSystem.FileSystem | Path.Path>,
29 +) =>
30 + DatabaseStorage.layer.pipe(
31 + Layer.provide(ProjectionMaintenance.layer),
32 + Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
33 + Layer.provideMerge(Sqlite.layerMemory),
34 + Layer.provideMerge(config),
35 + Layer.provide(NodeServices.layer),
36 + );
37 +
38 +const testConfig = ServerConfig.layerTest(process.cwd(), { prefix: "database-storage-" });
39 +
40 +const currentStatus = Effect.flatMap(DatabaseStorage.DatabaseStorage, (storage) =>
41 + storage.status.pipe(Stream.take(1), Stream.runHead),
42 +);
43 +
44 it.effect("a new database returns freed pages online without losing data", () =>
45 Effect.gen(function* () {
46 const sql = yield* SqlClient.SqlClient;
@@ -31,12 +55,55 @@ it.effect("a new database returns freed pages online without losing data", () =>
55 yield* storage.reclaim;
56 assert.equal(yield* freePages, 0);
57 assert.deepEqual(yield* sql`SELECT value FROM retained`, [{ value: "keep" }]);
58 + }).pipe(Effect.provide(storageLayer(testConfig))),
59 +);
60 +
61 +it.effect("publishes file accounting and the doctor command after each pass", () =>
62 + Effect.gen(function* () {
63 + const sql = yield* SqlClient.SqlClient;
64 + const config = yield* ServerConfig.ServerConfig;
65 + yield* sql`CREATE TABLE discarded (value BLOB)`;
66 + yield* sql`INSERT INTO discarded VALUES (zeroblob(1048576))`;
67 + yield* TestClock.adjust("1 minute");
68 + const before = (yield* currentStatus).pipe(Option.getOrThrow);
69 + assert.isNotNull(before);
70 + assert.isAbove(before!.databaseBytes, 1048576);
71 + assert.isTrue(before!.incrementalVacuumEnabled);
72 + // Quoting follows the host shell, so check each word on its own.
73 + assert.include(before!.compactCommand, "doctor");
74 + assert.include(before!.compactCommand, "--base-dir");
75 + assert.include(before!.compactCommand, config.baseDir);
76 +
77 + // The next reclaim pass frees the dropped table and republishes.
78 + yield* sql`DROP TABLE discarded`;
79 + yield* TestClock.adjust("1 minute");
80 + const storage = yield* DatabaseStorage.DatabaseStorage;
81 + const after = yield* storage.status.pipe(
82 + Stream.filter((status) => status !== null && status.databaseBytes < before!.databaseBytes),
83 + Stream.runHead,
84 + Effect.map(Option.getOrThrow),
85 + );
86 + assert.isAtMost(after!.databaseBytes, before!.databaseBytes - 1048576);
87 + assert.equal(after!.reclaimableBytes, 0);
88 + }).pipe(Effect.provide(storageLayer(testConfig))),
89 +);
90 +
91 +it.effect("publishes nothing when doctor would repair a different database", () =>
92 + Effect.gen(function* () {
93 + yield* TestClock.adjust("1 minute");
94 + assert.deepEqual(yield* currentStatus, Option.some(null));
95 }).pipe(
96 Effect.provide(
36 - DatabaseStorage.layer.pipe(
37 - Layer.provide(ProjectionMaintenance.layer),
38 - Layer.provide(Layer.merge(EventStore.layer, ProjectionStore.layer)),
39 - Layer.provideMerge(Sqlite.layerMemory),
97 + storageLayer(
98 + // A dev server without an explicit home keeps state in <baseDir>/dev,
99 + // while `doctor --base-dir` targets <baseDir>/userdata.
100 + Layer.effect(
101 + ServerConfig.ServerConfig,
102 + Effect.gen(function* () {
103 + const config = yield* ServerConfig.ServerConfig;
104 + return { ...config, dbPath: `${config.baseDir}/dev/statev2.sqlite` };
105 + }),
106 + ).pipe(Layer.provide(testConfig)),
107 ),
108 ),
109 ),
apps/server/src/persistence/DatabaseStorage.ts
+54 -4
@@ -1,9 +1,16 @@
1 +import type { DatabaseStorageStatus } from "@t3tools/contracts";
2 import * as Context from "effect/Context";
3 import * as Effect from "effect/Effect";
4 +import * as Equal from "effect/Equal";
5 import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 import * as Schedule from "effect/Schedule";
8 +import * as Stream from "effect/Stream";
9 +import * as SubscriptionRef from "effect/SubscriptionRef";
10 import * as SqlClient from "effect/sql/SqlClient";
11
12 +import { resolveHostCliCommand } from "../cli/invocation.ts";
13 +import * as ServerConfig from "../config.ts";
14 import * as ProjectionMaintenance from "../orchestration-v2/ProjectionMaintenance.ts";
15 import { forkParked } from "../serverActivation.ts";
16
@@ -15,6 +22,8 @@ export class DatabaseStorage extends Context.Service<
22 {
23 /** Return free pages to the filesystem on databases with incremental auto_vacuum. */
24 readonly reclaim: Effect.Effect<void>;
25 + /** Current file accounting, re-published after each maintenance pass. Null until first read. */
26 + readonly status: Stream.Stream<DatabaseStorageStatus | null>;
27 }
28 >()("t3/persistence/DatabaseStorage") {}
29
@@ -27,6 +36,42 @@ export class DatabaseStorage extends Context.Service<
36 const make = Effect.gen(function* () {
37 const sql = yield* SqlClient.SqlClient;
38 const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
39 + const config = yield* ServerConfig.ServerConfig;
40 + const path = yield* Path.Path;
41 + const statusRef = yield* SubscriptionRef.make<DatabaseStorageStatus | null>(null);
42 +
43 + // The notice shows this verbatim; quote for the host's shell. Desktop
44 + // installs have no `t3` on PATH, so the command names their launcher.
45 + const { command: compactCommand } = yield* resolveHostCliCommand("doctor", [
46 + "--base-dir",
47 + config.baseDir,
48 + ]);
49 + // `t3 doctor --base-dir` repairs <baseDir>/userdata. A dev server without
50 + // an explicit home keeps its state in <baseDir>/dev instead, so there the
51 + // command would target the live install; publish no status at all.
52 + const doctorTargetsThisDatabase =
53 + path.resolve(config.dbPath) ===
54 + path.resolve(config.baseDir, "userdata", path.basename(config.dbPath));
55 + const publishStatus = Effect.gen(function* () {
56 + if (!doctorTargetsThisDatabase) return;
57 + const pages = yield* sql<{ readonly page_count: number }>`PRAGMA page_count`;
58 + const free = yield* sql<{ readonly freelist_count: number }>`PRAGMA freelist_count`;
59 + const size = yield* sql<{ readonly page_size: number }>`PRAGMA page_size`;
60 + const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
61 + const pageSize = size[0]?.page_size ?? 0;
62 + const next: DatabaseStorageStatus = {
63 + databaseBytes: (pages[0]?.page_count ?? 0) * pageSize,
64 + reclaimableBytes: (free[0]?.freelist_count ?? 0) * pageSize,
65 + incrementalVacuumEnabled: mode[0]?.auto_vacuum === 2,
66 + compactCommand,
67 + };
68 + // Every set reaches each open Storage page; most passes change nothing.
69 + if (!Equal.equals(yield* SubscriptionRef.get(statusRef), next)) {
70 + yield* SubscriptionRef.set(statusRef, next);
71 + }
72 + }).pipe(
73 + Effect.catch((cause) => Effect.logWarning("Database storage inspection failed", { cause })),
74 + );
75
76 const reclaim = Effect.gen(function* () {
77 const mode = yield* sql<{ readonly auto_vacuum: number }>`PRAGMA auto_vacuum`;
@@ -57,16 +102,21 @@ const make = Effect.gen(function* () {
102
103 yield* forkParked(
104 Effect.sleep("1 minute").pipe(
60 - Effect.andThen(compact.pipe(Effect.repeat(Schedule.spaced("6 hours")))),
105 + Effect.andThen(
106 + compact.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("6 hours"))),
107 + ),
108 ),
109 );
110 yield* forkParked(
64 - Effect.sleep("1 minute").pipe(
65 - Effect.andThen(reclaim.pipe(Effect.repeat(Schedule.spaced("1 minute")))),
111 + publishStatus.pipe(
112 + Effect.andThen(Effect.sleep("1 minute")),
113 + Effect.andThen(
114 + reclaim.pipe(Effect.andThen(publishStatus), Effect.repeat(Schedule.spaced("1 minute"))),
115 + ),
116 ),
117 );
118
69 - return DatabaseStorage.of({ reclaim });
119 + return DatabaseStorage.of({ reclaim, status: SubscriptionRef.changes(statusRef) });
120 });
121
122 export const layer = Layer.effect(DatabaseStorage, make);
apps/server/src/ws.ts
+3
@@ -176,6 +176,7 @@ import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
176 import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
177 import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
178 import * as ServerSettings from "./serverSettings.ts";
179 +import * as DatabaseStorage from "./persistence/DatabaseStorage.ts";
180 import * as StorageCleanup from "./storageCleanup.ts";
181 import * as TerminalManager from "./terminal/Manager.ts";
182 import { withTerminalOutputWindow } from "./terminal/OutputProtocol.ts";
@@ -1299,6 +1300,7 @@ const layerWsRpc = (
1300 const config = yield* ServerConfig.ServerConfig;
1301 const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
1302 const storageCleanup = yield* StorageCleanup.StorageCleanup;
1303 + const databaseStorage = yield* DatabaseStorage.DatabaseStorage;
1304 const serverSettings = yield* ServerSettings.ServerSettingsService;
1305 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
1306 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
@@ -2414,6 +2416,7 @@ const layerWsRpc = (
2416 }),
2417 [WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,
2418 [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,
2419 + [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,
2420 [WS_METHODS.serverGetSettings]: (_input) =>
2421 serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),
2422 [WS_METHODS.serverUpdateSettings]: ({ patch, providerInstanceMutation }) =>
apps/web/src/components/settings/DatabaseStorageNotice.tsx new
+60
@@ -0,0 +1,60 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { shouldRecommendDatabaseCompaction, type EnvironmentId } from "@t3tools/contracts";
3 +import * as Schema from "effect/Schema";
4 +
5 +import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
6 +import { useLocalStorage } from "../../hooks/useLocalStorage";
7 +import { serverEnvironment } from "../../state/server";
8 +import { Button } from "../ui/button";
9 +import { SettingsGroup } from "./SettingsGroup";
10 +import { SettingsRow, SettingsSection } from "./settingsLayout";
11 +
12 +/** Suggests `t3 doctor` for a database that still holds at least 1 GiB of freed pages. */
13 +export function DatabaseStorageNotice({
14 + environmentId,
15 + label,
16 +}: {
17 + environmentId: EnvironmentId;
18 + label: string;
19 +}) {
20 + const result = useAtomValue(serverEnvironment.databaseStorage({ environmentId, input: {} }));
21 + const [dismissed, setDismissed] = useLocalStorage(
22 + `database-storage-notice-dismissed:${environmentId}`,
23 + false,
24 + Schema.Boolean,
25 + );
26 + const { copyToClipboard } = useCopyToClipboard({ target: "command" });
27 + const status = result._tag === "Success" ? result.value : null;
28 + if (dismissed || status === null || !shouldRecommendDatabaseCompaction(status)) return null;
29 + return (
30 + <SettingsSection id={`storage-database-${environmentId}`} title="Database">
31 + <SettingsGroup>
32 + <SettingsRow
33 + title={`Reclaim ${(status.reclaimableBytes / 1024 ** 3).toFixed(1)} GiB on ${label}`}
34 + description={
35 + <>
36 + Old history is cleaned up automatically, but this database still holds the freed
37 + space. Run the command on {label} to return it to disk; it pauses and restarts the
38 + background service. Quit the desktop app first if it hosts this environment.
39 + <code className="mt-2 block select-text break-all">{status.compactCommand}</code>
40 + </>
41 + }
42 + control={
43 + <div className="flex flex-wrap items-center gap-1.5">
44 + <Button
45 + variant="outline"
46 + size="sm"
47 + onClick={() => copyToClipboard(status.compactCommand, undefined)}
48 + >
49 + Copy command
50 + </Button>
51 + <Button variant="ghost" size="sm" onClick={() => setDismissed(true)}>
52 + Dismiss
53 + </Button>
54 + </div>
55 + }
56 + />
57 + </SettingsGroup>
58 + </SettingsSection>
59 + );
60 +}
apps/web/src/components/settings/StorageSettings.tsx
+14
@@ -35,6 +35,7 @@ import {
35 SettingsSection,
36 useRelativeTimeTick,
37 } from "./settingsLayout";
38 +import { DatabaseStorageNotice } from "./DatabaseStorageNotice";
39 import { SettingsScopeNotice } from "./SettingsScopeNotice";
40 import { FoldedSettingsSection } from "./FoldedSettingsSection";
41 import { SettingsGroup } from "./SettingsGroup";
@@ -483,6 +484,19 @@ export function StorageSettingsPanel() {
484
485 return (
486 <SettingsPageContainer>
487 + {!isProjectScope &&
488 + connectedEnvironments
489 + .filter(
490 + (environment) =>
491 + environment.serverConfig?.environment.capabilities.databaseStorage === true,
492 + )
493 + .map((environment) => (
494 + <DatabaseStorageNotice
495 + key={environment.environmentId}
496 + environmentId={environment.environmentId}
497 + label={environment.label}
498 + />
499 + ))}
500 <SettingsSection id="storage-worktrees" title="Worktrees">
501 {!isProjectScope && <WorktreesDirectoryRow />}
502 {isProjectScope && (
packages/client-runtime/src/rpc/client.ts
+1
@@ -59,6 +59,7 @@ export type EnvironmentSubscriptionRpcTag =
59 | typeof WS_METHODS.subscribeServerLifecycle
60 | typeof WS_METHODS.scheduledTasksSubscribe
61 | typeof WS_METHODS.serverGetStorageCleanupReport
62 + | typeof WS_METHODS.serverGetDatabaseStorage
63 | typeof WS_METHODS.subscribeTerminalEvents
64 | typeof WS_METHODS.subscribeTerminalMetadata
65 | typeof WS_METHODS.subscribePreviewEvents
packages/client-runtime/src/state/server.ts
+5
@@ -1000,6 +1000,11 @@ export function createServerEnvironmentAtoms<R, E>(
1000 tag: WS_METHODS.serverRunStorageCleanup,
1001 concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId },
1002 }),
1003 + databaseStorage: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1004 + label: "environment-data:server:database-storage",
1005 + tag: WS_METHODS.serverGetDatabaseStorage,
1006 + idleTtlMs: 0,
1007 + }),
1008 storageCleanupReport: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1009 label: "environment-data:server:storage-cleanup-report",
1010 tag: WS_METHODS.serverGetStorageCleanupReport,
packages/contracts/src/environment.ts
+2
@@ -126,6 +126,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
126 threadAutoSettlement: Schema.optionalKey(Schema.Boolean),
127 storageCleanup: Schema.optionalKey(Schema.Boolean),
128 storageCleanupRun: Schema.optionalKey(Schema.Boolean),
129 + /** Server streams database size and reclaimable space for the Storage settings notice. */
130 + databaseStorage: Schema.optionalKey(Schema.Boolean),
131 /** Server checks OTLP endpoints for the telemetry export settings. */
132 otlpEndpointCheck: Schema.optionalKey(Schema.Boolean),
133 projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/rpc.ts
+10
@@ -326,6 +326,7 @@ import {
326 import { UsagePricing, UsageReadError, UsageSummary, UsageSummaryInput } from "./usage.ts";
327 import {
328 StorageCleanupReport,
329 + DatabaseStorageStatus,
330 ServerSettings,
331 ServerSettingsError,
332 ServerSettingsPatch,
@@ -483,6 +484,7 @@ export const WS_METHODS = {
484 serverRemoveKeybinding: "server.removeKeybinding",
485 serverRunStorageCleanup: "server.runStorageCleanup",
486 serverGetStorageCleanupReport: "server.getStorageCleanupReport",
487 + serverGetDatabaseStorage: "server.getDatabaseStorage",
488 serverGetSettings: "server.getSettings",
489 serverUpdateSettings: "server.updateSettings",
490 serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -761,6 +763,13 @@ const WsServerGetStorageCleanupReportRpc = Rpc.make(WS_METHODS.serverGetStorageC
763 error: EnvironmentAuthorizationError,
764 });
765
766 +const WsServerGetDatabaseStorageRpc = Rpc.make(WS_METHODS.serverGetDatabaseStorage, {
767 + payload: Schema.Struct({}),
768 + success: Schema.NullOr(DatabaseStorageStatus),
769 + stream: true,
770 + error: EnvironmentAuthorizationError,
771 +});
772 +
773 const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
774 payload: Schema.Struct({}),
775 success: ServerSettings,
@@ -1902,6 +1911,7 @@ export const WsRpcGroup = RpcGroup.make(
1911 WsServerRemoveKeybindingRpc,
1912 WsServerRunStorageCleanupRpc,
1913 WsServerGetStorageCleanupReportRpc,
1914 + WsServerGetDatabaseStorageRpc,
1915 WsServerGetSettingsRpc,
1916 WsServerUpdateSettingsRpc,
1917 WsServerDiscoverSourceControlRpc,
packages/contracts/src/settings.ts
+20
@@ -1077,6 +1077,26 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet<ProjectScopedServerSettin
1077 /** Reclaimable bytes from which the offline `t3 doctor` repair is worth suggesting. */
1078 export const DATABASE_COMPACTION_RECOMMENDED_BYTES = 1024 ** 3;
1079
1080 +/** Live SQLite file accounting for the environment's state database. */
1081 +export const DatabaseStorageStatus = Schema.Struct({
1082 + databaseBytes: Schema.Number,
1083 + /** Free pages inside the file that an offline VACUUM (or incremental auto_vacuum) returns to disk. */
1084 + reclaimableBytes: Schema.Number,
1085 + /** False on databases created before incremental auto_vacuum; `t3 doctor` converts them. */
1086 + incrementalVacuumEnabled: Schema.Boolean,
1087 + /** Command to run on the host to reclaim the space offline. */
1088 + compactCommand: Schema.String,
1089 +});
1090 +export type DatabaseStorageStatus = typeof DatabaseStorageStatus.Type;
1091 +
1092 +/** Only suggest the offline conversion when it can reclaim enough to matter. */
1093 +export function shouldRecommendDatabaseCompaction(status: DatabaseStorageStatus): boolean {
1094 + return (
1095 + !status.incrementalVacuumEnabled &&
1096 + status.reclaimableBytes >= DATABASE_COMPACTION_RECOMMENDED_BYTES
1097 + );
1098 +}
1099 +
1100 export const StorageCleanupReportEntry = Schema.Struct({
1101 kind: Schema.Literals(["worktree", "browser-artifacts", "logs"]),
1102 outcome: Schema.Literals(["removed", "kept", "failed"]),