diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index d70694a7a8538..066032dbb2bd3 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -51,7 +51,9 @@ const watchedDirectories = [ const forcedShutdownTimeoutMs = 1_500; const restartDebounceMs = 120; const childTreeGracePeriodMs = 1_200; -const remoteDebuggingPort = process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); +const remoteDebuggingPort = + process.env.M3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim() || + process.env.T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT?.trim(); // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone dev script has no Effect runtime. const hostPlatform = NodeOS.platform(); const parentPid = process.ppid; @@ -79,8 +81,8 @@ const childEnv = { ...process.env }; delete childEnv.ELECTRON_RUN_AS_NODE; const devProtocolClient = resolveDevProtocolClient(); if (devProtocolClient) { - childEnv.T3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId; - childEnv.T3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1"; + childEnv.M3CODE_DESKTOP_APP_USER_MODEL_ID = devProtocolClient.appBundleId; + childEnv.M3CODE_DESKTOP_PROTOCOL_REGISTRATION_MANAGED = "1"; } let shuttingDown = false; diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index b3aa4a16c29e9..f41a2c2e4047d 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -15,9 +15,9 @@ const devBundleIdSuffix = NodePath.basename(repoRoot) .replaceAll(/[^a-z0-9]+/g, ""); const APP_DISPLAY_NAME = isDevelopment ? "M3 Code (Dev)" : "M3 Code (Beta)"; const APP_BUNDLE_ID = isDevelopment - ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}` - : "com.t3tools.t3code"; -const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"]; + ? `com.m3code.m3code.dev.${devBundleIdSuffix || "local"}` + : "com.m3code.m3code"; +const APP_PROTOCOL_SCHEMES = isDevelopment ? ["m3code-dev", "t3code-dev"] : ["m3code", "t3code"]; const LAUNCHER_VERSION = 21; const developmentMacIconPngPath = NodePath.join( repoRoot, @@ -109,10 +109,10 @@ function shellSingleQuote(value) { export function makeDevelopmentEnvironmentScript(environment) { const envEntries = [ ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL], - ["T3CODE_PORT", environment.T3CODE_PORT], - ["T3CODE_HOME", environment.T3CODE_HOME], - ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH], - ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID], + ["M3CODE_PORT", environment.M3CODE_PORT ?? environment.T3CODE_PORT], + ["M3CODE_HOME", environment.M3CODE_HOME ?? environment.T3CODE_HOME], + ["M3CODE_COMMIT_HASH", environment.M3CODE_COMMIT_HASH ?? environment.T3CODE_COMMIT_HASH], + ["M3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID], ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0); return [ ...envEntries.map( diff --git a/apps/desktop/scripts/electron-launcher.test.mjs b/apps/desktop/scripts/electron-launcher.test.mjs index 4c8fb996c7596..64f292a5034a5 100644 --- a/apps/desktop/scripts/electron-launcher.test.mjs +++ b/apps/desktop/scripts/electron-launcher.test.mjs @@ -30,7 +30,7 @@ describe("electron development launcher", () => { ); assert.include( environmentScript, - "if [ -z \"${T3CODE_COMMIT_HASH:-}\" ]; then export T3CODE_COMMIT_HASH='abc123'; fi", + "if [ -z \"${M3CODE_COMMIT_HASH:-}\" ]; then export M3CODE_COMMIT_HASH='abc123'; fi", ); assert.notInclude(environmentScript, "\nexport VITE_DEV_SERVER_URL="); }); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 970db1a707d63..9554f3f13cb0f 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -77,7 +77,7 @@ export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErr {}, ) { override get message(): string { - return "T3CODE_PORT is required in desktop development."; + return "M3CODE_PORT (or legacy T3CODE_PORT) is required in desktop development."; } } diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index 39329ddcd7468..89fdcc8216715 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -10,11 +10,32 @@ const trimNonEmptyOption = (value: string): Option.Option => { export const trimmedString = (name: string) => Config.String(name).pipe(Config.option, Config.map(Option.flatMap(trimNonEmptyOption))); -const optionalBoolean = (name: string) => - Config.Boolean(name).pipe(Config.option, Config.map(Option.getOrElse(() => false))); +export const trimmedStringWithLegacy = (primary: string, legacy: string) => + Config.all([trimmedString(primary), trimmedString(legacy)]).pipe( + Config.map(([next, prev]) => Option.orElse(next, () => prev)), + ); + +const optionalBooleanWithLegacy = (primary: string, legacy: string) => + Config.all([ + Config.Boolean(primary).pipe(Config.option), + Config.Boolean(legacy).pipe(Config.option), + ]).pipe( + Config.map(([next, prev]) => + Option.getOrElse( + Option.orElse(next, () => prev), + () => false, + ), + ), + ); + +const optionalPortWithLegacy = (primary: string, legacy: string) => + Config.all([ + Config.Port(primary).pipe(Config.option), + Config.Port(legacy).pipe(Config.option), + ]).pipe(Config.map(([next, prev]) => Option.orElse(next, () => prev))); -const commaSeparatedStrings = (name: string) => - trimmedString(name).pipe( +const commaSeparatedStringsWithLegacy = (primary: string, legacy: string) => + trimmedStringWithLegacy(primary, legacy).pipe( Config.map( Option.match({ onNone: () => [], @@ -36,21 +57,43 @@ export const DesktopConfig = Config.all({ appDataDirectory: trimmedString("APPDATA"), xdgConfigHome: trimmedString("XDG_CONFIG_HOME"), xdgDataHome: trimmedString("XDG_DATA_HOME"), - t3Home: trimmedString("T3CODE_HOME"), + t3Home: trimmedStringWithLegacy("M3CODE_HOME", "T3CODE_HOME"), devServerUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option), - appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"), - devRemoteT3ServerEntryPath: trimmedString("T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH"), - configuredBackendPort: Config.Port("T3CODE_PORT").pipe(Config.option), - commitHashOverride: trimmedString("T3CODE_COMMIT_HASH"), - desktopLanHostOverride: trimmedString("T3CODE_DESKTOP_LAN_HOST"), - desktopHttpsEndpointUrls: commaSeparatedStrings("T3CODE_DESKTOP_HTTPS_ENDPOINTS"), - desktopLauncherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), + appUserModelIdOverride: trimmedStringWithLegacy( + "M3CODE_DESKTOP_APP_USER_MODEL_ID", + "T3CODE_DESKTOP_APP_USER_MODEL_ID", + ), + devRemoteT3ServerEntryPath: trimmedStringWithLegacy( + "M3CODE_DEV_REMOTE_M3_SERVER_ENTRY_PATH", + "T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH", + ), + configuredBackendPort: optionalPortWithLegacy("M3CODE_PORT", "T3CODE_PORT"), + commitHashOverride: trimmedStringWithLegacy("M3CODE_COMMIT_HASH", "T3CODE_COMMIT_HASH"), + desktopLanHostOverride: trimmedStringWithLegacy( + "M3CODE_DESKTOP_LAN_HOST", + "T3CODE_DESKTOP_LAN_HOST", + ), + desktopHttpsEndpointUrls: commaSeparatedStringsWithLegacy( + "M3CODE_DESKTOP_HTTPS_ENDPOINTS", + "T3CODE_DESKTOP_HTTPS_ENDPOINTS", + ), + desktopLauncherPath: trimmedStringWithLegacy( + "M3CODE_DESKTOP_LAUNCHER_PATH", + "T3CODE_DESKTOP_LAUNCHER_PATH", + ), appImagePath: trimmedString("APPIMAGE"), - disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"), - mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"), - mockUpdateServerPort: Config.Port("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe( - Config.withDefault(3000), + disableAutoUpdate: optionalBooleanWithLegacy( + "M3CODE_DISABLE_AUTO_UPDATE", + "T3CODE_DISABLE_AUTO_UPDATE", + ), + mockUpdates: optionalBooleanWithLegacy( + "M3CODE_DESKTOP_MOCK_UPDATES", + "T3CODE_DESKTOP_MOCK_UPDATES", ), + mockUpdateServerPort: optionalPortWithLegacy( + "M3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT", + "T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT", + ).pipe(Config.map(Option.getOrElse(() => 3000))), }); export const layerTest = (env: Readonly>) => diff --git a/apps/desktop/src/app/DesktopEarlyElectronStartup.ts b/apps/desktop/src/app/DesktopEarlyElectronStartup.ts index 3c571bcf02b1f..899731a30d02d 100644 --- a/apps/desktop/src/app/DesktopEarlyElectronStartup.ts +++ b/apps/desktop/src/app/DesktopEarlyElectronStartup.ts @@ -20,6 +20,7 @@ interface EarlyDesktopSettingsInput { readonly homeDirectory: string; readonly joinPath: JoinPath; readonly readFileString: (path: string) => string; + readonly pathExists?: (path: string) => boolean; } type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput; @@ -31,7 +32,7 @@ export interface EarlyLinuxElectronOptions { } export const resolveLinuxDesktopEntryName = (isDevelopment: boolean): string => - isDevelopment ? "com.t3tools.T3Code.Development.desktop" : "com.t3tools.T3Code.desktop"; + isDevelopment ? "com.m3code.M3Code.Development.desktop" : "com.m3code.M3Code.desktop"; const trimNonEmpty = (value: string | undefined): string | null => { const trimmed = value?.trim(); @@ -52,12 +53,16 @@ function resolveEarlyDesktopSettingsPath(input: { readonly env: NodeJS.ProcessEnv; readonly homeDirectory: string; readonly joinPath: JoinPath; + readonly pathExists?: (path: string) => boolean; }): string { - const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME); + const t3Home = Option.fromUndefinedOr( + trimNonEmpty(input.env.M3CODE_HOME) ?? trimNonEmpty(input.env.T3CODE_HOME) ?? undefined, + ); const baseDir = resolveDesktopBaseDir({ homeDirectory: input.homeDirectory, joinPath: input.joinPath, t3Home, + ...(input.pathExists ? { pathExists: input.pathExists } : {}), }); const stateDir = resolveDesktopStateDir({ baseDir, diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts index 060c8328d7c8d..b756d810a0ec4 100644 --- a/apps/desktop/src/app/DesktopEnvironment.test.ts +++ b/apps/desktop/src/app/DesktopEnvironment.test.ts @@ -68,8 +68,8 @@ describe("DesktopEnvironment", () => { ); const production = yield* makeEnvironment(); - assert.equal(development.stateDir, "/Users/alice/.t3/dev"); - assert.equal(production.stateDir, "/Users/alice/.t3/userdata"); + assert.equal(development.stateDir, "/Users/alice/.m3/dev"); + assert.equal(production.stateDir, "/Users/alice/.m3/userdata"); }), ); }); diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index b98546d585388..4884d249ad967 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -7,6 +7,7 @@ import type { import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -149,10 +150,23 @@ const make = Effect.fn("desktop.environment.make")(function* ( : input.platform === "darwin" ? path.join(homeDirectory, "Library", "Application Support") : Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config")); + const maybeFileSystem = yield* Effect.serviceOption(FileSystem.FileSystem); + const m3Dir = path.join(homeDirectory, ".m3"); + const legacyT3Dir = path.join(homeDirectory, ".t3"); + const existingPaths = new Set(); + if (Option.isNone(config.t3Home) && Option.isSome(maybeFileSystem)) { + const fs = maybeFileSystem.value; + if (yield* fs.exists(m3Dir).pipe(Effect.orElseSucceed(() => false))) { + existingPaths.add(m3Dir); + } else if (yield* fs.exists(legacyT3Dir).pipe(Effect.orElseSucceed(() => false))) { + existingPaths.add(legacyT3Dir); + } + } const baseDir = resolveDesktopBaseDir({ homeDirectory, joinPath: path.join, t3Home: config.t3Home, + pathExists: (candidate) => existingPaths.has(candidate), }); const rootDir = path.resolve(input.dirname, "../../.."); const appRoot = input.isPackaged ? input.appPath : rootDir; @@ -215,7 +229,7 @@ const make = Effect.fn("desktop.environment.make")(function* ( branding, displayName, appUserModelId: Option.getOrElse(config.appUserModelIdOverride, () => - isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code", + isDevelopment ? "com.m3code.m3code.dev" : "com.m3code.m3code", ), linuxDesktopEntryName: resolveLinuxDesktopEntryName(isDevelopment), linuxApplicationsDir, diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index af3f83d31c77b..a732b44887043 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -134,7 +134,7 @@ describe("DesktopPreReadyPlatform", () => { let desktopEntry = previousEntry; let iconInstalled = false; const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png"; - const iconPath = "/xdg/icons/com.t3tools.T3Code.desktop.png"; + const iconPath = "/xdg/icons/com.m3code.M3Code.desktop.png"; const iconBytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); readFileSyncMock.mockImplementation((path: string) => { if (path === iconSource) return iconBytes; @@ -144,7 +144,7 @@ describe("DesktopPreReadyPlatform", () => { desktopName = name; }); writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { - if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = String(contents); + if (path === "/xdg/applications/com.m3code.M3Code.desktop") desktopEntry = String(contents); if (path === iconPath) iconInstalled = Buffer.compare(Buffer.from(contents), iconBytes) === 0; }); @@ -167,13 +167,13 @@ describe("DesktopPreReadyPlatform", () => { ), ); const identity = yield* Effect.promise(() => portalIdentity); - assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop"); + assert.equal(identity.desktopName, "com.m3code.M3Code.desktop"); assert.include(identity.desktopEntry ?? "", "Exec=/Applications/current.AppImage %U"); assert.include(identity.desktopEntry ?? "", "Name=M3 Code (Beta)"); assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;"); assert.include( identity.desktopEntry ?? "", - "Icon=/xdg/icons/com.t3tools.T3Code.desktop.png", + "Icon=/xdg/icons/com.m3code.M3Code.desktop.png", ); assert.equal( copyFileSyncMock.mock.calls.length, @@ -193,7 +193,7 @@ describe("DesktopPreReadyPlatform", () => { ({ relaunchedByUpdater, restored }) => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); getSwitchValueMock.mockReturnValue(""); - const entryPath = "/xdg/applications/com.t3tools.T3Code.desktop"; + const entryPath = "/xdg/applications/com.m3code.M3Code.desktop"; const files = new Map([[entryPath, "Exec=/Applications/T3-Code-0.1.8-x86_64.AppImage %U\n"]]); readFileSyncMock.mockImplementation((path: string) => files.get(path) ?? "{}"); writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { @@ -245,7 +245,7 @@ describe("DesktopPreReadyPlatform", () => { ), ); const entry = writeFileSyncMock.mock.calls.find( - ([path]) => path === "/xdg/applications/com.t3tools.T3Code.desktop", + ([path]) => path === "/xdg/applications/com.m3code.M3Code.desktop", )?.[1]; assert.include(entry, 'Exec="/opt/M3 Code/t3code" %U'); }), diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index 8ac4654636ab6..6149b2f2d71b3 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -12,7 +12,7 @@ import * as Electron from "electron"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts"; -import { trimmedString } from "./DesktopConfig.ts"; +import { trimmedString, trimmedStringWithLegacy } from "./DesktopConfig.ts"; import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts"; import { renderUrlHandlerDesktopEntry, @@ -45,6 +45,13 @@ export const resolveEarlyLinuxElectronOptionsFromProcess = ( homeDirectory, joinPath: NodePath.posix.join, readFileString: (path) => NodeFS.readFileSync(path, "utf8"), + pathExists: (path) => { + try { + return typeof NodeFS.existsSync === "function" && NodeFS.existsSync(path); + } catch { + return false; + } + }, }); export class DesktopPreReadyElectronOptions extends Context.Service< @@ -57,7 +64,10 @@ export class DesktopPreReadyElectronOptions extends Context.Service< const LinuxDesktopEntryConfig = Config.all({ xdgDataHome: trimmedString("XDG_DATA_HOME"), - launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), + launcherPath: trimmedStringWithLegacy( + "M3CODE_DESKTOP_LAUNCHER_PATH", + "T3CODE_DESKTOP_LAUNCHER_PATH", + ), appImagePath: trimmedString("APPIMAGE"), // electron-updater sets this on the AppImage it relaunches after installing an update. relaunchedByUpdater: trimmedString("APPIMAGE_SILENT_INSTALL"), @@ -83,6 +93,13 @@ export const make = Effect.gen(function* () { joinPath: NodePath.posix.join, commandLine: Electron.app.commandLine, readFileString: (path) => NodeFS.readFileSync(path, "utf8"), + pathExists: (path) => { + try { + return typeof NodeFS.existsSync === "function" && NodeFS.existsSync(path); + } catch { + return false; + } + }, writeFileString: (path, value) => { NodeFS.mkdirSync(NodePath.posix.dirname(path), { recursive: true }); NodeFS.writeFileSync(path, value, "utf8"); diff --git a/apps/desktop/src/app/DesktopStatePaths.ts b/apps/desktop/src/app/DesktopStatePaths.ts index 006dd97092d42..bd64e22a4a67e 100644 --- a/apps/desktop/src/app/DesktopStatePaths.ts +++ b/apps/desktop/src/app/DesktopStatePaths.ts @@ -10,14 +10,24 @@ function normalizeConfiguredBaseDir(t3Home: Option.Option): Option.Optio return trimmed.length > 0 ? Option.some(trimmed) : Option.none(); } +/** + * Resolves the desktop base dir: explicit `M3CODE_HOME`/`T3CODE_HOME`, else `~/.m3`, + * falling back to legacy `~/.t3` when `~/.m3` does not exist yet and `~/.t3` exists. + */ export function resolveDesktopBaseDir(input: { readonly homeDirectory: string; readonly joinPath: JoinPath; readonly t3Home: Option.Option; + readonly pathExists?: (path: string) => boolean; }): string { - return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () => - input.joinPath(input.homeDirectory, ".t3"), - ); + return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () => { + const m3Dir = input.joinPath(input.homeDirectory, ".m3"); + const legacyT3Dir = input.joinPath(input.homeDirectory, ".t3"); + if (input.pathExists && !input.pathExists(m3Dir) && input.pathExists(legacyT3Dir)) { + return legacyT3Dir; + } + return m3Dir; + }); } export function resolveDesktopStateDir(input: { diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 24c32dba18bde..9ee1ebe4e1da9 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -52,6 +52,15 @@ export class DesktopBackendConfiguration extends Context.Service< >()("@t3tools/desktop/backend/DesktopBackendConfiguration") {} const DESKTOP_BACKEND_ENV_NAMES = [ + "M3CODE_PORT", + "M3CODE_MODE", + "M3CODE_NO_BROWSER", + "M3CODE_HOST", + "M3CODE_DESKTOP_WS_URL", + "M3CODE_DESKTOP_LAN_HOST", + "M3CODE_DESKTOP_HTTPS_ENDPOINTS", + "M3CODE_TAILSCALE_SERVE", + "M3CODE_TAILSCALE_SERVE_PORT", "T3CODE_PORT", "T3CODE_MODE", "T3CODE_NO_BROWSER", @@ -576,7 +585,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const parentEnvWithoutT3Home: Record = {}; for (const [key, value] of Object.entries(env)) { - if (key === "T3CODE_HOME") continue; + if (key === "M3CODE_HOME" || key === "T3CODE_HOME") continue; parentEnvWithoutT3Home[key] = value; } const wslEnv = mergeWslEnv(parentEnvWithoutT3Home.WSLENV, forwardedEnvNames); diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index c2be2f901366a..53f82fbaf81d4 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -13,7 +13,8 @@ const domTests = ["src/preview/PickPreload.test.ts"]; // Install only bundle externals; the server bundle already carries its dependency tree. const isMainProcessExternal = (id: string) => id === "electron" || id.startsWith("electron/") || isDesktopRuntimeExternalDependency(id); -const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1"; +const shouldLaunchElectronAfterPack = + (process.env.M3CODE_DESKTOP_DEV ?? process.env.T3CODE_DESKTOP_DEV) === "1"; // tsdown runs onSuccess through a shell. dash forks instead of exec'ing the last command, which // would leave an `sh` between `vp pack` and the supervisor and hide `vp pack` dying from it. const devElectronCommand = @@ -66,7 +67,7 @@ export default defineConfig({ }, dev: { command: - "node scripts/build-browser-secret.mjs && node scripts/build-apple-speech.mjs && node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch", + "node scripts/build-browser-secret.mjs && node scripts/build-apple-speech.mjs && node scripts/build-preview-annotation-css.mjs && cross-env M3CODE_DESKTOP_DEV=1 vp pack --watch", dependsOn: ["t3#build:bundle"], cache: false, }, diff --git a/apps/server/package.json b/apps/server/package.json index 98e1e269000b8..f9522703d3369 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -8,6 +8,7 @@ "directory": "apps/server" }, "bin": { + "m3": "./dist/bin.mjs", "t3": "./dist/bin.mjs" }, "files": [ diff --git a/apps/server/src/cli/app.ts b/apps/server/src/cli/app.ts index de4d6003eb9a9..a43cfcbf78f31 100644 --- a/apps/server/src/cli/app.ts +++ b/apps/server/src/cli/app.ts @@ -192,7 +192,19 @@ async function sendDesktopAppActivationRequest(input: { } const appEnvironment = Config.all({ - t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + t3Home: Config.all([ + Config.String("M3CODE_HOME").pipe(Config.option), + Config.String("T3CODE_HOME").pipe(Config.option), + ]).pipe( + Config.map(([next, prev]) => + Option.getOrUndefined( + Option.orElse( + Option.filter(next, (value) => value.trim().length > 0), + () => Option.filter(prev, (value) => value.trim().length > 0), + ), + ), + ), + ), sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option), sshTty: Config.String("SSH_TTY").pipe(Config.option), }); diff --git a/apps/server/src/cli/browser.ts b/apps/server/src/cli/browser.ts index a82b84ef82d4b..38423ed0f01ab 100644 --- a/apps/server/src/cli/browser.ts +++ b/apps/server/src/cli/browser.ts @@ -10,7 +10,7 @@ import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as PreviewBrowserHost from "../preview/PreviewBrowserHost.ts"; -import { resolveBaseDir } from "../os-jank.ts"; +import { resolveBaseDir, resolveDefaultHomeBaseDir } from "../os-jank.ts"; import { baseDirFlag } from "./config.ts"; import { resolveRootCliCommand } from "./invocation.ts"; @@ -39,10 +39,12 @@ const runStep = Effect.fn("browserSetup.runStep")(function* ( } }); -/** Under sudo, an unspecified home uses the invoking user's ~/.t3. */ +/** Under sudo, an unspecified home uses the invoking user's default M3/T3 home. */ const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Option.Option) { const env = yield* HostProcess.Environment; - const raw = Option.getOrUndefined(explicit) ?? env.T3CODE_HOME; + const raw = + Option.getOrUndefined(explicit) ?? + (env.M3CODE_HOME?.trim() || env.T3CODE_HOME?.trim() || undefined); if (raw !== undefined || env.SUDO_USER === undefined) return yield* resolveBaseDir(raw); const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const entry = yield* spawner @@ -51,8 +53,7 @@ const setupBaseDir = Effect.fn("browserSetup.baseDir")(function* (explicit: Opti ) .pipe(Effect.orElseSucceed(() => "")); const home = entry.trim().split(":")[5]; - const path = yield* Path.Path; - return home ? path.join(home, ".t3") : yield* resolveBaseDir(undefined); + return home ? yield* resolveDefaultHomeBaseDir(home) : yield* resolveBaseDir(undefined); }); const aptOffers = Effect.fn("browserSetup.aptOffers")(function* (name: string) { @@ -119,7 +120,9 @@ const browserSetupCommand = Command.make("setup", { baseDir: baseDirFlag }).pipe // sudo resets the environment, so a chosen home has to be on the command line. const setupCommand = yield* resolveRootCliCommand( PreviewBrowserHost.SETUP_SUBCOMMAND, - Option.isSome(baseDir) || env.T3CODE_HOME !== undefined ? ["--base-dir", baseDirPath] : [], + Option.isSome(baseDir) || env.M3CODE_HOME !== undefined || env.T3CODE_HOME !== undefined + ? ["--base-dir", baseDirPath] + : [], ); // Root, unless sudo came from another user, is likely the server's own account. const rootWarning = diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index fa7c4cf0a7c2f..bdf158998802d 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -111,18 +111,41 @@ const tlsCaFlag = Flag.String("tls-ca").pipe( Flag.optional, ); +const envWithLegacy = ( + primary: Config.Config, + legacy: Config.Config, +): Config.Config> => + Config.all([primary.pipe(Config.option), legacy.pipe(Config.option)]).pipe( + Config.map(([next, prev]) => Option.orElse(next, () => prev)), + ); + +export const envHomeConfig = envWithLegacy( + Config.String("M3CODE_HOME"), + Config.String("T3CODE_HOME"), +); + const EnvServerConfig = Config.all({ - logLevel: Config.LogLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")), - mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe( - Config.option, + logLevel: envWithLegacy( + Config.LogLevel("M3CODE_LOG_LEVEL"), + Config.LogLevel("T3CODE_LOG_LEVEL"), + ).pipe(Config.map(Option.getOrElse(() => "Info" as const))), + mode: envWithLegacy( + Config.schema(ServerConfig.RuntimeMode, "M3CODE_MODE"), + Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE"), + ).pipe(Config.map(Option.getOrUndefined)), + port: envWithLegacy(Config.Port("M3CODE_PORT"), Config.Port("T3CODE_PORT")).pipe( Config.map(Option.getOrUndefined), ), - port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)), - host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)), - t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)), + host: envWithLegacy(Config.String("M3CODE_HOST"), Config.String("T3CODE_HOST")).pipe( + Config.map(Option.getOrUndefined), + ), + t3Home: envHomeConfig.pipe(Config.map(Option.getOrUndefined)), devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)), - devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe( - Config.withDefault(""), + devAllowedOrigins: envWithLegacy( + Config.String("M3CODE_DEV_ALLOWED_ORIGINS"), + Config.String("T3CODE_DEV_ALLOWED_ORIGINS"), + ).pipe( + Config.map(Option.getOrElse(() => "")), Config.map((value) => value .split(",") @@ -130,59 +153,71 @@ const EnvServerConfig = Config.all({ .filter((entry) => entry.length > 0), ), ), - noBrowser: Config.Boolean("T3CODE_NO_BROWSER").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - bootstrapFd: Config.Int("T3CODE_BOOTSTRAP_FD").pipe( - Config.option, + noBrowser: envWithLegacy( + Config.Boolean("M3CODE_NO_BROWSER"), + Config.Boolean("T3CODE_NO_BROWSER"), + ).pipe(Config.map(Option.getOrUndefined)), + bootstrapFd: envWithLegacy( + Config.Int("M3CODE_BOOTSTRAP_FD"), + Config.Int("T3CODE_BOOTSTRAP_FD"), + ).pipe(Config.map(Option.getOrUndefined)), + autoBootstrapProjectFromCwd: envWithLegacy( + Config.Boolean("M3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD"), + Config.Boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD"), + ).pipe(Config.map(Option.getOrUndefined)), + logWebSocketEvents: envWithLegacy( + Config.Boolean("M3CODE_LOG_WS_EVENTS"), + Config.Boolean("T3CODE_LOG_WS_EVENTS"), + ).pipe(Config.map(Option.getOrUndefined)), + tailscaleServeEnabled: envWithLegacy( + Config.Boolean("M3CODE_TAILSCALE_SERVE"), + Config.Boolean("T3CODE_TAILSCALE_SERVE"), + ).pipe(Config.map(Option.getOrUndefined)), + tailscaleServePort: envWithLegacy( + Config.Port("M3CODE_TAILSCALE_SERVE_PORT"), + Config.Port("T3CODE_TAILSCALE_SERVE_PORT"), + ).pipe(Config.map(Option.getOrUndefined)), + lan: envWithLegacy(Config.Boolean("M3CODE_LAN"), Config.Boolean("T3CODE_LAN")).pipe( Config.map(Option.getOrUndefined), ), - autoBootstrapProjectFromCwd: Config.Boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe( - Config.option, + mtlsEnabled: envWithLegacy(Config.Boolean("M3CODE_MTLS"), Config.Boolean("T3CODE_MTLS")).pipe( Config.map(Option.getOrUndefined), ), - logWebSocketEvents: Config.Boolean("T3CODE_LOG_WS_EVENTS").pipe( - Config.option, + tlsCertPath: envWithLegacy( + Config.String("M3CODE_TLS_CERT"), + Config.String("T3CODE_TLS_CERT"), + ).pipe(Config.map(Option.getOrUndefined)), + tlsKeyPath: envWithLegacy(Config.String("M3CODE_TLS_KEY"), Config.String("T3CODE_TLS_KEY")).pipe( Config.map(Option.getOrUndefined), ), - tailscaleServeEnabled: Config.Boolean("T3CODE_TAILSCALE_SERVE").pipe( - Config.option, + tlsCaPath: envWithLegacy(Config.String("M3CODE_TLS_CA"), Config.String("T3CODE_TLS_CA")).pipe( Config.map(Option.getOrUndefined), ), - tailscaleServePort: Config.Port("T3CODE_TAILSCALE_SERVE_PORT").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - lan: Config.Boolean("T3CODE_LAN").pipe(Config.option, Config.map(Option.getOrUndefined)), - mtlsEnabled: Config.Boolean("T3CODE_MTLS").pipe(Config.option, Config.map(Option.getOrUndefined)), - tlsCertPath: Config.String("T3CODE_TLS_CERT").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - tlsKeyPath: Config.String("T3CODE_TLS_KEY").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), - tlsCaPath: Config.String("T3CODE_TLS_CA").pipe(Config.option, Config.map(Option.getOrUndefined)), }); -const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe( - Config.map((token) => Redacted.make(Redacted.value(token).trim())), - Config.mapEffect((token) => - Redacted.value(token).length === 0 || Redacted.value(token).length >= 32 - ? Effect.succeed(token) - : Effect.fail( - new Config.ConfigError( - new Schema.SchemaError( - new SchemaIssue.InvalidValue({ - message: "T3CODE_DEV_AUTH_TOKEN must contain at least 32 characters.", - }), +const DevAuthTokenConfig = envWithLegacy( + Config.Redacted("M3CODE_DEV_AUTH_TOKEN"), + Config.Redacted("T3CODE_DEV_AUTH_TOKEN"), +).pipe( + Config.map(Option.map((token) => Redacted.make(Redacted.value(token).trim()))), + Config.mapEffect( + Option.match({ + onNone: () => Effect.succeed(Option.none>()), + onSome: (token) => + Redacted.value(token).length === 0 || Redacted.value(token).length >= 32 + ? Effect.succeed(Option.some(token)) + : Effect.fail( + new Config.ConfigError( + new Schema.SchemaError( + new SchemaIssue.InvalidValue({ + message: + "M3CODE_DEV_AUTH_TOKEN (or T3CODE_DEV_AUTH_TOKEN) must contain at least 32 characters.", + }), + ), + ), ), - ), - ), + }), ), - Config.option, Config.map(Option.filter((token) => Redacted.value(token).length > 0)), Config.map(Option.getOrUndefined), ); diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index 1d4f4d65b7ba1..df748737e0b8f 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -285,7 +285,17 @@ const discoverPairTarget = Effect.fn("pair.discoverPairTarget")(function* ( bases.push(worktreeHome); inLinkedWorktree = true; } else { - const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option); + const envHome = yield* Config.all([ + Config.String("M3CODE_HOME").pipe(Config.option), + Config.String("T3CODE_HOME").pipe(Config.option), + ]).pipe( + Config.map(([next, prev]) => + Option.orElse( + Option.filter(next, (value) => value.trim().length > 0), + () => Option.filter(prev, (value) => value.trim().length > 0), + ), + ), + ); bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome))); } } diff --git a/apps/server/src/cli/theme.ts b/apps/server/src/cli/theme.ts index 9151d8dea2192..2e5981cf48077 100644 --- a/apps/server/src/cli/theme.ts +++ b/apps/server/src/cli/theme.ts @@ -172,7 +172,17 @@ export class ThemeTargetMissingError extends Schema.TaggedError + Option.orElse( + Option.filter(next, (value) => value.trim().length > 0), + () => Option.filter(prev, (value) => value.trim().length > 0), + ), + ), +); const DEV_STATE_PLACEHOLDER_URL = new URL("http://localhost"); const hasLiveServer = (statePath: string) => diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index 205bb7fa12518..65729034f4c49 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -175,7 +175,17 @@ export const triageCommand = Command.make("triage", { Effect.gen(function* () { // Triage is a user-facing feature: always the userdata state, never dev. const explicitBaseDir = Option.getOrUndefined(flags.baseDir); - const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option); + const envHome = yield* Config.all([ + Config.String("M3CODE_HOME").pipe(Config.option), + Config.String("T3CODE_HOME").pipe(Config.option), + ]).pipe( + Config.map(([next, prev]) => + Option.orElse( + Option.filter(next, (value) => value.trim().length > 0), + () => Option.filter(prev, (value) => value.trim().length > 0), + ), + ), + ); const baseDir = yield* resolveBaseDir(explicitBaseDir ?? Option.getOrUndefined(envHome)); const paths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {}); diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index b0167e10d4076..c85df9906c810 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -258,10 +258,32 @@ export const expandHomePath = Effect.fn(function* (input: string) { return input; }); +/** + * Resolves `/.m3` by default, falling back to `/.t3` when `.m3` does not exist yet + * and `.t3` already exists so existing state and paired devices remain intact. + */ +export const resolveDefaultHomeBaseDir = Effect.fn(function* (home: string) { + const { join } = yield* Path.Path; + const m3Dir = join(home, ".m3"); + const legacyT3Dir = join(home, ".t3"); + const maybeFs = yield* Effect.serviceOption(FileSystem.FileSystem); + if (Option.isSome(maybeFs)) { + const fs = maybeFs.value; + const hasM3 = yield* fs.exists(m3Dir).pipe(Effect.orElseSucceed(() => false)); + if (!hasM3) { + const hasLegacyT3 = yield* fs.exists(legacyT3Dir).pipe(Effect.orElseSucceed(() => false)); + if (hasLegacyT3) { + return legacyT3Dir; + } + } + } + return m3Dir; +}); + export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) { - const { join, resolve } = yield* Path.Path; + const { resolve } = yield* Path.Path; if (!raw || raw.trim().length === 0) { - return join(yield* HostProcess.HomeDirectory, ".t3"); + return yield* resolveDefaultHomeBaseDir(yield* HostProcess.HomeDirectory); } return resolve(yield* expandHomePath(raw.trim())); }); diff --git a/apps/server/src/project/T3ProjectFileLoader.ts b/apps/server/src/project/T3ProjectFileLoader.ts index 1cc008d07cc83..6fd771fbea1d4 100644 --- a/apps/server/src/project/T3ProjectFileLoader.ts +++ b/apps/server/src/project/T3ProjectFileLoader.ts @@ -6,7 +6,11 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import { T3_PROJECT_FILE_NAME, type T3ProjectFile } from "@t3tools/contracts"; +import { + LEGACY_T3_PROJECT_FILE_NAME, + T3_PROJECT_FILE_NAME, + type T3ProjectFile, +} from "@t3tools/contracts"; import { T3ProjectFileFromJson } from "@t3tools/shared/t3ProjectFile"; const decodeT3ProjectFileJson = Schema.decodeEffect(T3ProjectFileFromJson); @@ -50,27 +54,42 @@ export const make = Effect.gen(function* () { const load: T3ProjectFileLoader["Service"]["load"] = Effect.fn("T3ProjectFileLoader.load")( function* (workspaceRoot) { - const filePath = path.join(workspaceRoot, T3_PROJECT_FILE_NAME); - const raw = yield* fileSystem.readFileString(filePath).pipe( - Effect.asSome, - Effect.catchTags({ - PlatformError: (error) => - error.reason._tag === "NotFound" - ? Effect.succeed(Option.none()) - : logT3ProjectFileLoadError( - new T3ProjectFileLoadError({ - operation: "read", - workspaceRoot, - filePath, - cause: error, - }), - ).pipe(Effect.as(Option.none())), - }), + const readCandidate = (fileName: string) => { + const filePath = path.join(workspaceRoot, fileName); + return fileSystem.readFileString(filePath).pipe( + Effect.map((content) => Option.some({ content, filePath })), + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" + ? Effect.succeed( + Option.none<{ readonly content: string; readonly filePath: string }>(), + ) + : logT3ProjectFileLoadError( + new T3ProjectFileLoadError({ + operation: "read", + workspaceRoot, + filePath, + cause: error, + }), + ).pipe( + Effect.as( + Option.none<{ readonly content: string; readonly filePath: string }>(), + ), + ), + }), + ); + }; + + const loaded = Option.orElse(yield* readCandidate(T3_PROJECT_FILE_NAME), () => + Option.none<{ readonly content: string; readonly filePath: string }>(), ); - if (Option.isNone(raw)) { + const resolved = Option.isSome(loaded) + ? loaded + : yield* readCandidate(LEGACY_T3_PROJECT_FILE_NAME); + if (Option.isNone(resolved)) { return Option.none(); } - return yield* decodeT3ProjectFileJson(raw.value).pipe( + return yield* decodeT3ProjectFileJson(resolved.value.content).pipe( Effect.asSome, Effect.catchTags({ SchemaError: (error) => @@ -78,7 +97,7 @@ export const make = Effect.gen(function* () { new T3ProjectFileLoadError({ operation: "decode", workspaceRoot, - filePath, + filePath: resolved.value.filePath, cause: error, }), ).pipe(Effect.as(Option.none())), diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 50df4ca80bea5..5a1c02102a95e 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1585,9 +1585,11 @@ export interface LauncherOptions { } export async function main(options: LauncherOptions = {}): Promise { - const baseDir = options.baseDir ?? process.env.T3CODE_HOME; + const baseDir = + options.baseDir ?? + (process.env.M3CODE_HOME?.trim() || process.env.T3CODE_HOME?.trim() || undefined); if (baseDir === undefined || baseDir.trim() === "") { - throw new Error("T3CODE_HOME is required by the M3 Code service launcher."); + throw new Error("M3CODE_HOME (or T3CODE_HOME) is required by the M3 Code service launcher."); } const output = options.logFile === undefined ? undefined : NodeFS.openSync(options.logFile, "a", 0o600); diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 92e4ca71f6293..993712c2d76f1 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -26,7 +26,8 @@ const repoEnv = loadRepoEnv(); Object.assign(process.env, repoEnv); // Signal single-origin dev explicitly; loadRepoEnv can restore deleted URL keys from .env. -const isSingleOriginDev = process.env.T3CODE_SINGLE_ORIGIN_DEV === "1"; +const isSingleOriginDev = + (process.env.M3CODE_SINGLE_ORIGIN_DEV ?? process.env.T3CODE_SINGLE_ORIGIN_DEV) === "1"; const port = Number(process.env.PORT ?? 5733); const explicitHost = process.env.HOST?.trim(); @@ -216,7 +217,10 @@ function resolveDevProxyTarget( } } -const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl); +const devProxyTarget = resolveDevProxyTarget( + process.env.M3CODE_PORT ?? process.env.T3CODE_PORT, + configuredWsUrl, +); // Brotli quality 5 encodes in hundreds of ms; default quality 11 would replace transfer stalls with encode stalls. function devCompressionPlugin(): Plugin { diff --git a/packages/contracts/src/t3ProjectFile.ts b/packages/contracts/src/t3ProjectFile.ts index c36199566c3e7..eddce19faff3a 100644 --- a/packages/contracts/src/t3ProjectFile.ts +++ b/packages/contracts/src/t3ProjectFile.ts @@ -5,7 +5,8 @@ import { ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { ProjectScriptIcon } from "./project.ts"; import type { ProjectScopedServerSettingKey, ServerSettings } from "./settings.ts"; -export const T3_PROJECT_FILE_NAME = "t3.json"; +export const T3_PROJECT_FILE_NAME = "m3.json"; +export const LEGACY_T3_PROJECT_FILE_NAME = "t3.json"; export const T3_PROJECT_FILE_SCHEMA_URL = "https://t3.codes/schema/t3.json"; diff --git a/packages/shared/src/devHome.ts b/packages/shared/src/devHome.ts index dbd4f0b05e98d..112a7a21fc2c9 100644 --- a/packages/shared/src/devHome.ts +++ b/packages/shared/src/devHome.ts @@ -53,6 +53,8 @@ export const resolveGitWorktreePath = Effect.fn("devHome.resolveGitWorktreePath" /** * Deliberately does not require the directory to exist yet: falling back * because it is missing would send callers at the shared home. + * Uses `.m3` for fresh worktrees, falling back to an existing `.t3` directory + * so existing worktree state is preserved. */ export const resolveWorktreeT3Home = Effect.fn("devHome.resolveWorktreeT3Home")(function* ( cwd: string, @@ -61,6 +63,18 @@ export const resolveWorktreeT3Home = Effect.fn("devHome.resolveWorktreeT3Home")( if (worktreePath === undefined) { return undefined; } + const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - return path.join(worktreePath, ".t3"); + const m3Dir = path.join(worktreePath, ".m3"); + const legacyT3Dir = path.join(worktreePath, ".t3"); + const hasM3 = yield* fileSystem.exists(m3Dir).pipe(Effect.orElseSucceed(() => false)); + if (!hasM3) { + const hasLegacyT3 = yield* fileSystem + .exists(legacyT3Dir) + .pipe(Effect.orElseSucceed(() => false)); + if (hasLegacyT3) { + return legacyT3Dir; + } + } + return m3Dir; }); diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 6324cd04c1929..66a609f76c16e 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -63,7 +63,7 @@ import { Command, Flag } from "effect/cli"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const; -const DESKTOP_APP_ID = "com.t3tools.t3code"; +const DESKTOP_APP_ID = "com.m3code.m3code"; const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u; const BuildPlatform = Schema.Literals(["mac", "linux", "win"]); @@ -2909,7 +2909,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( desktop: { entry: { // Match Electron's WM_CLASS from setDesktopName so docks use this launcher. - StartupWMClass: "com.t3tools.T3Code", + StartupWMClass: "com.m3code.M3Code", }, }, }; diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index 95b49bd05a64e..0fc5458b56f1e 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -67,9 +67,24 @@ function sharedBackendTargetHost(host: string | undefined): string { return "127.0.0.1"; } -export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) => - path.join(NodeOS.homedir(), ".t3"), -); +export const DEFAULT_T3_HOME = Effect.gen(function* () { + const path = yield* Path.Path; + const home = NodeOS.homedir(); + const m3Dir = path.join(home, ".m3"); + const legacyT3Dir = path.join(home, ".t3"); + const maybeFs = yield* Effect.serviceOption(FileSystem.FileSystem); + if (Option.isSome(maybeFs)) { + const fs = maybeFs.value; + const hasM3 = yield* fs.exists(m3Dir).pipe(Effect.orElseSucceed(() => false)); + if (!hasM3) { + const hasLegacyT3 = yield* fs.exists(legacyT3Dir).pipe(Effect.orElseSucceed(() => false)); + if (hasLegacyT3) { + return legacyT3Dir; + } + } + } + return m3Dir; +}); const MODE_ARGS = { dev: [ @@ -208,19 +223,32 @@ const optionalStringConfig = (name: string): Config.Config = Config.option, Config.map((value) => Option.getOrUndefined(value)), ); -const optionalBooleanConfig = (name: string): Config.Config => - Config.Boolean(name).pipe( - Config.option, - Config.map((value) => Option.getOrUndefined(value)), - ); -const optionalIntegerConfig = (name: string): Config.Config => - Config.Int(name).pipe( - Config.option, - Config.map((value) => Option.getOrUndefined(value)), +const optionalBooleanWithLegacy = ( + primary: string, + legacy: string, +): Config.Config => + Config.all([ + Config.Boolean(primary).pipe(Config.option), + Config.Boolean(legacy).pipe(Config.option), + ]).pipe(Config.map(([next, prev]) => Option.getOrUndefined(Option.orElse(next, () => prev)))); +const optionalIntegerWithLegacy = ( + primary: string, + legacy: string, +): Config.Config => + Config.all([ + Config.Int(primary).pipe(Config.option), + Config.Int(legacy).pipe(Config.option), + ]).pipe(Config.map(([next, prev]) => Option.getOrUndefined(Option.orElse(next, () => prev)))); +const optionalStringWithLegacy = ( + primary: string, + legacy: string, +): Config.Config => + Config.all([optionalStringConfig(primary), optionalStringConfig(legacy)]).pipe( + Config.map(([next, prev]) => (next?.trim() ? next : prev)), ); const OffsetConfig = Config.all({ - portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"), - devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"), + portOffset: optionalIntegerWithLegacy("M3CODE_PORT_OFFSET", "T3CODE_PORT_OFFSET"), + devInstance: optionalStringWithLegacy("M3CODE_DEV_INSTANCE", "T3CODE_DEV_INSTANCE"), }); export function resolveOffset(config: { @@ -330,12 +358,17 @@ export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(fun }; const path = yield* Path.Path; - // The server stores an explicit home's state in userdata, which for ~/.t3 is the live - // install. Left implicit, dev state goes to ~/.t3/dev. - const isLiveHome = resolvedBaseDir === path.join(yield* HostProcess.HomeDirectory, ".t3"); + const homeDirectory = yield* HostProcess.HomeDirectory; + // The server stores an explicit home's state in userdata, which for ~/.m3 or legacy ~/.t3 is + // the live install. Left implicit, dev state goes to /dev. + const isLiveHome = + resolvedBaseDir === path.join(homeDirectory, ".m3") || + resolvedBaseDir === path.join(homeDirectory, ".t3"); if (configuredBaseDir !== undefined && !isLiveHome) { - output.T3CODE_HOME = resolvedBaseDir; + output.M3CODE_HOME = resolvedBaseDir; + delete output.T3CODE_HOME; } else { + delete output.M3CODE_HOME; delete output.T3CODE_HOME; } @@ -345,7 +378,8 @@ export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(fun delete output.T3_BOOT_SERVICE_UNIT; if (!isDesktopMode) { - output.T3CODE_PORT = String(serverPort); + output.M3CODE_PORT = String(serverPort); + delete output.T3CODE_PORT; // An inherited HOST pins Vite's HMR socket via explicitHost in apps/web/vite.config.ts. // Only desktop mode should set it. delete output.HOST; @@ -359,60 +393,80 @@ export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(fun // which merges `.env`/`.env.local` *under* this env, so a developer // with either URL in their `.env` would get it back and silently lose // single-origin mode. - output.T3CODE_SINGLE_ORIGIN_DEV = "1"; + output.M3CODE_SINGLE_ORIGIN_DEV = "1"; + delete output.T3CODE_SINGLE_ORIGIN_DEV; } else { output.VITE_HTTP_URL = `http://localhost:${serverPort}`; output.VITE_WS_URL = `ws://localhost:${serverPort}`; + delete output.M3CODE_SINGLE_ORIGIN_DEV; delete output.T3CODE_SINGLE_ORIGIN_DEV; } } else { - output.T3CODE_PORT = String(serverPort); + output.M3CODE_PORT = String(serverPort); + delete output.T3CODE_PORT; output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; // Desktop pins the renderer to loopback on purpose; an ambient marker // must not make Vite drop those URLs. + delete output.M3CODE_SINGLE_ORIGIN_DEV; delete output.T3CODE_SINGLE_ORIGIN_DEV; + delete output.M3CODE_MODE; delete output.T3CODE_MODE; + delete output.M3CODE_NO_BROWSER; delete output.T3CODE_NO_BROWSER; + delete output.M3CODE_DEV_AUTH_TOKEN; delete output.T3CODE_DEV_AUTH_TOKEN; } // Agent shells inherit the parent T3 server's bind settings; only --host widens the dev server. + delete output.M3CODE_LAN; delete output.T3CODE_LAN; if (!isDesktopMode && host !== undefined) { - output.T3CODE_HOST = host; + output.M3CODE_HOST = host; + delete output.T3CODE_HOST; } else { + delete output.M3CODE_HOST; delete output.T3CODE_HOST; } if (!isDesktopMode) { - output.T3CODE_NO_BROWSER = browser === true ? "0" : "1"; + output.M3CODE_NO_BROWSER = browser === true ? "0" : "1"; + delete output.T3CODE_NO_BROWSER; } if (autoBootstrapProjectFromCwd !== undefined) { - output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0"; + output.M3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0"; + delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD; } else { + delete output.M3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD; delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD; } if (logWebSocketEvents !== undefined) { - output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0"; + output.M3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0"; + delete output.T3CODE_LOG_WS_EVENTS; } else { + delete output.M3CODE_LOG_WS_EVENTS; delete output.T3CODE_LOG_WS_EVENTS; } if (mode === "dev") { - output.T3CODE_MODE = "web"; + output.M3CODE_MODE = "web"; + delete output.T3CODE_MODE; + delete output.M3CODE_DESKTOP_WS_URL; delete output.T3CODE_DESKTOP_WS_URL; } if (mode === "dev:server" || mode === "dev:web") { - output.T3CODE_MODE = "web"; + output.M3CODE_MODE = "web"; + delete output.T3CODE_MODE; + delete output.M3CODE_DESKTOP_WS_URL; delete output.T3CODE_DESKTOP_WS_URL; } if (isDesktopMode) { output.HOST = DESKTOP_DEV_LOOPBACK_HOST; + delete output.M3CODE_DESKTOP_WS_URL; delete output.T3CODE_DESKTOP_WS_URL; } @@ -639,7 +693,10 @@ const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (i ); } } - const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite"); + const homeDir = yield* HostProcess.HomeDirectory; + const m3Source = path.join(homeDir, ".m3", "userdata", "statev2.sqlite"); + const legacyT3Source = path.join(homeDir, ".t3", "userdata", "statev2.sqlite"); + const source = (yield* exists(m3Source)) ? m3Source : legacyT3Source; // A V1 state.sqlite counts as data too: the server imports it only while // statev2.sqlite is missing, so seeding would hide it. if ( @@ -655,7 +712,7 @@ const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (i ); } else { yield* Effect.logInfo( - `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`, + `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or M3CODE_DEV_SEED=0 skips this.`, ); yield* runRepoScript( "apps/server/scripts/migrate-dev-db.ts", @@ -780,7 +837,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput const resolvedT3Home = (input.t3Home?.trim() || undefined) ?? worktreeHome ?? - (hostEnvironment.T3CODE_HOME?.trim() || undefined); + (hostEnvironment.M3CODE_HOME?.trim() || hostEnvironment.T3CODE_HOME?.trim() || undefined); const env = yield* createDevRunnerEnv({ mode: input.mode, baseEnv: hostEnvironment, @@ -799,10 +856,10 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput serverOffset !== offset || webOffset !== offset ? ` selectedOffset(server=${serverOffset},web=${webOffset})` : ""; - const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME); + const baseDir = env.M3CODE_HOME ?? env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME); yield* Effect.logInfo( - `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`, + `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.M3CODE_PORT ?? env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`, ); // Before the share block: --dry-run only resolves and prints. Sharing would @@ -835,7 +892,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput ...(input.built ? { localTarget: { - port: Number(env.T3CODE_PORT), + port: Number(env.M3CODE_PORT ?? env.T3CODE_PORT), host: sharedBackendTargetHost(input.host), }, } @@ -869,24 +926,25 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput // The app is reached from the tailnet origin. Vite already allows // *.ts.net hosts; the backend needs the origin for credentialed // requests that bypass the proxy (desktop renderer, direct calls). - env.T3CODE_DEV_ALLOWED_ORIGINS = [ - env.T3CODE_DEV_ALLOWED_ORIGINS, + env.M3CODE_DEV_ALLOWED_ORIGINS = [ + env.M3CODE_DEV_ALLOWED_ORIGINS ?? env.T3CODE_DEV_ALLOWED_ORIGINS, new URL(shared.url).origin, ] .filter((entry) => entry && entry.length > 0) .join(","); + delete env.T3CODE_DEV_ALLOWED_ORIGINS; if (input.devUrl === undefined) { env.VITE_DEV_SERVER_URL = shared.url; } if (input.built) { built = true; - env.T3CODE_BUILT_DEV = "1"; - } else if (env.T3CODE_BUNDLED_DEV === undefined) { + env.M3CODE_BUILT_DEV = "1"; + } else if ((env.M3CODE_BUNDLED_DEV ?? env.T3CODE_BUNDLED_DEV) === undefined) { // A shared origin serves a remote browser, where unbundled dev's // per-module requests each pay a tailnet round trip — a cold module // graph takes minutes to first paint. Bundled dev collapses that to a // few chunk requests. - env.T3CODE_BUNDLED_DEV = "1"; + env.M3CODE_BUNDLED_DEV = "1"; } yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`); } else if (input.built) { @@ -979,14 +1037,23 @@ const devRunnerCli = Command.make("dev-runner", { ), autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe( Flag.withDescription( - "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).", + "Auto-bootstrap toggle (equivalent to M3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD / T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).", + ), + Flag.withFallbackConfig( + optionalBooleanWithLegacy( + "M3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD", + "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD", + ), ), - Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")), ), logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe( - Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."), + Flag.withDescription( + "WebSocket event logging toggle (equivalent to M3CODE_LOG_WS_EVENTS / T3CODE_LOG_WS_EVENTS).", + ), Flag.withAlias("log-ws-events"), - Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")), + Flag.withFallbackConfig( + optionalBooleanWithLegacy("M3CODE_LOG_WS_EVENTS", "T3CODE_LOG_WS_EVENTS"), + ), ), host: Flag.String("host").pipe( Flag.withDescription( @@ -1023,9 +1090,9 @@ const devRunnerCli = Command.make("dev-runner", { ), seed: Flag.Boolean("seed").pipe( Flag.withDescription( - "Seed an empty worktree database from ~/.t3 on first start (read-only, via migrate-dev-db) if the source is at most 500 MiB. On by default; --no-seed or T3CODE_DEV_SEED=0 skips it.", + "Seed an empty worktree database from ~/.m3 (or legacy ~/.t3) on first start (read-only, via migrate-dev-db) if the source is at most 500 MiB. On by default; --no-seed or M3CODE_DEV_SEED=0 skips it.", ), - Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")), + Flag.withFallbackConfig(optionalBooleanWithLegacy("M3CODE_DEV_SEED", "T3CODE_DEV_SEED")), ), built: Flag.Boolean("built").pipe( Flag.withDescription( @@ -1036,13 +1103,13 @@ const devRunnerCli = Command.make("dev-runner", { memoryLimitGb: Flag.Int("memory-limit-gb").pipe( Flag.withSchema(NonNegativeInt), Flag.withDescription( - "Stop the dev server when it and its child processes use more than this many GiB of RAM plus swap (equivalent to T3CODE_DEV_MEMORY_LIMIT_GB). Defaults to half of RAM, at most 16. 0 turns it off. Linux only.", + "Stop the dev server when it and its child processes use more than this many GiB of RAM plus swap (equivalent to M3CODE_DEV_MEMORY_LIMIT_GB / T3CODE_DEV_MEMORY_LIMIT_GB). Defaults to half of RAM, at most 16. 0 turns it off. Linux only.", ), Flag.withFallbackConfig( - Config.schema(NonNegativeInt, "T3CODE_DEV_MEMORY_LIMIT_GB").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), + Config.all([ + Config.schema(NonNegativeInt, "M3CODE_DEV_MEMORY_LIMIT_GB").pipe(Config.option), + Config.schema(NonNegativeInt, "T3CODE_DEV_MEMORY_LIMIT_GB").pipe(Config.option), + ]).pipe(Config.map(([next, prev]) => Option.getOrUndefined(Option.orElse(next, () => prev)))), ), ), runArgs: Argument.String("run-arg").pipe(