From dc5ed3f134a3eee7065493e62928f23c96d70c8e Mon Sep 17 00:00:00 2001
From: TB516 <77514919+TB516@users.noreply.github.com>
Date: Tue, 10 Nov 2026 17:06:31 +0000
Subject: [PATCH 1/4] chore(flatpak): update T3 Code to v0.1.8
---
flatpak/com.t3tools.t3code.metainfo.xml | 4 ++++
flatpak/modules/t3code.yml | 4 ++--
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/flatpak/com.t3tools.t3code.metainfo.xml b/flatpak/com.t3tools.t3code.metainfo.xml
index b14ebef..c7f7a49 100644
--- a/flatpak/com.t3tools.t3code.metainfo.xml
+++ b/flatpak/com.t3tools.t3code.metainfo.xml
@@ -19,6 +19,10 @@
com.t3tools.t3code.desktophttps://t3.codes
+
+ https://github.com/pingdotgg/t3code/releases/tag/v0.1.8
+
+ https://github.com/pingdotgg/t3code/releases/tag/v0.1.7
diff --git a/flatpak/modules/t3code.yml b/flatpak/modules/t3code.yml
index 9ea55dd..a340d70 100644
--- a/flatpak/modules/t3code.yml
+++ b/flatpak/modules/t3code.yml
@@ -59,8 +59,8 @@ test-commands:
sources:
- type: git
url: https://github.com/pingdotgg/t3code.git
- tag: v0.1.7
- commit: 322f6544dfad0a3c8a0c8cbecf2c7f7874b14268
+ tag: v0.1.8
+ commit: bf469bb19669671d0df2efda74ed73867a7137c0
x-checker-data:
type: json
url: https://api.github.com/repos/pingdotgg/t3code/releases/latest
From fd3bd5dda6f9117edfa61056d5eca4e6bdc76fb8 Mon Sep 17 00:00:00 2001
From: Thomas
Date: Wed, 11 Nov 2026 00:54:00 -0500
Subject: [PATCH 2/4] chore(flatpak): refresh patches for T3 Code v0.1.8
Use upstream's Reclaim button and keep only deleting the database from
before 0.1.0 in Settings. Keep the t3 command off the host, find host
browser profiles for browser import, and follow upstream's new lint rules.
---
docs/building.md | 4 +-
flatpak/com.t3tools.t3code.metainfo.xml | 7 +-
flatpak/modules/t3code.yml | 3 +-
flatpak/package/host-server.sh | 7 -
.../0001-flatpak-desktop-integration.patch | 64 +-
patches/0002-flatpak-host-backend.patch | 17 +-
patches/0003-flatpak-host-environment.patch | 13 +-
.../0006-flatpak-document-portal-paths.patch | 45 +-
patches/0008-flatpak-cli-launcher.patch | 55 +-
patches/0009-flatpak-server-updates.patch | 6 +-
.../0010-flatpak-browser-requirements.patch | 4 +-
.../0011-flatpak-database-maintenance.patch | 935 ------------------
patches/0011-flatpak-legacy-database.patch | 269 +++++
patches/0012-flatpak-update-channel.patch | 12 +-
patches/0014-flatpak-managed-policy.patch | 2 +-
patches/0015-flatpak-browser-import.patch | 58 ++
.../fixtures/sandbox-database-maintenance.sh | 15 -
tests/packaged/packaged.test.ts | 24 +-
18 files changed, 472 insertions(+), 1068 deletions(-)
delete mode 100644 patches/0011-flatpak-database-maintenance.patch
create mode 100644 patches/0011-flatpak-legacy-database.patch
create mode 100644 patches/0015-flatpak-browser-import.patch
delete mode 100644 tests/packaged/fixtures/sandbox-database-maintenance.sh
diff --git a/docs/building.md b/docs/building.md
index 1e4a02a..9250eb5 100644
--- a/docs/building.md
+++ b/docs/building.md
@@ -30,8 +30,8 @@ Build state and output stay in `build-flatpak/`.
The packaged app checks install a build in a throwaway container, launch it
headless, and check the places where the sandbox and host meet: the host
server, agent CLIs found through the login shell, downloads, terminals,
-editors, SSH, Tailscale, managed policy, database maintenance, and the recovery
-screen when the host is out of reach. Docker runs them by default; set
+editors, SSH, Tailscale, managed policy, deleting the old database, and the
+recovery screen when the host is out of reach. Docker runs them by default; set
`CONTAINER_ENGINE=podman` to use Podman.
```sh
diff --git a/flatpak/com.t3tools.t3code.metainfo.xml b/flatpak/com.t3tools.t3code.metainfo.xml
index c7f7a49..76a6ca3 100644
--- a/flatpak/com.t3tools.t3code.metainfo.xml
+++ b/flatpak/com.t3tools.t3code.metainfo.xml
@@ -21,7 +21,12 @@
https://github.com/pingdotgg/t3code/releases/tag/v0.1.8
-
+
+
Update to T3 Code 0.1.8.
+
Reclaiming database space now uses T3 Code's own Reclaim button in
+ Settings. Settings still offers to delete the database kept from before
+ 0.1.0. Browser import keeps finding your browsers' profiles.
+ https://github.com/pingdotgg/t3code/releases/tag/v0.1.7
diff --git a/flatpak/modules/t3code.yml b/flatpak/modules/t3code.yml
index a340d70..03a04a9 100644
--- a/flatpak/modules/t3code.yml
+++ b/flatpak/modules/t3code.yml
@@ -79,10 +79,11 @@ sources:
- ../../patches/0008-flatpak-cli-launcher.patch
- ../../patches/0009-flatpak-server-updates.patch
- ../../patches/0010-flatpak-browser-requirements.patch
- - ../../patches/0011-flatpak-database-maintenance.patch
+ - ../../patches/0011-flatpak-legacy-database.patch
- ../../patches/0012-flatpak-update-channel.patch
- ../../patches/0013-flatpak-startup-recovery.patch
- ../../patches/0014-flatpak-managed-policy.patch
+ - ../../patches/0015-flatpak-browser-import.patch
use-git: true
- type: dir
path: ../package
diff --git a/flatpak/package/host-server.sh b/flatpak/package/host-server.sh
index 256320e..5db3533 100755
--- a/flatpak/package/host-server.sh
+++ b/flatpak/package/host-server.sh
@@ -12,11 +12,4 @@ unset T3CODE_DESKTOP_HTTPS_ENDPOINTS T3CODE_TAILSCALE_SERVE T3CODE_TAILSCALE_SER
cd "$HOME"
export ELECTRON_RUN_AS_NODE=1
-# Desktop maintenance runs with the same runtime and sanitized host environment.
-# The desktop stops its server first when compacting. No user-facing CLI is installed.
-if [ "${1:-}" = "--database-maintenance" ]; then
- shift
- exec "$T3CODE_FLATPAK_SERVER" --require "$T3CODE_FLATPAK_COMPILE_CACHE" "$T3CODE_FLATPAK_ENTRY" flatpak-database-maintenance --base-dir "$T3CODE_HOME" "$@"
-fi
-
exec "$T3CODE_FLATPAK_SERVER" --require "$T3CODE_FLATPAK_COMPILE_CACHE" "$T3CODE_FLATPAK_ENTRY" --bootstrap-fd 3
diff --git a/patches/0001-flatpak-desktop-integration.patch b/patches/0001-flatpak-desktop-integration.patch
index f894629..4acf311 100644
--- a/patches/0001-flatpak-desktop-integration.patch
+++ b/patches/0001-flatpak-desktop-integration.patch
@@ -1,5 +1,5 @@
diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts
-index 11f975a6b8..586db466b6 100644
+index ef2909045b..98a7852535 100644
--- a/apps/desktop/src/app/DesktopConfig.ts
+++ b/apps/desktop/src/app/DesktopConfig.ts
@@ -37,6 +37,7 @@ export const DesktopConfig = Config.all({
@@ -137,10 +137,10 @@ index cfa8498ae6..4626a2601c 100644
}
yield* writeDesktopEntry;
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
-index f2b176ee37..0baac17608 100644
+index 22bfc969c4..da1d29ea71 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
-@@ -60,6 +60,23 @@ vi.mock("node:child_process", () => ({
+@@ -61,6 +61,24 @@ import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
@@ -155,6 +155,7 @@ index f2b176ee37..0baac17608 100644
+ Effect.provide(
+ DesktopPreReadyPlatform.layer.pipe(
+ Layer.provide(Layer.succeed(HostProcess.Platform, "linux")),
++ Layer.provide(DesktopConfig.layerTest({ FLATPAK_ID: "com.t3tools.t3code" })),
+ ),
+ ),
+ Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())),
@@ -165,25 +166,26 @@ index f2b176ee37..0baac17608 100644
appendSwitchMock.mockReset();
getSwitchValueMock.mockReset();
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
-index d77544f54b..cbf87853eb 100644
+index ff8c97b8f8..7214f0d672 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts
-@@ -9,6 +9,7 @@ import * as Layer from "effect/Layer";
- import * as Electron from "electron";
- import * as HostProcess from "@t3tools/shared/HostProcess";
+@@ -56,6 +56,7 @@ const LinuxDesktopEntryConfig = Config.all({
+ xdgDataHome: trimmedString("XDG_DATA_HOME"),
+ launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"),
+ appImagePath: trimmedString("APPIMAGE"),
++ flatpakId: trimmedString("FLATPAK_ID"),
+ });
-+import { flatpakAppId } from "./Flatpak.ts";
- import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
- import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts";
- import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts";
-@@ -75,50 +76,52 @@ export const make = Effect.gen(function* () {
+ /** @public */
+@@ -85,54 +86,56 @@ export const make = Effect.gen(function* () {
});
// The portal also requires a valid desktop entry. An AppImage update may
// have removed the executable referenced by the previous launch's entry.
- try {
- const applicationsDir = NodePath.posix.join(
-- process.env.XDG_DATA_HOME?.trim() ||
+- Option.getOrElse(linuxDesktopEntryConfig.xdgDataHome, () =>
- NodePath.posix.join(homeDirectory, ".local", "share"),
+- ),
- "applications",
- );
- NodeFS.mkdirSync(applicationsDir, { recursive: true });
@@ -215,20 +217,16 @@ index d77544f54b..cbf87853eb 100644
- appVersion: Electron.app.getVersion(),
- }).displayName,
- execTarget:
-- process.env.T3CODE_DESKTOP_LAUNCHER_PATH?.trim() ||
-- process.env.APPIMAGE?.trim() ||
-- process.execPath,
-- scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
-- ...(iconPath === undefined ? {} : { iconPath }),
-- }),
-- "utf8",
-- );
-- } catch {}
-+ if (flatpakAppId(process.env, platform) === null) {
+- Option.getOrUndefined(
+- Option.orElse(
+- linuxDesktopEntryConfig.launcherPath,
+- () => linuxDesktopEntryConfig.appImagePath,
++ if (Option.isNone(linuxDesktopEntryConfig.flatpakId)) {
+ try {
+ const applicationsDir = NodePath.posix.join(
-+ process.env.XDG_DATA_HOME?.trim() ||
++ Option.getOrElse(linuxDesktopEntryConfig.xdgDataHome, () =>
+ NodePath.posix.join(homeDirectory, ".local", "share"),
++ ),
+ "applications",
+ );
+ NodeFS.mkdirSync(applicationsDir, { recursive: true });
@@ -247,7 +245,14 @@ index d77544f54b..cbf87853eb 100644
+ NodePath.posix.join(
+ Electron.app.getAppPath(),
+ "apps/desktop/prod-resources/icon.png",
-+ ),
+ ),
+- ) ?? process.execPath,
+- scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
+- ...(iconPath === undefined ? {} : { iconPath }),
+- }),
+- "utf8",
+- );
+- } catch {}
+ iconPath,
+ );
+ } catch {}
@@ -260,9 +265,12 @@ index d77544f54b..cbf87853eb 100644
+ appVersion: Electron.app.getVersion(),
+ }).displayName,
+ execTarget:
-+ process.env.T3CODE_DESKTOP_LAUNCHER_PATH?.trim() ||
-+ process.env.APPIMAGE?.trim() ||
-+ process.execPath,
++ Option.getOrUndefined(
++ Option.orElse(
++ linuxDesktopEntryConfig.launcherPath,
++ () => linuxDesktopEntryConfig.appImagePath,
++ ),
++ ) ?? process.execPath,
+ scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment),
+ ...(iconPath === undefined ? {} : { iconPath }),
+ }),
diff --git a/patches/0002-flatpak-host-backend.patch b/patches/0002-flatpak-host-backend.patch
index a43b207..01f1775 100644
--- a/patches/0002-flatpak-host-backend.patch
+++ b/patches/0002-flatpak-host-backend.patch
@@ -1,5 +1,5 @@
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
-index 69a70b68a4..bcf48615be 100644
+index abadf58f3f..c1d7300493 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts
@@ -1,5 +1,8 @@
@@ -10,8 +10,8 @@ index 69a70b68a4..bcf48615be 100644
+
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
- import * as Clock from "effect/Clock";
-@@ -518,7 +521,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
+ import * as HostProcess from "@t3tools/shared/HostProcess";
+@@ -520,7 +523,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
...buildObservabilityFragment(input.observabilitySettings),
};
@@ -20,17 +20,14 @@ index 69a70b68a4..bcf48615be 100644
executablePath: process.execPath,
// Packaged builds have a separate cache; --require prevents cache settings leaking to provider subprocesses.
args: [
-@@ -542,6 +545,15 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
+@@ -544,6 +547,12 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv
captureOutput: true,
preflightFailure: Option.none(),
} satisfies DesktopBackendManager.DesktopBackendStartConfig;
+
-+ if (flatpakAppId(process.env, environment.platform) !== null) {
-+ return flatpakBackendConfig(
-+ config,
-+ process.env.T3CODE_FLATPAK_RUNTIME,
-+ process.env.T3CODE_FLATPAK_HOST_PATH,
-+ );
++ const env = yield* HostProcess.Environment;
++ if (flatpakAppId(env, environment.platform) !== null) {
++ return flatpakBackendConfig(config, env.T3CODE_FLATPAK_RUNTIME, env.T3CODE_FLATPAK_HOST_PATH);
+ }
+ return config;
},
diff --git a/patches/0003-flatpak-host-environment.patch b/patches/0003-flatpak-host-environment.patch
index b9c007b..76156d0 100644
--- a/patches/0003-flatpak-host-environment.patch
+++ b/patches/0003-flatpak-host-environment.patch
@@ -1,5 +1,5 @@
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
-index 124dbbeae8..e85dfc7552 100644
+index 0c78691943..b68be05c8d 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts
@@ -163,6 +163,34 @@ function runShellEnvironment(input: {
@@ -38,10 +38,10 @@ index 124dbbeae8..e85dfc7552 100644
Effect.gen(function* () {
const started = yield* Deferred.make();
diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts
-index 37826f8ee5..212ce6d148 100644
+index 9d9e390c95..0f4e738aba 100644
--- a/apps/desktop/src/shell/DesktopShellEnvironment.ts
+++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts
-@@ -22,6 +22,7 @@ import * as Stream from "effect/Stream";
+@@ -23,6 +23,7 @@ import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -49,7 +49,7 @@ index 37826f8ee5..212ce6d148 100644
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
type EnvironmentPatch = Record;
-@@ -563,6 +564,14 @@ const CACHED_ENV_NAMES = [
+@@ -580,6 +581,15 @@ const CACHED_ENV_NAMES = [
/** @public */
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
@@ -58,6 +58,7 @@ index 37826f8ee5..212ce6d148 100644
+ return DesktopShellEnvironment.of({
+ installIntoProcess: Effect.succeed(false),
+ awaitDiscovery: Effect.succeed(false),
++ awaitUserShellDiscovery: Effect.succeed(false),
+ updates: Stream.empty,
+ });
+ }
@@ -104,7 +105,7 @@ index 3b45d80bbc..cc2cc4c537 100644
Effect.gen(function* () {
const linuxState = (packageType: string | undefined) =>
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
-index 6279e8b614..637b0bc113 100644
+index 14688e5258..81ee76338d 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -1,3 +1,4 @@
@@ -112,7 +113,7 @@ index 6279e8b614..637b0bc113 100644
import {
DESKTOP_UPDATE_RESTART_MARKER_FILE,
DesktopUpdateChannelSchema,
-@@ -338,6 +339,9 @@ function getAutoUpdateDisabledReason(args: {
+@@ -339,6 +340,9 @@ function getAutoUpdateDisabledReason(args: {
disabledByEnv: boolean;
hasUpdateFeedConfig: boolean;
}): string | null {
diff --git a/patches/0006-flatpak-document-portal-paths.patch b/patches/0006-flatpak-document-portal-paths.patch
index 5000381..cb39b66 100644
--- a/patches/0006-flatpak-document-portal-paths.patch
+++ b/patches/0006-flatpak-document-portal-paths.patch
@@ -99,7 +99,7 @@ index 0000000000..8ae86ba2fa
+ );
+});
diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.ts
-index 4f9ab12edd..30db8e3217 100644
+index 4f9ab12edd..058975103d 100644
--- a/apps/desktop/src/electron/ElectronDialog.ts
+++ b/apps/desktop/src/electron/ElectronDialog.ts
@@ -1,3 +1,7 @@
@@ -110,7 +110,7 @@ index 4f9ab12edd..30db8e3217 100644
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
-@@ -6,6 +10,49 @@ import * as Schema from "effect/Schema";
+@@ -6,6 +10,64 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
@@ -156,11 +156,26 @@ index 4f9ab12edd..30db8e3217 100644
+ }
+ return origin;
+}
++
++export class ElectronDialogResolveHostPathError extends Schema.TaggedError()(
++ "ElectronDialogResolveHostPathError",
++ { path: Schema.String, cause: Schema.Defect() },
++) {
++ override get message(): string {
++ return `Failed to resolve ${this.path} to a host path.`;
++ }
++}
++
++export const tryResolveHostPath = (path: string) =>
++ Effect.try({
++ try: () => resolveHostPath(path),
++ catch: (cause) => new ElectronDialogResolveHostPathError({ path, cause }),
++ });
+
export class ElectronDialogPickFolderError extends Schema.TaggedError()(
"ElectronDialogPickFolderError",
{
-@@ -138,7 +185,20 @@ export const make = ElectronDialog.of({
+@@ -138,7 +200,20 @@ export const make = ElectronDialog.of({
if (result.canceled) {
return Option.none();
}
@@ -219,27 +234,27 @@ index 354acc5a81..e8e89d9502 100644
Effect.annotateLogs({ channel }),
Effect.withSpan("desktop.ipc.invokeSync"),
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
-index a46dbafab0..8be9e500a7 100644
+index 6a1b1c62e7..4808d16401 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
-@@ -48,6 +48,7 @@ import {
+@@ -50,6 +50,7 @@ import {
revealWindow,
pickFolder,
pickProjectFavicon,
+ resolveHostPath,
pickThemeFiles,
setTheme,
- showContextMenu,
-@@ -94,6 +95,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
- yield* ipc.handleSync(getAppBranding);
+ syncHtmlFullscreen,
+@@ -99,6 +100,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* installRelayTelemetryEnabled();
yield* ipc.handleSync(getSystemLocale);
+ yield* ipc.handleSync(getPreferredSystemLanguages);
+ yield* ipc.handleSync(resolveHostPath);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handleSync(getLocalEnvironmentEnabled);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
-index 0f125c05de..9ca25157de 100644
+index aebbc1c24f..dceb96e655 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -1,6 +1,7 @@
@@ -251,17 +266,17 @@ index 0f125c05de..9ca25157de 100644
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
-index 63b8db03da..063a1a54a4 100644
+index e0eea5c74c..d1e22371a9 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
-@@ -267,10 +267,24 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
+@@ -276,10 +276,24 @@ export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
},
],
});
- return paths[0] ?? null;
+ const iconPath = paths[0];
+ if (!iconPath) return null;
-+ return yield* Effect.try(() => ElectronDialog.resolveHostPath(iconPath)).pipe(
++ return yield* ElectronDialog.tryResolveHostPath(iconPath).pipe(
+ Effect.orElseSucceed(() => iconPath),
+ );
}),
@@ -272,7 +287,7 @@ index 63b8db03da..063a1a54a4 100644
+ channel: IpcChannels.RESOLVE_HOST_PATH_CHANNEL,
+ handler: (path) =>
+ Schema.decodeUnknownEffect(Schema.String)(path).pipe(
-+ Effect.flatMap((portalPath) => Effect.try(() => ElectronDialog.resolveHostPath(portalPath))),
++ Effect.flatMap(ElectronDialog.tryResolveHostPath),
+ Effect.orElseSucceed(() => ""),
+ ),
+};
@@ -281,10 +296,10 @@ index 63b8db03da..063a1a54a4 100644
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
-index da56807186..907b74c481 100644
+index 2dbc4eeda3..045d6dba29 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
-@@ -82,7 +82,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {
+@@ -95,7 +95,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {
},
getRelayTelemetryEnabled: () =>
ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true,
diff --git a/patches/0008-flatpak-cli-launcher.patch b/patches/0008-flatpak-cli-launcher.patch
index 03a3f47..62691f7 100644
--- a/patches/0008-flatpak-cli-launcher.patch
+++ b/patches/0008-flatpak-cli-launcher.patch
@@ -1,21 +1,14 @@
diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts
-index 8566613dd6..5544427bf7 100644
+index 2dc59c5889..0a13af3121 100644
--- a/apps/desktop/src/app/DesktopCliCommand.test.ts
+++ b/apps/desktop/src/app/DesktopCliCommand.test.ts
-@@ -1,5 +1,5 @@
- import * as NodeServices from "@effect/platform-node/NodeServices";
--import { afterEach, beforeEach, expect, it } from "@effect/vitest";
-+import { afterEach, beforeEach, expect, it, vi } from "@effect/vitest";
- import * as HostProcess from "@t3tools/shared/HostProcess";
- import * as Effect from "effect/Effect";
- import * as FileSystem from "effect/FileSystem";
-@@ -93,6 +93,37 @@ afterEach(() => {
- });
+@@ -94,6 +94,38 @@ const fakePowerShell = (initial: string, inherited: Record = {})
+ };
it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
+ it.effect("hides Flatpak CLI setup and leaves launchers and host command links untouched", () =>
+ Effect.gen(function* () {
-+ vi.stubEnv("FLATPAK_ID", "com.t3tools.t3code");
++ const env = { FLATPAK_ID: "com.t3tools.t3code" };
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const home = yield* fs.makeTempDirectoryScoped();
@@ -23,7 +16,7 @@ index 8566613dd6..5544427bf7 100644
+ const link = path.join(home, ".local", "bin", "t3");
+ yield* fs.makeDirectory(path.dirname(link), { recursive: true });
+ yield* fs.writeFileString(link, "existing host command");
-+ const command = yield* commandIn({ home, baseDir });
++ const command = yield* commandIn({ home, baseDir, env });
+ expect(yield* command.state).toEqual({
+ supported: false,
+ installedPath: null,
@@ -37,33 +30,34 @@ index 8566613dd6..5544427bf7 100644
+ DesktopEnvironment.DesktopEnvironment,
+ environmentFor(path, { home, baseDir }),
+ ),
++ Effect.provideService(HostProcess.Environment, env),
+ );
+ expect(Option.isNone(shim)).toBe(true);
+ expect(yield* fs.exists(path.join(baseDir, "bin", "t3"))).toBe(false);
+ expect(yield* fs.readFileString(link)).toBe("existing host command");
-+ }).pipe(Effect.scoped, Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))),
++ }).pipe(Effect.scoped),
+ );
+
it.effect("links the launcher onto PATH and removes only that link", () =>
Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
+ const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts
-index f53895a60a..ca20eb3ecf 100644
+index b5306a6bb5..afb011e165 100644
--- a/apps/desktop/src/app/DesktopCliCommand.ts
+++ b/apps/desktop/src/app/DesktopCliCommand.ts
-@@ -12,6 +12,7 @@ import * as Stream from "effect/Stream";
- import * as ChildProcess from "effect/process/ChildProcess";
- import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+@@ -17,6 +17,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+
+ import { pathSetup, readUserLoginShell } from "@t3tools/shared/shell";
+import { flatpakAppId } from "./Flatpak.ts";
import * as DesktopCliShim from "./DesktopCliShim.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+ import { makeComponentLogger } from "./DesktopObservability.ts";
+@@ -79,6 +80,24 @@ export class DesktopCliCommand extends Context.Service<
-@@ -64,6 +65,22 @@ export class DesktopCliCommand extends Context.Service<
- /** @public */
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
-+ if (flatpakAppId(process.env, environment.platform) !== null) {
++ if (flatpakAppId(yield* HostProcess.Environment, environment.platform) !== null) {
+ const unsupported = {
+ supported: false,
+ installedPath: null,
@@ -77,29 +71,38 @@ index f53895a60a..ca20eb3ecf 100644
+ state: Effect.succeed(unsupported),
+ install: unavailable,
+ uninstall: unavailable,
++ addToPath: unavailable,
++ installOnFirstLaunch: Effect.void,
+ });
+ }
const fs = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const path = environment.path;
+ // Read the live env: shell discovery patches PATH after startup, and Windows variable
diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts
-index 3d4b94abff..f4dc8cb4c0 100644
+index f8bd8b5f91..7ab57eec94 100644
--- a/apps/desktop/src/app/DesktopCliShim.ts
+++ b/apps/desktop/src/app/DesktopCliShim.ts
-@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
+@@ -1,9 +1,11 @@
++import * as HostProcess from "@t3tools/shared/HostProcess";
+ import * as Cause from "effect/Cause";
+ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
+ import * as Random from "effect/Random";
+import { flatpakAppId } from "./Flatpak.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
-@@ -121,7 +122,9 @@ export const launcherPath = (environment: DesktopEnvironment.DesktopEnvironment[
+@@ -122,7 +124,12 @@ export const launcherPath = (environment: DesktopEnvironment.DesktopEnvironment[
export const install = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
- if (!environment.isPackaged) return Option.none();
-+ if (!environment.isPackaged || flatpakAppId(process.env, environment.platform) !== null) {
++ if (
++ !environment.isPackaged ||
++ flatpakAppId(yield* HostProcess.Environment, environment.platform) !== null
++ ) {
+ return Option.none();
+ }
const fs = yield* FileSystem.FileSystem;
diff --git a/patches/0009-flatpak-server-updates.patch b/patches/0009-flatpak-server-updates.patch
index 28001da..2a482ce 100644
--- a/patches/0009-flatpak-server-updates.patch
+++ b/patches/0009-flatpak-server-updates.patch
@@ -68,7 +68,7 @@ index 58baa160ad..85835f020a 100644
},
),
diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts
-index 3960b5b8d1..5016da75a2 100644
+index dc719ed93c..bd07d0af2e 100644
--- a/apps/server/src/environment/ServerEnvironment.test.ts
+++ b/apps/server/src/environment/ServerEnvironment.test.ts
@@ -91,7 +91,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen
@@ -113,10 +113,10 @@ index 3960b5b8d1..5016da75a2 100644
settledWorktreeCleanup: true,
storageCleanupRun: true,
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
-index 0787a3702c..e8edc3cfee 100644
+index 74c6865807..f1df53d13a 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
-@@ -201,8 +201,11 @@ export const make = Effect.gen(function* () {
+@@ -203,8 +203,11 @@ export const make = Effect.gen(function* () {
const serverInstallation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
// Desktop and server ship together; a control fd guarantees requestDesktopUpdate support.
diff --git a/patches/0010-flatpak-browser-requirements.patch b/patches/0010-flatpak-browser-requirements.patch
index 4124074..a280b46 100644
--- a/patches/0010-flatpak-browser-requirements.patch
+++ b/patches/0010-flatpak-browser-requirements.patch
@@ -76,10 +76,10 @@ index 1847e5f232..eea911ee35 100644
// Playwright reports Chrome's refusal to sandbox as root as a sandbox failure too.
return (yield* HostProcess.UserId) === 0
diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts
-index e03d7e3b35..a70ff7d236 100644
+index 7f128dc5d4..51364a0b16 100644
--- a/apps/server/src/preview/ServerBrowser.ts
+++ b/apps/server/src/preview/ServerBrowser.ts
-@@ -2710,7 +2710,9 @@ const make = Effect.gen(function* () {
+@@ -2759,7 +2759,9 @@ const make = Effect.gen(function* () {
(yield* PreviewBrowserHost.sandboxBlocked)
) {
yield* Effect.logWarning(
diff --git a/patches/0011-flatpak-database-maintenance.patch b/patches/0011-flatpak-database-maintenance.patch
deleted file mode 100644
index 388f117..0000000
--- a/patches/0011-flatpak-database-maintenance.patch
+++ /dev/null
@@ -1,935 +0,0 @@
-diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts
-index 66fc83adae..b095321153 100644
---- a/apps/desktop/src/app/DesktopApp.test.ts
-+++ b/apps/desktop/src/app/DesktopApp.test.ts
-@@ -54,6 +54,7 @@ import * as DesktopBackendConfiguration from "../backend/DesktopBackendConfigura
- import * as DesktopCliCommand from "./DesktopCliCommand.ts";
- import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
- import * as DesktopConnectionCatalogStore from "./DesktopConnectionCatalogStore.ts";
-+import * as DesktopDatabaseMaintenance from "./DesktopDatabaseMaintenance.ts";
- import * as DesktopIpc from "../ipc/DesktopIpc.ts";
- import * as DesktopLocalEnvironmentAuth from "../backend/DesktopLocalEnvironmentAuth.ts";
- import * as DesktopManagedPolicy from "./DesktopManagedPolicy.ts";
-@@ -193,6 +194,7 @@ it.effect(
- Layer.mock(DesktopCliCommand.DesktopCliCommand, {}),
- Layer.mock(DesktopClientSettings.DesktopClientSettings, {}),
- Layer.mock(DesktopConnectionCatalogStore.DesktopConnectionCatalogStore, {}),
-+ Layer.mock(DesktopDatabaseMaintenance.DesktopDatabaseMaintenance, { supported: false }),
- Layer.mock(DesktopIpc.DesktopIpc, {}),
- Layer.mock(DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth, {}),
- Layer.mock(DesktopManagedPolicy.DesktopManagedPolicy, {}),
-diff --git a/apps/desktop/src/app/DesktopDatabaseMaintenance.test.ts b/apps/desktop/src/app/DesktopDatabaseMaintenance.test.ts
-new file mode 100644
-index 0000000000..7799a47cea
---- /dev/null
-+++ b/apps/desktop/src/app/DesktopDatabaseMaintenance.test.ts
-@@ -0,0 +1,252 @@
-+import * as NodeServices from "@effect/platform-node/NodeServices";
-+import { assert, afterEach, it, vi } from "@effect/vitest";
-+import * as Deferred from "effect/Deferred";
-+import * as Effect from "effect/Effect";
-+import * as FileSystem from "effect/FileSystem";
-+import * as Fiber from "effect/Fiber";
-+import * as Layer from "effect/Layer";
-+import * as Option from "effect/Option";
-+import * as Path from "effect/Path";
-+import * as Sink from "effect/Sink";
-+import * as Stream from "effect/Stream";
-+import * as ChildProcess from "effect/process/ChildProcess";
-+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
-+
-+import * as DesktopDatabaseMaintenance from "./DesktopDatabaseMaintenance.ts";
-+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
-+import * as DesktopState from "./DesktopState.ts";
-+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
-+import * as ElectronDialog from "../electron/ElectronDialog.ts";
-+import * as ElectronWindow from "../electron/ElectronWindow.ts";
-+
-+const runtime = "/installed Flatpak/files/t3code";
-+const baseDir = "/home/alice/.var/app/com.t3tools.t3code/data/t3";
-+afterEach(() => vi.unstubAllEnvs());
-+
-+const harness = Effect.fn("test.databaseMaintenance.harness")(function* (
-+ options: {
-+ runtime?: string;
-+ response?: number;
-+ exitCode?: number;
-+ ready?: boolean;
-+ confirm?: Effect.Effect;
-+ stoppedPid?: number;
-+ legacyDatabase?: boolean;
-+ checkbox?: boolean;
-+ } = {},
-+) {
-+ const fs = yield* FileSystem.FileSystem;
-+ const path = yield* Path.Path;
-+ const stateDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-flatpak-state-" });
-+ if (options.legacyDatabase) {
-+ yield* fs.writeFileString(path.join(stateDir, "state.sqlite"), "rollback");
-+ }
-+ vi.stubEnv("FLATPAK_ID", "com.t3tools.t3code");
-+ vi.stubEnv("T3CODE_FLATPAK_RUNTIME", options.runtime ?? runtime);
-+ const order: string[] = [];
-+ const errors: string[] = [];
-+ const commands: ChildProcess.Command[] = [];
-+ const confirmations: Electron.MessageBoxOptions[] = [];
-+ let stopped = false;
-+ const primary: DesktopBackendPool.DesktopBackendInstance = {
-+ id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
-+ label: Effect.succeed("Local"),
-+ currentConfig: Effect.succeedNone,
-+ snapshot: Effect.sync(() => ({
-+ desiredRunning: !stopped,
-+ ready: !stopped,
-+ activePid: stopped ? Option.fromNullishOr(options.stoppedPid) : Option.some(123),
-+ restartAttempt: 0,
-+ restartScheduled: false,
-+ })),
-+ stop: () =>
-+ Effect.sync(() => {
-+ order.push("stop");
-+ stopped = true;
-+ }),
-+ start: Effect.sync(() => {
-+ order.push("start");
-+ stopped = false;
-+ }),
-+ waitForReady: () =>
-+ Effect.sync(() => {
-+ order.push("ready");
-+ return options.ready ?? true;
-+ }),
-+ };
-+ const dialog = ElectronDialog.ElectronDialog.of({
-+ pickFolder: () => Effect.die("unexpected folder picker"),
-+ pickFiles: () => Effect.die("unexpected file picker"),
-+ showMessageBox: (input) =>
-+ Effect.gen(function* () {
-+ const confirm = input.buttons !== undefined && input.buttons.length > 1;
-+ order.push(confirm ? "confirm" : "success");
-+ if (confirm) confirmations.push(input);
-+ if (confirm && options.confirm) yield* options.confirm;
-+ return {
-+ response: confirm ? (options.response ?? 1) : 0,
-+ checkboxChecked: options.checkbox ?? false,
-+ };
-+ }),
-+ showErrorBox: (_title, message) =>
-+ Effect.sync(() => {
-+ order.push("error");
-+ errors.push(message);
-+ }),
-+ });
-+ const spawner = ChildProcessSpawner.make((command) =>
-+ Effect.sync(() => {
-+ order.push(stopped ? "compact" : "live");
-+ commands.push(command);
-+ const stdout = Stream.make(new TextEncoder().encode("Database: 2 GiB -> 1 GiB."));
-+ const stderr = Stream.make(new TextEncoder().encode("Not enough disk space."));
-+ return ChildProcessSpawner.makeHandle({
-+ pid: ChildProcessSpawner.ProcessId(456),
-+ stdout,
-+ stderr,
-+ all: stdout,
-+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(options.exitCode ?? 0)),
-+ isRunning: Effect.succeed(false),
-+ kill: () => Effect.void,
-+ stdin: Sink.drain,
-+ getInputFd: () => Sink.drain,
-+ getOutputFd: () => Stream.empty,
-+ unref: Effect.succeed(Effect.void),
-+ });
-+ }),
-+ );
-+ const maintenance = yield* DesktopDatabaseMaintenance.make.pipe(
-+ Effect.provide(
-+ Layer.mergeAll(
-+ DesktopBackendPool.layerTest([primary]),
-+ DesktopState.layer,
-+ Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
-+ platform: "linux",
-+ baseDir,
-+ stateDir,
-+ } as DesktopEnvironment.DesktopEnvironment["Service"]),
-+ Layer.succeed(ElectronDialog.ElectronDialog, dialog),
-+ Layer.mock(ElectronWindow.ElectronWindow)({
-+ currentMainOrFirst: Effect.succeedNone,
-+ }),
-+ Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
-+ ),
-+ ),
-+ );
-+ return { maintenance, order, errors, commands, confirmations };
-+});
-+
-+it.effect(
-+ "stops the server, cleans only its own database, and restarts before reporting success",
-+ () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order, commands, confirmations } = yield* harness();
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.deepEqual(order, ["confirm", "stop", "compact", "start", "ready", "success"]);
-+ assert.isUndefined(confirmations[0]?.checkboxLabel);
-+ const command = commands[0]!;
-+ assert.equal(command._tag, "StandardCommand");
-+ if (command._tag !== "StandardCommand") return;
-+ assert.equal(command.command, "/usr/bin/flatpak-spawn");
-+ assert.deepEqual(command.args.slice(-4), [
-+ "/bin/sh",
-+ `${runtime}/host-server.sh`,
-+ "--database-maintenance",
-+ "--compact",
-+ ]);
-+ assert.include(command.args, `--env=T3CODE_FLATPAK_SERVER=${runtime}/t3code`);
-+ assert.include(command.args, `--env=T3CODE_HOME=${baseDir}`);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("cancelling the confirmation leaves the server running", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order } = yield* harness({ response: 0 });
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.deepEqual(order, ["confirm"]);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("restarts after cleanup failure and reports the actual failure", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order, errors } = yield* harness({ exitCode: 1 });
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.deepEqual(order, ["confirm", "stop", "compact", "start", "ready", "error"]);
-+ assert.include(errors[0]!, "Not enough disk space.");
-+ assert.include(errors[0]!, "The local server has restarted.");
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("does not run maintenance when the server has not exited", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order, commands } = yield* harness({ stoppedPid: 123 });
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.deepEqual(order, ["confirm", "stop", "start", "ready", "error"]);
-+ assert.equal(commands.length, 0);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("ignores a second request while confirmation is open", () =>
-+ Effect.gen(function* () {
-+ const opened = yield* Deferred.make();
-+ const proceed = yield* Deferred.make();
-+ const { maintenance, order } = yield* harness({
-+ confirm: Deferred.succeed(opened, undefined).pipe(Effect.andThen(Deferred.await(proceed))),
-+ });
-+ const first = yield* maintenance.run({ reclaimSpace: true }).pipe(Effect.forkChild);
-+ yield* Deferred.await(opened);
-+ yield* maintenance.run({ reclaimSpace: true });
-+ yield* Deferred.succeed(proceed, undefined);
-+ yield* Fiber.join(first);
-+ assert.equal(order.filter((entry) => entry === "compact").length, 1);
-+ assert.equal(order.filter((entry) => entry === "confirm").length, 1);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("does not expose cleanup without a Flatpak runtime", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order } = yield* harness({ runtime: "" });
-+ assert.isFalse(maintenance.supported);
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.deepEqual(order, []);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("offers deleting the legacy database, unticked, alongside reclaiming space", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, commands, confirmations } = yield* harness({
-+ legacyDatabase: true,
-+ checkbox: true,
-+ });
-+ assert.equal(yield* maintenance.legacyDatabaseBytes, "rollback".length);
-+ yield* maintenance.run({ reclaimSpace: true });
-+ assert.isString(confirmations[0]?.checkboxLabel);
-+ assert.isFalse(confirmations[0]?.checkboxChecked);
-+ const command = commands[0]!;
-+ assert.equal(command._tag, "StandardCommand");
-+ if (command._tag !== "StandardCommand") return;
-+ assert.deepEqual(command.args.slice(-2), ["--compact", "--remove-legacy"]);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("deletes only the legacy database without stopping the server", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order, commands } = yield* harness({ legacyDatabase: true });
-+ yield* maintenance.run({ reclaimSpace: false });
-+ assert.deepEqual(order, ["confirm", "live", "success"]);
-+ const command = commands[0]!;
-+ assert.equal(command._tag, "StandardCommand");
-+ if (command._tag !== "StandardCommand") return;
-+ assert.deepEqual(command.args.slice(-2), ["--database-maintenance", "--remove-legacy"]);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-+
-+it.effect("does nothing when only the legacy database was requested and it is gone", () =>
-+ Effect.gen(function* () {
-+ const { maintenance, order, confirmations } = yield* harness();
-+ assert.isNull(yield* maintenance.legacyDatabaseBytes);
-+ yield* maintenance.run({ reclaimSpace: false });
-+ assert.deepEqual(order, []);
-+ assert.equal(confirmations.length, 0);
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-diff --git a/apps/desktop/src/app/DesktopDatabaseMaintenance.ts b/apps/desktop/src/app/DesktopDatabaseMaintenance.ts
-new file mode 100644
-index 0000000000..2b44350768
---- /dev/null
-+++ b/apps/desktop/src/app/DesktopDatabaseMaintenance.ts
-@@ -0,0 +1,241 @@
-+import * as Cause from "effect/Cause";
-+import * as Context from "effect/Context";
-+import * as Duration from "effect/Duration";
-+import * as Effect from "effect/Effect";
-+import * as Exit from "effect/Exit";
-+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 Ref from "effect/Ref";
-+import * as Schema from "effect/Schema";
-+import * as Stream from "effect/Stream";
-+import * as ChildProcess from "effect/process/ChildProcess";
-+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
-+
-+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
-+import * as DesktopState from "./DesktopState.ts";
-+import { flatpakAppId } from "./Flatpak.ts";
-+import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
-+import * as ElectronDialog from "../electron/ElectronDialog.ts";
-+import * as ElectronWindow from "../electron/ElectronWindow.ts";
-+
-+class DesktopDatabaseCleanupError extends Schema.TaggedError()(
-+ "DesktopDatabaseCleanupError",
-+ { message: Schema.String },
-+) {}
-+
-+const formatSize = (bytes: number) => `${(bytes / 1024 ** 2).toFixed(0)} MiB`;
-+
-+/**
-+ * Coordinates the `t3 doctor` database repairs for the Flatpak desktop's own database,
-+ * since the Flatpak installs no `t3` command.
-+ */
-+export class DesktopDatabaseMaintenance extends Context.Service<
-+ DesktopDatabaseMaintenance,
-+ {
-+ readonly supported: boolean;
-+ /** Size of the database kept from before 0.1.0 for rolling back, or null once it is gone. */
-+ readonly legacyDatabaseBytes: Effect.Effect;
-+ /**
-+ * Confirms, then reclaims space while the server is stopped and/or deletes the legacy
-+ * database. The legacy database is only offered while it exists.
-+ */
-+ readonly run: (input: { readonly reclaimSpace: boolean }) => Effect.Effect;
-+ }
-+>()("@t3tools/desktop/app/DesktopDatabaseMaintenance") {}
-+
-+/** @public Service construction is part of the canonical Effect module API. */
-+export const make = Effect.gen(function* () {
-+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
-+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
-+ const dialog = yield* ElectronDialog.ElectronDialog;
-+ const windows = yield* ElectronWindow.ElectronWindow;
-+ const state = yield* DesktopState.DesktopState;
-+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
-+ const fs = yield* FileSystem.FileSystem;
-+ const path = yield* Path.Path;
-+ const busy = yield* Ref.make(false);
-+ const runtime = process.env.T3CODE_FLATPAK_RUNTIME;
-+ const supported =
-+ flatpakAppId(process.env, environment.platform) !== null && runtime?.startsWith("/") === true;
-+ // Matches the server's DatabaseMaintenance, which keeps it next to statev2.sqlite.
-+ const legacyPath = path.join(environment.stateDir, "state.sqlite");
-+
-+ const legacyDatabaseBytes = fs.stat(legacyPath).pipe(
-+ Effect.map((info) => Number(info.size)),
-+ Effect.orElseSucceed(() => null),
-+ );
-+
-+ // Run the installed package directly on the host, with no CLI launcher or service install.
-+ const runHostMaintenance = (flags: ReadonlyArray) =>
-+ Effect.scoped(
-+ Effect.gen(function* () {
-+ const child = yield* spawner.spawn(
-+ ChildProcess.make(
-+ "/usr/bin/flatpak-spawn",
-+ [
-+ "--host",
-+ "--watch-bus",
-+ `--directory=${runtime}`,
-+ `--env=T3CODE_HOME=${environment.baseDir}`,
-+ `--env=T3CODE_FLATPAK_SERVER=${runtime}/t3code`,
-+ `--env=T3CODE_FLATPAK_ENTRY=${runtime}/resources/app.asar/apps/server/dist/bin.mjs`,
-+ `--env=T3CODE_FLATPAK_COMPILE_CACHE=${runtime}/resources/app.asar/apps/desktop/dist-electron/compileCache.cjs`,
-+ "/bin/sh",
-+ `${runtime}/host-server.sh`,
-+ "--database-maintenance",
-+ ...flags,
-+ ],
-+ { stdin: "ignore" },
-+ ),
-+ );
-+ const [output, errors, code] = yield* Effect.all(
-+ [
-+ child.stdout.pipe(Stream.decodeText(), Stream.mkString),
-+ child.stderr.pipe(Stream.decodeText(), Stream.mkString),
-+ child.exitCode,
-+ ],
-+ { concurrency: "unbounded" },
-+ );
-+ if (code !== 0) {
-+ return yield* new DesktopDatabaseCleanupError({
-+ message: errors.trim() || output.trim() || "Database cleanup failed.",
-+ });
-+ }
-+ return output.trim();
-+ }),
-+ );
-+
-+ const errorMessage = (cause: Cause.Cause) => {
-+ const error = Cause.squash(cause);
-+ return error instanceof Error ? error.message : String(error);
-+ };
-+
-+ const run = Effect.fn("desktop.databaseMaintenance.run")(
-+ function* (input: { readonly reclaimSpace: boolean }) {
-+ if (!supported || !runtime || (yield* Ref.get(state.quitting))) return;
-+ if (yield* Ref.getAndSet(busy, true)) return;
-+ yield* Effect.gen(function* () {
-+ const owner = Option.getOrUndefined(yield* windows.currentMainOrFirst);
-+ const legacyBytes = yield* legacyDatabaseBytes;
-+
-+ if (!input.reclaimSpace) {
-+ if (legacyBytes === null) return;
-+ const confirmation = yield* dialog.showMessageBox(
-+ {
-+ type: "warning",
-+ title: "Delete old database",
-+ message: "Delete the database from before 0.1.0?",
-+ detail: `Frees ${formatSize(legacyBytes)}. Your threads and settings are already in the current database. After this, T3 Code versions before 0.1.0 start with no threads or settings, so you can no longer roll back to them.`,
-+ buttons: ["Cancel", "Delete database"],
-+ defaultId: 0,
-+ cancelId: 0,
-+ noLink: true,
-+ },
-+ owner,
-+ );
-+ if (confirmation.response !== 1 || (yield* Ref.get(state.quitting))) return;
-+ // Only versions before 0.1.0 open this file, so the server keeps running.
-+ const result = yield* runHostMaintenance(["--remove-legacy"]).pipe(Effect.exit);
-+ if (Exit.isFailure(result)) {
-+ yield* dialog.showErrorBox("Database cleanup failed", errorMessage(result.cause));
-+ return;
-+ }
-+ yield* dialog.showMessageBox(
-+ {
-+ type: "info",
-+ title: "Database cleanup complete",
-+ message: "Deleted the database from before 0.1.0.",
-+ buttons: ["OK"],
-+ },
-+ owner,
-+ );
-+ return;
-+ }
-+
-+ const confirmation = yield* dialog.showMessageBox(
-+ {
-+ type: "question",
-+ title: "Reclaim database space",
-+ message: "Reclaim space and restart the local server?",
-+ detail:
-+ "Finish active work first. T3 Code will temporarily disconnect while its local server stops and database cleanup runs. This can take several minutes and needs temporary disk space. Afterwards, the server returns freed space to disk on its own.",
-+ buttons: ["Cancel", "Reclaim space and restart"],
-+ defaultId: 0,
-+ cancelId: 0,
-+ noLink: true,
-+ ...(legacyBytes === null
-+ ? {}
-+ : {
-+ checkboxLabel: `Also delete the database from before 0.1.0 (${formatSize(legacyBytes)}). T3 Code versions before 0.1.0 will then start with no threads or settings.`,
-+ checkboxChecked: false,
-+ }),
-+ },
-+ owner,
-+ );
-+ if (confirmation.response !== 1 || (yield* Ref.get(state.quitting))) return;
-+ const primary = yield* pool.primary;
-+ const snapshot = yield* primary.snapshot;
-+ if (!snapshot.ready) {
-+ yield* dialog.showErrorBox(
-+ "Database cleanup unavailable",
-+ "Wait for the local server to finish starting, then try again.",
-+ );
-+ return;
-+ }
-+
-+ const result = yield* Effect.gen(function* () {
-+ yield* primary.stop();
-+ const stopped = yield* primary.snapshot;
-+ if (Option.isSome(stopped.activePid)) {
-+ return yield* new DesktopDatabaseCleanupError({
-+ message: "The local server did not stop. Database cleanup was not started.",
-+ });
-+ }
-+ return yield* runHostMaintenance([
-+ "--compact",
-+ ...(confirmation.checkboxChecked ? ["--remove-legacy"] : []),
-+ ]);
-+ }).pipe(
-+ Effect.ensuring(
-+ Effect.gen(function* () {
-+ if (!(yield* Ref.get(state.quitting))) yield* primary.start;
-+ }),
-+ ),
-+ Effect.exit,
-+ );
-+ if (yield* Ref.get(state.quitting)) return;
-+ const ready = yield* primary.waitForReady(Duration.seconds(60));
-+ if (Exit.isFailure(result)) {
-+ yield* dialog.showErrorBox(
-+ "Database cleanup failed",
-+ `${errorMessage(result.cause)}\n\n${ready ? "The local server has restarted." : "The local server has not become ready. Close and reopen T3 Code to retry starting it."}`,
-+ );
-+ return;
-+ }
-+ yield* dialog.showMessageBox(
-+ {
-+ type: ready ? "info" : "warning",
-+ title: "Database cleanup complete",
-+ message: ready
-+ ? "Database space reclaimed. The local server has restarted."
-+ : "Database space reclaimed, but the local server has not become ready.",
-+ detail:
-+ result.value +
-+ (ready ? "" : "\nClose and reopen T3 Code to retry starting the server."),
-+ buttons: ["OK"],
-+ },
-+ owner,
-+ );
-+ }).pipe(Effect.ensuring(Ref.set(busy, false)));
-+ },
-+ Effect.catchCause((cause) =>
-+ dialog.showErrorBox("Database cleanup failed", errorMessage(cause)),
-+ ),
-+ );
-+
-+ return DesktopDatabaseMaintenance.of({ supported, legacyDatabaseBytes, run });
-+});
-+
-+export const layer = Layer.effect(DesktopDatabaseMaintenance, make);
-diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
-index 8be9e500a7..71e31275ed 100644
---- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
-+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
-@@ -81,6 +81,12 @@ import {
- uninstallCliCommand,
- } from "./methods/cliCommand.ts";
-
-+import {
-+ getDatabaseMaintenanceSupported,
-+ getLegacyDatabaseBytes,
-+ runDatabaseMaintenance,
-+} from "./methods/databaseMaintenance.ts";
-+
- export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
- const ipc = yield* DesktopIpc.DesktopIpc;
- yield* installNotificationBadge();
-@@ -90,6 +96,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
- yield* ipc.handle(AppActivationIpc.complete);
- yield* ipc.handle(WebLinksIpc.setReady);
-
-+ yield* ipc.handleSync(getDatabaseMaintenanceSupported);
-+ yield* ipc.handle(getLegacyDatabaseBytes);
-+ yield* ipc.handle(runDatabaseMaintenance);
- yield* ipc.handleSync(takeLegacyLocalStorage);
- yield* ipc.handle(completeLegacyLocalStorage);
- yield* ipc.handleSync(getAppBranding);
-diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
-index 9ca25157de..b425244c66 100644
---- a/apps/desktop/src/ipc/channels.ts
-+++ b/apps/desktop/src/ipc/channels.ts
-@@ -125,3 +125,7 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-
- export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback";
- export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage";
- export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage";
-+
-+export const DATABASE_MAINTENANCE_SUPPORTED_CHANNEL = "desktop:database-maintenance-supported";
-+export const DATABASE_MAINTENANCE_LEGACY_BYTES_CHANNEL = "desktop:database-maintenance-legacy-bytes";
-+export const DATABASE_MAINTENANCE_RUN_CHANNEL = "desktop:database-maintenance-run";
-diff --git a/apps/desktop/src/ipc/methods/databaseMaintenance.ts b/apps/desktop/src/ipc/methods/databaseMaintenance.ts
-new file mode 100644
-index 0000000000..00cb4b9191
---- /dev/null
-+++ b/apps/desktop/src/ipc/methods/databaseMaintenance.ts
-@@ -0,0 +1,33 @@
-+import * as Effect from "effect/Effect";
-+import * as Schema from "effect/Schema";
-+
-+import * as DesktopDatabaseMaintenance from "../../app/DesktopDatabaseMaintenance.ts";
-+import * as IpcChannels from "../channels.ts";
-+import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
-+
-+export const getDatabaseMaintenanceSupported = makeSyncIpcMethod({
-+ channel: IpcChannels.DATABASE_MAINTENANCE_SUPPORTED_CHANNEL,
-+ result: Schema.Boolean,
-+ handler: Effect.fn("desktop.ipc.databaseMaintenance.supported")(function* () {
-+ return (yield* DesktopDatabaseMaintenance.DesktopDatabaseMaintenance).supported;
-+ }),
-+});
-+
-+export const getLegacyDatabaseBytes = makeIpcMethod({
-+ channel: IpcChannels.DATABASE_MAINTENANCE_LEGACY_BYTES_CHANNEL,
-+ payload: Schema.Void,
-+ result: Schema.NullOr(Schema.Number),
-+ handler: Effect.fn("desktop.ipc.databaseMaintenance.legacyDatabaseBytes")(function* () {
-+ return yield* (yield* DesktopDatabaseMaintenance.DesktopDatabaseMaintenance)
-+ .legacyDatabaseBytes;
-+ }),
-+});
-+
-+export const runDatabaseMaintenance = makeIpcMethod({
-+ channel: IpcChannels.DATABASE_MAINTENANCE_RUN_CHANNEL,
-+ payload: Schema.Struct({ reclaimSpace: Schema.Boolean }),
-+ result: Schema.Void,
-+ handler: Effect.fn("desktop.ipc.databaseMaintenance.run")(function* (input) {
-+ yield* (yield* DesktopDatabaseMaintenance.DesktopDatabaseMaintenance).run(input);
-+ }),
-+});
-diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
-index d109518be1..9e4c7f3f36 100644
---- a/apps/desktop/src/main.ts
-+++ b/apps/desktop/src/main.ts
-@@ -41,6 +41,7 @@ import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";
- import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";
- import * as DesktopClerk from "./app/DesktopClerk.ts";
- import * as DesktopCliCommand from "./app/DesktopCliCommand.ts";
-+import * as DesktopDatabaseMaintenance from "./app/DesktopDatabaseMaintenance.ts";
- import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";
- import * as DesktopAssets from "./app/DesktopAssets.ts";
- import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";
-@@ -212,6 +213,7 @@ const layerDesktopApplication = Layer.mergeAll(
- DesktopApplicationMenu.layer,
- DesktopLinuxUrlHandler.layer,
- DesktopCliCommand.layer,
-+ DesktopDatabaseMaintenance.layer,
- layerDesktopSsh,
- ).pipe(
- Layer.provideMerge(layerDesktopSnapShot),
-diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
-index 907b74c481..29b59ebedb 100644
---- a/apps/desktop/src/preload.ts
-+++ b/apps/desktop/src/preload.ts
-@@ -279,6 +279,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
- downloadUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_DOWNLOAD_CHANNEL),
- installUpdate: (expectedVersion) =>
- ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL, expectedVersion),
-+ ...(ipcRenderer.sendSync(IpcChannels.DATABASE_MAINTENANCE_SUPPORTED_CHANNEL) === true
-+ ? {
-+ databaseMaintenance: {
-+ legacyDatabaseBytes: () =>
-+ ipcRenderer.invoke(IpcChannels.DATABASE_MAINTENANCE_LEGACY_BYTES_CHANNEL),
-+ run: (input) => ipcRenderer.invoke(IpcChannels.DATABASE_MAINTENANCE_RUN_CHANNEL, input),
-+ },
-+ }
-+ : {}),
- cliCommand: {
- getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL),
- install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL),
-diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
-index 15a3a9321f..5b13325ec5 100644
---- a/apps/server/src/binCli.ts
-+++ b/apps/server/src/binCli.ts
-@@ -1,4 +1,4 @@
--import { doctorCommand } from "./cli/doctor.ts";
-+import { doctorCommand, flatpakDatabaseMaintenanceCommand } from "./cli/doctor.ts";
- import { policyCommand } from "./cli/policy.ts";
- import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
- import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
-@@ -98,6 +98,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
- traceCommand,
- doctorCommand,
- policyCommand,
-+ flatpakDatabaseMaintenanceCommand,
- triageCommand,
- cloudEnabled ? connectCommand : connectUnavailableCommand,
- ]),
-diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts
-index 2b9abe89f2..23a2121dbd 100644
---- a/apps/server/src/cli/doctor.test.ts
-+++ b/apps/server/src/cli/doctor.test.ts
-@@ -1,10 +1,18 @@
- 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 Path from "effect/Path";
-+import * as SqlClient from "effect/sql/SqlClient";
-+import { Command } from "effect/cli";
-+import * as HostProcess from "@t3tools/shared/HostProcess";
-+import * as NetService from "@t3tools/shared/Net";
-+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
-+import * as Sqlite from "../persistence/Sqlite.ts";
- import * as Layer from "effect/Layer";
-
- import * as BootService from "../cloud/bootService.ts";
--import { runDoctor } from "./doctor.ts";
-+import { runDoctor, flatpakDatabaseMaintenanceCommand } from "./doctor.ts";
- import { DatabaseMaintenance } from "../persistence/DatabaseMaintenance.ts";
-
- it.effect(
-@@ -53,3 +61,41 @@ it.effect(
- assert.deepEqual(calls, ["pause", "compact", "resume"]);
- }),
- );
-+
-+it.effect(
-+ "the Flatpak desktop command compacts without a service and deletes the rollback database only on request",
-+ () =>
-+ Effect.gen(function* () {
-+ const fs = yield* FileSystem.FileSystem;
-+ const path = yield* Path.Path;
-+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-flatpak-compact-" });
-+ const dbPath = path.join(baseDir, "userdata", "statev2.sqlite");
-+ const legacy = path.join(baseDir, "userdata", "state.sqlite");
-+ yield* Effect.void.pipe(Effect.provide(Sqlite.layerFromPath(dbPath)));
-+ yield* Effect.flatMap(SqlClient.SqlClient, (sql) => sql`CREATE TABLE rollback (id)`).pipe(
-+ Effect.provide(NodeSqliteClient.layer({ filename: legacy })),
-+ );
-+ const run = (...args: ReadonlyArray) =>
-+ Command.runWith(flatpakDatabaseMaintenanceCommand, { version: "0.0.0" })([
-+ "--base-dir",
-+ baseDir,
-+ ...args,
-+ ]).pipe(
-+ Effect.provide(NetService.layer),
-+ Effect.provideService(HostProcess.Environment, {
-+ T3CODE_FLATPAK_SERVER: "/installed/flatpak/t3code",
-+ }),
-+ );
-+
-+ yield* run("--compact");
-+ assert.isTrue(yield* fs.exists(legacy));
-+ const mode = yield* Effect.flatMap(
-+ SqlClient.SqlClient,
-+ (sql) => sql<{ auto_vacuum: number }>`PRAGMA auto_vacuum`,
-+ ).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
-+ assert.equal(mode[0]?.auto_vacuum, 2);
-+
-+ yield* run("--remove-legacy");
-+ assert.isFalse(yield* fs.exists(legacy));
-+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
-+);
-diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts
-index f7afaf9e4d..a9a202abd9 100644
---- a/apps/server/src/cli/doctor.ts
-+++ b/apps/server/src/cli/doctor.ts
-@@ -1,8 +1,10 @@
-+import * as HostProcess from "@t3tools/shared/HostProcess";
- import { DATABASE_COMPACTION_RECOMMENDED_BYTES } from "@t3tools/contracts";
- import * as Console from "effect/Console";
- import * as Effect from "effect/Effect";
- import * as Layer from "effect/Layer";
- import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
-+import * as CliError from "effect/cli/CliError";
-
- import * as BootService from "../cloud/bootService.ts";
- import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts";
-@@ -145,3 +147,38 @@ export const doctorCommand = Command.make("doctor", {
- }),
- ),
- );
-+
-+/**
-+ * Internal Flatpak desktop action, run by the desktop after its confirmation dialog.
-+ * Never reconciles services. `--compact` needs the desktop to have stopped its server.
-+ */
-+export const flatpakDatabaseMaintenanceCommand = Command.make("flatpak-database-maintenance", {
-+ ...projectLocationFlags,
-+ compact: Flag.Boolean("compact").pipe(Flag.withDefault(false)),
-+ removeLegacy: Flag.Boolean("remove-legacy").pipe(Flag.withDefault(false)),
-+}).pipe(
-+ Command.unlisted,
-+ Command.withHandler((flags) =>
-+ Effect.gen(function* () {
-+ if (!(yield* HostProcess.Environment).T3CODE_FLATPAK_SERVER) {
-+ return yield* new CliError.UserError({
-+ cause: "This action is only available to the Flatpak desktop.",
-+ });
-+ }
-+ const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel);
-+ yield* Effect.gen(function* () {
-+ const maintenance = yield* DatabaseMaintenance.DatabaseMaintenance;
-+ if (flags.compact) {
-+ const result = yield* maintenance.compact(config.dbPath);
-+ yield* Console.log(
-+ `Database: ${formatBytes(result.beforeBytes)} -> ${formatBytes(result.afterBytes)}. ${result.deletedEventCount} superseded events removed.`,
-+ );
-+ }
-+ if (flags.removeLegacy) {
-+ yield* maintenance.removeLegacyDatabase(config.dbPath);
-+ yield* Console.log("Deleted the database from before 0.1.0.");
-+ }
-+ }).pipe(Effect.provide(DatabaseMaintenance.layer));
-+ }),
-+ ),
-+);
-diff --git a/apps/web/src/components/settings/DatabaseStorageNotice.tsx b/apps/web/src/components/settings/DatabaseStorageNotice.tsx
-index 08ccf816a9..fa8f1d484c 100644
---- a/apps/web/src/components/settings/DatabaseStorageNotice.tsx
-+++ b/apps/web/src/components/settings/DatabaseStorageNotice.tsx
-@@ -1,42 +1,123 @@
- import { useAtomValue } from "@effect/atom-react";
--import type { EnvironmentId } from "@t3tools/contracts";
-+import type { DatabaseStorageStatus, EnvironmentId } from "@t3tools/contracts";
-+import { AsyncResult, Atom } from "effect/reactivity";
- import * as Schema from "effect/Schema";
-+import { useEffect, useState } from "react";
-
- import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
- import { useLocalStorage } from "../../hooks/useLocalStorage";
-+import { usePrimaryEnvironmentId } from "../../state/environments";
- import { serverEnvironment } from "../../state/server";
-+import { stackedThreadToast, toastManager } from "../ui/toast";
- import { Button } from "../ui/button";
- import { SettingsRow, SettingsSection } from "./settingsLayout";
-
- const DismissedEnvironmentIds = Schema.Array(Schema.String);
-+const NO_LOCAL_DATABASE_STORAGE = Atom.make(
-+ AsyncResult.initial(false),
-+).pipe(Atom.withLabel("database-storage-notice:no-local-database"));
-
--/** Suggests `t3 doctor` on every machine whose database still holds at least 1 GiB of freed pages. */
-+const formatSize = (bytes: number) => `${(bytes / 1024 ** 2).toFixed(0)} MiB`;
-+
-+/**
-+ * Suggests `t3 doctor` on every machine whose database still holds at least 1 GiB of freed
-+ * pages. The Flatpak desktop has no `t3` command, so it offers the same repairs for its own
-+ * database until they are done.
-+ */
- export function DatabaseStorageNotice({
- environments,
- }: {
- environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>;
- }) {
-+ const primaryEnvironmentId = usePrimaryEnvironmentId();
-+ const maintenance = window.desktopBridge?.databaseMaintenance;
-+ const local = maintenance
-+ ? environments.find((environment) => environment.environmentId === primaryEnvironmentId)
-+ : undefined;
-+ const remoteEnvironments = environments.filter((environment) => environment !== local);
- const recommendations = useAtomValue(
- serverEnvironment.databaseCompactionRecommendations(
-- JSON.stringify(environments.map((environment) => environment.environmentId)),
-+ JSON.stringify(remoteEnvironments.map((environment) => environment.environmentId)),
- ),
- );
-+ const localStorage = useAtomValue(
-+ local
-+ ? serverEnvironment.databaseStorage({ environmentId: local.environmentId, input: {} })
-+ : NO_LOCAL_DATABASE_STORAGE,
-+ );
-+ const localEnvironmentId = local?.environmentId;
-+ const [legacyDatabaseBytes, setLegacyDatabaseBytes] = useState(null);
-+ useEffect(() => {
-+ if (!maintenance || !localEnvironmentId) return;
-+ void maintenance.legacyDatabaseBytes().then(setLegacyDatabaseBytes);
-+ }, [maintenance, localEnvironmentId]);
- const [dismissed, setDismissed] = useLocalStorage(
- "database-storage-notice-dismissed",
- [],
- DismissedEnvironmentIds,
- );
- const { copyToClipboard } = useCopyToClipboard({ target: "command" });
-+ const [pending, setPending] = useState(false);
-+ const runMaintenance = async (reclaimSpace: boolean) => {
-+ if (!maintenance || pending) return;
-+ setPending(true);
-+ try {
-+ await maintenance.run({ reclaimSpace });
-+ setLegacyDatabaseBytes(await maintenance.legacyDatabaseBytes());
-+ } catch (error) {
-+ toastManager.add(
-+ stackedThreadToast({
-+ type: "error",
-+ title: "Could not start database cleanup",
-+ description:
-+ error instanceof Error ? error.message : "Try again after the local server reconnects.",
-+ }),
-+ );
-+ } finally {
-+ setPending(false);
-+ }
-+ };
-+
-+ const localStatus = localStorage._tag === "Success" ? localStorage.value : null;
-+ // Once converted, the server returns freed space to disk on its own.
-+ const reclaimSpace = localStatus !== null && !localStatus.incrementalVacuumEnabled;
-+ const showLocal = local !== undefined && (reclaimSpace || legacyDatabaseBytes !== null);
- const visible = recommendations.filter(
- (recommendation) => !dismissed.includes(recommendation.environmentId),
- );
-- if (visible.length === 0) return null;
-+ if (!showLocal && visible.length === 0) return null;
- return (
-
--
-+ {showLocal && (
-+
-+ {reclaimSpace &&
-+ `${formatSize(localStatus.reclaimableBytes)} of ${formatSize(localStatus.databaseBytes)} can be returned to disk. Reclaiming it once turns on automatic shrinking and restarts the local server.`}
-+ {reclaimSpace && legacyDatabaseBytes !== null && " "}
-+ {legacyDatabaseBytes !== null &&
-+ `The database from before 0.1.0 (${formatSize(legacyDatabaseBytes)}) is kept for rolling back.`}
-+ >
-+ }
-+ control={
-+
-+ }
-+ />
-+ )}
-+ {visible.length > 0 && (
-+
-+ )}
- {visible.map(({ environmentId, status }) => (
- Promise;
- onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
-+ /** The `t3 doctor` database repairs for this Flatpak desktop's local database. */
-+ databaseMaintenance?: {
-+ /** Size of the database kept from before 0.1.0 for rolling back, or null once it is gone. */
-+ legacyDatabaseBytes: () => Promise;
-+ /** Confirms, then reclaims space (restarting the server) and/or deletes the legacy database. */
-+ run: (input: { reclaimSpace: boolean }) => Promise;
-+ };
- cliCommand: {
- getState: () => Promise;
- install: () => Promise;
diff --git a/patches/0011-flatpak-legacy-database.patch b/patches/0011-flatpak-legacy-database.patch
new file mode 100644
index 0000000..493b344
--- /dev/null
+++ b/patches/0011-flatpak-legacy-database.patch
@@ -0,0 +1,269 @@
+diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+index 4808d16401..dc702af8f8 100644
+--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
++++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+@@ -85,6 +85,12 @@ import {
+ addCliCommandToPath,
+ } from "./methods/cliCommand.ts";
+
++import {
++ getLegacyDatabaseBytes,
++ getLegacyDatabaseSupported,
++ removeLegacyDatabase,
++} from "./methods/legacyDatabase.ts";
++
+ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
+ const ipc = yield* DesktopIpc.DesktopIpc;
+ yield* installNotificationBadge();
+@@ -94,6 +100,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
+ yield* ipc.handle(AppActivationIpc.complete);
+ yield* ipc.handle(WebLinksIpc.setReady);
+
++ yield* ipc.handleSync(getLegacyDatabaseSupported);
++ yield* ipc.handle(getLegacyDatabaseBytes);
++ yield* ipc.handle(removeLegacyDatabase);
+ yield* ipc.handleSync(takeLegacyLocalStorage);
+ yield* ipc.handle(completeLegacyLocalStorage);
+ yield* ipc.handleSync(getAppBranding);
+diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
+index dceb96e655..55da5a9d8c 100644
+--- a/apps/desktop/src/ipc/channels.ts
++++ b/apps/desktop/src/ipc/channels.ts
+@@ -133,3 +133,7 @@ export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-
+ export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback";
+ export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage";
+ export const COMPLETE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:complete-legacy-local-storage";
++
++export const LEGACY_DATABASE_SUPPORTED_CHANNEL = "desktop:legacy-database-supported";
++export const LEGACY_DATABASE_BYTES_CHANNEL = "desktop:legacy-database-bytes";
++export const LEGACY_DATABASE_REMOVE_CHANNEL = "desktop:legacy-database-remove";
+diff --git a/apps/desktop/src/ipc/methods/legacyDatabase.ts b/apps/desktop/src/ipc/methods/legacyDatabase.ts
+new file mode 100644
+index 0000000000..277e1908ca
+--- /dev/null
++++ b/apps/desktop/src/ipc/methods/legacyDatabase.ts
+@@ -0,0 +1,54 @@
++import * as HostProcess from "@t3tools/shared/HostProcess";
++import * as Effect from "effect/Effect";
++import * as FileSystem from "effect/FileSystem";
++import * as Schema from "effect/Schema";
++
++import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
++import { flatpakAppId } from "../../app/Flatpak.ts";
++import * as IpcChannels from "../channels.ts";
++import { makeIpcMethod, makeSyncIpcMethod } from "../DesktopIpc.ts";
++
++// Upstream deletes the database kept from before 0.1.0 only through `t3 doctor`, which the
++// Flatpak does not install. It sits in the app's own data, next to statev2.sqlite.
++const legacyDatabasePath = Effect.map(DesktopEnvironment.DesktopEnvironment, (environment) =>
++ environment.path.join(environment.stateDir, "state.sqlite"),
++);
++
++export const getLegacyDatabaseSupported = makeSyncIpcMethod({
++ channel: IpcChannels.LEGACY_DATABASE_SUPPORTED_CHANNEL,
++ result: Schema.Boolean,
++ handler: Effect.fn("desktop.ipc.legacyDatabase.supported")(function* () {
++ const environment = yield* DesktopEnvironment.DesktopEnvironment;
++ return flatpakAppId(yield* HostProcess.Environment, environment.platform) !== null;
++ }),
++});
++
++export const getLegacyDatabaseBytes = makeIpcMethod({
++ channel: IpcChannels.LEGACY_DATABASE_BYTES_CHANNEL,
++ payload: Schema.Void,
++ result: Schema.NullOr(Schema.Number),
++ handler: Effect.fn("desktop.ipc.legacyDatabase.bytes")(function* () {
++ const fs = yield* FileSystem.FileSystem;
++ return yield* fs.stat(yield* legacyDatabasePath).pipe(
++ Effect.map((info) => Number(info.size)),
++ Effect.orElseSucceed(() => null),
++ );
++ }),
++});
++
++export const removeLegacyDatabase = makeIpcMethod({
++ channel: IpcChannels.LEGACY_DATABASE_REMOVE_CHANNEL,
++ payload: Schema.Void,
++ result: Schema.Void,
++ handler: Effect.fn("desktop.ipc.legacyDatabase.remove")(function* () {
++ const fs = yield* FileSystem.FileSystem;
++ const legacy = yield* legacyDatabasePath;
++ // Only versions before 0.1.0 open it. As upstream does, delete the database before its WAL
++ // so a failed unlink keeps its commits.
++ yield* Effect.forEach(
++ ["", "-wal", "-shm"],
++ (suffix) => fs.remove(legacy + suffix, { force: true }),
++ { discard: true },
++ );
++ }),
++});
+diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
+index 045d6dba29..e19a6c373d 100644
+--- a/apps/desktop/src/preload.ts
++++ b/apps/desktop/src/preload.ts
+@@ -299,6 +299,14 @@ contextBridge.exposeInMainWorld("desktopBridge", {
+ downloadUpdate: () => ipcRenderer.invoke(IpcChannels.UPDATE_DOWNLOAD_CHANNEL),
+ installUpdate: (expectedVersion) =>
+ ipcRenderer.invoke(IpcChannels.UPDATE_INSTALL_CHANNEL, expectedVersion),
++ ...(ipcRenderer.sendSync(IpcChannels.LEGACY_DATABASE_SUPPORTED_CHANNEL) === true
++ ? {
++ legacyDatabase: {
++ bytes: () => ipcRenderer.invoke(IpcChannels.LEGACY_DATABASE_BYTES_CHANNEL),
++ remove: () => ipcRenderer.invoke(IpcChannels.LEGACY_DATABASE_REMOVE_CHANNEL),
++ },
++ }
++ : {}),
+ cliCommand: {
+ getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL),
+ install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL),
+diff --git a/apps/web/src/components/settings/DatabaseStorageNotice.tsx b/apps/web/src/components/settings/DatabaseStorageNotice.tsx
+index b9a0de493a..fee108569f 100644
+--- a/apps/web/src/components/settings/DatabaseStorageNotice.tsx
++++ b/apps/web/src/components/settings/DatabaseStorageNotice.tsx
+@@ -9,7 +9,7 @@ import {
+ type EnvironmentId,
+ } from "@t3tools/contracts";
+ import * as Schema from "effect/Schema";
+-import { type ReactNode, useState } from "react";
++import { type ReactNode, useEffect, useState } from "react";
+
+ import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
+ import { useLocalStorage } from "../../hooks/useLocalStorage";
+@@ -36,6 +36,7 @@ const reclaimPermissionsAtom = environmentAtomList(
+ );
+
+ const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
++const formatMiB = (bytes: number) => `${(bytes / 1024 ** 2).toFixed(0)} MiB`;
+
+ /** Offers to reclaim the space on every machine whose database still holds at least 1 GiB of freed pages. */
+ export function DatabaseStorageNotice({
+@@ -54,6 +55,12 @@ export function DatabaseStorageNotice({
+ DismissedEnvironmentIds,
+ );
+ const { copyToClipboard } = useCopyToClipboard({ target: "command" });
++ const legacyDatabase = window.desktopBridge?.legacyDatabase;
++ const [legacyDatabaseBytes, setLegacyDatabaseBytes] = useState(null);
++ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads a file size from the desktop app.
++ useEffect(() => {
++ void legacyDatabase?.bytes().then(setLegacyDatabaseBytes);
++ }, [legacyDatabase]);
+ const visible = recommendations
+ .filter((recommendation) => !dismissed.includes(recommendation.environmentId))
+ .map((recommendation) => ({
+@@ -66,17 +73,25 @@ export function DatabaseStorageNotice({
+ recommendation.status.canReclaim === true &&
+ permissions[environmentIds.indexOf(recommendation.environmentId)] === true,
+ }));
+- if (visible.length === 0) return null;
++ if (visible.length === 0 && legacyDatabaseBytes === null) return null;
+ return (
+
+- recommendation.reclaimable)
+- ? ""
+- : " Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment."
+- }`}
+- />
++ {legacyDatabase && legacyDatabaseBytes !== null && (
++ legacyDatabase.remove().then(() => setLegacyDatabaseBytes(null))}
++ />
++ )}
++ {visible.length > 0 && (
++ recommendation.reclaimable)
++ ? ""
++ : " Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment."
++ }`}
++ />
++ )}
+ {visible.map(({ environmentId, status, label, reclaimable }) => {
+ const dismiss = (
+
+ );
+ }
++
++function LegacyDatabaseRow({
++ bytes,
++ remove,
++}: {
++ readonly bytes: number;
++ readonly remove: () => Promise;
++}) {
++ const [confirming, setConfirming] = useState(false);
++ const [removing, setRemoving] = useState(false);
++ const start = async () => {
++ setConfirming(false);
++ setRemoving(true);
++ try {
++ await remove();
++ } catch (error) {
++ toastManager.add({
++ type: "error",
++ title: "Could not delete the old database",
++ description: error instanceof Error ? error.message : "An error occurred.",
++ });
++ } finally {
++ setRemoving(false);
++ }
++ };
++ return (
++
++
++
++
++
++ Delete the database from before 0.1.0?
++
++ Frees {formatMiB(bytes)}. Your threads and settings are already in the current
++ database. T3 Code versions before 0.1.0 will start with no threads or settings.
++
++
++
++ }>Cancel
++
++
++
++
++ >
++ }
++ />
++ );
++}
+diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
+index 29be3d6d02..03b4f4d363 100644
+--- a/packages/contracts/src/ipc.ts
++++ b/packages/contracts/src/ipc.ts
+@@ -1140,6 +1140,12 @@ export interface DesktopBridge {
+ /** With a version, installs only that downloaded build. */
+ installUpdate: (expectedVersion?: string) => Promise;
+ onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;
++ /** The Flatpak desktop's database from before 0.1.0, which it has no `t3 doctor` to delete. */
++ legacyDatabase?: {
++ /** Its size, or null once it is gone. */
++ bytes: () => Promise;
++ remove: () => Promise;
++ };
+ cliCommand: {
+ getState: () => Promise;
+ install: () => Promise;
diff --git a/patches/0012-flatpak-update-channel.patch b/patches/0012-flatpak-update-channel.patch
index 42eb1cc..2252b3d 100644
--- a/patches/0012-flatpak-update-channel.patch
+++ b/patches/0012-flatpak-update-channel.patch
@@ -15,10 +15,10 @@ index cc2cc4c537..7e5bdf2ac7 100644
Effect.scoped,
Effect.provide(harness.layer),
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
-index 637b0bc113..c8be030780 100644
+index 81ee76338d..cc607dfada 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
-@@ -1202,6 +1202,9 @@ export const make = Effect.gen(function* () {
+@@ -1204,6 +1204,9 @@ export const make = Effect.gen(function* () {
options?: { readonly minimumVersion?: string | undefined },
) {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
@@ -29,10 +29,10 @@ index 637b0bc113..c8be030780 100644
return yield* new DesktopUpdateChannelManagedError({
channel: nextChannel,
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
-index 362210f96e..20e160eafd 100644
+index 00bdcf6cf5..d985b4801d 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
-@@ -347,6 +347,8 @@ function AboutVersionSection() {
+@@ -352,6 +352,8 @@ function AboutVersionSection() {
Review
>
@@ -41,7 +41,7 @@ index 362210f96e..20e160eafd 100644
) : (
"Switches this app and every connected machine whose database the target release supports."
)
-@@ -355,6 +357,7 @@ function AboutVersionSection() {
+@@ -360,6 +362,7 @@ function AboutVersionSection() {
control={