Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): back up settings and notification sounds (#100534)

Paul D'Ambra8cb583f36fa2
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index 48fe1bc59d2f..df2e38d7322c 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -136,6 +136,10 @@ import type { MAIN_WINDOW_SERVICE } from "@posthog/platform/main-window";
import type { NOTIFIER_SERVICE } from "@posthog/platform/notifier";
import type { POWER_MANAGER_SERVICE } from "@posthog/platform/power-manager";
import type { SECURE_STORAGE_SERVICE } from "@posthog/platform/secure-storage";
+import type {
+ ISettingsBackupFiles,
+ SETTINGS_BACKUP_FILES,
+} from "@posthog/platform/settings-backup-files";
import type { STORAGE_PATHS_SERVICE } from "@posthog/platform/storage-paths";
import type { UPDATER_SERVICE } from "@posthog/platform/updater";
import type { URL_LAUNCHER_SERVICE } from "@posthog/platform/url-launcher";
@@ -331,6 +335,7 @@ import type {
} from "./tokens";
export interface MainBindings {
+ [SETTINGS_BACKUP_FILES]: ISettingsBackupFiles;
// Platform adapters
[URL_LAUNCHER_SERVICE]: ElectronUrlLauncher;
[STORAGE_PATHS_SERVICE]: ElectronStoragePaths;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index f4f8e267d428..d13f484d3bd8 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -1,3 +1,5 @@
+import { SETTINGS_BACKUP_FILES } from "@posthog/platform/settings-backup-files";
+import { ElectronSettingsBackupFiles } from "../platform-adapters/electron-settings-backup-files";
import "reflect-metadata";
import { readFile as fsReadFile, stat as fsStat } from "node:fs/promises";
@@ -359,6 +361,7 @@ container.bind(URL_LAUNCHER_SERVICE).to(ElectronUrlLauncher);
container.bind(STORAGE_PATHS_SERVICE).to(ElectronStoragePaths);
container.bind(APP_META_SERVICE).to(ElectronAppMeta);
container.bind(DIALOG_SERVICE).to(ElectronDialog);
+container.bind(SETTINGS_BACKUP_FILES).to(ElectronSettingsBackupFiles);
container.bind(CLIPBOARD_SERVICE).to(ElectronClipboard);
container.bind(CRYPTO_SERVICE).to(ElectronCrypto);
container.bind(ANALYTICS_SERVICE).toConstantValue(posthogNodeAnalytics);
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-dialog.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-dialog.ts
index 6a42dd37f1e2..ba8cb3a92298 100644
--- a/products/desktop/apps/code/src/main/platform-adapters/electron-dialog.ts
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-dialog.ts
@@ -28,7 +28,7 @@ function severityToType(severity?: DialogSeverity): MessageBoxOptions["type"] {
* completely unresponsive to the user. Fall back to a visible window and focus
* it so the dialog is always parented to and rendered on top of a real window.
*/
-function resolveDialogParent(): BrowserWindow | null {
+export function resolveDialogParent(): BrowserWindow | null {
const focused = BrowserWindow.getFocusedWindow();
if (focused) return focused;
const windows = BrowserWindow.getAllWindows();
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.test.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.test.ts
new file mode 100644
index 000000000000..f45868a92835
--- /dev/null
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.test.ts
@@ -0,0 +1,181 @@
+// @vitest-environment node
+import "reflect-metadata";
+import * as fsPromises from "node:fs/promises";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const dialogs = vi.hoisted(() => ({
+ showOpenDialog: vi.fn(),
+ showSaveDialog: vi.fn(),
+}));
+vi.mock("electron", () => ({
+ app: { getVersion: () => "1.2.3" },
+ dialog: dialogs,
+ BrowserWindow: { getFocusedWindow: () => null, getAllWindows: () => [] },
+}));
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs/promises")>();
+ return { ...actual, rename: vi.fn(actual.rename) };
+});
+
+import { ElectronSettingsBackupFiles } from "./electron-settings-backup-files";
+
+const directories: string[] = [];
+afterEach(async () => {
+ await Promise.all(
+ directories
+ .splice(0)
+ .map((path) => rm(path, { recursive: true, force: true })),
+ );
+ vi.clearAllMocks();
+});
+
+describe("ElectronSettingsBackupFiles", () => {
+ it("saves and reads the complete backup through the selected native paths", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ const filePath = join(directory, "settings.json");
+ await writeFile(filePath, "old backup");
+ dialogs.showSaveDialog.mockResolvedValue({ canceled: false, filePath });
+ dialogs.showOpenDialog.mockResolvedValue({
+ canceled: false,
+ filePaths: [filePath],
+ });
+ const files = new ElectronSettingsBackupFiles();
+ const contents = JSON.stringify({
+ sounds: [
+ { name: "Test chime", dataUrl: "data:audio/wav;base64,UklGRg==" },
+ ],
+ });
+ expect(
+ await files.save({
+ contents,
+ defaultName: "posthog-settings-2026-01-01.json",
+ }),
+ ).toBe(true);
+ expect(await readFile(filePath, "utf8")).toBe(contents);
+ expect(await files.open()).toBe(contents);
+ });
+
+ it("replaces an existing backup on Windows even when rename first refuses to overwrite it", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ const filePath = join(directory, "settings.json");
+ await writeFile(filePath, "old backup");
+ dialogs.showSaveDialog.mockResolvedValue({ canceled: false, filePath });
+ const rename = vi.mocked(fsPromises.rename);
+ rename.mockImplementationOnce(async () => {
+ throw Object.assign(new Error("EPERM"), { code: "EPERM" });
+ });
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, "platform", { value: "win32" });
+ try {
+ const files = new ElectronSettingsBackupFiles();
+ expect(
+ await files.save({
+ contents: "new backup",
+ defaultName: "backup.json",
+ }),
+ ).toBe(true);
+ } finally {
+ Object.defineProperty(process, "platform", { value: originalPlatform });
+ }
+ expect(await readFile(filePath, "utf8")).toBe("new backup");
+ });
+
+ it("restores the existing backup if the Windows retry also fails", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ const filePath = join(directory, "settings.json");
+ await writeFile(filePath, "old backup");
+ dialogs.showSaveDialog.mockResolvedValue({ canceled: false, filePath });
+ const rename = vi.mocked(fsPromises.rename);
+ const { rename: realRename } =
+ await vi.importActual<typeof import("node:fs/promises")>(
+ "node:fs/promises",
+ );
+ let attemptsOntoDestination = 0;
+ rename.mockImplementation(async (from, to, ...rest) => {
+ // Moving the existing backup aside, and restoring it, are real; only
+ // the rename of the new temp file onto the destination is faked, for
+ // both the initial attempt and the retry.
+ if (typeof from !== "string" || !from.endsWith(".tmp"))
+ return realRename(from, to, ...rest);
+ attemptsOntoDestination++;
+ throw Object.assign(new Error(`attempt ${attemptsOntoDestination}`), {
+ code: attemptsOntoDestination === 1 ? "EPERM" : "EBUSY",
+ });
+ });
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, "platform", { value: "win32" });
+ try {
+ const files = new ElectronSettingsBackupFiles();
+ await expect(
+ files.save({ contents: "new backup", defaultName: "backup.json" }),
+ ).rejects.toThrow("(EBUSY)");
+ } finally {
+ Object.defineProperty(process, "platform", { value: originalPlatform });
+ rename.mockImplementation(realRename);
+ }
+ expect(await readFile(filePath, "utf8")).toBe("old backup");
+ });
+
+ it("reports a read failure by its code, without the chosen path", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ dialogs.showOpenDialog.mockResolvedValue({
+ canceled: false,
+ filePaths: [join(directory, "missing.json")],
+ });
+ const files = new ElectronSettingsBackupFiles();
+
+ const message = await files.open().then(
+ () => "",
+ (error: Error) => error.message,
+ );
+
+ expect(message).toContain("(ENOENT)");
+ expect(message).not.toContain(directory);
+ });
+
+ it("reports a save failure by its code, without the chosen path", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ const filePath = join(directory, "settings.json");
+ dialogs.showSaveDialog.mockResolvedValue({ canceled: false, filePath });
+ vi.mocked(fsPromises.rename).mockImplementationOnce(async (from, to) => {
+ throw Object.assign(
+ new Error(
+ `EACCES: permission denied, rename '${String(from)}' -> '${String(to)}'`,
+ ),
+ { code: "EACCES", syscall: "rename" },
+ );
+ });
+ const files = new ElectronSettingsBackupFiles();
+
+ const message = await files
+ .save({ contents: "new backup", defaultName: "backup.json" })
+ .then(
+ () => "",
+ (error: Error) => error.message,
+ );
+
+ expect(message).toContain("(EACCES)");
+ expect(message).not.toContain(directory);
+ });
+
+ it("leaves an existing backup untouched when the save dialog is canceled", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "posthog-backup-test-"));
+ directories.push(directory);
+ const filePath = join(directory, "settings.json");
+ await writeFile(filePath, "keep this backup");
+ dialogs.showSaveDialog.mockResolvedValue({ canceled: true, filePath });
+ const files = new ElectronSettingsBackupFiles();
+ expect(
+ await files.save({ contents: "replacement", defaultName: "backup.json" }),
+ ).toBe(false);
+ expect(await readFile(filePath, "utf8")).toBe("keep this backup");
+ });
+});
diff --git a/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.ts b/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.ts
new file mode 100644
index 000000000000..8a11d990dbf7
--- /dev/null
+++ b/products/desktop/apps/code/src/main/platform-adapters/electron-settings-backup-files.ts
@@ -0,0 +1,161 @@
+import { randomUUID } from "node:crypto";
+import { open, rename, unlink, writeFile } from "node:fs/promises";
+import { MAX_SETTINGS_BACKUP_BYTES } from "@posthog/core/settings/schemas";
+import type { ISettingsBackupFiles } from "@posthog/platform/settings-backup-files";
+import { app, dialog } from "electron";
+import { injectable } from "inversify";
+import { resolveDialogParent } from "./electron-dialog";
+
+/** A failure this adapter describes itself. The message carries no file path. */
+class BackupFileError extends Error {}
+
+/**
+ * Node file-system errors embed the operand paths, and a thrown message crosses
+ * the tRPC boundary into the error log that ships to log ingestion. Report the
+ * error code instead, so the path the user picked in the dialog stays on this
+ * machine. Failures this adapter describes itself already carry no path, so
+ * they pass through with their guidance intact.
+ */
+function describeFailure(
+ error: unknown,
+ action: string,
+ guidance: string,
+): Error {
+ if (error instanceof BackupFileError) return error;
+ const code = (error as NodeJS.ErrnoException | null)?.code;
+ return new BackupFileError(
+ `Could not ${action}${typeof code === "string" ? ` (${code})` : ""}. ${guidance}`,
+ );
+}
+
+@injectable()
+export class ElectronSettingsBackupFiles implements ISettingsBackupFiles {
+ async getAppVersion(): Promise<string> {
+ return app.getVersion();
+ }
+
+ async open(): Promise<string | null> {
+ const parent = resolveDialogParent();
+ const options = {
+ title: "Import settings and sounds",
+ filters: [{ name: "PostHog backup", extensions: ["json"] }],
+ properties: ["openFile" as const],
+ };
+ const result = parent
+ ? await dialog.showOpenDialog(parent, options)
+ : await dialog.showOpenDialog(options);
+ if (result.canceled || !result.filePaths[0]) return null;
+ try {
+ return await this.read(result.filePaths[0]);
+ } catch (error) {
+ throw describeFailure(
+ error,
+ "read the backup file",
+ "Check that the file still exists and try again.",
+ );
+ }
+ }
+
+ private async read(path: string): Promise<string> {
+ const file = await open(path, "r");
+ try {
+ const stat = await file.stat();
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BACKUP_BYTES)
+ throw new BackupFileError(
+ "Choose a PostHog backup file of 64 MB or less.",
+ );
+ // Bound the read even if another process grows the file after stat().
+ const buffer = Buffer.alloc(stat.size + 1);
+ let size = 0;
+ while (size < buffer.length) {
+ const { bytesRead } = await file.read(
+ buffer,
+ size,
+ buffer.length - size,
+ null,
+ );
+ if (bytesRead === 0) break;
+ size += bytesRead;
+ }
+ if (size > stat.size)
+ throw new BackupFileError(
+ "The backup changed while it was being read. Choose the file again.",
+ );
+ return buffer.subarray(0, size).toString("utf8");
+ } finally {
+ await file.close();
+ }
+ }
+
+ async save(input: {
+ contents: string;
+ defaultName: string;
+ }): Promise<boolean> {
+ if (Buffer.byteLength(input.contents, "utf8") > MAX_SETTINGS_BACKUP_BYTES)
+ throw new Error(
+ "This backup exceeds 64 MB. Remove unused clips and try again.",
+ );
+ const parent = resolveDialogParent();
+ const options = {
+ title: "Export settings and sounds",
+ defaultPath: input.defaultName,
+ filters: [{ name: "PostHog backup", extensions: ["json"] }],
+ // Without this, the Linux dialog can replace the chosen file with no prompt.
+ properties: ["showOverwriteConfirmation" as const],
+ };
+ const result = parent
+ ? await dialog.showSaveDialog(parent, options)
+ : await dialog.showSaveDialog(options);
+ if (result.canceled || !result.filePath) return false;
+ const temporary = `${result.filePath}.${randomUUID()}.tmp`;
+ try {
+ // fsync before the rename below replaces the user's previous backup.
+ await writeFile(temporary, input.contents, {
+ encoding: "utf8",
+ mode: 0o600,
+ flag: "wx",
+ flush: true,
+ });
+ await this.replace(temporary, result.filePath);
+ } catch (error) {
+ throw describeFailure(
+ error,
+ "save the backup",
+ "Check available disk space and folder permissions, then try again.",
+ );
+ } finally {
+ await unlink(temporary).catch(() => {});
+ }
+ return true;
+ }
+
+ /**
+ * Windows can refuse to rename onto an existing file (EPERM/EEXIST) even
+ * though the save dialog already confirmed the overwrite; POSIX rename
+ * replaces the destination outright. Move the existing destination aside
+ * rather than deleting it outright, so a retry that also fails still has
+ * something to restore instead of losing both the old and new backups.
+ */
+ private async replace(temporary: string, destination: string): Promise<void> {
+ try {
+ await rename(temporary, destination);
+ return;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (
+ process.platform !== "win32" ||
+ (code !== "EPERM" && code !== "EEXIST")
+ )
+ throw error;
+ }
+ const recovery = `${destination}.${randomUUID()}.bak`;
+ await rename(destination, recovery);
+ try {
+ await rename(temporary, destination);
+ } catch (error) {
+ await rename(recovery, destination).catch(() => {});
+ throw error;
+ }
+ await unlink(recovery).catch(() => {});
+ }
+}
diff --git a/products/desktop/apps/code/src/main/services/speech/service.test.ts b/products/desktop/apps/code/src/main/services/speech/service.test.ts
new file mode 100644
index 000000000000..8173ca11bfec
--- /dev/null
+++ b/products/desktop/apps/code/src/main/services/speech/service.test.ts
@@ -0,0 +1,32 @@
+import "reflect-metadata";
+import type { ISecureStoreService } from "@posthog/workspace-server/services/secure-store/identifiers";
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("@main/utils/logger", () => ({
+ logger: { scope: () => ({ info: vi.fn(), warn: vi.fn() }) },
+}));
+
+import { ElevenLabsSpeechService } from "./service";
+
+describe("ElevenLabsSpeechService", () => {
+ it("keeps the voice id inside one path segment", async () => {
+ const fetchMock = vi.fn(
+ async (_url: string) => new Response(new ArrayBuffer(8), { status: 200 }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const secureStore = {
+ getItem: () => "test-key",
+ } as unknown as ISecureStoreService;
+
+ await new ElevenLabsSpeechService(secureStore).synthesize(
+ "hello",
+ "../convai/knowledge-base/text",
+ );
+
+ const url = new URL(fetchMock.mock.calls[0][0]);
+ expect(url.origin).toBe("https://api.elevenlabs.io");
+ expect(url.pathname).toBe(
+ "/v1/text-to-speech/..%2Fconvai%2Fknowledge-base%2Ftext",
+ );
+ });
+});
diff --git a/products/desktop/apps/code/src/main/services/speech/service.ts b/products/desktop/apps/code/src/main/services/speech/service.ts
index a9ef588887cb..3b3df03251ba 100644
--- a/products/desktop/apps/code/src/main/services/speech/service.ts
+++ b/products/desktop/apps/code/src/main/services/speech/service.ts
@@ -63,7 +63,10 @@ export class ElevenLabsSpeechService implements ISpeechSynthesizer {
);
try {
const res = await fetch(
- `https://api.elevenlabs.io/v1/text-to-speech/${voice}?output_format=${OUTPUT_FORMAT}`,
+ // Encode the voice so it stays one path segment. An unencoded value
+ // could add segments or a query string and move this authenticated
+ // request to a different ElevenLabs route.
+ `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}?output_format=${OUTPUT_FORMAT}`,
{
method: "POST",
headers: { "xi-api-key": apiKey, "content-type": "application/json" },
diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.ts
index b472921401e8..1c17b548bd0d 100644
--- a/products/desktop/apps/code/src/main/trpc/router.ts
+++ b/products/desktop/apps/code/src/main/trpc/router.ts
@@ -44,6 +44,7 @@ import { processTrackingRouter } from "@posthog/host-router/routers/process-trac
import { provisioningRouter } from "@posthog/host-router/routers/provisioning.router";
import { releaseFeedRouter } from "@posthog/host-router/routers/release-feed.router";
import { secureStoreRouter } from "@posthog/host-router/routers/secure-store.router";
+import { settingsBackupRouter } from "@posthog/host-router/routers/settings-backup.router";
import { shellRouter } from "@posthog/host-router/routers/shell.router";
import { skillsRouter } from "@posthog/host-router/routers/skills.router";
import { slackIntegrationRouter } from "@posthog/host-router/routers/slack-integration.router";
@@ -106,6 +107,7 @@ export const trpcRouter = router({
oauth: oauthRouter,
logs: logsRouter,
os: osRouter,
+ settingsBackup: settingsBackupRouter,
piSession: piSessionRouter,
processTracking: processTrackingRouter,
provisioning: provisioningRouter,
diff --git a/products/desktop/apps/code/src/renderer/desktop-services.ts b/products/desktop/apps/code/src/renderer/desktop-services.ts
index cec9a612180a..c4859689032e 100644
--- a/products/desktop/apps/code/src/renderer/desktop-services.ts
+++ b/products/desktop/apps/code/src/renderer/desktop-services.ts
@@ -1,3 +1,4 @@
+import { SETTINGS_BACKUP_FILES } from "@posthog/platform/settings-backup-files";
import { CLAUDE_SUBSCRIPTION_TOKEN_SETTINGS } from "@posthog/ui/features/settings/claudeSubscriptionTokenSettings";
// Desktop host service bindings live here as features move into packages.
// Importing the renderer container performs today's existing bindings.
@@ -462,3 +463,9 @@ container.bind(HOST_CAPABILITIES).toConstantValue({
} satisfies HostCapabilities);
container.bind(DISK_CACHE_IMAGES).toConstantValue(desktopDiskCacheImages);
+
+container.bind(SETTINGS_BACKUP_FILES).toConstantValue({
+ getAppVersion: () => hostTrpcClient.os.getAppVersion.query(),
+ open: () => hostTrpcClient.settingsBackup.open.mutate(),
+ save: (input) => hostTrpcClient.settingsBackup.save.mutate(input),
+});
diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.ts
index 3a98bb83c04f..cf1f271fa6d3 100644
--- a/products/desktop/apps/code/src/renderer/di/bindings.ts
+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts
@@ -169,6 +169,10 @@ import {
type INotifications,
NOTIFICATIONS_SERVICE,
} from "@posthog/platform/notifications";
+import type {
+ ISettingsBackupFiles,
+ SETTINGS_BACKUP_FILES,
+} from "@posthog/platform/settings-backup-files";
import { type ISpeech, SPEECH_SERVICE } from "@posthog/platform/speech";
import {
AUTH_SIDE_EFFECTS,
@@ -299,6 +303,7 @@ import { TASK_SERVICE as RENDERER_TASK_SERVICE, TRPC_CLIENT } from "./tokens";
* ContainerModules without typing their internal bindings).
*/
export interface RendererBindings {
+ [SETTINGS_BACKUP_FILES]: ISettingsBackupFiles;
// --- di/container.ts ---
[HOST_LOGGER]: HostLogger;
[TRPC_CLIENT]: TRPCClient<TrpcRouter>;
diff --git a/products/desktop/docs/SETTINGS-BACKUP.md b/products/desktop/docs/SETTINGS-BACKUP.md
new file mode 100644
index 000000000000..efbecfd4d20c
--- /dev/null
+++ b/products/desktop/docs/SETTINGS-BACKUP.md
@@ -0,0 +1,51 @@
+# Back up settings and sounds
+
+The section is behind the `posthog-desktop-settings-backup` feature flag while it rolls out.
+When the flag is off, the section and its search entry are hidden.
+
+Open **Settings → Advanced → Back up settings and sounds**.
+Choose **Settings and sounds** or **Sounds only**, then select **Export backup** and choose where to save the JSON file.
+Copy the file to the other machine and use **Import backup** in the same section.
+Review the export version, the names of the settings the import writes, warnings, and sound previews, then select **Import settings and sounds** or **Import sounds**.
+When the backup carries custom instructions, the review shows the text that will replace yours, because the agent reads those instructions in every task.
+A backup with empty or missing custom instructions leaves the instructions on this machine unchanged.
+Canceling the file picker or the review leaves your settings unchanged.
+
+Custom sounds are embedded in the file, including their names and audio, so you do not need to copy the original recordings separately.
+Both export options include the selected completion sound, volume, and the setting that scales playback with task length.
+Import keeps existing custom sounds, skips clips already imported, and preserves both clips when their IDs collide.
+It updates the selected sound to use the imported clip's new ID when needed.
+Settings missing from a backup keep their current values.
+
+The full backup includes the portable preferences in the main settings store: task and model defaults, notifications, composer behavior, custom instructions, diff display, terminal appearance, and Advanced toggles, plus the theme.
+It excludes accounts and API keys, subscription connections, server-managed settings, workspace and repository paths, cached selections tied to a repository, system shortcuts, power settings, and onboarding history.
+It also excludes bypass-permissions mode and spend limits, since both are machine-local safety controls that normally require their own explicit confirmation; a backup file cannot enable bypass mode or clear a spend cap on the destination machine.
+Custom instruction file syncing stays configured on each machine; the files themselves are not included.
+A custom terminal font must also be installed on the destination machine.
+The backup is a readable JSON file and includes any text you put in custom instructions.
+
+Backups record the exporting app version and a separate file format version.
+Import warns when the app versions differ, skips unavailable settings or unsupported values, and lists invalid sound entries.
+A missing or invalid selected clip leaves the destination's current sound selection unchanged.
+A newer file format requires an app update before import.
+Backups are limited to 64 MB; each custom sound retains the existing 1 MB and 5-second capture limits, with the same allowance for encoder rounding.
+A backup can contain at most 1,000 sound entries and 1,000 settings entries, so malformed files cannot produce an unbounded review list.
+
+## Maintaining the format
+
+`packages/core/src/settings/schemas.ts` defines the explicit allowlist and validators for portable settings.
+When a preference is added, changed, or removed, update this contract alongside its settings UI and persistence.
+Unknown fields and invalid values are skipped individually; missing values are never replaced with defaults.
+If a change cannot be represented compatibly, bump the file format version and add a migration before accepting it.
+Keep app version metadata independent of the file format version.
+
+The core service owns validation and merging, the UI supplies a store adapter, and Electron supplies native file dialogs and bounded file reads.
+Exports write to a temporary sibling file before replacing the destination.
+Export reads the current settings when you start it.
+Import merges the validated backup with the current sound library when you confirm it, then updates the settings and theme stores.
+The existing persistence code saves those changes in the same way as changes made with the settings controls.
+Import does not wait for a separate disk write before it reports success.
+
+The UI reports each finished operation to analytics: `Settings backup exported`, `Settings backup export failed`, `Settings backup imported`, and `Settings backup import failed`.
+The events carry the chosen scope, counts, and the error message the user saw. They carry no file path, setting value, or sound audio.
+A closed file dialog reports nothing, because it is neither a success nor a failure.
diff --git a/products/desktop/packages/core/src/settings/schemas.ts b/products/desktop/packages/core/src/settings/schemas.ts
new file mode 100644
index 000000000000..2ac61ba10531
--- /dev/null
+++ b/products/desktop/packages/core/src/settings/schemas.ts
@@ -0,0 +1,177 @@
+import { z } from "zod";
+import {
+ AUTO_COMPACT_MAX_PERCENT,
+ AUTO_COMPACT_MIN_PERCENT,
+} from "../sessions/autoCompact";
+
+export const SETTINGS_BACKUP_FORMAT_VERSION = 1;
+export const MAX_SETTINGS_BACKUP_BYTES = 64 * 1024 * 1024;
+export const MAX_SETTINGS_BACKUP_ENTRIES = 1_000;
+export const MAX_CUSTOM_SOUND_BYTES = 1_000_000;
+export const MAX_CUSTOM_SOUND_DURATION_MS = 5_000;
+export const DURATION_TOLERANCE_MS = 300;
+
+export const completionSoundSchema = z.union([
+ z.enum([
+ "none",
+ "guitar",
+ "danilo",
+ "revi",
+ "meep",
+ "meep-smol",
+ "bubbles",
+ "drop",
+ "knock",
+ "ring",
+ "shoot",
+ "slide",
+ "switch",
+ "wilhelm",
+ "icq",
+ "msn",
+ "random-all",
+ "random-custom",
+ ]),
+ z
+ .string()
+ .regex(/^custom:.+$/)
+ .transform((value) => value as `custom:${string}`),
+]);
+
+const audioDataUrlSchema = z
+ .string()
+ .max(Math.ceil(MAX_CUSTOM_SOUND_BYTES / 3) * 4 + 200)
+ .refine((value) => {
+ const match =
+ /^data:(?:audio\/[a-z0-9.+-]+|application\/octet-stream)(?:;codecs=[a-z0-9.,-]+)?;base64,([A-Za-z0-9+/]+={0,2})$/i.exec(
+ value,
+ );
+ if (!match || !match[1] || match[1].length % 4 !== 0) return false;
+ const data = match[1];
+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;
+ return (data.length * 3) / 4 - padding <= MAX_CUSTOM_SOUND_BYTES;
+ }, "Expected embedded audio of 1 MB or less");
+
+export const customSoundSchema = z.object({
+ id: z.string().min(1).max(256),
+ name: z.string().min(1).max(256),
+ dataUrl: audioDataUrlSchema,
+ durationMs: z
+ .number()
+ .positive()
+ .max(MAX_CUSTOM_SOUND_DURATION_MS + DURATION_TOLERANCE_MS),
+});
+export type CustomSound = z.infer<typeof customSoundSchema>;
+export type CompletionSound = z.infer<typeof completionSoundSchema>;
+
+const text = z.string().max(20_000);
+const nullableText = text.nullable();
+const messagingMode = z.enum(["queue", "steer"]);
+// The voice ID goes into the ElevenLabs request path. Reject URL delimiters and
+// control characters so an imported backup cannot point the authenticated
+// request at another ElevenLabs route. An empty value selects the default voice.
+const voiceId = z
+ .string()
+ .max(64)
+ .regex(/^[A-Za-z0-9_-]*$/);
+
+// This allowlist is the portable contract. Account state, credentials, caches,
+// paths and preferences owned by the operating system must not cross machines.
+// Machine-local safety controls stay off it too, even though they are
+// preferences: allowBypassPermissions normally requires an explicit consent
+// dialog, and spendLimits guards against runaway spend, so a backup file must
+// not be able to change either without the user seeing it happen.
+// spokenNotifications and debugLogsCloudRuns stay off it as well: their
+// controls sit behind rollout flags, so a backup could switch them on where
+// the user has no control to switch them off.
+export const portableSettingsSchema = z
+ .object({
+ theme: z.enum(["light", "dark", "system"]),
+ defaultRunMode: z.enum(["local", "cloud", "last_used"]),
+ lastUsedRunMode: z.enum(["local", "cloud"]),
+ lastUsedLocalWorkspaceMode: z.enum(["worktree", "local"]),
+ lastUsedWorkspaceMode: z.enum(["worktree", "local", "cloud"]),
+ lastUsedAgentRuntime: z.enum(["acp", "pi"]),
+ lastUsedAdapter: z.enum(["claude", "codex"]),
+ lastUsedModel: nullableText,
+ lastUsedPiModel: nullableText,
+ lastUsedReasoningEffort: nullableText,
+ lastUsedContextWindow: z.enum(["200k", "1m"]).nullable(),
+ lastUsedFastMode: z.boolean().nullable(),
+ defaultInitialTaskMode: z.enum(["plan", "last_used"]),
+ defaultReasoningEffort: z.enum([
+ "last_used",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultracode",
+ ]),
+ defaultMessagingMode: messagingMode,
+ defaultCloudMessagingMode: messagingMode,
+ desktopNotifications: z.boolean(),
+ dockBadgeNotifications: z.boolean(),
+ dockBounceNotifications: z.boolean(),
+ toastNotifications: z.boolean(),
+ completionSound: completionSoundSchema,
+ completionVolume: z.number().min(0).max(100),
+ scaleSoundWithTaskLength: z.boolean(),
+ spokenNotifyNeedsInput: z.boolean(),
+ spokenNotifyCompletion: z.boolean(),
+ spokenNotifyProgress: z.boolean(),
+ spokenFocusMode: z.enum(["always", "unviewed_task", "app_unfocused"]),
+ elevenLabsVoiceId: voiceId,
+ autoConvertLongText: z.enum(["off", "1000", "2500", "5000", "10000"]),
+ sendMessagesWith: z.enum(["enter", "cmd+enter"]),
+ customInstructions: text,
+ ste100Enabled: z.boolean(),
+ diffOpenMode: z.enum(["auto", "split", "same-pane", "last-active-pane"]),
+ warnOnMidSessionModelSwitch: z.boolean(),
+ autoCompactPercent: z
+ .number()
+ .min(AUTO_COMPACT_MIN_PERCENT)
+ .max(AUTO_COMPACT_MAX_PERCENT)
+ .nullable(),
+ autoPublishCloudRuns: z.boolean(),
+ rtkEnabledLocal: z.boolean(),
+ rtkEnabledCloud: z.boolean(),
+ terminalFont: z.enum([
+ "berkeley-mono",
+ "jetbrains-mono",
+ "system",
+ "custom",
+ ]),
+ terminalCustomFontFamily: text,
+ terminalGpuRendering: z.boolean(),
+ showSidebarWorktrees: z.boolean(),
+ hedgehogMode: z.boolean(),
+ slotMachineMode: z.boolean(),
+ brainrotMode: z.boolean(),
+ downloadUpdatesAutomatically: z.boolean(),
+ dismissibleUpdateBanners: z.boolean(),
+ tipsEnabled: z.boolean(),
+ })
+ .partial();
+export type PortableSettings = z.infer<typeof portableSettingsSchema>;
+
+export const settingsBackupSchema = z.object({
+ format: z.literal("posthog-desktop-settings"),
+ formatVersion: z.number().int().positive(),
+ appVersion: z.string().min(1).max(100),
+ exportedAt: z.iso.datetime(),
+ settings: z
+ .record(z.string().max(256), z.unknown())
+ .refine(
+ (settings) => Object.keys(settings).length <= MAX_SETTINGS_BACKUP_ENTRIES,
+ ),
+ sounds: z.array(z.unknown()).max(MAX_SETTINGS_BACKUP_ENTRIES),
+});
+export type SettingsBackup = z.infer<typeof settingsBackupSchema>;
+
+export const saveSettingsBackupInput = z.object({
+ contents: z.string().max(MAX_SETTINGS_BACKUP_BYTES),
+ defaultName: z
+ .string()
+ .regex(/^posthog-(?:settings|sounds)-\d{4}-\d{2}-\d{2}\.json$/),
+});
diff --git a/products/desktop/packages/core/src/settings/settingsBackup.test.ts b/products/desktop/packages/core/src/settings/settingsBackup.test.ts
new file mode 100644
index 000000000000..5dd6b07c19f9
--- /dev/null
+++ b/products/desktop/packages/core/src/settings/settingsBackup.test.ts
@@ -0,0 +1,386 @@
+import "reflect-metadata";
+import type { ISettingsBackupFiles } from "@posthog/platform/settings-backup-files";
+import { describe, expect, it, vi } from "vitest";
+import {
+ type CustomSound,
+ MAX_CUSTOM_SOUND_BYTES,
+ type SettingsBackup,
+} from "./schemas";
+import {
+ SettingsBackupService,
+ type SettingsBackupSnapshot,
+} from "./settingsBackup";
+
+const clip = (overrides: Partial<CustomSound> = {}): CustomSound => ({
+ id: "clip-a",
+ name: "My chime",
+ dataUrl: "data:audio/wav;base64,UklGRg==",
+ durationMs: 1000,
+ ...overrides,
+});
+const backup = (overrides: Partial<SettingsBackup> = {}): SettingsBackup => ({
+ format: "posthog-desktop-settings",
+ formatVersion: 1,
+ appVersion: "1.0.0",
+ exportedAt: "2026-01-01T12:00:00.000Z",
+ settings: {
+ completionSound: "custom:clip-a",
+ completionVolume: 65,
+ scaleSoundWithTaskLength: true,
+ theme: "dark",
+ },
+ sounds: [clip()],
+ ...overrides,
+});
+
+function setup(
+ initial: SettingsBackupSnapshot = {
+ settings: { theme: "light", completionSound: "none" },
+ sounds: [],
+ },
+) {
+ let snapshot = initial;
+ let saved = "";
+ const files: ISettingsBackupFiles = {
+ getAppVersion: async () => "2.0.0",
+ open: async () => saved,
+ save: async ({ contents }) => {
+ saved = contents;
+ return true;
+ },
+ };
+ const apply = vi.fn((patch: SettingsBackupSnapshot) => {
+ snapshot = {
+ settings: { ...snapshot.settings, ...patch.settings },
+ sounds: patch.sounds,
+ };
+ });
+ const service = new SettingsBackupService(
+ { read: () => snapshot, apply },
+ files,
+ );
+ const rename = (from: string, to: string) => {
+ snapshot = {
+ ...snapshot,
+ sounds: snapshot.sounds.map((sound) =>
+ sound.name === from ? { ...sound, name: to } : sound,
+ ),
+ };
+ };
+ return {
+ service,
+ files,
+ apply,
+ rename,
+ read: () => snapshot,
+ saved: () => saved,
+ };
+}
+
+describe("SettingsBackupService", () => {
+ it("round-trips embedded clips, names, selection and playback settings onto a fresh machine", async () => {
+ const source = setup({
+ settings: {
+ ...backup().settings,
+ customInstructions: "Use short sentences.",
+ },
+ sounds: [
+ clip(),
+ clip({
+ id: "clip-b",
+ name: "Second chime",
+ dataUrl: "data:audio/webm;codecs=opus;base64,AQID",
+ }),
+ ],
+ });
+ await source.service.exportBackup("all");
+ const exported = JSON.parse(source.saved());
+ expect(exported).toMatchObject({ appVersion: "2.0.0", formatVersion: 1 });
+ const target = setup();
+ const review = target.service.inspect(source.saved(), "2.0.0");
+ expect(review.warnings).toEqual([]);
+ expect(await target.service.importBackup(review, "all")).toBe(2);
+ expect(target.read()).toEqual(source.read());
+ });
+
+ it("preserves destination sounds, remaps a conflicting selection, and makes repeat imports idempotent", async () => {
+ const existing = clip({
+ name: "Keep this clip",
+ dataUrl: "data:audio/wav;base64,AQID",
+ });
+ const target = setup({ settings: { theme: "light" }, sounds: [existing] });
+ const review = target.service.inspect(JSON.stringify(backup()), "2.0.0");
+ await target.service.importBackup(review, "all");
+ const imported = target
+ .read()
+ .sounds.find((sound) => sound.name === "My chime");
+ expect(target.read().sounds[0]).toEqual(existing);
+ expect(imported?.id).not.toBe(existing.id);
+ expect(target.read().settings.completionSound).toBe(
+ `custom:${imported?.id}`,
+ );
+ expect(await target.service.importBackup(review, "all")).toBe(0);
+ expect(target.read().sounds).toHaveLength(2);
+ // A rename keeps the clip's audio, so a later import of the same file
+ // must still recognize the clip and keep the destination name.
+ target.rename("My chime", "My ding");
+ expect(await target.service.importBackup(review, "all")).toBe(0);
+ expect(target.read().sounds.map((sound) => sound.name)).toEqual([
+ "Keep this clip",
+ "My ding",
+ ]);
+ });
+
+ it("exports only allowed preferences and keeps sounds-only transfers independent of other settings", async () => {
+ const source = setup({
+ settings: {
+ theme: "dark",
+ completionVolume: 45,
+ completionSound: "random-custom",
+ ...{
+ elevenLabsKeyConfigured: true,
+ lastUsedCloudRepository: "example/repo",
+ secret: "fake-token",
+ },
+ },
+ sounds: [clip()],
+ });
+ await source.service.exportBackup("all");
+ expect(JSON.parse(source.saved()).settings).toEqual({
+ theme: "dark",
+ completionVolume: 45,
+ completionSound: "random-custom",
+ });
+ await source.service.exportBackup("sounds");
+ expect(JSON.parse(source.saved()).settings).toEqual({
+ completionVolume: 45,
+ completionSound: "random-custom",
+ });
+ const target = setup();
+ await target.service.importBackup(
+ target.service.inspect(source.saved(), "2.0.0"),
+ "sounds",
+ );
+ expect(target.read().settings).toEqual({
+ theme: "light",
+ completionVolume: 45,
+ completionSound: "random-custom",
+ });
+ });
+
+ it("warns about removed and changed fields without importing them or invoking unsafe keys", async () => {
+ const target = setup();
+ const review = target.service.inspect(
+ JSON.stringify(
+ backup({
+ settings: JSON.parse(
+ '{"theme":"dark","completionVolume":101,"removedPreference":true,"__proto__":{"polluted":true},"elevenLabsKeyConfigured":true}',
+ ),
+ }),
+ ),
+ "2.0.0",
+ );
+ expect(review.warnings.map(({ key, reason }) => [key, reason])).toEqual([
+ ["completionVolume", "changed"],
+ ["removedPreference", "unknown"],
+ ["elevenLabsKeyConfigured", "unknown"],
+ ]);
+ await target.service.importBackup(review, "all");
+ expect(target.read().settings).toEqual({
+ theme: "dark",
+ completionSound: "none",
+ });
+ });
+
+ it("keeps the instructions on this machine when the backup carries none", async () => {
+ const target = setup({
+ settings: { theme: "light", customInstructions: "Use short sentences." },
+ sounds: [],
+ });
+ const review = target.service.inspect(
+ JSON.stringify(
+ backup({ settings: { theme: "dark", customInstructions: "" } }),
+ ),
+ "2.0.0",
+ );
+
+ expect(review.settings.customInstructions).toBeUndefined();
+ await target.service.importBackup(review, "all");
+ expect(target.read().settings.customInstructions).toBe(
+ "Use short sentences.",
+ );
+ });
+
+ it.each<[string, string, boolean]>([
+ ["path traversal", "../convai/knowledge-base/text", false],
+ ["extra path segment", "voice/other", false],
+ ["query string", "voice?output_format=mp3", false],
+ ["fragment", "voice#tail", false],
+ ["plain token", "goT3UYdM9bhm0n2lmKQx", true],
+ ])(
+ "checks an imported voice id: %s",
+ async (_name, elevenLabsVoiceId, accepted) => {
+ const target = setup();
+ const review = target.service.inspect(
+ JSON.stringify(backup({ settings: { elevenLabsVoiceId } })),
+ "2.0.0",
+ );
+ expect(review.warnings).toEqual(
+ accepted ? [] : [{ key: "elevenLabsVoiceId", reason: "changed" }],
+ );
+ await target.service.importBackup(review, "all");
+ expect(target.read().settings.elevenLabsVoiceId).toBe(
+ accepted ? elevenLabsVoiceId : undefined,
+ );
+ },
+ );
+
+ it.each([
+ ["missing clip", [], "custom:clip-a"],
+ ["empty random library", [], "random-custom"],
+ [
+ "remote audio",
+ [clip({ dataUrl: "https://example.com/chime.wav" })],
+ "custom:clip-a",
+ ],
+ [
+ "broken base64",
+ [clip({ dataUrl: "data:audio/wav;base64,invalid!!" })],
+ "custom:clip-a",
+ ],
+ [
+ "oversized clip",
+ [
+ clip({
+ dataUrl: `data:audio/wav;base64,${Buffer.alloc(MAX_CUSTOM_SOUND_BYTES + 1).toString("base64")}`,
+ }),
+ ],
+ "custom:clip-a",
+ ],
+ ])(
+ "keeps the current selection when the backup has %s",
+ async (_name, sounds, selection) => {
+ const target = setup({
+ settings: { completionSound: "guitar" },
+ sounds: [clip({ id: "local" })],
+ });
+ const review = target.service.inspect(
+ JSON.stringify(
+ backup({ sounds, settings: { completionSound: selection } }),
+ ),
+ "2.0.0",
+ );
+ expect(
+ review.warnings.some((warning) => warning.reason === "selection"),
+ ).toBe(true);
+ await target.service.importBackup(review, "all");
+ expect(target.read().settings.completionSound).toBe("guitar");
+ expect(target.read().sounds).toHaveLength(1);
+ },
+ );
+
+ it("keeps valid clips when another clip is invalid or has a duplicate ID", async () => {
+ const target = setup();
+ const review = target.service.inspect(
+ JSON.stringify(
+ backup({
+ sounds: [
+ clip(),
+ clip({ name: "Duplicate" }),
+ clip({ id: "other", durationMs: -1 }),
+ ],
+ }),
+ ),
+ "2.0.0",
+ );
+ expect(review.warnings).toHaveLength(2);
+ await target.service.importBackup(review, "all");
+ expect(target.read().sounds).toEqual([clip()]);
+ });
+
+ it.each([
+ ["invalid JSON", "not JSON"],
+ ["invalid shape", "[]"],
+ ["future format", JSON.stringify(backup({ formatVersion: 2 }))],
+ [
+ "too many sounds",
+ JSON.stringify(
+ backup({ sounds: Array.from({ length: 1001 }, () => null) }),
+ ),
+ ],
+ [
+ "oversized setting key",
+ JSON.stringify(backup({ settings: { ["k".repeat(257)]: true } })),
+ ],
+ [
+ "too many settings",
+ JSON.stringify(
+ backup({
+ settings: Object.fromEntries(
+ Array.from({ length: 1001 }, (_, index) => [
+ `unknown-${index}`,
+ true,
+ ]),
+ ),
+ }),
+ ),
+ ],
+ ])(
+ "rejects invalid or future formats without writes: %s",
+ (_name, contents) => {
+ const target = setup();
+ expect(() => target.service.inspect(contents, "2.0.0")).toThrow();
+ expect(target.apply).not.toHaveBeenCalled();
+ },
+ );
+
+ it("treats canceled dialogs as cancellation and releases the operation guard after a save failure", async () => {
+ const target = setup();
+ target.files.open = async () => null;
+ expect(await target.service.openBackup()).toBeNull();
+ target.files.save = async () => {
+ throw new Error("Disk full");
+ };
+ await expect(target.service.exportBackup("all")).rejects.toThrow(
+ "Disk full",
+ );
+ target.files.save = async () => false;
+ expect(await target.service.exportBackup("all")).toBe(false);
+ expect(target.apply).not.toHaveBeenCalled();
+ });
+
+ it.each(["export", "open", "import"] as const)(
+ "blocks %s while an export is running",
+ async (operation) => {
+ const target = setup();
+ let finish!: (version: string) => void;
+ target.files.getAppVersion = () =>
+ new Promise<string>((resolve) => {
+ finish = resolve;
+ });
+ const review = target.service.inspect(JSON.stringify(backup()), "2.0.0");
+ const exporting = target.service.exportBackup("all");
+ const operations = {
+ export: () => target.service.exportBackup("all"),
+ open: () => target.service.openBackup(),
+ import: () => target.service.importBackup(review, "all"),
+ };
+ await expect(operations[operation]()).rejects.toThrow("already running");
+ finish("2.0.0");
+ await exporting;
+ },
+ );
+
+ it("rejects a sound library that exceeds the import limit before saving", async () => {
+ const target = setup({
+ settings: {},
+ sounds: Array.from({ length: 1001 }, (_, index) =>
+ clip({ id: `clip-${index}` }),
+ ),
+ });
+ await expect(target.service.exportBackup("sounds")).rejects.toThrow(
+ "1,000",
+ );
+ expect(target.saved()).toBe("");
+ });
+});
diff --git a/products/desktop/packages/core/src/settings/settingsBackup.ts b/products/desktop/packages/core/src/settings/settingsBackup.ts
new file mode 100644
index 000000000000..0a15d5b5c89c
--- /dev/null
+++ b/products/desktop/packages/core/src/settings/settingsBackup.ts
@@ -0,0 +1,266 @@
+import {
+ type ISettingsBackupFiles,
+ SETTINGS_BACKUP_FILES,
+} from "@posthog/platform/settings-backup-files";
+import { inject, injectable } from "inversify";
+import {
+ type CustomSound,
+ customSoundSchema,
+ MAX_SETTINGS_BACKUP_BYTES,
+ MAX_SETTINGS_BACKUP_ENTRIES,
+ type PortableSettings,
+ portableSettingsSchema,
+ SETTINGS_BACKUP_FORMAT_VERSION,
+ type SettingsBackup,
+ settingsBackupSchema,
+} from "./schemas";
+
+const settingsSchemas = {
+ all: portableSettingsSchema,
+ sounds: portableSettingsSchema.pick({
+ completionSound: true,
+ completionVolume: true,
+ scaleSoundWithTaskLength: true,
+ }),
+};
+export type BackupScope = keyof typeof settingsSchemas;
+export interface SettingsBackupSnapshot {
+ settings: PortableSettings;
+ sounds: CustomSound[];
+}
+export interface SettingsBackupState {
+ read(): SettingsBackupSnapshot;
+ apply(snapshot: SettingsBackupSnapshot): void;
+}
+export const SETTINGS_BACKUP_STATE = Symbol.for("posthog.settings.backupState");
+export const SETTINGS_BACKUP_SERVICE = Symbol.for(
+ "posthog.settings.backupService",
+);
+
+export interface BackupWarning {
+ key: string;
+ reason: "unknown" | "changed" | "sound" | "selection";
+}
+export interface BackupReview {
+ backup: SettingsBackup;
+ settings: PortableSettings;
+ sounds: CustomSound[];
+ warnings: BackupWarning[];
+ currentVersion: string;
+}
+
+export const SOUND_SETTINGS: ReadonlySet<string> = new Set(
+ Object.keys(settingsSchemas.sounds.shape),
+);
+
+export interface SettingsBackupSoundMerge {
+ sounds: CustomSound[];
+ remappedIds: Map<string, string>;
+}
+
+export function mergeSettingsBackupSounds(
+ currentSounds: CustomSound[],
+ importedSounds: CustomSound[],
+): SettingsBackupSoundMerge {
+ const sounds = [...currentSounds];
+ const remappedIds = new Map<string, string>();
+ // A backup can hold many large clips, so the lookups stay constant time.
+ const soundsByDataUrl = new Map(sounds.map((s) => [s.dataUrl, s]));
+ const idSet = new Set(sounds.map((s) => s.id));
+ for (const sound of importedSounds) {
+ // The audio identifies a clip. A rename on either machine keeps the same
+ // audio, so comparing names here would import a clip the library already
+ // holds a second time.
+ const existing = soundsByDataUrl.get(sound.dataUrl);
+ if (existing) {
+ remappedIds.set(sound.id, existing.id);
+ continue;
+ }
+ let id = sound.id;
+ let suffix = 1;
+ while (idSet.has(id)) id = `${sound.id.slice(0, 220)}-import-${suffix++}`;
+ const imported = { ...sound, id };
+ sounds.push(imported);
+ soundsByDataUrl.set(imported.dataUrl, imported);
+ idSet.add(id);
+ remappedIds.set(sound.id, id);
+ }
+ return { sounds, remappedIds };
+}
+
+@injectable()
+export class SettingsBackupService {
+ private busy = false;
+
+ constructor(
+ @inject(SETTINGS_BACKUP_STATE) private readonly state: SettingsBackupState,
+ @inject(SETTINGS_BACKUP_FILES) private readonly files: ISettingsBackupFiles,
+ ) {}
+
+ private async exclusively<T>(action: () => Promise<T>): Promise<T> {
+ if (this.busy)
+ throw new Error(
+ "A backup operation is already running. Wait for it to finish.",
+ );
+ this.busy = true;
+ try {
+ return await action();
+ } finally {
+ this.busy = false;
+ }
+ }
+
+ async exportBackup(scope: BackupScope): Promise<boolean> {
+ return this.exclusively(async () => {
+ const snapshot = this.state.read();
+ if (snapshot.sounds.length > MAX_SETTINGS_BACKUP_ENTRIES)
+ throw new Error(
+ "This backup has more than 1,000 sounds. Remove unused clips and try again.",
+ );
+ const settings = settingsSchemas[scope].safeParse(snapshot.settings);
+ if (!settings.success)
+ throw new Error(
+ "Some saved settings are no longer supported. Export sounds only, or reset the affected preferences before trying again.",
+ );
+ const sounds = snapshot.sounds.map((sound) => {
+ const result = customSoundSchema.safeParse(sound);
+ if (!result.success)
+ throw new Error(
+ `Could not back up sound “${sound.name}”. Reimport that clip in Notifications settings and try again.`,
+ );
+ return result.data;
+ });
+ const backup: SettingsBackup = {
+ format: "posthog-desktop-settings",
+ formatVersion: SETTINGS_BACKUP_FORMAT_VERSION,
+ appVersion: await this.files.getAppVersion(),
+ exportedAt: new Date().toISOString(),
+ settings: settings.data,
+ sounds,
+ };
+ const contents = JSON.stringify(backup, null, 2);
+ if (
+ new TextEncoder().encode(contents).length > MAX_SETTINGS_BACKUP_BYTES
+ ) {
+ throw new Error(
+ "This backup exceeds 64 MB. Remove unused clips and try again.",
+ );
+ }
+ return this.files.save({
+ contents,
+ defaultName: `posthog-${scope === "sounds" ? "sounds" : "settings"}-${backup.exportedAt.slice(0, 10)}.json`,
+ });
+ });
+ }
+
+ inspect(contents: string, currentVersion: string): BackupReview {
+ if (new TextEncoder().encode(contents).length > MAX_SETTINGS_BACKUP_BYTES)
+ throw new Error(
+ "This file exceeds 64 MB. Choose a smaller PostHog backup.",
+ );
+ let raw: unknown;
+ try {
+ raw = JSON.parse(contents);
+ } catch {
+ throw new Error(
+ "This file is not valid JSON. Choose a PostHog settings backup.",
+ );
+ }
+ const result = settingsBackupSchema.safeParse(raw);
+ if (!result.success)
+ throw new Error(
+ "This is not a valid PostHog settings backup. Choose a file exported from Advanced settings.",
+ );
+ const backup = result.data;
+ if (backup.formatVersion !== SETTINGS_BACKUP_FORMAT_VERSION)
+ throw new Error(
+ "This backup uses a newer file format. Update PostHog Desktop before importing it.",
+ );
+ const warnings: BackupWarning[] = [];
+ const settings: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(backup.settings)) {
+ if (!Object.hasOwn(portableSettingsSchema.shape, key)) {
+ warnings.push({ key, reason: "unknown" });
+ continue;
+ }
+ const schema =
+ portableSettingsSchema.shape[key as keyof PortableSettings];
+ const parsed = schema.safeParse(value);
+ if (!parsed.success) {
+ warnings.push({ key, reason: "changed" });
+ continue;
+ }
+ // A backup that carries no instructions must not clear the text the
+ // user wrote on this machine.
+ if (key === "customInstructions" && parsed.data === "") continue;
+ settings[key] = parsed.data;
+ }
+ const sounds: CustomSound[] = [];
+ const ids = new Set<string>();
+ for (const [index, value] of backup.sounds.entries()) {
+ const parsed = customSoundSchema.safeParse(value);
+ if (!parsed.success || ids.has(parsed.data.id)) {
+ warnings.push({ key: `Sound ${index + 1}`, reason: "sound" });
+ continue;
+ }
+ ids.add(parsed.data.id);
+ sounds.push(parsed.data);
+ }
+ const selected = settings.completionSound;
+ if (
+ typeof selected === "string" &&
+ ((selected.startsWith("custom:") && !ids.has(selected.slice(7))) ||
+ (selected === "random-custom" && sounds.length === 0))
+ ) {
+ delete settings.completionSound;
+ warnings.push({ key: "Completion sound", reason: "selection" });
+ }
+ return {
+ backup,
+ settings: portableSettingsSchema.parse(settings),
+ sounds,
+ warnings,
+ currentVersion,
+ };
+ }
+
+ async openBackup(): Promise<BackupReview | null> {
+ return this.exclusively(async () => {
+ const contents = await this.files.open();
+ return contents === null
+ ? null
+ : this.inspect(contents, await this.files.getAppVersion());
+ });
+ }
+
+ async importBackup(
+ review: BackupReview,
+ scope: BackupScope,
+ ): Promise<number> {
+ return this.exclusively(async () => {
+ // Revalidate at the write boundary; only the reviewed file supplies values.
+ const validated = this.inspect(
+ JSON.stringify(review.backup),
+ review.currentVersion,
+ );
+ const current = this.state.read();
+ const { sounds, remappedIds } = mergeSettingsBackupSounds(
+ current.sounds,
+ validated.sounds,
+ );
+ const settings = settingsSchemas[scope].parse(validated.settings);
+ if (settings.completionSound?.startsWith("custom:")) {
+ const remappedId = remappedIds.get(settings.completionSound.slice(7));
+ if (remappedId) {
+ settings.completionSound = `custom:${remappedId}`;
+ } else {
+ // The merge did not carry the clip, so drop the selection rather
+ // than persist a reference to a sound that does not exist.
+ delete settings.completionSound;
+ }
+ }
+ this.state.apply({ settings, sounds });
+ return sounds.length - current.sounds.length;
+ });
+ }
+}
diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.ts
index d6d415bd1d51..ace126ca631e 100644
--- a/products/desktop/packages/host-router/src/router.ts
+++ b/products/desktop/packages/host-router/src/router.ts
@@ -43,6 +43,7 @@ import { processTrackingRouter } from "./routers/process-tracking.router";
import { provisioningRouter } from "./routers/provisioning.router";
import { releaseFeedRouter } from "./routers/release-feed.router";
import { secureStoreRouter } from "./routers/secure-store.router";
+import { settingsBackupRouter } from "./routers/settings-backup.router";
import { shellRouter } from "./routers/shell.router";
import { skillsRouter } from "./routers/skills.router";
import { slackIntegrationRouter } from "./routers/slack-integration.router";
@@ -94,6 +95,7 @@ export const hostRouter = router({
notification: notificationRouter,
oauth: oauthRouter,
os: osRouter,
+ settingsBackup: settingsBackupRouter,
piSession: piSessionRouter,
processTracking: processTrackingRouter,
provisioning: provisioningRouter,
diff --git a/products/desktop/packages/host-router/src/routers/settings-backup.router.ts b/products/desktop/packages/host-router/src/routers/settings-backup.router.ts
new file mode 100644
index 000000000000..3e26c3f539dd
--- /dev/null
+++ b/products/desktop/packages/host-router/src/routers/settings-backup.router.ts
@@ -0,0 +1,19 @@
+import { saveSettingsBackupInput } from "@posthog/core/settings/schemas";
+import { publicProcedure, router } from "@posthog/host-trpc/trpc";
+import {
+ type ISettingsBackupFiles,
+ SETTINGS_BACKUP_FILES,
+} from "@posthog/platform/settings-backup-files";
+
+export const settingsBackupRouter = router({
+ open: publicProcedure.mutation(({ ctx }) =>
+ ctx.container.get<ISettingsBackupFiles>(SETTINGS_BACKUP_FILES).open(),
+ ),
+ save: publicProcedure
+ .input(saveSettingsBackupInput)
+ .mutation(({ ctx, input }) =>
+ ctx.container
+ .get<ISettingsBackupFiles>(SETTINGS_BACKUP_FILES)
+ .save(input),
+ ),
+});
diff --git a/products/desktop/packages/platform/package.json b/products/desktop/packages/platform/package.json
index 137e029d2def..763fcff19d77 100644
--- a/products/desktop/packages/platform/package.json
+++ b/products/desktop/packages/platform/package.json
@@ -107,6 +107,10 @@
"./disk-cache": {
"types": "./dist/disk-cache.d.ts",
"import": "./dist/disk-cache.js"
+ },
+ "./settings-backup-files": {
+ "types": "./dist/settings-backup-files.d.ts",
+ "import": "./dist/settings-backup-files.js"
}
},
"scripts": {
diff --git a/products/desktop/packages/platform/src/settings-backup-files.ts b/products/desktop/packages/platform/src/settings-backup-files.ts
new file mode 100644
index 000000000000..9a7d61054a0c
--- /dev/null
+++ b/products/desktop/packages/platform/src/settings-backup-files.ts
@@ -0,0 +1,9 @@
+export interface ISettingsBackupFiles {
+ getAppVersion(): Promise<string>;
+ open(): Promise<string | null>;
+ save(input: { contents: string; defaultName: string }): Promise<boolean>;
+}
+
+export const SETTINGS_BACKUP_FILES = Symbol.for(
+ "posthog.platform.settingsBackupFiles",
+);
diff --git a/products/desktop/packages/platform/tsup.config.ts b/products/desktop/packages/platform/tsup.config.ts
index 68701038a65a..8dbea961439d 100644
--- a/products/desktop/packages/platform/tsup.config.ts
+++ b/products/desktop/packages/platform/tsup.config.ts
@@ -7,6 +7,7 @@ export default defineConfig({
"src/storage-paths.ts",
"src/app-meta.ts",
"src/dialog.ts",
+ "src/settings-backup-files.ts",
"src/clipboard.ts",
"src/file-icon.ts",
"src/feedback-context.ts",
diff --git a/products/desktop/packages/shared/src/analytics-events.ts b/products/desktop/packages/shared/src/analytics-events.ts
index 46f381b289b3..ef039ea5e163 100644
--- a/products/desktop/packages/shared/src/analytics-events.ts
+++ b/products/desktop/packages/shared/src/analytics-events.ts
@@ -388,6 +388,35 @@ export interface SettingChangedProperties {
old_value?: string | boolean | number;
}
+type SettingsBackupScope = "all" | "sounds";
+
+export interface SettingsBackupExportProperties {
+ scope: SettingsBackupScope;
+ sound_count: number;
+}
+
+export interface SettingsBackupExportFailedProperties
+ extends SettingsBackupExportProperties {
+ error: string;
+}
+
+export interface SettingsBackupImportedProperties {
+ scope: SettingsBackupScope;
+ setting_count: number;
+ sound_count: number;
+ added_sound_count: number;
+ warning_count: number;
+ backup_app_version: string;
+ version_matches: boolean;
+}
+
+export interface SettingsBackupImportFailedProperties {
+ scope: SettingsBackupScope;
+ /** "open" = reading and validating the file; "apply" = writing the settings. */
+ stage: "open" | "apply";
+ error: string;
+}
+
export interface CloudCredentialRelayProperties {
credential: "claude_subscription_token";
outcome: "sent" | "no_token" | "expired" | "rejected";
@@ -1645,6 +1674,10 @@ export const ANALYTICS_EVENTS = {
// Settings events
SETTING_CHANGED: "Setting changed",
CUSTOM_SOUND_ADDED: "Custom sound added",
+ SETTINGS_BACKUP_EXPORTED: "Settings backup exported",
+ SETTINGS_BACKUP_EXPORT_FAILED: "Settings backup export failed",
+ SETTINGS_BACKUP_IMPORTED: "Settings backup imported",
+ SETTINGS_BACKUP_IMPORT_FAILED: "Settings backup import failed",
CUSTOM_SOUND_RECORDING_SILENT: "Custom sound recording silent",
CODEX_SUBSCRIPTION_CONNECTED: "Codex subscription connected",
CODEX_SUBSCRIPTION_SIGNED_OUT: "Codex subscription signed out",
@@ -1865,6 +1898,10 @@ export type EventPropertyMap = {
[ANALYTICS_EVENTS.CLAUDE_CLOUD_TOKEN_REMOVED]: never;
[ANALYTICS_EVENTS.CLOUD_CREDENTIAL_RELAY]: CloudCredentialRelayProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_ADDED]: CustomSoundAddedProperties;
+ [ANALYTICS_EVENTS.SETTINGS_BACKUP_EXPORTED]: SettingsBackupExportProperties;
+ [ANALYTICS_EVENTS.SETTINGS_BACKUP_EXPORT_FAILED]: SettingsBackupExportFailedProperties;
+ [ANALYTICS_EVENTS.SETTINGS_BACKUP_IMPORTED]: SettingsBackupImportedProperties;
+ [ANALYTICS_EVENTS.SETTINGS_BACKUP_IMPORT_FAILED]: SettingsBackupImportFailedProperties;
[ANALYTICS_EVENTS.CUSTOM_SOUND_RECORDING_SILENT]: never;
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_CONNECTED]: never;
[ANALYTICS_EVENTS.CODEX_SUBSCRIPTION_SIGNED_OUT]: never;
diff --git a/products/desktop/packages/shared/src/feature-flag-keys.json b/products/desktop/packages/shared/src/feature-flag-keys.json
index 266871d0192e..483604e605d2 100644
--- a/products/desktop/packages/shared/src/feature-flag-keys.json
+++ b/products/desktop/packages/shared/src/feature-flag-keys.json
@@ -26,6 +26,7 @@
"REPORTS_INBOX_FLAG": "posthog-desktop-reports-inbox",
"SAVED_SEARCHES_RAIL_FLAG": "posthog-desktop-saved-searches-rail",
"SELF_DRIVING_SETUP_TASK_FLAG": "posthog-code-self-driving-setup-task",
+ "SETTINGS_BACKUP_FLAG": "posthog-desktop-settings-backup",
"SIGNALS_PR_REFUNDS_FLAG": "signals-pr-refunds",
"SPOKEN_NARRATION_FLAG": "posthog-code-spoken-narration",
"TASK_ANALYSIS_FLAG": "posthog-code-task-analysis",
diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.ts
index 6db22630078d..aa39fa2fc936 100644
--- a/products/desktop/packages/shared/src/flags.ts
+++ b/products/desktop/packages/shared/src/flags.ts
@@ -107,6 +107,8 @@ export const CONTEXT_LAYER_FLAG = featureFlagKeys.CONTEXT_LAYER_FLAG;
export const BACKGROUND_AGENT_LOGS_FLAG =
featureFlagKeys.BACKGROUND_AGENT_LOGS_FLAG;
+/** Gates the settings and sounds backup section in Advanced settings. */
+export const SETTINGS_BACKUP_FLAG = featureFlagKeys.SETTINGS_BACKUP_FLAG;
export const CUSTOM_IMAGES_FEATURE_FLAG =
featureFlagKeys.CUSTOM_IMAGES_FEATURE_FLAG;
export const PI_HARNESS_FLAG = featureFlagKeys.PI_HARNESS_FLAG;
diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
index 82595e639b24..2892d4d62946 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsPanel.tsx
@@ -31,6 +31,7 @@ import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
import { useQuickAskAvailable } from "@posthog/ui/features/quick-ask/useQuickAskAvailable";
import { SettingsPageContent } from "@posthog/ui/features/settings/components/SettingsPageContent";
import { closeSettings } from "@posthog/ui/features/settings/hooks/useOpenSettings";
+import { useSettingsBackupAvailable } from "@posthog/ui/features/settings/hooks/useSettingsBackupAvailable";
import {
type SettingsSearchEntry,
searchSettings,
@@ -149,6 +150,7 @@ export function SettingsPanel({
const { data: user } = useCurrentUser({ client });
const { localWorkspaces } = useHostCapabilities();
const quickAskAvailable = useQuickAskAvailable();
+ const backupAvailable = useSettingsBackupAvailable();
const hiddenCategories = getHiddenSettingsCategories({
localWorkspaces,
@@ -158,7 +160,11 @@ export function SettingsPanel({
...group,
items: group.items.filter((item) => !hiddenCategories.has(item.id)),
})).filter((group) => group.items.length > 0);
- const searchResults = searchSettings(searchQuery, hiddenCategories);
+ const searchResults = searchSettings(
+ searchQuery,
+ hiddenCategories,
+ backupAvailable,
+ );
// Guard direct navigation (URL, deep link, programmatic openSettings) to a
// category hidden on this host. Fall back to General so a hidden section is
diff --git a/products/desktop/packages/ui/src/features/settings/components/SettingsSelect.tsx b/products/desktop/packages/ui/src/features/settings/components/SettingsSelect.tsx
index 49f6d4346412..5e87951ddb38 100644
--- a/products/desktop/packages/ui/src/features/settings/components/SettingsSelect.tsx
+++ b/products/desktop/packages/ui/src/features/settings/components/SettingsSelect.tsx
@@ -19,6 +19,7 @@ export function SettingsSelect({
onChange,
ariaLabel,
placeholder,
+ disabled = false,
triggerClassName = "w-full",
}: {
value: string | null;
@@ -26,10 +27,12 @@ export function SettingsSelect({
onChange: (value: string | null) => void;
ariaLabel: string;
placeholder?: string;
+ disabled?: boolean;
triggerClassName?: string;
}) {
return (
<Select
+ disabled={disabled}
value={value}
onValueChange={(next: string | null) => onChange(next)}
items={options.map((o) => ({ value: o.value, label: o.label }))}
diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.test.ts b/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.test.ts
new file mode 100644
index 000000000000..820dc29dfda0
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.test.ts
@@ -0,0 +1,32 @@
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ filesBound: true,
+ flagEnabled: true,
+}));
+
+vi.mock("@posthog/di/react", () => ({
+ useServiceOptional: () => (mocks.filesBound ? {} : null),
+}));
+vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
+ useFeatureFlag: () => mocks.flagEnabled,
+}));
+
+import { useSettingsBackupAvailable } from "./useSettingsBackupAvailable";
+
+describe("useSettingsBackupAvailable", () => {
+ it.each([
+ ["files bound and flag on", true, true, true],
+ ["files bound and flag off", true, false, false],
+ ["files missing and flag on", false, true, false],
+ ["files missing and flag off", false, false, false],
+ ])("%s", (_name, filesBound, flagEnabled, expected) => {
+ mocks.filesBound = filesBound;
+ mocks.flagEnabled = flagEnabled;
+
+ const { result } = renderHook(() => useSettingsBackupAvailable());
+
+ expect(result.current).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.ts b/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.ts
new file mode 100644
index 000000000000..dce754f8ffc4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/hooks/useSettingsBackupAvailable.ts
@@ -0,0 +1,10 @@
+import { useServiceOptional } from "@posthog/di/react";
+import { SETTINGS_BACKUP_FILES } from "@posthog/platform/settings-backup-files";
+import { SETTINGS_BACKUP_FLAG } from "@posthog/shared";
+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
+
+export function useSettingsBackupAvailable(): boolean {
+ const files = useServiceOptional(SETTINGS_BACKUP_FILES);
+ const enabled = useFeatureFlag(SETTINGS_BACKUP_FLAG);
+ return files !== null && enabled;
+}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/AdvancedSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/AdvancedSettings.tsx
index 735d6c8da8f1..a045a5afa373 100644
--- a/products/desktop/packages/ui/src/features/settings/sections/AdvancedSettings.tsx
+++ b/products/desktop/packages/ui/src/features/settings/sections/AdvancedSettings.tsx
@@ -23,6 +23,7 @@ import { Button, Checkbox, Flex, Switch, Text } from "@radix-ui/themes";
import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
import { OnboardingTestTools } from "./OnboardingTestTools";
+import { SettingsBackup } from "./SettingsBackup";
export function AdvancedSettings() {
const showDebugLogsToggle =
@@ -46,6 +47,7 @@ export function AdvancedSettings() {
return (
<div className="flex flex-col gap-7">
+ <SettingsBackup />
<SettingsCard>
<SettingsCardRow
label="Always create pull requests for cloud runs"
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.stories.tsx b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.stories.tsx
new file mode 100644
index 000000000000..baebe36103f7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.stories.tsx
@@ -0,0 +1,88 @@
+import type { BackupReview } from "@posthog/core/settings/settingsBackup";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { SettingsBackupView } from "./SettingsBackup";
+
+const previewAudio =
+ "data:audio/wav;base64,UklGRmQGAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YUAGAAAAAHYP1BohHz8bORD5AILx4eUj4YLkFe8S/oYNZBmRHrUblhHfAnPzWufC4Rzkx+00/JUL4xfkHQkc1BK0BGL14+h94tnjmOxp+qcJUxYbHTwc9BN1Bk/3eepT47jjiOuy+L0HtxQ4HE0c9BQhCDX5G+xD5LfjmOoS99oFEBM8Gz0c1BW2CRT7x+1K5dbjx+mJ9QAEYREqGg4clRYzC+n8eO9o5hTkFukY9DACrQ8CGcEbNheXDLP+L/GY53DkhejB8m4A9Q3JF1gbtxfhDW0A5/Lb6OjkFOiF8bv+PAx+FtIaGRgPDxkCoPQt6nvlwudk8Bf9hAolFTIaXBgiELQDV/aM6yfmjudf74b7zwjAE3oZgBgZETwFCfj27Ovmeed27gf6IAdREqsYhxj0EbAGtflq7sXngeeq7Z74eAXaEMYXcRixEg8IWfvl77Popef77Er32QNcD84WPxhSE1cJ8vxk8bTp5Odp7A32RQLbDcUV8xfWE4gKgP7m8sXqPejz6+j0vgBZDKwUjRc9FKELAABp9OXrr+ia69zzRv/WCoYTDxeIFKEMcQHq9RLtOelc6+jy3f1WCVQSexa4FIgN0QJo90nu2Ok66w7yhfzbBxgR0RXNFFUOIATh+Invi+oz607xP/tlBtUPFBXIFAgPXAVT+s/wUetF66jwDfr4BIsORRSpFKEPhAa7+xvyKOxv6xzw8PiUAz8NZxNyFCAQlwca/WnzDu2y66rv5/c7AvALehIlFIUQlQhs/rf0Au4L7FLv9fbvAKIKgBHBE9EQfAmx/wX2Ae947BLvGfay/1UJfBBJEwQRTArnAFD3CfD67OvuVfWE/gwIbw++Eh8RBQsNApb4GvGO7dzup/Rm/ckGWw4iEiMRpwsiA9b5MfIz7uTuEfRa/I0FQg11EQ8RMQwmBA77S/Pn7gLvk/Ng+1oEJgy6EOcQpAwWBTz8afSo7zbvK/N5+jADCQvzD6kQAA3zBWD9hvV18H3v2vKm+RMC6wkgD1gQRQ28Bnf+o/ZM8dfvoPLo+AIB0AhFDvUPdA1wB4H/vPcs8kPwfPI++AAAuAdhDYEPjg0PCHsA0vgT87/wbvKp9w3/pgZ4DP4Okg2aCGcB4fn+80nxc/Ip9yn+mwWLC2wOgg0PCUIC6Prt9OHxjfK+9lb9lwSbCs4NXw1wCQwD5/vd9YXyufJo9pX8ngOqCSYNKg27CcUD2/zO9jLz9/Im9ub7rwK7CHQM5AzzCWsExP289+jzRfP59Un7zAHOB7oLjgwWCv4EoP6o+KX0o/Pf9b/69wDkBvoKKQwnCn8Fb/+O+Wf1DvTY9Uj6LwABBjYKuAslCuwFLgBv+i32hvTj9eT5d/8kBW8JOgsRCkcG3wBH+/X2CfX/9ZP5zv5QBKcIsgrsCY8GgAEX/L73lvUs9lT5Nf6FA98HIQq4CcQGEQLd/IX4K/Zo9ij5rf3EAhgHiAl1CecGkQKY/Ur5xvay9g75Nv0PAlUG6ggkCfkG/wJG/gr6Z/cJ9wX50PxnAZcFRwjHCPkGXQPo/sb6C/hs9w35e/zNAN8EogdfCOkGqQN7/3r7sfjZ9yT5OPxAAC8E+wbtB8oG4wMAACf8WPlP+Ev5BvzE/4cDVQZzB5wGDQR2AMr8/vnM+ID55PtV/+gCsAXzBmEGJgTcAGP9ovpQ+cH50/v3/lUCDgVtBhkGLwQzAfH9QfvY+Q/60vuo/s0BcQTjBcYFKAR6AXL+3Ptj+mf64ftp/lIB2QNWBWkFEgSwAef+cPzw+sn6/vs7/uQASQPJBAMF7gPXAU7//Px++zL7Kfwc/oQAwQI8BJYEvQPtAab/gP0K/KP7YfwN/jMAQgKxAyMEfwP1AfD/+f2T/Bj8pfwO/vH/zgEqA6sDNQPsASoAaP4Z/ZL88/wd/r7/ZQGnAjAD4gLWAVYAy/6Z/Q79TP07/pr/CQEqArMChQKxAXMAIf8S/oz9rP1m/oX/uQC0ATYCIAJ/AYAAav+E/gn+Ff6f/n//dwBHAbkBtQFAAX4Apf/t/oT+g/7j/on/QwDjAD8BRQH2AG0A0v9L//z+9f4z/6H/HgCKAMkA0AChAE4A8P+f/3D/a/+N/8f/BwA8AFkAWQBDACAA///m/93/4//v//z/";
+
+const review: BackupReview = {
+ backup: {
+ format: "posthog-desktop-settings",
+ formatVersion: 1,
+ appVersion: "1.3.0",
+ exportedAt: "2026-01-12T12:00:00.000Z",
+ settings: {},
+ sounds: [],
+ },
+ settings: {
+ theme: "dark",
+ completionSound: "random-custom",
+ completionVolume: 75,
+ customInstructions: "Use short sentences.",
+ },
+ sounds: [
+ {
+ id: "chime",
+ name: "My chime",
+ durationMs: 100,
+ dataUrl: previewAudio,
+ },
+ {
+ id: "bell",
+ name: "Little bell",
+ durationMs: 100,
+ dataUrl: previewAudio,
+ },
+ ],
+ warnings: [],
+ currentVersion: "1.3.0",
+};
+const meta: Meta<typeof SettingsBackupView> = {
+ title: "Settings/Backup",
+ component: SettingsBackupView,
+ decorators: [
+ (Story) => (
+ <div className="mx-auto my-8 w-full max-w-160 px-4">
+ <Story />
+ </div>
+ ),
+ ],
+ args: {
+ soundCount: 4,
+ scope: "all",
+ busy: null,
+ review: null,
+ error: null,
+ message: null,
+ onScopeChange: () => {},
+ onExport: () => {},
+ onOpen: () => {},
+ onImport: () => {},
+ onCancel: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof SettingsBackupView>;
+export const Default: Story = {};
+export const SoundsOnly: Story = { args: { scope: "sounds" } };
+export const Review: Story = { args: { review } };
+export const CompatibilityWarnings: Story = {
+ args: {
+ review: {
+ ...review,
+ currentVersion: "1.4.0",
+ warnings: [
+ { key: "completionVolume", reason: "changed" },
+ { key: "removedPreference", reason: "unknown" },
+ { key: "Sound 3", reason: "sound" },
+ ],
+ },
+ },
+};
+export const Importing: Story = { args: { review, busy: "import" } };
+export const SaveFailed: Story = {
+ args: {
+ review,
+ error: "Could not save settings. Check available disk space and try again.",
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.test.tsx b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.test.tsx
new file mode 100644
index 000000000000..a01c3b22ed8e
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.test.tsx
@@ -0,0 +1,100 @@
+import type {
+ BackupReview,
+ BackupScope,
+} from "@posthog/core/settings/settingsBackup";
+import { render, screen, within } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import {
+ SettingsBackupView,
+ type SettingsBackupViewProps,
+} from "./SettingsBackup";
+
+describe("SettingsBackupView", () => {
+ const review: BackupReview = {
+ backup: {
+ format: "posthog-desktop-settings",
+ formatVersion: 1,
+ appVersion: "1.3.0",
+ exportedAt: "2026-01-12T12:00:00.000Z",
+ settings: {},
+ sounds: [],
+ },
+ settings: { theme: "dark", completionVolume: 75 },
+ sounds: [],
+ warnings: [
+ { key: "completionVolume", reason: "changed" },
+ { key: "theme", reason: "changed" },
+ { key: "removedPreference", reason: "unknown" },
+ { key: "Completion sound", reason: "selection" },
+ { key: "Sound 3", reason: "sound" },
+ ],
+ currentVersion: "1.3.0",
+ };
+ const props: SettingsBackupViewProps = {
+ soundCount: 4,
+ scope: "all",
+ onScopeChange: () => {},
+ busy: null,
+ review,
+ error: null,
+ message: null,
+ onExport: () => {},
+ onOpen: () => {},
+ onImport: () => {},
+ onCancel: () => {},
+ };
+
+ it.each<[BackupScope, string[]]>([
+ [
+ "all",
+ [
+ "Completion volume",
+ "Theme",
+ "Removed preference",
+ "Completion sound",
+ "Sound 3",
+ ],
+ ],
+ ["sounds", ["Completion volume", "Completion sound", "Sound 3"]],
+ ])("warns only about what the %s import reads", (scope, expected) => {
+ render(<SettingsBackupView {...props} scope={scope} />);
+
+ expect(
+ within(screen.getByLabelText("Compatibility warnings"))
+ .getAllByRole("listitem")
+ .map((item) => item.firstElementChild?.textContent),
+ ).toEqual(expected);
+ expect(screen.getByText(/compatibility warning/).textContent).toBe(
+ `${expected.length} compatibility warnings`,
+ );
+ });
+
+ it.each<[BackupScope, string[], boolean]>([
+ ["all", ["Theme", "Completion volume", "Custom instructions"], true],
+ ["sounds", ["Completion volume"], false],
+ ])(
+ "names the settings a %s import writes",
+ (scope, expected, showsInstructions) => {
+ render(
+ <SettingsBackupView
+ {...props}
+ scope={scope}
+ review={{
+ ...review,
+ settings: { ...review.settings, customInstructions: "Ship it." },
+ warnings: [],
+ }}
+ />,
+ );
+
+ expect(
+ Array.from(screen.getByLabelText("Settings to import").children).map(
+ (item) => item.textContent,
+ ),
+ ).toEqual(expected);
+ expect(screen.queryByText("Ship it.")).toEqual(
+ showsInstructions ? expect.anything() : null,
+ );
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.tsx b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.tsx
new file mode 100644
index 000000000000..6d9dfa0aa6eb
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/SettingsBackup.tsx
@@ -0,0 +1,384 @@
+import {
+ type BackupReview,
+ type BackupScope,
+ SETTINGS_BACKUP_SERVICE,
+ type SettingsBackupService,
+ SOUND_SETTINGS,
+} from "@posthog/core/settings/settingsBackup";
+import { useService } from "@posthog/di/react";
+import { Button } from "@posthog/quill";
+import { ANALYTICS_EVENTS } from "@posthog/shared";
+import {
+ SettingsCard,
+ SettingsSection,
+} from "@posthog/ui/features/settings/components/SettingsCard";
+import { SettingsSelect } from "@posthog/ui/features/settings/components/SettingsSelect";
+import { useSettingsBackupAvailable } from "@posthog/ui/features/settings/hooks/useSettingsBackupAvailable";
+import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
+import { track } from "@posthog/ui/shell/analytics";
+import { useMutation } from "@tanstack/react-query";
+import { Download, Upload } from "lucide-react";
+import { useState } from "react";
+
+const SCOPE_OPTIONS = [
+ { value: "all", label: "Settings and sounds" },
+ { value: "sounds", label: "Sounds only" },
+];
+const WARNING_TEXT = {
+ unknown: "Unavailable or removed; will be skipped.",
+ changed: "Value is no longer supported; will be skipped.",
+ sound: "Invalid or duplicate sound; will be skipped.",
+ selection: "The selected sound is missing; your current selection will stay.",
+};
+
+const CUSTOM_INSTRUCTIONS_PREVIEW_LENGTH = 400;
+
+type BackupOperation = "export" | "open" | "import";
+
+// A sounds-only import reads no other setting, so the other keys in the file
+// do not describe the operation the user chose.
+function importedSettingKeys(
+ review: BackupReview,
+ scope: BackupScope,
+): string[] {
+ return Object.keys(review.settings).filter(
+ (key) => scope === "all" || SOUND_SETTINGS.has(key),
+ );
+}
+
+function instructionsPreview(text: string): string {
+ return text.length > CUSTOM_INSTRUCTIONS_PREVIEW_LENGTH
+ ? `${text.slice(0, CUSTOM_INSTRUCTIONS_PREVIEW_LENGTH)}…`
+ : text;
+}
+
+function settingLabel(key: string): string {
+ return key
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .toLowerCase()
+ .replace(/^./, (letter) => letter.toUpperCase());
+}
+
+export interface SettingsBackupViewProps {
+ soundCount: number;
+ scope: BackupScope;
+ onScopeChange: (scope: BackupScope) => void;
+ busy: BackupOperation | null;
+ review: BackupReview | null;
+ error: string | null;
+ message: string | null;
+ onExport: () => void;
+ onOpen: () => void;
+ onImport: () => void;
+ onCancel: () => void;
+}
+
+export function SettingsBackupView({
+ soundCount,
+ scope,
+ onScopeChange,
+ busy,
+ review,
+ error,
+ message,
+ onExport,
+ onOpen,
+ onImport,
+ onCancel,
+}: SettingsBackupViewProps): React.ReactElement {
+ const settingKeys = review ? importedSettingKeys(review, scope) : [];
+ const hasImport =
+ review !== null && (review.sounds.length > 0 || settingKeys.length > 0);
+ const customInstructions = settingKeys.includes("customInstructions")
+ ? (review?.settings.customInstructions ?? "")
+ : null;
+ // Sound and selection warnings apply to both scopes, because both scopes
+ // import sounds.
+ const warnings = (review?.warnings ?? []).filter(
+ (warning) =>
+ scope === "all" ||
+ warning.reason === "sound" ||
+ warning.reason === "selection" ||
+ SOUND_SETTINGS.has(warning.key),
+ );
+ return (
+ <SettingsSection
+ label="Back up settings and sounds"
+ description="Move your setup to another machine with a single backup file."
+ >
+ <SettingsCard>
+ <div className="flex flex-col gap-3 px-3.5 py-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="text-[13px]">
+ {soundCount} custom {soundCount === 1 ? "sound" : "sounds"} on
+ this machine
+ </span>
+ <SettingsSelect
+ ariaLabel="Backup contents"
+ value={scope}
+ options={SCOPE_OPTIONS}
+ onChange={(value) => {
+ if (value === "all" || value === "sounds") onScopeChange(value);
+ }}
+ disabled={busy !== null}
+ />
+ </div>
+ <p className="m-0 text-[12px] text-muted-foreground">
+ {scope === "sounds"
+ ? "Includes your custom audio, selected completion sound, volume, and playback speed setting."
+ : "Includes portable preferences, theme, custom instructions, and all custom audio. Accounts, API keys, workspace paths, and machine-specific settings stay on this machine."}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy !== null || review !== null}
+ loading={busy === "export"}
+ onClick={onExport}
+ >
+ <Download />
+ Export backup
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy !== null || review !== null}
+ loading={busy === "open"}
+ onClick={onOpen}
+ >
+ <Upload />
+ Import backup
+ </Button>
+ </div>
+ {error && (
+ <p
+ role="alert"
+ className="m-0 break-words text-[12px] text-destructive"
+ >
+ {error}
+ </p>
+ )}
+ {message && (
+ <output className="m-0 text-[12px] text-muted-foreground">
+ {message}
+ </output>
+ )}
+ </div>
+ {review && (
+ <div className="flex min-w-0 flex-col gap-3 px-3.5 py-3">
+ <div>
+ <h4 className="m-0 font-semibold text-[13px]">Review import</h4>
+ <p className="mt-1 mb-0 break-words text-[12px] text-muted-foreground">
+ Exported from PostHog Desktop {review.backup.appVersion} on{" "}
+ {new Date(review.backup.exportedAt).toLocaleDateString()}.
+ </p>
+ </div>
+ {review.backup.appVersion !== review.currentVersion && (
+ <p className="m-0 rounded border border-(--amber-6) bg-(--amber-2) p-2 text-(--amber-11) text-[12px]">
+ This machine runs {review.currentVersion}. Settings may have
+ changed between versions. Review the warnings before importing.
+ </p>
+ )}
+ <p className="m-0 text-[12px]">
+ {scope === "all"
+ ? `${settingKeys.length} supported settings will replace matching preferences. Settings absent from the backup will stay as they are.`
+ : "Only sounds and their playback settings will be imported."}{" "}
+ Existing custom sounds will be kept. Sounds already imported will
+ not be added again.
+ </p>
+ {settingKeys.length > 0 && (
+ <details className="text-[12px]">
+ <summary className="cursor-pointer font-medium">
+ Show the {settingKeys.length} settings this import writes
+ </summary>
+ <ul
+ aria-label="Settings to import"
+ className="mt-2 mb-0 max-h-40 list-disc space-y-1 overflow-y-auto pl-4"
+ >
+ {settingKeys.map((key) => (
+ <li key={key} className="break-words">
+ {settingLabel(key)}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ {customInstructions !== null && (
+ <div className="rounded border border-(--amber-6) bg-(--amber-2) p-2 text-(--amber-11) text-[12px]">
+ <p className="m-0 font-medium">
+ This import replaces your custom instructions
+ </p>
+ <p className="m-0 mt-1">
+ The agent reads them in every task. Read the text below before
+ you import.
+ </p>
+ <p className="m-0 mt-2 max-h-32 overflow-y-auto whitespace-pre-wrap break-words">
+ {instructionsPreview(customInstructions)}
+ </p>
+ </div>
+ )}
+ {review.sounds.length > 0 && (
+ <details className="text-[12px]">
+ <summary className="cursor-pointer font-medium">
+ Preview {review.sounds.length} custom{" "}
+ {review.sounds.length === 1 ? "sound" : "sounds"}
+ </summary>
+ <ul className="m-0 mt-2 flex max-h-56 list-none flex-col gap-3 overflow-y-auto p-0">
+ {review.sounds.map((sound) => (
+ <li
+ key={sound.id}
+ className="flex flex-wrap items-center justify-between gap-2"
+ >
+ <span className="min-w-0 break-words">
+ {sound.name}{" "}
+ <span className="text-muted-foreground">
+ ({(sound.durationMs / 1000).toFixed(1)}s)
+ </span>
+ </span>
+ {/* biome-ignore lint/a11y/useMediaCaption: notification sound previews contain no supplied captions. */}
+ <audio
+ controls
+ preload="none"
+ src={sound.dataUrl}
+ aria-label={`Preview ${sound.name}`}
+ className="h-8 w-56 max-w-full"
+ />
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ {warnings.length > 0 && (
+ <details open className="text-[12px]">
+ <summary className="cursor-pointer font-medium">
+ {warnings.length} compatibility{" "}
+ {warnings.length === 1 ? "warning" : "warnings"}
+ </summary>
+ <ul
+ aria-label="Compatibility warnings"
+ className="mt-2 mb-0 max-h-40 list-disc space-y-1 overflow-y-auto pl-4"
+ >
+ {warnings.map((warning, index) => (
+ <li key={`${warning.key}-${index}`} className="break-words">
+ <span className="font-medium">
+ {settingLabel(warning.key)}
+ </span>
+ : {WARNING_TEXT[warning.reason]}
+ </li>
+ ))}
+ </ul>
+ </details>
+ )}
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={busy !== null}
+ onClick={onCancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ disabled={busy !== null || !hasImport}
+ loading={busy === "import"}
+ onClick={onImport}
+ >
+ {scope === "sounds"
+ ? "Import sounds"
+ : "Import settings and sounds"}
+ </Button>
+ </div>
+ </div>
+ )}
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
+
+function SettingsBackupConnected(): React.ReactElement {
+ const service = useService<SettingsBackupService>(SETTINGS_BACKUP_SERVICE);
+ const soundCount = useSettingsStore((state) => state.customSounds.length);
+ const [scope, setScope] = useState<BackupScope>("all");
+ const [review, setReview] = useState<BackupReview | null>(null);
+ const [message, setMessage] = useState<string | null>(null);
+ const mutation = useMutation({
+ onMutate: () => setMessage(null),
+ mutationFn: async (operation: BackupOperation): Promise<void> => {
+ switch (operation) {
+ case "export":
+ // A closed save dialog is neither a success nor a failure, so it
+ // reports nothing.
+ if (await service.exportBackup(scope)) {
+ track(ANALYTICS_EVENTS.SETTINGS_BACKUP_EXPORTED, {
+ scope,
+ sound_count: soundCount,
+ });
+ setMessage(
+ "Backup saved. Copy this file to your other machine, then import it in Advanced settings.",
+ );
+ }
+ break;
+ case "open":
+ setReview(await service.openBackup());
+ break;
+ case "import": {
+ if (!review) throw new Error("Choose a backup first.");
+ const added = await service.importBackup(review, scope);
+ track(ANALYTICS_EVENTS.SETTINGS_BACKUP_IMPORTED, {
+ scope,
+ setting_count: importedSettingKeys(review, scope).length,
+ sound_count: review.sounds.length,
+ added_sound_count: added,
+ warning_count: review.warnings.length,
+ backup_app_version: review.backup.appVersion,
+ version_matches: review.backup.appVersion === review.currentVersion,
+ });
+ setReview(null);
+ setMessage(
+ `Backup imported. Added ${added} custom ${added === 1 ? "sound" : "sounds"}. Your settings are ready to use.`,
+ );
+ break;
+ }
+ }
+ },
+ onError: (error: Error, operation) => {
+ if (operation === "export")
+ track(ANALYTICS_EVENTS.SETTINGS_BACKUP_EXPORT_FAILED, {
+ scope,
+ sound_count: soundCount,
+ error: error.message,
+ });
+ else
+ track(ANALYTICS_EVENTS.SETTINGS_BACKUP_IMPORT_FAILED, {
+ scope,
+ stage: operation === "open" ? "open" : "apply",
+ error: error.message,
+ });
+ },
+ });
+ return (
+ <SettingsBackupView
+ soundCount={soundCount}
+ scope={scope}
+ onScopeChange={setScope}
+ review={review}
+ error={mutation.error?.message ?? null}
+ message={message}
+ busy={mutation.isPending ? mutation.variables : null}
+ onExport={() => mutation.mutate("export")}
+ onOpen={() => mutation.mutate("open")}
+ onImport={() => mutation.mutate("import")}
+ onCancel={() => {
+ setReview(null);
+ mutation.reset();
+ }}
+ />
+ );
+}
+
+export function SettingsBackup(): React.ReactElement | null {
+ const available = useSettingsBackupAvailable();
+ return available ? <SettingsBackupConnected /> : null;
+}
diff --git a/products/desktop/packages/ui/src/features/settings/settings.module.ts b/products/desktop/packages/ui/src/features/settings/settings.module.ts
index 4c7ef8aa70ba..76fd8051ee12 100644
--- a/products/desktop/packages/ui/src/features/settings/settings.module.ts
+++ b/products/desktop/packages/ui/src/features/settings/settings.module.ts
@@ -1,7 +1,15 @@
+import {
+ SETTINGS_BACKUP_SERVICE,
+ SETTINGS_BACKUP_STATE,
+ SettingsBackupService,
+} from "@posthog/core/settings/settingsBackup";
import { CONTRIBUTION } from "@posthog/di/contribution";
import { ContainerModule } from "inversify";
import { CustomInstructionsSyncContribution } from "./customInstructionsSync.contribution";
+import { settingsBackupState } from "./settingsBackupState";
export const settingsUiModule = new ContainerModule(({ bind }) => {
+ bind(SETTINGS_BACKUP_STATE).toConstantValue(settingsBackupState);
+ bind(SETTINGS_BACKUP_SERVICE).to(SettingsBackupService).inSingletonScope();
bind(CONTRIBUTION).to(CustomInstructionsSyncContribution).inSingletonScope();
});
diff --git a/products/desktop/packages/ui/src/features/settings/settingsBackupState.test.ts b/products/desktop/packages/ui/src/features/settings/settingsBackupState.test.ts
new file mode 100644
index 000000000000..85f6a654da2c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/settingsBackupState.test.ts
@@ -0,0 +1,89 @@
+import {
+ flushRendererStateWrites,
+ registerRendererStateStorage,
+} from "@posthog/ui/shell/rendererStorage";
+import { useThemeStore } from "@posthog/ui/shell/themeStore";
+import { beforeEach, describe, expect, it } from "vitest";
+import { settingsBackupState } from "./settingsBackupState";
+import { useSettingsStore } from "./settingsStore";
+
+const data = new Map<string, string>();
+registerRendererStateStorage({
+ getItem: (key) => data.get(key) ?? null,
+ setItem: (key, value) => {
+ data.set(key, value);
+ },
+ removeItem: (key) => {
+ data.delete(key);
+ },
+});
+
+beforeEach(async () => {
+ await flushRendererStateWrites();
+ data.clear();
+ await useSettingsStore.persist.rehydrate();
+ useSettingsStore.setState(useSettingsStore.getInitialState());
+ useSettingsStore.getState().setHasHydrated(true);
+ useThemeStore.getState().setTheme("light");
+ await flushRendererStateWrites();
+});
+
+describe("settingsBackupState", () => {
+ it.each([
+ [undefined, "light"],
+ ["dark", "dark"],
+ ] as const)(
+ "applies theme %s and saves imported values through normal persistence",
+ async (theme, expectedTheme) => {
+ const sounds = [
+ {
+ id: "portable",
+ name: "Portable chime",
+ dataUrl: "data:audio/wav;base64,UklGRg==",
+ durationMs: 1000,
+ },
+ ];
+ useSettingsStore.getState().setDefaultMessagingMode("steer");
+ const storedBeforeImport = data.get("settings-storage");
+
+ settingsBackupState.apply({
+ settings: {
+ completionSound: "custom:portable",
+ completionVolume: 42,
+ ...(theme === undefined ? {} : { theme }),
+ },
+ sounds,
+ });
+
+ expect(settingsBackupState.read()).toMatchObject({
+ settings: {
+ theme: expectedTheme,
+ completionSound: "custom:portable",
+ completionVolume: 42,
+ defaultMessagingMode: "steer",
+ },
+ sounds,
+ });
+ expect(data.get("settings-storage")).toBe(storedBeforeImport);
+
+ useSettingsStore.getState().setTipsEnabled(false);
+ await flushRendererStateWrites();
+ const persisted = JSON.parse(data.get("settings-storage") ?? "{}").state;
+ expect(persisted).toMatchObject({
+ customSounds: sounds,
+ completionSound: "custom:portable",
+ completionVolume: 42,
+ defaultMessagingMode: "steer",
+ tipsEnabled: false,
+ });
+ await useSettingsStore.persist.rehydrate();
+ expect(settingsBackupState.read().sounds).toEqual(sounds);
+ expect(useSettingsStore.getState().completionSound).toBe(
+ "custom:portable",
+ );
+ expect(typeof useSettingsStore.getState().addCustomSound).toBe(
+ "function",
+ );
+ },
+ );
+});
diff --git a/products/desktop/packages/ui/src/features/settings/settingsBackupState.ts b/products/desktop/packages/ui/src/features/settings/settingsBackupState.ts
new file mode 100644
index 000000000000..13a52f26d1e4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/settingsBackupState.ts
@@ -0,0 +1,23 @@
+import type {
+ SettingsBackupSnapshot,
+ SettingsBackupState,
+} from "@posthog/core/settings/settingsBackup";
+import { useThemeStore } from "@posthog/ui/shell/themeStore";
+import { useSettingsStore } from "./settingsStore";
+
+export const settingsBackupState: SettingsBackupState = {
+ read(): SettingsBackupSnapshot {
+ const state = useSettingsStore.getState();
+ if (!state._hasHydrated)
+ throw new Error("Settings are still loading. Try again in a moment.");
+ return {
+ settings: { ...state, theme: useThemeStore.getState().theme },
+ sounds: state.customSounds,
+ };
+ },
+ apply({ settings, sounds }: SettingsBackupSnapshot): void {
+ const { theme, ...preferences } = settings;
+ useSettingsStore.setState({ ...preferences, customSounds: sounds });
+ if (theme !== undefined) useThemeStore.getState().setTheme(theme);
+ },
+};
diff --git a/products/desktop/packages/ui/src/features/settings/settingsSearch.test.ts b/products/desktop/packages/ui/src/features/settings/settingsSearch.test.ts
index 301fbb45c6dd..da7c63f045b6 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsSearch.test.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsSearch.test.ts
@@ -6,6 +6,7 @@ const NO_HIDDEN: ReadonlySet<SettingsCategory> = new Set();
describe("searchSettings", () => {
it.each([
+ ["finds backups by export", "export sounds", "Back up settings and sounds"],
["matches labels case-insensitively", "THEME", "Theme"],
[
"matches keywords the label doesn't contain",
@@ -32,4 +33,8 @@ describe("searchSettings", () => {
const results = searchSettings("terminal", hidden);
expect(results.every((r) => r.category !== "terminal")).toBe(true);
});
+
+ it("hides backup search when the host does not provide file access", () => {
+ expect(searchSettings("backup", NO_HIDDEN, false)).toEqual([]);
+ });
});
diff --git a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
index 5d294750203c..76b19d869906 100644
--- a/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
+++ b/products/desktop/packages/ui/src/features/settings/settingsSearch.ts
@@ -7,6 +7,7 @@ export interface SettingsSearchEntry {
category: SettingsCategory;
label: string;
keywords?: string[];
+ requiresBackupFiles?: boolean;
}
// Hand-curated index of the settings each page holds. When a page gains or
@@ -275,6 +276,19 @@ const SETTINGS_SEARCH_INDEX: SettingsSearchEntry[] = [
keywords: ["presence", "integration"],
},
+ {
+ category: "advanced",
+ label: "Back up settings and sounds",
+ requiresBackupFiles: true,
+ keywords: [
+ "backup",
+ "export",
+ "import",
+ "restore",
+ "transfer",
+ "custom sounds",
+ ],
+ },
{
category: "advanced",
label: "Always create pull requests for cloud runs",
@@ -326,12 +340,15 @@ function tokenScore(entry: SettingsSearchEntry, token: string): number {
export function searchSettings(
query: string,
hiddenCategories: ReadonlySet<SettingsCategory>,
+ backupAvailable = true,
): SettingsSearchEntry[] {
const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
if (tokens.length === 0) return [];
return SETTINGS_SEARCH_INDEX.filter(
- (entry) => !hiddenCategories.has(entry.category),
+ (entry) =>
+ !hiddenCategories.has(entry.category) &&
+ (backupAvailable || !entry.requiresBackupFiles),
)
.map((entry) => {
let score = 0;
diff --git a/products/desktop/packages/ui/src/utils/customSound.ts b/products/desktop/packages/ui/src/utils/customSound.ts
index a74bbd27b4f9..b686d50b5ae6 100644
--- a/products/desktop/packages/ui/src/utils/customSound.ts
+++ b/products/desktop/packages/ui/src/utils/customSound.ts
@@ -1,3 +1,9 @@
+import {
+ DURATION_TOLERANCE_MS,
+ MAX_CUSTOM_SOUND_BYTES,
+ MAX_CUSTOM_SOUND_DURATION_MS,
+} from "@posthog/core/settings/schemas";
+
// Helpers for capturing user-installed notification sounds (live recording or
// file import). Custom clips are stored inline as base64 data URLs in the
// settings store, so they're deliberately short: the duration cap keeps that
@@ -5,19 +11,19 @@
// Hard cap on clip length. Live recordings auto-stop here; imported files longer
// than this are rejected.
-export const MAX_CUSTOM_SOUND_DURATION_MS = 5_000;
+export { MAX_CUSTOM_SOUND_DURATION_MS };
// Backstop on the stored payload regardless of reported duration (e.g. a
// high-bitrate import). ~1 MB of base64 sits comfortably within the settings
// store.
-export const MAX_CUSTOM_SOUND_BYTES = 1_000_000;
+export { MAX_CUSTOM_SOUND_BYTES };
// Seconds form of the duration cap, for display copy.
export const MAX_CUSTOM_SOUND_SECONDS = MAX_CUSTOM_SOUND_DURATION_MS / 1000;
// Decoded durations can read a touch over the cap (encoder rounding); allow a
// small slack before rejecting an otherwise-fine clip.
-export const DURATION_TOLERANCE_MS = 300;
+export { DURATION_TOLERANCE_MS };
// Preferred recorder containers, best first. Chromium (the Electron renderer)
// records Opus-in-WebM; the fallbacks cover other hosts.