Skip to content

Commit 47db4e3

Browse files
benjaminshafiiBenjamin Shafii
andauthored
feat(desktop): migration engine for Tauri → Electron (draft, do not merge) (anomalyco#1523)
* feat(desktop): migration engine for Tauri → Electron handoff Implements the infrastructure needed to move users from Tauri to Electron without losing state or Launchpad/Dock presence. Zero user impact on its own — this becomes live only when paired with a final Tauri release that calls the snapshot writer and installs Electron. What lands here: - Unify app identity with Tauri. electron-builder appId goes from com.differentai.openwork.electron → com.differentai.openwork so macOS reuses the same bundle identifier (no duplicate Dock icon, no new Gatekeeper prompt, same TCC permissions). - Unify userData path. Electron's app.setPath("userData", ...) now points at the exact folder Tauri uses (~/Library/Application Support/com.differentai.openwork on macOS, %APPDATA%/com.differentai.openwork on Windows, ~/.config/ com.differentai.openwork on Linux). An OPENWORK_ELECTRON_USERDATA env var override is available for dogfooders who want isolation. - Filename compat. On first launch, Electron copies Tauri's openwork-workspaces.json → workspace-state.json (leaves the legacy file in place for rollback safety). - electron-updater wiring. New deps + IPC handlers (openwork:updater:check / download / installAndRestart). Packaged-only. Publish config points at the same GitHub release as Tauri. - Migration snapshot plumbing. * Tauri Rust command `write_migration_snapshot` serializes an allowlist of localStorage keys to app_data_dir/migration-snapshot.v1.json. * `apps/app/src/app/lib/migration.ts` has matching writeMigrationSnapshotFromTauri() / ingestMigrationSnapshotOnElectronBoot(). * Scope: workspace list + selection only (openwork.react.activeWorkspace, .sessionByWorkspace, openwork.server.list/active/urlOverride/token). Everything else is cheap to redo. * Electron main exposes openwork:migration:read / ack IPC; preload bridges them under window.__OPENWORK_ELECTRON__.migration. * desktop-runtime-boot.ts ingests the snapshot once on first launch, hydrates empty localStorage keys, then acks. - Updated prds/electron-migration-plan.md with the localStorage scope decision and the remaining work (last Tauri release ships the UI prompt + installer downloader). Verified: `pnpm --filter @openwork/app typecheck` ✓, `pnpm --filter @openwork/desktop build:electron` ✓, `cargo check` against src-tauri ✓. * fix(desktop): emit relative asset paths for Electron packaged builds Packaged Electron loads index.html via file:// (Contents/Resources/app-dist/ index.html inside the .app bundle), but Vite was building with the default base: '/' which resolves /assets/*.js to the filesystem root. Result: a working dev experience (Vite dev server on localhost:5173) and a broken packaged .app that renders an empty <div id="root"></div>. The Tauri shell doesn't hit this because Tauri serves the built HTML through its own tauri:// protocol which rewrites paths. Electron's file:// loader has no such rewriter. Fix: electron-build.mjs sets OPENWORK_ELECTRON_BUILD=1 when invoking vite build, and vite.config.ts flips base to './' only when that env var is set. Dev server and Tauri builds unchanged. Discovered while manually exercising the Electron prod-build migration flow (packaged app launch, snapshot ingest, idempotency, updater IPC). Latent since PR anomalyco#1522 landed the packaged build path; never caught because dogfood ran via dev:electron which uses the Vite dev server. --------- Co-authored-by: Benjamin Shafii <[email protected]>
1 parent a9fd83e commit 47db4e3

13 files changed

Lines changed: 551 additions & 23 deletions

File tree

‎apps/app/src/app/lib/migration.ts‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
// One-way Tauri → Electron migration snapshot plumbing.
2+
//
3+
// The Tauri shell exports localStorage keys the user actively depends on
4+
// (workspace list, selected workspace, per-workspace last-session, server
5+
// list) into a JSON file in app_data_dir just before launching the
6+
// Electron installer. Electron reads that file on first launch, hydrates
7+
// localStorage for the keys that are still empty, then marks the file as
8+
// acknowledged.
9+
//
10+
// Scope decision: we migrate *workspace* keys only. Everything else
11+
// (theme, font zoom, sidebar widths, feature flags) is cheap to redo and
12+
// not worth the complexity of a cross-origin localStorage transfer.
13+
14+
import { invoke } from "@tauri-apps/api/core";
15+
16+
export const MIGRATION_SNAPSHOT_VERSION = 1;
17+
18+
// Keep this list tiny and strict. Adding keys here expands blast radius
19+
// if a later release renames them.
20+
export const MIGRATION_KEY_PATTERNS: Array<RegExp> = [
21+
/^openwork\.react\.activeWorkspace$/,
22+
/^openwork\.react\.sessionByWorkspace$/,
23+
/^openwork\.server\.list$/,
24+
/^openwork\.server\.active$/,
25+
/^openwork\.server\.urlOverride$/,
26+
/^openwork\.server\.token$/,
27+
];
28+
29+
export type MigrationSnapshot = {
30+
version: typeof MIGRATION_SNAPSHOT_VERSION;
31+
writtenAt: number;
32+
source: "tauri";
33+
keys: Record<string, string>;
34+
};
35+
36+
function matchesMigrationKey(key: string) {
37+
return MIGRATION_KEY_PATTERNS.some((pattern) => pattern.test(key));
38+
}
39+
40+
function collectMigrationKeysFromLocalStorage(): Record<string, string> {
41+
const out: Record<string, string> = {};
42+
if (typeof window === "undefined") return out;
43+
for (let i = 0; i < window.localStorage.length; i++) {
44+
const key = window.localStorage.key(i);
45+
if (!key || !matchesMigrationKey(key)) continue;
46+
const value = window.localStorage.getItem(key);
47+
if (value != null) out[key] = value;
48+
}
49+
return out;
50+
}
51+
52+
/**
53+
* Tauri-only. Called by the last Tauri release right before it kicks off
54+
* the Electron installer. Snapshots the workspace-related localStorage
55+
* keys to <app_data_dir>/migration-snapshot.v1.json via a Rust command
56+
* that does the actual disk write (renderer can't write outside the
57+
* sandbox on its own).
58+
*/
59+
export async function writeMigrationSnapshotFromTauri(): Promise<{
60+
ok: boolean;
61+
keyCount: number;
62+
reason?: string;
63+
}> {
64+
try {
65+
const keys = collectMigrationKeysFromLocalStorage();
66+
const snapshot: MigrationSnapshot = {
67+
version: MIGRATION_SNAPSHOT_VERSION,
68+
writtenAt: Date.now(),
69+
source: "tauri",
70+
keys,
71+
};
72+
await invoke("write_migration_snapshot", { snapshot });
73+
return { ok: true, keyCount: Object.keys(keys).length };
74+
} catch (error) {
75+
return {
76+
ok: false,
77+
keyCount: 0,
78+
reason: error instanceof Error ? error.message : String(error),
79+
};
80+
}
81+
}
82+
83+
type ElectronMigrationBridge = {
84+
readSnapshot: () => Promise<MigrationSnapshot | null>;
85+
ackSnapshot: () => Promise<{ ok: boolean; moved: boolean }>;
86+
};
87+
88+
function electronMigrationBridge(): ElectronMigrationBridge | null {
89+
if (typeof window === "undefined") return null;
90+
const bridge = (window as unknown as {
91+
__OPENWORK_ELECTRON__?: { migration?: ElectronMigrationBridge };
92+
}).__OPENWORK_ELECTRON__;
93+
return bridge?.migration ?? null;
94+
}
95+
96+
/**
97+
* Electron-only. Called once during app boot. Reads the migration
98+
* snapshot (if any), hydrates localStorage for keys that aren't already
99+
* set on the Electron install, and acks the file so we don't re-ingest
100+
* on subsequent launches.
101+
*
102+
* Returns the number of keys hydrated. Returns 0 when there is no
103+
* snapshot, which is the steady-state case after the first launch.
104+
*/
105+
export async function ingestMigrationSnapshotOnElectronBoot(): Promise<number> {
106+
const bridge = electronMigrationBridge();
107+
if (!bridge) return 0;
108+
109+
let snapshot: MigrationSnapshot | null = null;
110+
try {
111+
snapshot = await bridge.readSnapshot();
112+
} catch {
113+
return 0;
114+
}
115+
if (!snapshot || snapshot.version !== MIGRATION_SNAPSHOT_VERSION) return 0;
116+
117+
const entries = Object.entries(snapshot.keys ?? {});
118+
let hydrated = 0;
119+
if (typeof window !== "undefined") {
120+
for (const [key, value] of entries) {
121+
if (!matchesMigrationKey(key)) continue;
122+
if (window.localStorage.getItem(key) != null) continue;
123+
try {
124+
window.localStorage.setItem(key, value);
125+
hydrated += 1;
126+
} catch {
127+
// localStorage write failures are non-fatal; the user just won't
128+
// see that key migrated this launch.
129+
}
130+
}
131+
}
132+
133+
try {
134+
await bridge.ackSnapshot();
135+
} catch {
136+
// A failed ack means we'll re-ingest on next launch, but the
137+
// "skip if already set" guard keeps that idempotent.
138+
}
139+
140+
return hydrated;
141+
}

‎apps/app/src/react-app/shell/desktop-runtime-boot.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ import {
99
resolveWorkspaceListSelectedId,
1010
workspaceBootstrap,
1111
} from "../../app/lib/desktop";
12+
import { ingestMigrationSnapshotOnElectronBoot } from "../../app/lib/migration";
1213
import { hydrateOpenworkServerSettingsFromEnv, writeOpenworkServerSettings } from "../../app/lib/openwork-server";
13-
import { isDesktopRuntime, safeStringify } from "../../app/utils";
14+
import { isDesktopRuntime, isElectronRuntime, safeStringify } from "../../app/utils";
1415
import { useServer } from "../kernel/server-provider";
1516
import { useBootState } from "./boot-state";
1617

@@ -45,6 +46,18 @@ export function useDesktopRuntimeBoot() {
4546

4647
void (async () => {
4748
try {
49+
// On Electron specifically: if the previous Tauri install dropped
50+
// a migration snapshot, fold it into localStorage before any of
51+
// the boot code reads workspace preferences. Idempotent across
52+
// launches (the helper only writes keys that are still empty
53+
// and acks the file after ingestion).
54+
if (isElectronRuntime()) {
55+
const hydrated = await ingestMigrationSnapshotOnElectronBoot();
56+
if (hydrated > 0) {
57+
// eslint-disable-next-line no-console -- valuable one-time signal
58+
console.info(`[migration] hydrated ${hydrated} localStorage keys from Tauri snapshot`);
59+
}
60+
}
4861
hydrateOpenworkServerSettingsFromEnv();
4962

5063
setPhase("bootstrapping-workspaces");

‎apps/app/vite.config.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ if (shortHostname && shortHostname !== hostname) {
2626
}
2727
const appRoot = resolve(fileURLToPath(new URL(".", import.meta.url)));
2828

29+
// Electron packaged builds load index.html via `file://`, so asset URLs
30+
// must be relative. Tauri serves via its own protocol so absolute paths
31+
// work there. Gate on an env var the electron build script sets.
32+
const isElectronPackagedBuild = process.env.OPENWORK_ELECTRON_BUILD === "1";
33+
2934
export default defineConfig({
35+
base: isElectronPackagedBuild ? "./" : "/",
3036
plugins: [
3137
{
3238
name: "openwork-dev-server-id",

‎apps/desktop/electron-builder.yml‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
appId: com.differentai.openwork.electron
1+
# IMPORTANT: appId intentionally matches the Tauri shell so both builds share
2+
# the same macOS bundle identifier, keychain entries, Launchpad slot, and TCC
3+
# permissions. In-place migration from Tauri to Electron depends on this.
4+
appId: com.differentai.openwork
25
productName: OpenWork
36
directories:
47
output: dist-electron
@@ -12,11 +15,24 @@ extraResources:
1215
to: sidecars
1316
asar: true
1417
npmRebuild: false
18+
# electron-updater feed. Matches the existing release workflow's GitHub target
19+
# so both Tauri (latest.json) and Electron (latest*.yml) can live on the same
20+
# release assets during the migration window.
21+
publish:
22+
- provider: github
23+
owner: different-ai
24+
repo: openwork
25+
releaseType: release
1526
mac:
1627
icon: src-tauri/icons/icon.icns
28+
category: public.app-category.developer-tools
29+
hardenedRuntime: true
30+
gatekeeperAssess: false
1731
target:
18-
- dmg
19-
- zip
32+
- target: dmg
33+
arch: [x64, arm64]
34+
- target: zip
35+
arch: [x64, arm64]
2036
linux:
2137
icon: src-tauri/icons/icon.png
2238
target:
@@ -26,4 +42,4 @@ win:
2642
icon: src-tauri/icons/icon.ico
2743
target:
2844
- nsis
29-
artifactName: openwork-electron-${os}-${arch}-${version}.${ext}
45+
artifactName: openwork-${os}-${arch}-${version}.${ext}

0 commit comments

Comments
 (0)